Struct tskit::IndividualTable
source · #[repr(transparent)]pub struct IndividualTable { /* private fields */ }
Expand description
An immutable view of a individual table.
These are not created directly but are accessed
by types implementing std::ops::Deref
to
crate::table_views::TableViews
Implementations§
source§impl IndividualTable
impl IndividualTable
sourcepub fn num_rows(&self) -> SizeType
pub fn num_rows(&self) -> SizeType
Return the number of rows
Examples found in repository?
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
pub fn flags<I: Into<IndividualId> + Copy>(&self, row: I) -> Option<IndividualFlags> {
sys::tsk_column_access::<IndividualFlags, _, _, _>(
row.into(),
self.as_ref().flags,
self.num_rows(),
)
}
/// Return the locations for a given row.
///
/// # Returns
///
/// * `Some(location)` if `row` is valid.
/// * `None` otherwise.
pub fn location<I: Into<IndividualId> + Copy>(&self, row: I) -> Option<&[Location]> {
sys::tsk_ragged_column_access(
row.into(),
self.as_ref().location,
self.num_rows(),
self.as_ref().location_offset,
self.as_ref().location_length,
)
}
/// Return the parents for a given row.
///
/// # Returns
///
/// * `Some(parents)` if `row` is valid.
/// * `None` otherwise.
pub fn parents<I: Into<IndividualId> + Copy>(&self, row: I) -> Option<&[IndividualId]> {
sys::tsk_ragged_column_access(
row.into(),
self.as_ref().parents,
self.num_rows(),
self.as_ref().parents_offset,
self.as_ref().parents_length,
)
}
sourcepub fn flags<I: Into<IndividualId> + Copy>(
&self,
row: I
) -> Option<IndividualFlags>
pub fn flags<I: Into<IndividualId> + Copy>(
&self,
row: I
) -> Option<IndividualFlags>
Examples found in repository?
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
fn advance(&mut self) {
self.id = (i32::from(self.id) + 1).into();
self.flags = self.table.flags(self.id).unwrap_or_else(|| 0.into());
self.location = self.table.location(self.id);
self.parents = self.table.parents(self.id);
self.metadata = self.table.raw_metadata(self.id);
}
}
/// An immutable view of a individual table.
///
/// These are not created directly but are accessed
/// by types implementing [`std::ops::Deref`] to
/// [`crate::table_views::TableViews`]
#[derive(Debug)]
#[repr(transparent)]
pub struct IndividualTable {
table_: sys::LLIndividualTableRef,
}
fn make_individual_table_row(table: &IndividualTable, pos: tsk_id_t) -> Option<IndividualTableRow> {
Some(IndividualTableRow {
id: pos.into(),
flags: table.flags(pos)?,
location: table.location(pos).map(|s| s.to_vec()),
parents: table.parents(pos).map(|s| s.to_vec()),
metadata: table.raw_metadata(pos).map(|m| m.to_vec()),
})
}
pub(crate) type IndividualTableRefIterator<'a> =
crate::table_iterator::TableIterator<&'a IndividualTable>;
pub(crate) type IndividualTableIterator = crate::table_iterator::TableIterator<IndividualTable>;
impl<'a> Iterator for IndividualTableRefIterator<'a> {
type Item = IndividualTableRow;
fn next(&mut self) -> Option<Self::Item> {
let rv = make_individual_table_row(self.table, self.pos);
self.pos += 1;
rv
}
}
impl Iterator for IndividualTableIterator {
type Item = IndividualTableRow;
fn next(&mut self) -> Option<Self::Item> {
let rv = make_individual_table_row(&self.table, self.pos);
self.pos += 1;
rv
}
}
impl IndividualTable {
pub(crate) fn new_from_table(
individuals: *mut ll_bindings::tsk_individual_table_t,
) -> Result<Self, TskitError> {
let table_ = sys::LLIndividualTableRef::new_from_table(individuals)?;
Ok(IndividualTable { table_ })
}
pub(crate) fn as_ref(&self) -> &ll_bindings::tsk_individual_table_t {
self.table_.as_ref()
}
raw_metadata_getter_for_tables!(IndividualId);
/// Return the number of rows
pub fn num_rows(&self) -> crate::SizeType {
self.as_ref().num_rows.into()
}
/// Return the flags for a given row.
///
/// # Returns
///
/// * `Some(flags)` if `row` is valid.
/// * `None` otherwise.
pub fn flags<I: Into<IndividualId> + Copy>(&self, row: I) -> Option<IndividualFlags> {
sys::tsk_column_access::<IndividualFlags, _, _, _>(
row.into(),
self.as_ref().flags,
self.num_rows(),
)
}
/// Return the locations for a given row.
///
/// # Returns
///
/// * `Some(location)` if `row` is valid.
/// * `None` otherwise.
pub fn location<I: Into<IndividualId> + Copy>(&self, row: I) -> Option<&[Location]> {
sys::tsk_ragged_column_access(
row.into(),
self.as_ref().location,
self.num_rows(),
self.as_ref().location_offset,
self.as_ref().location_length,
)
}
/// Return the parents for a given row.
///
/// # Returns
///
/// * `Some(parents)` if `row` is valid.
/// * `None` otherwise.
pub fn parents<I: Into<IndividualId> + Copy>(&self, row: I) -> Option<&[IndividualId]> {
sys::tsk_ragged_column_access(
row.into(),
self.as_ref().parents,
self.num_rows(),
self.as_ref().parents_offset,
self.as_ref().parents_length,
)
}
/// Return the metadata for a given 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
///
/// For all examples, this is our metadata type.
/// We will add all instances with a value of `x = 1`.
///
/// ```
/// # #[cfg(feature = "derive")] {
/// #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::IndividualMetadata)]
/// #[serializer("serde_json")]
/// struct IndividualMetadata {
/// x: i32,
/// }
/// # }
/// ```
///
/// ## Without matches
///
/// ```
/// # #[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());
/// // We know the metadata are here, so we unwrap the Option and the Result:
/// let decoded = tables.individuals().metadata::<IndividualMetadata>(0.into()).unwrap().unwrap();
/// assert_eq!(decoded.x, 1);
/// # }
/// ```
///
/// ## Checking for errors and absence of metadata
///
/// The `Option<Result<_>>` return value allows all
/// three return possibilities to be easily covered:
///
/// ```
/// # #[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());
/// match tables.individuals().metadata::<IndividualMetadata>(0.into())
/// {
/// Some(Ok(metadata)) => assert_eq!(metadata.x, 1),
/// Some(Err(_)) => panic!("got an error??"),
/// None => panic!("Got None??"),
/// };
/// # }
/// ```
///
/// ## Attempting to use the wrong type.
///
/// Let's define a mutation metadata type with the exact same fields
/// as our individual metadata defined above:
///
/// ```
/// # #[cfg(feature = "derive")] {
/// #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::MutationMetadata)]
/// #[serializer("serde_json")]
/// struct MutationMetadata {
/// x: i32,
/// }
/// # }
/// ```
///
/// This type has the wrong trait bound and will cause compilation to fail:
///
#[cfg_attr(
feature = "derive",
doc = r##"
```compile_fail
# #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::MutationMetadata)]
# #[serializer("serde_json")]
# struct MutationMetadata {
# x: i32,
# }
#
# let mut tables = tskit::TableCollection::new(10.).unwrap();
match tables.individuals().metadata::<MutationMetadata>(0.into())
{
Some(Ok(metadata)) => assert_eq!(metadata.x, 1),
Some(Err(_)) => panic!("got an error??"),
None => panic!("Got None??"),
};
```
"##
)]
///
/// ## Limitations: different type, same trait bound
///
/// Finally, let us consider a different struct that has identical
/// fields to `IndividualMetadata` defined above and also implements
/// the correct trait:
///
/// ```
/// # #[cfg(feature = "derive")] {
/// #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::IndividualMetadata)]
/// #[serializer("serde_json")]
/// struct IndividualMetadataToo {
/// x: i32,
/// }
/// # }
/// ```
///
/// Let's walk through a detailed example:
///
/// ```
/// # #[cfg(feature = "derive")] {
/// #
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::IndividualMetadata)]
/// # #[serializer("serde_json")]
/// # struct IndividualMetadata {
/// # x: i32,
/// # }
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::IndividualMetadata)]
/// # #[serializer("serde_json")]
/// # struct IndividualMetadataToo {
/// # x: i32,
/// # }
/// // create a mutable table collection
/// let mut tables = tskit::TableCollection::new(100.).unwrap();
/// // Create some metadata based on our FIRST type
/// let metadata = IndividualMetadata { x: 1 };
/// // Add a row with our metadata
/// assert!(tables.add_individual_with_metadata(0, None, None, &metadata).is_ok());
/// // Trying to fetch using our SECOND type as the generic type works!
/// match tables.individuals().metadata::<IndividualMetadataToo>(0.into())
/// {
/// Some(Ok(metadata)) => assert_eq!(metadata.x, 1),
/// Some(Err(_)) => panic!("got an error??"),
/// None => panic!("Got None??"),
/// };
/// # }
/// ```
///
/// What is going on here?
/// Both types satisfy the same trait bound ([`metadata::IndividualMetadata`])
/// and their data fields look identical to `serde_json`.
/// Thus, one is exchangeable for the other because they have the exact same
/// *behavior*.
///
/// However, it is also true that this is (often/usually/always) not exactly what we want.
/// We are experimenting with encapsulation APIs involving traits with
/// [associated
/// types](https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#specifying-placeholder-types-in-trait-definitions-with-associated-types) to enforce at *compile time* that exactly one type (`struct/enum`, etc.) is a valid
/// metadata type for a table.
pub fn metadata<T: metadata::IndividualMetadata>(
&self,
row: IndividualId,
) -> 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 [`IndividualTableRow`].
///
pub fn iter(&self) -> impl Iterator<Item = IndividualTableRow> + '_ {
crate::table_iterator::make_table_iterator::<&IndividualTable>(self)
}
pub fn lending_iter(&self) -> IndividualTableRowView {
IndividualTableRowView::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<I: Into<IndividualId> + Copy>(&self, r: I) -> Option<IndividualTableRow> {
let ri = r.into().into();
table_row_access!(ri, self, make_individual_table_row)
}
/// Return a view of `r` of the table.
///
/// # Parameters
///
/// * `r`: the row id.
///
/// # Returns
///
/// * `Some(row view)` if `r` is valid
/// * `None` otherwise
pub fn row_view<I: Into<IndividualId> + Copy>(&self, r: I) -> Option<IndividualTableRowView> {
let view = IndividualTableRowView {
table: self,
id: r.into(),
flags: self.flags(r)?,
location: self.location(r),
parents: self.parents(r),
metadata: self.raw_metadata(r.into()),
};
Some(view)
}
sourcepub fn location<I: Into<IndividualId> + Copy>(
&self,
row: I
) -> Option<&[Location]>
pub fn location<I: Into<IndividualId> + Copy>(
&self,
row: I
) -> Option<&[Location]>
Examples found in repository?
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
fn advance(&mut self) {
self.id = (i32::from(self.id) + 1).into();
self.flags = self.table.flags(self.id).unwrap_or_else(|| 0.into());
self.location = self.table.location(self.id);
self.parents = self.table.parents(self.id);
self.metadata = self.table.raw_metadata(self.id);
}
}
/// An immutable view of a individual table.
///
/// These are not created directly but are accessed
/// by types implementing [`std::ops::Deref`] to
/// [`crate::table_views::TableViews`]
#[derive(Debug)]
#[repr(transparent)]
pub struct IndividualTable {
table_: sys::LLIndividualTableRef,
}
fn make_individual_table_row(table: &IndividualTable, pos: tsk_id_t) -> Option<IndividualTableRow> {
Some(IndividualTableRow {
id: pos.into(),
flags: table.flags(pos)?,
location: table.location(pos).map(|s| s.to_vec()),
parents: table.parents(pos).map(|s| s.to_vec()),
metadata: table.raw_metadata(pos).map(|m| m.to_vec()),
})
}
pub(crate) type IndividualTableRefIterator<'a> =
crate::table_iterator::TableIterator<&'a IndividualTable>;
pub(crate) type IndividualTableIterator = crate::table_iterator::TableIterator<IndividualTable>;
impl<'a> Iterator for IndividualTableRefIterator<'a> {
type Item = IndividualTableRow;
fn next(&mut self) -> Option<Self::Item> {
let rv = make_individual_table_row(self.table, self.pos);
self.pos += 1;
rv
}
}
impl Iterator for IndividualTableIterator {
type Item = IndividualTableRow;
fn next(&mut self) -> Option<Self::Item> {
let rv = make_individual_table_row(&self.table, self.pos);
self.pos += 1;
rv
}
}
impl IndividualTable {
pub(crate) fn new_from_table(
individuals: *mut ll_bindings::tsk_individual_table_t,
) -> Result<Self, TskitError> {
let table_ = sys::LLIndividualTableRef::new_from_table(individuals)?;
Ok(IndividualTable { table_ })
}
pub(crate) fn as_ref(&self) -> &ll_bindings::tsk_individual_table_t {
self.table_.as_ref()
}
raw_metadata_getter_for_tables!(IndividualId);
/// Return the number of rows
pub fn num_rows(&self) -> crate::SizeType {
self.as_ref().num_rows.into()
}
/// Return the flags for a given row.
///
/// # Returns
///
/// * `Some(flags)` if `row` is valid.
/// * `None` otherwise.
pub fn flags<I: Into<IndividualId> + Copy>(&self, row: I) -> Option<IndividualFlags> {
sys::tsk_column_access::<IndividualFlags, _, _, _>(
row.into(),
self.as_ref().flags,
self.num_rows(),
)
}
/// Return the locations for a given row.
///
/// # Returns
///
/// * `Some(location)` if `row` is valid.
/// * `None` otherwise.
pub fn location<I: Into<IndividualId> + Copy>(&self, row: I) -> Option<&[Location]> {
sys::tsk_ragged_column_access(
row.into(),
self.as_ref().location,
self.num_rows(),
self.as_ref().location_offset,
self.as_ref().location_length,
)
}
/// Return the parents for a given row.
///
/// # Returns
///
/// * `Some(parents)` if `row` is valid.
/// * `None` otherwise.
pub fn parents<I: Into<IndividualId> + Copy>(&self, row: I) -> Option<&[IndividualId]> {
sys::tsk_ragged_column_access(
row.into(),
self.as_ref().parents,
self.num_rows(),
self.as_ref().parents_offset,
self.as_ref().parents_length,
)
}
/// Return the metadata for a given 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
///
/// For all examples, this is our metadata type.
/// We will add all instances with a value of `x = 1`.
///
/// ```
/// # #[cfg(feature = "derive")] {
/// #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::IndividualMetadata)]
/// #[serializer("serde_json")]
/// struct IndividualMetadata {
/// x: i32,
/// }
/// # }
/// ```
///
/// ## Without matches
///
/// ```
/// # #[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());
/// // We know the metadata are here, so we unwrap the Option and the Result:
/// let decoded = tables.individuals().metadata::<IndividualMetadata>(0.into()).unwrap().unwrap();
/// assert_eq!(decoded.x, 1);
/// # }
/// ```
///
/// ## Checking for errors and absence of metadata
///
/// The `Option<Result<_>>` return value allows all
/// three return possibilities to be easily covered:
///
/// ```
/// # #[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());
/// match tables.individuals().metadata::<IndividualMetadata>(0.into())
/// {
/// Some(Ok(metadata)) => assert_eq!(metadata.x, 1),
/// Some(Err(_)) => panic!("got an error??"),
/// None => panic!("Got None??"),
/// };
/// # }
/// ```
///
/// ## Attempting to use the wrong type.
///
/// Let's define a mutation metadata type with the exact same fields
/// as our individual metadata defined above:
///
/// ```
/// # #[cfg(feature = "derive")] {
/// #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::MutationMetadata)]
/// #[serializer("serde_json")]
/// struct MutationMetadata {
/// x: i32,
/// }
/// # }
/// ```
///
/// This type has the wrong trait bound and will cause compilation to fail:
///
#[cfg_attr(
feature = "derive",
doc = r##"
```compile_fail
# #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::MutationMetadata)]
# #[serializer("serde_json")]
# struct MutationMetadata {
# x: i32,
# }
#
# let mut tables = tskit::TableCollection::new(10.).unwrap();
match tables.individuals().metadata::<MutationMetadata>(0.into())
{
Some(Ok(metadata)) => assert_eq!(metadata.x, 1),
Some(Err(_)) => panic!("got an error??"),
None => panic!("Got None??"),
};
```
"##
)]
///
/// ## Limitations: different type, same trait bound
///
/// Finally, let us consider a different struct that has identical
/// fields to `IndividualMetadata` defined above and also implements
/// the correct trait:
///
/// ```
/// # #[cfg(feature = "derive")] {
/// #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::IndividualMetadata)]
/// #[serializer("serde_json")]
/// struct IndividualMetadataToo {
/// x: i32,
/// }
/// # }
/// ```
///
/// Let's walk through a detailed example:
///
/// ```
/// # #[cfg(feature = "derive")] {
/// #
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::IndividualMetadata)]
/// # #[serializer("serde_json")]
/// # struct IndividualMetadata {
/// # x: i32,
/// # }
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::IndividualMetadata)]
/// # #[serializer("serde_json")]
/// # struct IndividualMetadataToo {
/// # x: i32,
/// # }
/// // create a mutable table collection
/// let mut tables = tskit::TableCollection::new(100.).unwrap();
/// // Create some metadata based on our FIRST type
/// let metadata = IndividualMetadata { x: 1 };
/// // Add a row with our metadata
/// assert!(tables.add_individual_with_metadata(0, None, None, &metadata).is_ok());
/// // Trying to fetch using our SECOND type as the generic type works!
/// match tables.individuals().metadata::<IndividualMetadataToo>(0.into())
/// {
/// Some(Ok(metadata)) => assert_eq!(metadata.x, 1),
/// Some(Err(_)) => panic!("got an error??"),
/// None => panic!("Got None??"),
/// };
/// # }
/// ```
///
/// What is going on here?
/// Both types satisfy the same trait bound ([`metadata::IndividualMetadata`])
/// and their data fields look identical to `serde_json`.
/// Thus, one is exchangeable for the other because they have the exact same
/// *behavior*.
///
/// However, it is also true that this is (often/usually/always) not exactly what we want.
/// We are experimenting with encapsulation APIs involving traits with
/// [associated
/// types](https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#specifying-placeholder-types-in-trait-definitions-with-associated-types) to enforce at *compile time* that exactly one type (`struct/enum`, etc.) is a valid
/// metadata type for a table.
pub fn metadata<T: metadata::IndividualMetadata>(
&self,
row: IndividualId,
) -> 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 [`IndividualTableRow`].
///
pub fn iter(&self) -> impl Iterator<Item = IndividualTableRow> + '_ {
crate::table_iterator::make_table_iterator::<&IndividualTable>(self)
}
pub fn lending_iter(&self) -> IndividualTableRowView {
IndividualTableRowView::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<I: Into<IndividualId> + Copy>(&self, r: I) -> Option<IndividualTableRow> {
let ri = r.into().into();
table_row_access!(ri, self, make_individual_table_row)
}
/// Return a view of `r` of the table.
///
/// # Parameters
///
/// * `r`: the row id.
///
/// # Returns
///
/// * `Some(row view)` if `r` is valid
/// * `None` otherwise
pub fn row_view<I: Into<IndividualId> + Copy>(&self, r: I) -> Option<IndividualTableRowView> {
let view = IndividualTableRowView {
table: self,
id: r.into(),
flags: self.flags(r)?,
location: self.location(r),
parents: self.parents(r),
metadata: self.raw_metadata(r.into()),
};
Some(view)
}
sourcepub fn parents<I: Into<IndividualId> + Copy>(
&self,
row: I
) -> Option<&[IndividualId]>
pub fn parents<I: Into<IndividualId> + Copy>(
&self,
row: I
) -> Option<&[IndividualId]>
Examples found in repository?
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
fn advance(&mut self) {
self.id = (i32::from(self.id) + 1).into();
self.flags = self.table.flags(self.id).unwrap_or_else(|| 0.into());
self.location = self.table.location(self.id);
self.parents = self.table.parents(self.id);
self.metadata = self.table.raw_metadata(self.id);
}
}
/// An immutable view of a individual table.
///
/// These are not created directly but are accessed
/// by types implementing [`std::ops::Deref`] to
/// [`crate::table_views::TableViews`]
#[derive(Debug)]
#[repr(transparent)]
pub struct IndividualTable {
table_: sys::LLIndividualTableRef,
}
fn make_individual_table_row(table: &IndividualTable, pos: tsk_id_t) -> Option<IndividualTableRow> {
Some(IndividualTableRow {
id: pos.into(),
flags: table.flags(pos)?,
location: table.location(pos).map(|s| s.to_vec()),
parents: table.parents(pos).map(|s| s.to_vec()),
metadata: table.raw_metadata(pos).map(|m| m.to_vec()),
})
}
pub(crate) type IndividualTableRefIterator<'a> =
crate::table_iterator::TableIterator<&'a IndividualTable>;
pub(crate) type IndividualTableIterator = crate::table_iterator::TableIterator<IndividualTable>;
impl<'a> Iterator for IndividualTableRefIterator<'a> {
type Item = IndividualTableRow;
fn next(&mut self) -> Option<Self::Item> {
let rv = make_individual_table_row(self.table, self.pos);
self.pos += 1;
rv
}
}
impl Iterator for IndividualTableIterator {
type Item = IndividualTableRow;
fn next(&mut self) -> Option<Self::Item> {
let rv = make_individual_table_row(&self.table, self.pos);
self.pos += 1;
rv
}
}
impl IndividualTable {
pub(crate) fn new_from_table(
individuals: *mut ll_bindings::tsk_individual_table_t,
) -> Result<Self, TskitError> {
let table_ = sys::LLIndividualTableRef::new_from_table(individuals)?;
Ok(IndividualTable { table_ })
}
pub(crate) fn as_ref(&self) -> &ll_bindings::tsk_individual_table_t {
self.table_.as_ref()
}
raw_metadata_getter_for_tables!(IndividualId);
/// Return the number of rows
pub fn num_rows(&self) -> crate::SizeType {
self.as_ref().num_rows.into()
}
/// Return the flags for a given row.
///
/// # Returns
///
/// * `Some(flags)` if `row` is valid.
/// * `None` otherwise.
pub fn flags<I: Into<IndividualId> + Copy>(&self, row: I) -> Option<IndividualFlags> {
sys::tsk_column_access::<IndividualFlags, _, _, _>(
row.into(),
self.as_ref().flags,
self.num_rows(),
)
}
/// Return the locations for a given row.
///
/// # Returns
///
/// * `Some(location)` if `row` is valid.
/// * `None` otherwise.
pub fn location<I: Into<IndividualId> + Copy>(&self, row: I) -> Option<&[Location]> {
sys::tsk_ragged_column_access(
row.into(),
self.as_ref().location,
self.num_rows(),
self.as_ref().location_offset,
self.as_ref().location_length,
)
}
/// Return the parents for a given row.
///
/// # Returns
///
/// * `Some(parents)` if `row` is valid.
/// * `None` otherwise.
pub fn parents<I: Into<IndividualId> + Copy>(&self, row: I) -> Option<&[IndividualId]> {
sys::tsk_ragged_column_access(
row.into(),
self.as_ref().parents,
self.num_rows(),
self.as_ref().parents_offset,
self.as_ref().parents_length,
)
}
/// Return the metadata for a given 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
///
/// For all examples, this is our metadata type.
/// We will add all instances with a value of `x = 1`.
///
/// ```
/// # #[cfg(feature = "derive")] {
/// #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::IndividualMetadata)]
/// #[serializer("serde_json")]
/// struct IndividualMetadata {
/// x: i32,
/// }
/// # }
/// ```
///
/// ## Without matches
///
/// ```
/// # #[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());
/// // We know the metadata are here, so we unwrap the Option and the Result:
/// let decoded = tables.individuals().metadata::<IndividualMetadata>(0.into()).unwrap().unwrap();
/// assert_eq!(decoded.x, 1);
/// # }
/// ```
///
/// ## Checking for errors and absence of metadata
///
/// The `Option<Result<_>>` return value allows all
/// three return possibilities to be easily covered:
///
/// ```
/// # #[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());
/// match tables.individuals().metadata::<IndividualMetadata>(0.into())
/// {
/// Some(Ok(metadata)) => assert_eq!(metadata.x, 1),
/// Some(Err(_)) => panic!("got an error??"),
/// None => panic!("Got None??"),
/// };
/// # }
/// ```
///
/// ## Attempting to use the wrong type.
///
/// Let's define a mutation metadata type with the exact same fields
/// as our individual metadata defined above:
///
/// ```
/// # #[cfg(feature = "derive")] {
/// #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::MutationMetadata)]
/// #[serializer("serde_json")]
/// struct MutationMetadata {
/// x: i32,
/// }
/// # }
/// ```
///
/// This type has the wrong trait bound and will cause compilation to fail:
///
#[cfg_attr(
feature = "derive",
doc = r##"
```compile_fail
# #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::MutationMetadata)]
# #[serializer("serde_json")]
# struct MutationMetadata {
# x: i32,
# }
#
# let mut tables = tskit::TableCollection::new(10.).unwrap();
match tables.individuals().metadata::<MutationMetadata>(0.into())
{
Some(Ok(metadata)) => assert_eq!(metadata.x, 1),
Some(Err(_)) => panic!("got an error??"),
None => panic!("Got None??"),
};
```
"##
)]
///
/// ## Limitations: different type, same trait bound
///
/// Finally, let us consider a different struct that has identical
/// fields to `IndividualMetadata` defined above and also implements
/// the correct trait:
///
/// ```
/// # #[cfg(feature = "derive")] {
/// #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::IndividualMetadata)]
/// #[serializer("serde_json")]
/// struct IndividualMetadataToo {
/// x: i32,
/// }
/// # }
/// ```
///
/// Let's walk through a detailed example:
///
/// ```
/// # #[cfg(feature = "derive")] {
/// #
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::IndividualMetadata)]
/// # #[serializer("serde_json")]
/// # struct IndividualMetadata {
/// # x: i32,
/// # }
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::IndividualMetadata)]
/// # #[serializer("serde_json")]
/// # struct IndividualMetadataToo {
/// # x: i32,
/// # }
/// // create a mutable table collection
/// let mut tables = tskit::TableCollection::new(100.).unwrap();
/// // Create some metadata based on our FIRST type
/// let metadata = IndividualMetadata { x: 1 };
/// // Add a row with our metadata
/// assert!(tables.add_individual_with_metadata(0, None, None, &metadata).is_ok());
/// // Trying to fetch using our SECOND type as the generic type works!
/// match tables.individuals().metadata::<IndividualMetadataToo>(0.into())
/// {
/// Some(Ok(metadata)) => assert_eq!(metadata.x, 1),
/// Some(Err(_)) => panic!("got an error??"),
/// None => panic!("Got None??"),
/// };
/// # }
/// ```
///
/// What is going on here?
/// Both types satisfy the same trait bound ([`metadata::IndividualMetadata`])
/// and their data fields look identical to `serde_json`.
/// Thus, one is exchangeable for the other because they have the exact same
/// *behavior*.
///
/// However, it is also true that this is (often/usually/always) not exactly what we want.
/// We are experimenting with encapsulation APIs involving traits with
/// [associated
/// types](https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#specifying-placeholder-types-in-trait-definitions-with-associated-types) to enforce at *compile time* that exactly one type (`struct/enum`, etc.) is a valid
/// metadata type for a table.
pub fn metadata<T: metadata::IndividualMetadata>(
&self,
row: IndividualId,
) -> 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 [`IndividualTableRow`].
///
pub fn iter(&self) -> impl Iterator<Item = IndividualTableRow> + '_ {
crate::table_iterator::make_table_iterator::<&IndividualTable>(self)
}
pub fn lending_iter(&self) -> IndividualTableRowView {
IndividualTableRowView::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<I: Into<IndividualId> + Copy>(&self, r: I) -> Option<IndividualTableRow> {
let ri = r.into().into();
table_row_access!(ri, self, make_individual_table_row)
}
/// Return a view of `r` of the table.
///
/// # Parameters
///
/// * `r`: the row id.
///
/// # Returns
///
/// * `Some(row view)` if `r` is valid
/// * `None` otherwise
pub fn row_view<I: Into<IndividualId> + Copy>(&self, r: I) -> Option<IndividualTableRowView> {
let view = IndividualTableRowView {
table: self,
id: r.into(),
flags: self.flags(r)?,
location: self.location(r),
parents: self.parents(r),
metadata: self.raw_metadata(r.into()),
};
Some(view)
}
sourcepub fn metadata<T: IndividualMetadata>(
&self,
row: IndividualId
) -> Option<Result<T, TskitError>>
pub fn metadata<T: IndividualMetadata>(
&self,
row: IndividualId
) -> Option<Result<T, TskitError>>
Return the metadata for a given row.
Returns
Some(Ok(T))
ifrow
is valid and decoding succeeded.Some(Err(_))
ifrow
is not valid and decoding failed.None
ifrow
is not valid.
Errors
TskitError::MetadataError
if decoding fails.
Examples
For all examples, this is our metadata type.
We will add all instances with a value of x = 1
.
#[derive(serde::Serialize, serde::Deserialize, tskit::metadata::IndividualMetadata)]
#[serializer("serde_json")]
struct IndividualMetadata {
x: i32,
}
Without matches
// We know the metadata are here, so we unwrap the Option and the Result:
let decoded = tables.individuals().metadata::<IndividualMetadata>(0.into()).unwrap().unwrap();
assert_eq!(decoded.x, 1);
Checking for errors and absence of metadata
The Option<Result<_>>
return value allows all
three return possibilities to be easily covered:
match tables.individuals().metadata::<IndividualMetadata>(0.into())
{
Some(Ok(metadata)) => assert_eq!(metadata.x, 1),
Some(Err(_)) => panic!("got an error??"),
None => panic!("Got None??"),
};
Attempting to use the wrong type.
Let’s define a mutation metadata type with the exact same fields as our individual metadata defined above:
#[derive(serde::Serialize, serde::Deserialize, tskit::metadata::MutationMetadata)]
#[serializer("serde_json")]
struct MutationMetadata {
x: i32,
}
This type has the wrong trait bound and will cause compilation to fail:
match tables.individuals().metadata::<MutationMetadata>(0.into())
{
Some(Ok(metadata)) => assert_eq!(metadata.x, 1),
Some(Err(_)) => panic!("got an error??"),
None => panic!("Got None??"),
};
Limitations: different type, same trait bound
Finally, let us consider a different struct that has identical
fields to IndividualMetadata
defined above and also implements
the correct trait:
#[derive(serde::Serialize, serde::Deserialize, tskit::metadata::IndividualMetadata)]
#[serializer("serde_json")]
struct IndividualMetadataToo {
x: i32,
}
Let’s walk through a detailed example:
// create a mutable table collection
let mut tables = tskit::TableCollection::new(100.).unwrap();
// Create some metadata based on our FIRST type
let metadata = IndividualMetadata { x: 1 };
// Add a row with our metadata
assert!(tables.add_individual_with_metadata(0, None, None, &metadata).is_ok());
// Trying to fetch using our SECOND type as the generic type works!
match tables.individuals().metadata::<IndividualMetadataToo>(0.into())
{
Some(Ok(metadata)) => assert_eq!(metadata.x, 1),
Some(Err(_)) => panic!("got an error??"),
None => panic!("Got None??"),
};
What is going on here?
Both types satisfy the same trait bound (metadata::IndividualMetadata
)
and their data fields look identical to serde_json
.
Thus, one is exchangeable for the other because they have the exact same
behavior.
However, it is also true that this is (often/usually/always) not exactly what we want.
We are experimenting with encapsulation APIs involving traits with
associated
types to enforce at compile time that exactly one type (struct/enum
, etc.) is a valid
metadata type for a table.
sourcepub fn iter(&self) -> impl Iterator<Item = IndividualTableRow> + '_
pub fn iter(&self) -> impl Iterator<Item = IndividualTableRow> + '_
Return an iterator over rows of the table.
The value of the iterator is IndividualTableRow
.
pub fn lending_iter(&self) -> IndividualTableRowView<'_>
sourcepub fn row<I: Into<IndividualId> + Copy>(
&self,
r: I
) -> Option<IndividualTableRow>
pub fn row<I: Into<IndividualId> + Copy>(
&self,
r: I
) -> Option<IndividualTableRow>
sourcepub fn row_view<I: Into<IndividualId> + Copy>(
&self,
r: I
) -> Option<IndividualTableRowView<'_>>
pub fn row_view<I: Into<IndividualId> + Copy>(
&self,
r: I
) -> Option<IndividualTableRowView<'_>>
Return a view of r
of the table.
Parameters
r
: the row id.
Returns
Some(row view)
ifr
is validNone
otherwise
sourcepub fn flags_slice(&self) -> &[IndividualFlags]
pub fn flags_slice(&self) -> &[IndividualFlags]
Get the flags column as a slice
sourcepub fn flags_slice_raw(&self) -> &[tsk_flags_t]
pub fn flags_slice_raw(&self) -> &[tsk_flags_t]
Get the flags column as a slice