pub fn build_index<K: Kmer + Sync + Send>(
seqs: &[DnaString],
tx_names: &[String],
tx_gene_map: &HashMap<String, String>,
num_threads: usize,
) -> Result<Pseudoaligner, Error> {
// Thread pool Configuration for calling BOOMphf
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(num_threads)
.build()?;
code
if seqs.len() >= U32_MAX {
panic!("Too many ({}) sequences to handle.", seqs.len());
}
info!("Sharding sequences...");
let mut buckets: Vec<_> = seqs
.iter()
.enumerate()
.flat_map(|(id, seq)| partition_contigs::<K>(seq, id as u32))
.collect();
pool.install(|| {
buckets.par_sort_unstable_by_key(|x| x.0);
});
info!("Got {} sequence chunks", buckets.len());
let summarizer = Arc::new(CountFilterEqClass::new(MIN_KMERS));
let sequence_shards = group_by_slices(&buckets, |x| x.0, MIN_SHARD_SEQUENCES);
info!("Assembling {} shards...", sequence_shards.len());
let shard_dbgs = pool.install(|| {
let mut shard_dbgs = Vec::with_capacity(sequence_shards.len());
sequence_shards
.into_par_iter()
.into_par_iter()
.map_with(summarizer.clone(), |s, strings| {
assemble_shard::<K>(strings, s)
})
.collect_into_vec(&mut shard_dbgs);
shard_dbgs
});
info!("Done dBG construction of shards");
info!("Starting merging disjoint graphs");
let dbg = merge_shard_dbgs(shard_dbgs);
info!("Graph merge complete");
let eq_classes = summarizer.get_eq_classes();
info!("Indexing de Bruijn graph");
let dbg_index = make_dbg_index(&dbg, &pool, num_threads);
Ok(Pseudoaligner::new(
dbg,
eq_classes,
dbg_index,
tx_names.to_owned(),
tx_gene_map.clone(),
))
}
type PmerType = debruijn::kmer::Kmer6;
lazy_static! {
static ref PERM: Vec = {
let maxp = 1 << (2 * PmerType::k());
let mut sorted_kmers: Vec = Vec::with_capacity(maxp);
for i in 0..maxp {
let kmer = Kmer::from_u64(i as u64);
sorted_kmers.push(kmer);
}
sorted_kmers.sort_by_key(count_a_t_bases);
code
let mut permutation = vec![0; maxp];
for (sort_pos, kmer) in sorted_kmers.into_iter().enumerate() {
permutation[kmer.to_u64() as usize] = sort_pos;
}
permutation
};
}
/// Count the number of A/T bases in a kmer
fn count_a_t_bases<K: Kmer>(kmer: &K) -> usize {
let mut count = 0;
for i in 0..K::k() {
let v = kmer.get(i);
if v == b'A' || v == b'T' {
count += 1;
}
}
count
}
fn partition_contigs<K: Kmer>(
contig: &DnaString,
contig_id: u32,
) -> Vec<(u16, u32, DnaStringSlice<'_>, Exts)> {
// One FASTA entry possibly broken into multiple contigs
// based on the location of N int he sequence.
code
if contig.len() >= K::k() {
// It is safe to always set rc to true when calling simple_scan. See
// https://github.com/10XGenomics/rust-debruijn/issues/10
// However, we set it to !STRANDED so stranded assays use more buckets.
#[allow(deprecated)]
let msps = debruijn::msp::simple_scan::<_, PmerType>(K::k(), contig, &PERM, !STRANDED);
msps.into_iter()
.map(|msp| {
let bucket_id = msp.bucket();
let slice = contig.slice(msp.start(), msp.end());
let exts = Exts::from_dna_string(contig, msp.start(), msp.len());
(bucket_id, contig_id, slice, exts)
})
.collect()
} else {
Vec::new()
}
println!("Total {:?} kmers to process in dbg", total_kmers);
println!("Making mphf of kmers");
let mphf =
//boomphf::Mphf::from_chunked_iterator(1.7, dbg, total_kmers);
boomphf::Mphf::from_chunked_iterator_parallel(1.7, dbg, None, total_kmers as u64, num_threads);
println!("Assigning offsets to kmers");
let mut node_and_offsets = Vec::with_capacity(total_kmers);
node_and_offsets.resize(total_kmers, (U32_MAX as u32, U32_MAX as u32));
let scatter = crate::scatter::ScatterToVec::new(&mut node_and_offsets[..]);
pool.install(|| {
(0..dbg.len()).into_par_iter().for_each_init(
// Each thread gets a scatter handle to write values from
|| scatter.handle(),
|handle, node_id| {
let node = dbg.get_node_kmer(node_id);
for (offset, kmer) in node.into_iter().enumerate() {
let index = mphf.try_hash(&kmer).expect("can't find kmer in DBG graph!");
handle.write(index as usize, (node_id as u32, offset as u32));
}
},
);
});
boomphf::hashmap::NoKeyBoomHashMap::new_with_mphf(mphf, node_and_offsets)
}
/// Split the slice data into subslices of size at least
/// min_size, while ensuring that consecutive runs of
/// items with the same key as defined by the key function f are
/// in the same subslice.
fn group_by_slices<T, K: PartialEq, F: Fn(&T) -> K>(
data: &[T],
f: F,
min_size: usize,
) -> Vec<&[T]> {
let mut slice_start = 0;
let mut result = Vec::new();
for ((i, d1), d2) in data.iter().enumerate().skip(1).zip(data.iter()) {
if (i - slice_start) > min_size && f(d1) != f(d2) {
result.push(&data[slice_start..i]);
slice_start = i;
}
}
if slice_start < data.len() {
result.push(&data[slice_start..]);
}
result
}
pub fn get_eq_classes(&self) -> Vec<Vec<D>> {
let mut eq_class_vec = vec![Vec::new(); self.get_number_of_eq_classes()];
let mut eq_ids = Vec::with_capacity(eq_class_vec.len());
for item in &self.eq_classes {
eq_class_vec[*item.value() as usize] = item.key().clone();
eq_ids.push(*item.value() as usize)
}
// consistency property the equivalence classes must be assigned
// unique ids from 0 to N, with no gaps. This could be violated
// if theres is a race condition when assigning equivalence class
// ids in CountFilterEqClass::summarize below. panic if this
// property doesn't hold.
eq_ids.sort_unstable();
for (i, id) in eq_ids.into_iter().enumerate() {
assert_eq!(id, i);
}
eq_class_vec
}
pub fn get_number_of_eq_classes(&self) -> usize {
self.num_eq_classes.load(Ordering::SeqCst)
}
// the ids of the sequences in the equivalence class
let mut eq_class = Vec::new();
let mut nobs = 0;
for (_, exts, d) in items {
eq_class.push(d);
all_exts = all_exts.add(exts);
nobs += 1;
}
eq_class.sort();
eq_class.dedup();
// register the equivalence class and assign it a unique id.
// IDs must be sequential from 0 to N. This must be an atomic operation.
// The correctness of the eqclass_ids is checked above int get_eq_classes.
let eq_ref = self
.eq_classes
.entry(eq_class)
.or_insert_with(|| self.num_eq_classes.fetch_add(1, Ordering::SeqCst) as u32);
let eq_id = *eq_ref.deref();
(nobs as usize >= self.min_kmer_obs, all_exts, eq_id)
}
}
is it possible to know which transcripts belong to which eq_classes?
The code you've shared appears to be written in Rust and pertains to a k-mer based bioinformatics application, which seems to process DNA sequences and potentially perform some form of sequence alignment or graph construction.
The core part that deals with equivalence classes (eq_classes) is the CountFilterEqClass struct and the summarize method implemented for it. This structure is using a DashMap to maintain the set of equivalence classes. Each equivalence class is represented by a Vec<D>, where D is some type parameter that, from the context, can be assumed to represent identifiers for sequences (e.g., transcript IDs). Each equivalence class is associated with a unique EqClassIdType (which is aliased to u32), serving as its unique identifier.
The method get_eq_classes on the CountFilterEqClass struct returns a vector containing the vectors of identifiers in each equivalence class, which would tell you which identifiers (likely transcript IDs) belong to which equivalence class.
In the context of bioinformatics, an equivalence class typically refers to a group of transcripts that share a set of observed k-mers. This is often used in transcriptome analysis to determine which transcripts a particular set of reads might originate from without requiring a full alignment.
However, the provided code does not seem to directly involve the transcript names (tx_names) or the transcript-to-gene map (tx_gene_map). These are passed to the Pseudoaligner::new constructor but without visibility into the Pseudoaligner or other areas of the code base, it's not clear how or if these structures are used to map equivalence class identifiers back to the transcript and gene information.
To specifically know which transcripts belong to which equivalence classes, you would need to maintain a mapping from the equivalence class IDs to the transcript identifiers and gene names. This might involve storing reverse mappings or ensuring that the identifiers being put into the equivalence classes are descriptive enough to recover the desired information.
If you want to modify the code to retain information about which transcripts belong to which equivalence classes, you will need to ensure that the k-mers being summarized in the summarize method and being inserted into equivalence classes in CountFilterEqClass structure are tagged with their originating transcripts. Then, when equivalence classes are formed or queried, that information needs to be associated with the specific equivalence classes.
In summary, the code as-is does not provide a direct way to query which transcripts correspond to which equivalence classes, but you can modify the structures and methods to maintain and extract this association based on the context of your application and the nature of the DNA sequences (seqs) being processed.
To implement tracking of which transcripts belong to which equivalence classes, you need to ensure that when k-mers are being summarized to create equivalence classes, you also keep track of the originating transcript identifiers. This could involve modifying the summarize method to parse additional information. Let's outline some changes.
Step 1: Maintain an association from k-mers to transcripts
First, you need a way to keep track of which k-mers came from which transcripts. Since the CountFilterEqClass struct is generic over the type D, you need to ensure that D contains or can be mapped back to the original transcript data (i.e., transcript ID or name). If D is simply an identifier like a u32, it might be a direct index into the tx_names array, or you might establish a more complex mapping.
Step 2: Modify summarize to store transcript information
When the summarize method constructs an equivalence class (a vector of Ds), it should ensure that the transcript information is included or inferable. We can't directly modify your summarize here because it's unclear what D represents in your code.
Step 3: Expose a method to retrieve the mapping
You'll want a method to retrieve the transcript identifiers associated with an equivalence class after they've been computed. Given an equivalence class ID, you should be able to look up the Vec<D> representing the class and map D back to transcript identifiers.
Below is a rough example of what these changes might involve. Please adjust the types and logic to fit your actual data structures:
rust
impl CountFilterEqClass<u32> {
// Call this method with an equivalence class ID to retrieve associated transcripts
pub fn get_transcripts_for_eq_class(&self, eq_class_id: EqClassIdType) -> Vec<&String> {
if let Some(eq_class) = self.eq_classes.iter().find(|entry| *entry.value() == eq_class_id) {
eq_class.key().iter().map(|&tx_id| &tx_names[tx_id as usize]).collect()
} else {
Vec::new()
}
}
}
In the method above, it's assumed that the D type is a u32 which directly corresponds to an index in the tx_names array. If D is a more complex type, you will need to provide a way to map it back to the original transcript names.
Step 4: Adjust calling code to use transcript IDs
Finally, when calling summarize and constructing equivalence classes, make sure that transcript identifiers are part of the data being processed so that the association can be made.
As we do not have the full codebase, especially details about how equivalence classes are currently being formed and what type D represents, the above modifications are a general guide. It is likely that these steps will need to be adapted to fit the specifics of your implementation and data structures within the larger application.
Remember that this is a non-trivial change and it requires a good understanding of both the existing codebase and the data it manages. If D already represents or includes transcript identifiers, you may already have everything you need, and it's just a matter of exposing the right method to retrieve the data. If D does not currently track transcript information, you may have to adjust the types and relationships across your functions to include this tracking.
I have found this code:
// 1. Given graph, build a data structure of transcripts
// - tx: tx_name, gene_name,
// 2. For each de Bruijn graph node
// - count = number of kmers (L - K + 1)
// - transcript multiplicity = # of colors (size of equiv class)
// - gene multiplicity = # of distinct genes
// - add count, transcript multiplicity to tx_mappability
// - add count, gene multiplicity to gene_mappability
// 3. Output results to tx_mappability.tsv and gene_mappability.tsv
// - tx_mappability:
// tx_name gene_name length kmer_count fraction_unique_tx fraction_unique_gene
// MappabilityRecord: tx_name, gene_name, tx_multiplicity: [usize], gene_multiplicity: [usize]
//
// fn update_counts(Vec, kmer_count, ids)
// fn update_counts(self, kmer_count, ids), Option(Gene_tx_map))
// - (if gene we'll need to make a gene vector instead of color)
// fn fraction_unique(self) -> f64
const MAPPABILITY_HEADER_STRING: &str =
"tx_name\tgene_name\ttx_kmer_count\tfrac_kmer_unique_tx\tfrac_kmer_unique_gene\n";
outfile.write_all(MAPPABILITY_HEADER_STRING.as_bytes())?;
for record in records {
writeln!(outfile, "{}", record.to_tsv())?;
}
Ok(())
}
// pub fn update_counts(records: &mut Vec,
// kmer_count: usize,
// ids: Vec) {
// let num_ids = ids.len();
// for id in ids {
// // add to total # kmers
// records[id].add_count(kmer_count, 0);
// // add to counts according to the size of this equiv class
// records[id].add_count(kmer_count, num_ids)
// }
// }
pub fn analyze_graph<K: Kmer>(
index: &Pseudoaligner,
) -> Result<Vec<MappabilityRecord<'>>, Error> {
// Make records
let mut records = index
.tx_names
.iter()
.map(|tx_name| MappabilityRecord::new(tx_name, index.tx_gene_mapping.get(tx_name).unwrap()))
.collect::<Vec<>>();
code
// Iterate through graph
for node in index.dbg.iter_nodes() {
let num_kmer = node.len() - K::k() + 1;
let eq_class_idx = *node.data() as usize;
let eq_class = &index.eq_classes[eq_class_idx];
let num_tx = eq_class.len();
let num_genes = eq_class
.iter()
.map(|&tx_id| {
let tx_name = &index.tx_names[tx_id as usize];
index.tx_gene_mapping.get(tx_name)
})
.unique()
.count();
for &tx_id in eq_class {
let record = &mut records[tx_id as usize];
record.add_tx_count(num_kmer, num_tx);
record.add_gene_count(num_kmer, num_genes);
}
}
Ok(records)
}
does this help?
Yes, the code you've provided seems to be a Rust program for calculating mappability statistics for transcripts and genes, based on a processed de Bruijn graph (Pseudoaligner<K> assumed to contain such a graph). Mappability in this context is likely referring to how uniquely a k-mer can be mapped to a single transcript or gene, which is an important metric in genomics for assessing the quality of sequence data.
The MappabilityRecord struct contains fields for tracking the number of k-mers shared by different transcripts or genes (tx_multiplicity and gene_multiplicity respectively), and methods for calculating fractions of unique k-mers.
The function analyze_graph seems to be the main part where the de Bruijn graph is analyzed to calculate the mappability statistics:
A vector of MappabilityRecord records is initialized for each transcript, associating them with their gene names.
It iterates through each node in the de Bruijn graph:
The total number of k-mers in the node is calculated (num_kmer).
The equivalence class ID for the node is retrieved, and with it, the corresponding set of transcript IDs that share those k-mers (eq_class).
For each transcript ID, it calculates the multiplicity (the number of transcripts sharing the same k-mers) and the gene multiplicity (the number of distinct genes corresponding to those transcripts).
Counts and multiplicities are added to the respective records.
With these pieces of code, yes, it is possible to know which transcripts belong to which equivalence classes (assuming eq_class correctly represents this relationship). Every node in the graph contains an equivalence class, and you can get the transcript IDs from the equivalence class. Furthermore, this code calculates mappability metrics across transcripts and genes, providing a deeper understanding of the sequencing data's quality and coverage.
If you want to map back to transcript names and/or details, you'd access index.tx_names using the transcript IDs returned in each equivalence class. Similarly, the gene name corresponding to each transcript can be found using index.tx_gene_mapping. The analyze_graph function collects all this information and computes the mappability records for each transcript.
Essentially, the analyze_graph function is:
Taking the information from the de Bruijn graph (nodes associated with transcript equivalence classes),
Mapping it back to transcript and gene information (names and unique counts),
Using it to calculate mappability statistics,
Storing these statistics in a structured format (MappabilityRecord).
You can write these records out to a TSV file with write_mappability_tsv, providing a human-readable summary of mappability by transcript and gene. This allows researchers to make informed decisions about the reliability of the sequence data for specific genes and transcripts.
The code you've provided is already outlining the structure to calculate mappability and associate equivalence classes with transcripts. However, to complete the implementation, you need to ensure that all parts work together and that you can run the analysis from start to finish.
Ensure prerequisites are in place:
Rust is installed on your system.
The project is set up with required dependencies (such as Rayon, Boomphf, etc.).
Integrate the provided code snippets into your existing project or set up a new Rust project.
To implement the mappability analysis, follow this high-level approach:
Step 1: Define necessary constant(s) and structures.
rust
// This value needs to be defined according to your requirements.
// It represents the max number of transcript multiplicity/gene multiplicity
// you want to track for mappability.
const MAPPABILITY_COUNTS_LEN: usize = 100;
// Make sure to include any other necessary imports and auxiliary functions
// from your existing codebase or define them if they are not present.
Step 2: Define the MappabilityRecord struct, which you already have.
Step 3: Write the function analyze_graph, which takes your Pseudoaligner<K> type and performs the analysis to fill out the MappabilityRecord entries.
Step 4: Write the write_mappability_tsv function to output records to a file.
Step 5: Define a main function or a test to run your mappability analysis.
rust
// Ensure your main function or test is calling `analyze_graph` with a properly
// constructed `Pseudoaligner<K>` instance and then uses `write_mappability_tsv`
// to output the results.
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Assuming `build_index` is a function that returns a `Pseudoaligner<K>`
// You need to replace the parameters with actual values/data you have.
let pseudoaligner: Pseudoaligner<K> = build_index(/* parameters here */)?;
// Perform the analysis to get the mappability records
let mappability_records = analyze_graph(&pseudoaligner)?;
// Specify the output directory for the TSV files.
let output_dir = "path/to/output/directory";
// Write the mappability records to a TSV file
write_mappability_tsv(mappability_records, output_dir)?;
Ok(())
}
Make sure you've defined all the functions and types referenced in your snippets, or replace them with appropriate alternatives from your project. If your project contains tests, consider adding a test case for this functionality.
Finally, run your project to see the analysis:
code
$ cargo run
Errors or panics may need to be resolved by carefully inspecting and debugging the code, which often depends on understanding how your Pseudoaligner<K> is defined and how it interacts with the assembly graph. If the Pseudoaligner<K> type or related functions (like build_index) are not defined, you'll need to implement or include them for this code to work.
Please note that the steps are based on the assumption that the data structures and types mentioned (like Pseudoaligner<K>) are part of your existing codebase. If that's not the case, you'll need to provide those implementations or replace them with your actual types and data structures.