1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 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 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
use crate::bindings as ll_bindings;
use crate::metadata;
use crate::metadata::NodeMetadata;
use crate::sys;
use crate::NodeFlags;
use crate::SizeType;
use crate::Time;
use crate::{tsk_id_t, TskitError};
use crate::{IndividualId, NodeId, PopulationId};
pub(crate) fn add_row_details(
flags: ll_bindings::tsk_flags_t,
time: f64,
population: ll_bindings::tsk_id_t,
individual: ll_bindings::tsk_id_t,
metadata: *const std::os::raw::c_char,
metadata_length: ll_bindings::tsk_size_t,
table: *mut ll_bindings::tsk_node_table_t,
) -> Result<NodeId, TskitError> {
let rv = unsafe {
ll_bindings::tsk_node_table_add_row(
table,
flags,
time,
population,
individual,
metadata,
metadata_length,
)
};
handle_tsk_return_value!(rv, rv.into())
}
pub(crate) fn add_row<F, T, P, I>(
flags: F,
time: T,
population: P,
individual: I,
table: *mut ll_bindings::tsk_node_table_t,
) -> Result<NodeId, TskitError>
where
F: Into<NodeFlags>,
T: Into<Time>,
P: Into<PopulationId>,
I: Into<IndividualId>,
{
add_row_details(
flags.into().bits(),
time.into().into(),
population.into().into(),
individual.into().into(),
std::ptr::null(),
0,
table,
)
}
pub(crate) fn add_row_with_metadata<F, T, P, I, N>(
flags: F,
time: T,
population: P,
individual: I,
metadata: &N,
table: *mut ll_bindings::tsk_node_table_t,
) -> Result<NodeId, TskitError>
where
F: Into<NodeFlags>,
T: Into<Time>,
P: Into<PopulationId>,
I: Into<IndividualId>,
N: NodeMetadata,
{
let md = crate::metadata::EncodedMetadata::new(metadata)?;
let mdlen = md.len()?;
add_row_details(
flags.into().bits(),
time.into().into(),
population.into().into(),
individual.into().into(),
md.as_ptr(),
mdlen.into(),
table,
)
}
pub(crate) fn add_row_with_defaults<T: Into<crate::Time>, D: crate::node_table::DefaultNodeData>(
time: T,
defaults: &D,
table: *mut ll_bindings::tsk_node_table_t,
) -> Result<NodeId, TskitError> {
let md = defaults.metadata()?;
let (ptr, mdlen) = match &md {
Some(value) => (
value.as_ptr().cast::<i8>(),
crate::SizeType::try_from(value.len())?,
),
None => (std::ptr::null(), 0.into()),
};
add_row_details(
defaults.flags().bits(),
time.into().into(),
defaults.population().into(),
defaults.individual().into(),
ptr,
mdlen.into(),
table,
)
}
/// Row of a [`NodeTable`]
#[derive(Debug)]
pub struct NodeTableRow {
pub id: NodeId,
pub time: Time,
pub flags: NodeFlags,
pub population: PopulationId,
pub individual: IndividualId,
pub metadata: Option<Vec<u8>>,
}
impl PartialEq for NodeTableRow {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
&& self.flags == other.flags
&& self.population == other.population
&& self.individual == other.individual
&& crate::util::partial_cmp_equal(&self.time, &other.time)
&& self.metadata == other.metadata
}
}
fn make_node_table_row(table: &NodeTable, pos: tsk_id_t) -> Option<NodeTableRow> {
Some(NodeTableRow {
id: pos.into(),
time: table.time(pos)?,
flags: table.flags(pos)?,
population: table.population(pos)?,
individual: table.individual(pos)?,
metadata: table.raw_metadata(pos).map(|m| m.to_vec()),
})
}
pub(crate) type NodeTableRefIterator<'a> = crate::table_iterator::TableIterator<&'a NodeTable>;
pub(crate) type NodeTableIterator = crate::table_iterator::TableIterator<NodeTable>;
impl<'a> Iterator for NodeTableRefIterator<'a> {
type Item = NodeTableRow;
fn next(&mut self) -> Option<Self::Item> {
let rv = make_node_table_row(self.table, self.pos);
self.pos += 1;
rv
}
}
impl Iterator for NodeTableIterator {
type Item = crate::node_table::NodeTableRow;
fn next(&mut self) -> Option<Self::Item> {
let rv = make_node_table_row(&self.table, self.pos);
self.pos += 1;
rv
}
}
#[derive(Debug)]
pub struct NodeTableRowView<'a> {
table: &'a NodeTable,
pub id: NodeId,
pub time: Time,
pub flags: NodeFlags,
pub population: PopulationId,
pub individual: IndividualId,
pub metadata: Option<&'a [u8]>,
}
impl<'a> NodeTableRowView<'a> {
fn new(table: &'a NodeTable) -> Self {
Self {
table,
id: NodeId::NULL,
time: f64::NAN.into(),
flags: 0.into(),
population: PopulationId::NULL,
individual: IndividualId::NULL,
metadata: None,
}
}
}
impl<'a> PartialEq for NodeTableRowView<'a> {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
&& self.flags == other.flags
&& self.population == other.population
&& self.individual == other.individual
&& crate::util::partial_cmp_equal(&self.time, &other.time)
&& self.metadata == other.metadata
}
}
impl<'a> Eq for NodeTableRowView<'a> {}
impl<'a> PartialEq<NodeTableRow> for NodeTableRowView<'a> {
fn eq(&self, other: &NodeTableRow) -> bool {
self.id == other.id
&& self.flags == other.flags
&& self.population == other.population
&& self.individual == other.individual
&& crate::util::partial_cmp_equal(&self.time, &other.time)
&& optional_container_comparison!(self.metadata, other.metadata)
}
}
impl PartialEq<NodeTableRowView<'_>> for NodeTableRow {
fn eq(&self, other: &NodeTableRowView) -> bool {
self.id == other.id
&& self.flags == other.flags
&& self.population == other.population
&& self.individual == other.individual
&& crate::util::partial_cmp_equal(&self.time, &other.time)
&& optional_container_comparison!(self.metadata, other.metadata)
}
}
impl<'a> streaming_iterator::StreamingIterator for NodeTableRowView<'a> {
type Item = Self;
row_lending_iterator_get!();
fn advance(&mut self) {
self.id = (i32::from(self.id) + 1).into();
self.time = self.table.time(self.id).unwrap_or_else(|| f64::NAN.into());
self.flags = self.table.flags(self.id).unwrap_or_else(|| 0.into());
self.population = self.table.population(self.id).unwrap_or(PopulationId::NULL);
self.individual = self.table.individual(self.id).unwrap_or(IndividualId::NULL);
self.metadata = self.table.raw_metadata(self.id);
}
}
/// Defaults for node table rows without metadata
///
/// # Examples
///
/// ```
/// let d = tskit::NodeDefaults::default();
/// assert_eq!(d.flags, tskit::NodeFlags::default());
/// assert_eq!(d.population, tskit::PopulationId::NULL);
/// assert_eq!(d.individual, tskit::IndividualId::NULL);
/// ```
///
/// [Struct update syntax](https://doc.rust-lang.org/book/ch05-01-defining-structs.html)
/// is your friend here:
///
/// ```
/// let d = tskit::NodeDefaults{population: 0.into(), ..Default::default()};
/// assert_eq!(d.flags, tskit::NodeFlags::default());
/// assert_eq!(d.population, 0);
/// assert_eq!(d.individual, tskit::IndividualId::NULL);
/// let d2 = tskit::NodeDefaults{flags: tskit::NodeFlags::default().mark_sample(),
/// // update remaining values from d
/// ..d};
/// assert!(d2.flags.is_sample());
/// assert_eq!(d2.population, 0);
/// assert_eq!(d2.individual, tskit::IndividualId::NULL);
/// ```
#[derive(Copy, Clone, Default, Eq, PartialEq, Debug)]
pub struct NodeDefaults {
pub flags: NodeFlags,
pub population: PopulationId,
pub individual: IndividualId,
}
// Defaults for node table rows with metadata
///
/// # Notes
///
/// This struct derives `Debug` and `Clone`.
/// However, neither is a trait bound on `M`.
/// Therefore, use of `Debug` and/or `Clone` will fail unless `M`
/// also implements the relevant trait.
///
/// See [the book](https://tskit-dev.github.io/tskit-rust/)
/// for details.
#[derive(Debug, Clone)]
pub struct NodeDefaultsWithMetadata<M>
where
M: crate::metadata::NodeMetadata,
{
pub flags: NodeFlags,
pub population: PopulationId,
pub individual: IndividualId,
pub metadata: Option<M>,
}
// Manual implementation required so that
// we do not force client code to impl Default
// for metadata types.
impl<M> Default for NodeDefaultsWithMetadata<M>
where
M: crate::metadata::NodeMetadata,
{
fn default() -> Self {
Self {
flags: NodeFlags::default(),
population: PopulationId::default(),
individual: IndividualId::default(),
metadata: None,
}
}
}
mod private {
pub trait DefaultNodeDataMarker {}
impl DefaultNodeDataMarker for super::NodeDefaults {}
impl<M> DefaultNodeDataMarker for super::NodeDefaultsWithMetadata<M> where
M: crate::metadata::NodeMetadata
{
}
}
/// This trait is sealed.
pub trait DefaultNodeData: private::DefaultNodeDataMarker {
fn flags(&self) -> NodeFlags;
fn population(&self) -> PopulationId;
fn individual(&self) -> IndividualId;
fn metadata(&self) -> Result<Option<Vec<u8>>, TskitError>;
}
impl DefaultNodeData for NodeDefaults {
fn flags(&self) -> NodeFlags {
self.flags
}
fn population(&self) -> PopulationId {
self.population
}
fn individual(&self) -> IndividualId {
self.individual
}
fn metadata(&self) -> Result<Option<Vec<u8>>, TskitError> {
Ok(None)
}
}
impl<M> DefaultNodeData for NodeDefaultsWithMetadata<M>
where
M: crate::metadata::NodeMetadata,
{
fn flags(&self) -> NodeFlags {
self.flags
}
fn population(&self) -> PopulationId {
self.population
}
fn individual(&self) -> IndividualId {
self.individual
}
fn metadata(&self) -> Result<Option<Vec<u8>>, TskitError> {
self.metadata.as_ref().map_or_else(
|| Ok(None),
|v| match v.encode() {
Ok(x) => Ok(Some(x)),
Err(e) => Err(e.into()),
},
)
}
}
/// This is a doctest hack as described in the rust book.
/// We do this b/c the specific error messages can change
/// across rust versions, making crates like trybuild
/// less useful.
///
/// ```compile_fail
/// #[derive(serde::Serialize, serde::Deserialize)]
/// struct NodeMetadata {
/// value: i32,
/// }
///
/// impl tskit::metadata::MetadataRoundtrip for NodeMetadata {
/// fn encode(&self) -> Result<Vec<u8>, tskit::metadata::MetadataError> {
/// match serde_json::to_string(self) {
/// Ok(x) => Ok(x.as_bytes().to_vec()),
/// Err(e) => Err(::tskit::metadata::MetadataError::RoundtripError { value: Box::new(e) }),
/// }
/// }
/// fn decode(md: &[u8]) -> Result<Self, tskit::metadata::MetadataError>
/// where
/// Self: Sized,
/// {
/// match serde_json::from_slice(md) {
/// Ok(v) => Ok(v),
/// Err(e) => Err(::tskit::metadata::MetadataError::RoundtripError { value: Box::new(e) }),
/// }
/// }
/// }
///
/// impl tskit::metadata::NodeMetadata for NodeMetadata {}
///
/// type DefaultsWithMetadata = tskit::NodeDefaultsWithMetadata<NodeMetadata>;
/// let defaults = DefaultsWithMetadata {
/// metadata: Some(NodeMetadata { value: 42 }),
/// ..Default::default()
/// };
///
/// // Fails because metadata type is not Debug
/// println!("{:?}", defaults);
/// ```
///
/// ```compile_fail
/// #[derive(serde::Serialize, serde::Deserialize)]
/// struct NodeMetadata {
/// value: i32,
/// }
///
/// impl tskit::metadata::MetadataRoundtrip for NodeMetadata {
/// fn encode(&self) -> Result<Vec<u8>, tskit::metadata::MetadataError> {
/// match serde_json::to_string(self) {
/// Ok(x) => Ok(x.as_bytes().to_vec()),
/// Err(e) => Err(::tskit::metadata::MetadataError::RoundtripError { value: Box::new(e) }),
/// }
/// }
/// fn decode(md: &[u8]) -> Result<Self, tskit::metadata::MetadataError>
/// where
/// Self: Sized,
/// {
/// match serde_json::from_slice(md) {
/// Ok(v) => Ok(v),
/// Err(e) => Err(::tskit::metadata::MetadataError::RoundtripError { value: Box::new(e) }),
/// }
/// }
/// }
///
/// impl tskit::metadata::NodeMetadata for NodeMetadata {}
///
/// let mut tables = tskit::TableCollection::new(10.0).unwrap();
/// type DefaultsWithMetadata = tskit::NodeDefaultsWithMetadata<NodeMetadata>;
/// // What if there is default metadata for all rows?
/// let defaults = DefaultsWithMetadata {
/// metadata: Some(NodeMetadata { value: 42 }),
/// ..Default::default()
/// };
/// // We can scoop all non-metadata fields even though
/// // type is not Copy/Clone
/// let _ = tables
/// .add_node_with_defaults(
/// 0.0,
/// &DefaultsWithMetadata {
/// metadata: Some(NodeMetadata { value: 2 * 42 }),
/// ..defaults
/// },
/// )
/// .unwrap();
/// // But now, we start to cause a problem:
/// // If we don't clone here, our metadata type moves,
/// // so our defaults are moved.
/// let _ = tables
/// .add_node_with_defaults(
/// 0.0,
/// &DefaultsWithMetadata {
/// population: 6.into(),
/// ..defaults
/// },
/// )
/// .unwrap();
/// // Now, we have a use-after-move error
/// // if we hadn't cloned in the last step.
/// let _ = tables
/// .add_node_with_defaults(
/// 0.0,
/// &DefaultsWithMetadata {
/// individual: 7.into(),
/// ..defaults
/// },
/// )
/// .unwrap();
/// ```
#[cfg(doctest)]
struct NodeDefaultsWithMetadataNotCloneNotDebug;
/// An immtable view of a node table.
#[derive(Debug)]
#[repr(transparent)]
pub struct NodeTable {
table_: sys::LLNodeTableRef,
}
impl NodeTable {
pub(crate) fn new_from_table(
nodes: *mut ll_bindings::tsk_node_table_t,
) -> Result<Self, TskitError> {
let table_ = sys::LLNodeTableRef::new_from_table(nodes)?;
Ok(NodeTable { table_ })
}
pub(crate) fn as_ref(&self) -> &ll_bindings::tsk_node_table_t {
self.table_.as_ref()
}
/// Return the number of rows
pub fn num_rows(&self) -> SizeType {
self.as_ref().num_rows.into()
}
raw_metadata_getter_for_tables!(NodeId);
/// Return the ``time`` value from row ``row`` of the table.
///
/// # Returns
///
/// * `Some(time)` if `row` is valid.
/// * `None` otherwise.
///
/// # Examples
///
/// ```
/// # use tskit::prelude::*;
/// # let mut tables = tskit::TableCollection::new(10.).unwrap();
/// # tables.add_node(0, 10.0, -1, -1).unwrap();
/// if let Some(time) = tables.nodes().time(0) {
/// // then node id 0 is a valid row id
/// # assert_eq!(time, 10.0);
/// }
/// # else {
/// # panic!("expected 0 to be a valid row id")
/// # }
/// ```
pub fn time<N: Into<NodeId> + Copy>(&self, row: N) -> Option<Time> {
sys::tsk_column_access::<Time, _, _, _>(row.into(), self.as_ref().time, self.num_rows())
}
/// Return the ``flags`` value from row ``row`` of the table.
///
/// # Returns
///
/// * `Some(flags)` if `row` is valid.
/// * `None` otherwise.
///
/// # Examples
///
/// ```
/// # use tskit::prelude::*;
/// # let mut tables = tskit::TableCollection::new(10.).unwrap();
/// # tables.add_node(tskit::NodeFlags::IS_SAMPLE, 10.0, -1, -1).unwrap();
/// if let Some(flags) = tables.nodes().flags(0) {
/// // then node id 0 is a valid row id
/// # assert!(flags.is_sample());
/// }
/// # else {
/// # panic!("expected 0 to be a valid row id")
/// # }
/// ```
pub fn flags<N: Into<NodeId> + Copy>(&self, row: N) -> Option<NodeFlags> {
sys::tsk_column_access::<NodeFlags, _, _, _>(
row.into(),
self.as_ref().flags,
self.num_rows(),
)
}
#[deprecated(since = "0.12.0", note = "use flags_slice_mut instead")]
pub fn flags_array_mut(&mut self) -> &mut [NodeFlags] {
sys::generate_slice_mut(self.as_ref().flags, self.num_rows())
}
#[deprecated(since = "0.12.0", note = "use time_slice_mut instead")]
pub fn time_array_mut(&mut self) -> &mut [Time] {
sys::generate_slice_mut(self.as_ref().flags, self.num_rows())
}
/// Return the ``population`` value from row ``row`` of the table.
///
/// # Examples
///
/// ```
/// # use tskit::prelude::*;
/// # let mut tables = tskit::TableCollection::new(10.).unwrap();
/// # tables.add_node(0, 10.0, -1, -1).unwrap();
/// if let Some(pop) = tables.nodes().population(0) {
/// // then node id 0 is a valid row id
/// # assert!(pop.is_null());
/// }
/// # else {
/// # panic!("expected 0 to be a valid row id")
/// # }
/// ```
///
/// # Returns
///
/// * `Some(population)` if `row` is valid.
/// * `None` otherwise.
pub fn population<N: Into<NodeId> + Copy>(&self, row: N) -> Option<PopulationId> {
sys::tsk_column_access::<PopulationId, _, _, _>(
row.into(),
self.as_ref().population,
self.num_rows(),
)
}
/// Return the ``population`` value from row ``row`` of the table.
///
/// # Examples
///
/// See [`NodeTable::population`] for examples.
///
/// # Returns
///
/// * `Some(population)` if `row` is valid.
/// * `None` otherwise.
pub fn deme<N: Into<NodeId> + Copy>(&self, row: N) -> Option<PopulationId> {
self.population(row)
}
/// Return the ``individual`` value from row ``row`` of the table.
///
/// # Examples
///
/// ```
/// # use tskit::prelude::*;
/// # let mut tables = tskit::TableCollection::new(10.).unwrap();
/// # tables.add_node(0, 10.0, -1, -1).unwrap();
/// if let Some(individual) = tables.nodes().individual(0) {
/// // then node id 0 is a valid row id
/// # assert!(individual.is_null());
/// }
/// # else {
/// # panic!("expected 0 to be a valid row id")
/// # }
/// ```
///
/// # Returns
///
/// * `Some(individual)` if `row` is valid.
/// * `None` otherwise.
pub fn individual<N: Into<NodeId> + Copy>(&self, row: N) -> Option<IndividualId> {
sys::tsk_column_access::<IndividualId, _, _, _>(
row.into(),
self.as_ref().individual,
self.num_rows(),
)
}
/// Retrieve decoded metadata for a `row`.
///
/// # Returns
///
/// * `Some(Ok(T))` if `row` is valid and decoding succeeded.
/// * `Some(Err(_))` if `row` is not valid and decoding failed.
/// * `None` if `row` is not valid.
///
/// # Errors
///
/// * [`TskitError::MetadataError`] if decoding fails.
///
/// # Examples.
///
/// The big-picture semantics are the same for all table types.
/// See [`crate::IndividualTable::metadata`] for examples.
pub fn metadata<T: metadata::NodeMetadata>(
&self,
row: NodeId,
) -> Option<Result<T, TskitError>> {
let buffer = self.raw_metadata(row)?;
Some(decode_metadata_row!(T, buffer).map_err(|e| e.into()))
}
/// Return an iterator over rows of the table.
/// The value of the iterator is [`NodeTableRow`].
pub fn iter(&self) -> impl Iterator<Item = NodeTableRow> + '_ {
crate::table_iterator::make_table_iterator::<&NodeTable>(self)
}
pub fn lending_iter(&self) -> NodeTableRowView {
NodeTableRowView::new(self)
}
/// Return row `r` of the table.
///
/// # Parameters
///
/// * `r`: the row id.
///
/// # Returns
///
/// * `Some(row)` if `r` is valid
/// * `None` otherwise
pub fn row<N: Into<NodeId> + Copy>(&self, r: N) -> Option<NodeTableRow> {
let ri = r.into().into();
table_row_access!(ri, self, make_node_table_row)
}
/// Return a view of row `r` of the table.
///
/// # Parameters
///
/// * `r`: the row id.
///
/// # Returns
///
/// * `Some(row view)` if `r` is valid
/// * `None` otherwise
pub fn row_view<N: Into<NodeId> + Copy>(&self, r: N) -> Option<NodeTableRowView> {
let view = NodeTableRowView {
table: self,
id: r.into(),
time: self.time(r)?,
flags: self.flags(r)?,
population: self.population(r)?,
individual: self.individual(r)?,
metadata: self.raw_metadata(r.into()),
};
Some(view)
}
/// Obtain a vector containing the indexes ("ids")
/// of all nodes for which [`crate::TSK_NODE_IS_SAMPLE`]
/// is `true`.
pub fn samples_as_vector(&self) -> Vec<NodeId> {
self.create_node_id_vector(|row| row.flags.contains(NodeFlags::IS_SAMPLE))
}
/// Obtain a vector containing the indexes ("ids") of all nodes
/// satisfying a certain criterion.
pub fn create_node_id_vector(&self, mut f: impl FnMut(&NodeTableRow) -> bool) -> Vec<NodeId> {
self.iter()
.filter(|row| f(row))
.map(|row| row.id)
.collect::<Vec<_>>()
}
build_table_column_slice_getter!(
/// Get the time column as a slice
=> time, time_slice, Time);
build_table_column_slice_getter!(
/// Get the time column as a slice
=> time, time_slice_raw, f64);
build_table_column_slice_mut_getter!(
/// Get the time column as a mutable slice
///
/// # Examples
///
/// For a [`crate::TableCollection`], accessing the table creates a temporary
/// that will be dropped, causing this code to not compile:
///
/// ```compile_fail
/// # use tskit::prelude::*;
/// # let mut tables = tskit::TableCollection::new(10.).unwrap();
/// # tables.add_node(tskit::NodeFlags::IS_SAMPLE, 10.0, -1, -1).unwrap();
/// let time = tables.nodes().time_slice_mut();
/// println!("{}", time.len()); // ERROR: the temporary node table is dropped by now
/// ```
///
/// Treating the returned slice as an iterable succeeds:
///
/// ```
/// # use tskit::prelude::*;
/// # let mut tables = tskit::TableCollection::new(10.).unwrap();
/// # tables.add_node(tskit::NodeFlags::IS_SAMPLE, 10.0, -1, -1).unwrap();
/// for time in tables.nodes_mut().time_slice_mut() {
/// *time = 55.0.into(); // change each node's time value
/// }
/// assert!(tables.nodes_mut().time_slice_mut().iter().all(|t| t == &55.0));
/// ```
///
/// # Panics
///
/// Internally, we rely on a conversion of u64 to usize.
/// This conversion is fallible on some platforms.
/// If the conversion fails, this function will panic.
=> time, time_slice_mut, Time);
build_table_column_slice_mut_getter!(
/// Get the time column as a mutable slice
=> time, time_slice_raw_mut, f64);
build_table_column_slice_getter!(
/// Get the flags column as a slice
=> flags, flags_slice, NodeFlags);
build_table_column_slice_getter!(
/// Get the flags column as a slice
=> flags, flags_slice_raw, ll_bindings::tsk_flags_t);
build_table_column_slice_mut_getter!(
/// Get the flags column as a mutable slice
///
/// # Examples
///
///
/// ```
/// # use tskit::prelude::*;
/// # let mut tables = tskit::TableCollection::new(10.).unwrap();
/// # tables.add_node(tskit::NodeFlags::IS_SAMPLE, 10.0, -1, -1).unwrap();
/// let flags = tables.nodes_mut().flags_slice_mut();
/// for flag in flags {
/// // Can do something...
/// # assert!(flag.is_sample());
/// }
/// ```
///
/// ```
/// # use tskit::prelude::*;
/// # let mut tables = tskit::TableCollection::new(10.).unwrap();
/// # tables.add_node(tskit::NodeFlags::IS_SAMPLE, 10.0, -1, -1).unwrap();
/// for flag in tables.nodes_mut().flags_slice_mut() {
/// # assert!(flag.is_sample());
/// }
/// ```
///
/// The returned slice is *mutable*, allowing one to do things like
/// clear the sample status of all nodes:
///
/// A copy of the flags can be obtained by collecting results into `Vec`:
///
/// ```
/// # use tskit::prelude::*;
/// # let mut tables = tskit::TableCollection::new(10.).unwrap();
/// # tables.add_node(tskit::NodeFlags::IS_SAMPLE, 10.0, -1, -1).unwrap();
/// for flag in tables.nodes_mut().flags_slice_mut() {
/// flag.remove(tskit::NodeFlags::IS_SAMPLE);
/// }
/// assert!(!tables.nodes_mut().flags_slice_mut().iter().any(|f| f.is_sample()));
/// assert!(tables.nodes().samples_as_vector().is_empty());
/// ```
///
/// ```
/// # use tskit::prelude::*;
/// # let mut tables = tskit::TableCollection::new(10.).unwrap();
/// # tables.add_node(tskit::NodeFlags::IS_SAMPLE, 10.0, -1, -1).unwrap();
/// let flags = tables.nodes_mut().flags_slice_mut().to_vec();
/// # assert!(flags.iter().all(|f| f.is_sample()));
/// ```
///
/// ## Owning tables
///
/// The ownership semantics differ when tables are not part of a
/// table collection:
///
/// ```
/// let mut nodes = tskit::OwningNodeTable::default();
/// assert!(nodes.add_row(tskit::NodeFlags::IS_SAMPLE, 10., -1, -1).is_ok());
/// # assert_eq!(nodes.num_rows(), 1);
/// let flags = nodes.flags_slice_mut();
/// # assert_eq!(flags.len(), 1);
/// assert!(flags.iter().all(|f| f.is_sample()));
///
/// // while we are at it, let's use our node
/// // table to populate a table collection.
/// #
/// let mut tables = tskit::TableCollection::new(10.0).unwrap();
/// tables.set_nodes(&nodes);
/// assert_eq!(tables.nodes().num_rows(), 1);
/// assert_eq!(tables.nodes_mut().flags_slice_mut().iter().filter(|f| f.is_sample()).count(), 1);
/// ```
///
/// # Panics
///
/// Internally, we rely on a conversion of u64 to usize.
/// This conversion is fallible on some platforms.
/// If the conversion fails, this function will panic.
=> flags, flags_slice_mut, NodeFlags);
build_table_column_slice_mut_getter!(
/// Get the flags column as a mutable slice
=> flags, flags_slice_raw_mut, ll_bindings::tsk_flags_t);
build_table_column_slice_getter!(
/// Get the individual column as a slice
=> individual, individual_slice, IndividualId);
build_table_column_slice_getter!(
/// Get the individual column as a slice
=> individual, individual_slice_raw, crate::tsk_id_t);
build_table_column_slice_getter!(
/// Get the population column as a slice
=> population, population_slice, PopulationId);
build_table_column_slice_getter!(
/// Get the population column as a slice
=> population, population_slice_raw, crate::tsk_id_t);
}
build_owned_table_type!(
/// A standalone node table that owns its data.
///
/// # Examples
///
/// ```
/// use tskit::OwningNodeTable;
///
/// let mut nodes = OwningNodeTable::default();
/// let rowid = nodes.add_row(0, 1.1, -1, -1).unwrap();
/// assert_eq!(rowid, 0);
/// assert_eq!(nodes.num_rows(), 1);
/// ```
///
/// An example with metadata.
/// This requires the cargo feature `"derive"` for `tskit`.
///
/// ```
/// # #[cfg(any(feature="doc", feature="derive"))] {
/// use tskit::OwningNodeTable;
///
/// #[derive(serde::Serialize,
/// serde::Deserialize,
/// tskit::metadata::NodeMetadata)]
/// #[serializer("serde_json")]
/// struct NodeMetadata {
/// value: i32,
/// }
///
/// let metadata = NodeMetadata{value: 42};
///
/// let mut nodes = OwningNodeTable::default();
///
/// let rowid = nodes.add_row_with_metadata(0, 1., -1, -1, &metadata).unwrap();
/// assert_eq!(rowid, 0);
///
/// match nodes.metadata::<NodeMetadata>(rowid) {
/// // rowid is in range, decoding succeeded
/// Some(Ok(decoded)) => assert_eq!(decoded.value, 42),
/// // rowid is in range, decoding failed
/// Some(Err(e)) => panic!("error decoding metadata: {:?}", e),
/// None => panic!("row id out of range")
/// }
///
/// # }
/// ```
=> OwningNodeTable,
NodeTable,
crate::sys::LLOwningNodeTable,
crate::bindings::tsk_node_table_t
);
impl OwningNodeTable {
pub fn add_row<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_row(flags, time, population, individual, self.as_mut_ptr())
}
pub fn add_row_with_metadata<F, T, P, I, N>(
&mut self,
flags: F,
time: T,
population: P,
individual: I,
metadata: &N,
) -> Result<NodeId, TskitError>
where
F: Into<NodeFlags>,
T: Into<Time>,
P: Into<PopulationId>,
I: Into<IndividualId>,
N: NodeMetadata,
{
add_row_with_metadata(
flags,
time,
population,
individual,
metadata,
self.as_mut_ptr(),
)
}
/// Add row with defaults
///
/// # Examples
///
/// ```
/// # let mut nodes = tskit::OwningNodeTable::default();
/// let node_defaults = tskit::NodeDefaults::default();
/// let rv = nodes.add_row_with_defaults(1.0, &node_defaults).unwrap();
/// assert_eq!(rv, 0);
/// let rv = nodes.add_row_with_defaults(1.0, &node_defaults).unwrap();
/// assert_eq!(rv, 1);
/// ```
pub fn add_row_with_defaults<T: Into<crate::Time> + Copy, D: DefaultNodeData>(
&mut self,
time: T,
defaults: &D,
) -> Result<NodeId, TskitError> {
add_row_with_defaults(time, defaults, self.as_mut_ptr())
}
}
#[cfg(test)]
mod test_owned_node_table {
use super::*;
#[test]
fn test_add_row() {
let mut nodes = OwningNodeTable::default();
let rowid = nodes.add_row(0, 1.1, -1, -1).unwrap();
assert_eq!(rowid, 0);
assert_eq!(nodes.num_rows(), 1);
}
}