data-beans 0.14.2

Sparse genomics data backends, QC, algorithms, and simulation
Documentation
use crate::sparse_io::ROW_SEP;
use genomic_data::coordinates::import_interval;
use rustc_hash::FxHashMap as HashMap;
use rustc_hash::FxHashSet as HashSet;

pub use genomic_data::name_matching::{idf_weight, locus_part, GeneIndex};

/// Make duplicate names unique by appending `-1`, `-2`, etc. to repeated entries.
/// Similar to scanpy's `var_names_make_unique()`. A suffixed name is never one
/// the list already holds (`ABC, ABC-1, ABC` gives `ABC, ABC-1, ABC-2`), so
/// the result has no duplicates.
pub fn make_names_unique(names: &mut [Box<str>]) -> usize {
    let mut used: HashSet<Box<str>> = names.iter().cloned().collect();
    if used.len() == names.len() {
        return 0;
    }
    let mut counts: HashMap<Box<str>, usize> = HashMap::default();
    let mut num_duped = 0usize;
    for name in names.iter_mut() {
        if let Some(count) = counts.get_mut(name.as_ref()) {
            if *count == 1 {
                num_duped += 1;
            }
            // Skip the suffixes another name already took.
            *name = loop {
                let candidate = format!("{}-{}", name, count).into_boxed_str();
                *count += 1;
                if used.insert(candidate.clone()) {
                    break candidate;
                }
            };
        } else {
            counts.insert(name.clone(), 1);
        }
    }
    if num_duped > 0 {
        log::warn!(
            "{} names had duplicates and were made unique with -N suffixes",
            num_duped
        );
    }
    num_duped
}

/// The composite name of one row: `id{ROW_SEP}name`, or the ID alone when
/// the name is empty or already equals it (e.g. 10x ATAC peaks, where both
/// `features/id` and `features/name` are `chr1:1000-2000`).
pub fn id_name(id: &str, name: &str) -> Box<str> {
    if name.is_empty() || name == id {
        id.into()
    } else {
        format!("{id}{ROW_SEP}{name}").into_boxed_str()
    }
}

/// [`id_name`] of each row.
pub fn compose_id_name(ids: Vec<Box<str>>, names: Vec<Box<str>>) -> Vec<Box<str>> {
    ids.iter()
        .zip(&names)
        .map(|(id, name)| id_name(id, name))
        .collect()
}

/// Import boundary for feature rows: peak rows get their id and name
/// rewritten in the colon locus form, whatever spelling the producer used
/// (`chr1-100-200` and `chr1_100_200` become `chr1:100-200`). With feature
/// types, a row is a peak when its type names peaks or ATAC; without them,
/// the file is a peak list only when every id reads as an interval. A gene
/// id that happens to end in two numbers is therefore left alone. Returns
/// how many rows were rewritten.
pub fn colon_peak_names(
    ids: &mut [Box<str>],
    names: &mut [Box<str>],
    types: Option<&[Box<str>]>,
) -> usize {
    let is_peak = |i: usize| match types {
        Some(types) => {
            contains_ignore_ascii_case(&types[i], "peak")
                || contains_ignore_ascii_case(&types[i], "atac")
        }
        None => true,
    };
    if types.is_none() {
        let n_read = ids
            .iter()
            .filter(|id| import_interval(id).is_some())
            .count();
        if n_read < ids.len() {
            if n_read * 2 >= ids.len() {
                log::info!(
                    "{n_read} of {} untyped rows read as intervals, but not all; \
                     the names are kept as written",
                    ids.len()
                );
            }
            return 0;
        }
    }
    let mut n = 0;
    for (i, (id, name)) in ids.iter_mut().zip(names.iter_mut()).enumerate() {
        if !is_peak(i) {
            continue;
        }
        let mut changed = false;
        for s in [id, name] {
            if let Some(l) = import_interval(s) {
                let colon = l.to_string().into_boxed_str();
                changed |= *s != colon;
                *s = colon;
            }
        }
        n += usize::from(changed);
    }
    n
}

/// Inverse of [`compose_id_name`]: split a composite `id{ROW_SEP}name` display
/// name back into `(id, name)` on the first `ROW_SEP`. When there is no
/// separator (a bare symbol, or an id-only composite where name was empty or
/// equalled id) both parts are the whole string, so a 10x `features.tsv` still
/// gets a non-empty gene name.
///
/// A locus id is not cut at a `ROW_SEP` of its contig name: an id-only
/// peak row comes back whole, whether the contig is an unplaced scaffold
/// (`chrUn_KI270742v1:100-200`, `chr1_KI270706v1_random:5-9`) or carries a
/// genome tag as multi-genome references do (`GRCh38_chr1:100-200`), and a
/// locus id with a name splits after the locus
/// (`chrUn_KI270742v1:100-200_GENE1`).
///
/// Other ids are cut at their first `ROW_SEP`, so an id-only row whose id
/// holds one (`Y_RNA`) is not told apart from an `id{ROW_SEP}name` pair.
/// Nor is an id joined to a locus name (`peak1_chr1:100-200`) told apart
/// from one locus on the contig `peak1_chr1`: a composite that is one locus
/// as a whole comes back whole.
pub fn split_id_name(composite: &str) -> (&str, &str) {
    let pair = match locus_part(composite) {
        Some((_, "")) => None,
        Some((locus, rest)) => rest
            .strip_prefix(ROW_SEP)
            .filter(|name| !name.is_empty())
            .map(|name| (locus, name)),
        None => composite
            .split_once(ROW_SEP)
            .filter(|(_, name)| !name.is_empty()),
    };
    pair.unwrap_or((composite, composite))
}

/// Comma-separated case-insensitive substring filter, parsed once and matched
/// many times. Used by `--select-row-type` / `--remove-row-type` /
/// `--hto-row-type` so callers can pass e.g. `"gene,peak"` to match either
/// "Gene Expression" or "Peaks".
pub struct RowTypeFilter {
    patterns: Vec<Box<str>>,
}

impl RowTypeFilter {
    pub fn parse(s: &str) -> Self {
        let patterns = s
            .split(',')
            .map(|p| p.trim())
            .filter(|p| !p.is_empty())
            .map(|p| p.to_ascii_lowercase().into_boxed_str())
            .collect();
        Self { patterns }
    }

    pub fn is_empty(&self) -> bool {
        self.patterns.is_empty()
    }

    /// True if any pattern is an ASCII-case-insensitive substring of `s`.
    /// Bytewise scan — does not allocate, so callers can pass row types
    /// straight from the backend without an intermediate lowercase copy.
    pub fn matches(&self, s: &str) -> bool {
        self.patterns
            .iter()
            .any(|p| contains_ignore_ascii_case(s, p))
    }
}

/// Bytewise case-insensitive substring search. ASCII only; non-ASCII bytes
/// compare verbatim. Allocation-free.
pub fn contains_ignore_ascii_case(haystack: &str, needle: &str) -> bool {
    let n = needle.len();
    if n == 0 {
        return true;
    }
    let h = haystack.as_bytes();
    if h.len() < n {
        return false;
    }
    h.windows(n)
        .any(|w| w.eq_ignore_ascii_case(needle.as_bytes()))
}

/// Return indices of rows whose type passes select/remove filtering.
/// - `select`: comma-separated patterns; row passes if any pattern is a
///   case-insensitive substring of the row type. Empty keeps all rows.
/// - `remove`: comma-separated patterns; row is dropped if any pattern matches.
pub fn filter_row_indices_by_type(
    row_types: &[Box<str>],
    select: &str,
    remove: &str,
) -> Vec<usize> {
    let sel = RowTypeFilter::parse(select);
    let rem = RowTypeFilter::parse(remove);
    if sel.is_empty() && rem.is_empty() {
        return (0..row_types.len()).collect();
    }
    row_types
        .iter()
        .enumerate()
        .filter_map(|(i, x)| {
            let selected = sel.is_empty() || sel.matches(x);
            let removed = !rem.is_empty() && rem.matches(x);
            if selected && !removed {
                Some(i)
            } else {
                None
            }
        })
        .collect()
}

/// Flexible gene name matching (case-insensitive, underscore-delimited)
/// Returns true if `query` matches `target` with these rules:
/// - Exact match (case-insensitive)
/// - Suffix match: target ends with `_query`
/// - Prefix match: target starts with `query_`
/// - Segment match: target contains `_query_`
///
/// Example: "CD8A" matches "ENSG00000153563_CD8A", "CD8A_variant1", "chr1_CD8A_isoform2"
#[allow(dead_code)]
pub fn flexible_name_match(query: &str, target: &str) -> bool {
    let q = query.to_lowercase();
    let t = target.to_lowercase();
    t == q
        || t.ends_with(&format!("_{}", q))
        || t.starts_with(&format!("{}_", q))
        || t.contains(&format!("_{}_", q))
}

/// Match names by substring queries and return matched indices and names
///
/// Each matched name is returned once, in the order the queries first reach
/// it, however many queries it matches. An empty query (a blank line in a
/// name file) is not a query and matches nothing.
///
/// # Arguments
/// * `all_names` - All available names to search through
/// * `queries` - Substring queries to match against
/// * `entity_type` - Description of what's being matched (e.g., "column", "row") for error messages
///
/// # Returns
/// A tuple of (matched_indices, matched_names)
pub fn match_by_substring(
    all_names: &[Box<str>],
    queries: &[Box<str>],
    entity_type: &str,
) -> anyhow::Result<(Vec<usize>, Vec<Box<str>>)> {
    let mut matched_indices = Vec::new();
    let mut is_matched = vec![false; all_names.len()];

    for query in queries.iter().filter(|q| !q.is_empty()) {
        for (idx, name) in all_names.iter().enumerate() {
            if !is_matched[idx] && name.contains(query.as_ref()) {
                is_matched[idx] = true;
                matched_indices.push(idx);
            }
        }
    }

    if matched_indices.is_empty() {
        return Err(anyhow::anyhow!(
            "No {} names matched the provided queries",
            entity_type
        ));
    }

    let matched_names: Vec<Box<str>> = matched_indices
        .iter()
        .map(|&i| all_names[i].clone())
        .collect();

    Ok((matched_indices, matched_names))
}

#[cfg(test)]
mod tests;

/// The places of the names `pattern` (a regex, matched case-insensitively)
/// finds in, in order.
pub fn names_matching(names: &[Box<str>], pattern: &str) -> anyhow::Result<Vec<usize>> {
    let re = regex::RegexBuilder::new(pattern)
        .case_insensitive(true)
        .build()
        .map_err(|e| anyhow::anyhow!("invalid pattern `{pattern}`: {e}"))?;
    Ok(names
        .iter()
        .enumerate()
        .filter_map(|(i, n)| re.is_match(n).then_some(i))
        .collect())
}