feat: add VCF export and refine alignment output infrastructure
Introduce `--vcf` and `--fasta` options for phylo commands, allowing users to export pseudo-alignment data as VCF or FASTA. Implement comprehensive VCF logic including stable virtual coordinates, canonical ID generation, and flexible genotype representation based on ambiguity settings. Refactor internal alignment structures to track k-mer families and site loci, ensuring consistent data flow from scanning through to output generation. - Add `src/obikmer/src/cmd/phylo/alignment_out.rs` with `create` and `write_alignment_outputs` to handle file creation and dispatching of FASTA/VCF formats based on `PhyloArgs`. - Add `src/obikphylo/src/siblings/algorithms/alignment_vcf.rs` implementing VCF-specific logic: `write_vcf`, `alignment`, `cell_alleles`, `majority_base`, and site construction via `site` using fixed $K=11$. Includes helpers for IUPAC state inversion, genotype ordering, and stable coordinate generation. - Update `src/obikmer/src/cmd/phylo/args.rs` to add `fasta` and `vcf` flags and a new `alignment_output()` method that returns true if any output format is requested. Add `pseudo_alignment` field documentation. - Modify `src/obikmer/src/cmd/phylo/mod.rs` to use `alignment_output()` for determining alignment needs, update error messages for `--n-sites`, and import `write_alignment_outputs` from the new module. - Refactor `src/obikphylo/src/siblings/algorithms/alignment.rs` by adding `SiteLocus` struct (partition, layer, family_idx, family_id) and updating `SnpAlignment` and `AlignmentReducer` to track sites. Update `new`, `finish`, and `reduce` to populate site information from `SurvivingFamily`. - Update `src/obikphylo/src/siblings/algorithms/iqtree.rs`: `alignment` now returns `SnpAlignment` with empty sites; update `drop_ascertainment_noninformative` and `recode_symbols_as_absent` to handle the new `sites` field. - Update `src/obikphylo/src/siblings/algorithms/family_scan.rs`: `GeneratedBatch` now includes a `kmers` field; `scan_layer_families` accepts `CanonicalKmer` and passes it to closures instead of masks. - Update `src/obikphylo/src/siblings/algorithms/subsample.rs`: `SurvivingFamily` gains a `kmer` field; `sample_layer` closure accepts and uses this k-mer. - Update `src/obikphylo/src/siblings/algorithms/snp_distance.rs`: `tally_2genomes` initializes `SurvivingFamily` with explicit `CanonicalKmer` values. - Update `src/obikphylo/src/siblings/algorithms/stats.rs`: `sibling_annex_stats` signature adds `_kmer` parameter. - Update `src/obikphylo/src/siblings/algorithms/family_annexes.rs`: closures in `ensure_layer_family_annexes` and `ensure_layer_pair_weight_annexes` now accept `_kmer`. - Update `src/obikphylo/src/siblings/algorithms/pairwise.rs`: `ambiguous_vs_single` initializes k-mer using `CanonicalKmer::from_raw_unchecked(0)`. - Add `iupac_state` function to `src/obikphylo/src/siblings/algorithms/masking.rs` mapping DNA characters to binary codes. - Update `src/obikphylo/src/siblings/algorithms/mod.rs` to export `SiteLocus` and include new `alignment_vcf` module. - Add `family_id` and `write_family_id_ascii` methods to `src/obikseq/src/kmer.rs` for stable k-mer family identification. - Add tests `family_id_partitions_kmers_into_families` and `family_id_ascii_masks_centre` to `src/obikseq/src/tests/kmer.rs`. - Update `src/obikphylo/src/siblings/mod.rs` imports to include new algorithm exports.
This commit is contained in:
1 parent
ee62b131f9
commit
b132f0847f
20 files changed
+558
-37
No files matched your search
@@ -0,0 +1,51 @@
|
||||
//! `--pseudo-alignment` / `--fasta` / `--vcf` file output.
|
||||
|
||||
use std::io::{BufWriter, Write};
|
||||
|
||||
use obikphylo::siblings::SnpAlignment;
|
||||
use tracing::info;
|
||||
|
||||
use super::args::PhyloArgs;
|
||||
|
||||
fn create(path: &str) -> BufWriter<std::fs::File> {
|
||||
BufWriter::new(std::fs::File::create(path).unwrap_or_else(|e| {
|
||||
eprintln!("error creating {path}: {e}");
|
||||
std::process::exit(1);
|
||||
}))
|
||||
}
|
||||
|
||||
/// Writes the drawn alignment as FASTA (default, or `--fasta`) and/or VCF
|
||||
/// (`--vcf`) next to `-o <prefix>`.
|
||||
pub(super) fn write_alignment_outputs(
|
||||
alignment: &SnpAlignment,
|
||||
labels: &[String],
|
||||
args: &PhyloArgs,
|
||||
) {
|
||||
let prefix = args.output.as_ref().map(|p| p.display().to_string());
|
||||
let path_for = |suffix: &str| match &prefix {
|
||||
Some(p) => format!("{p}_alignment.{suffix}"),
|
||||
None => format!("alignment.{suffix}"),
|
||||
};
|
||||
let n_sites = alignment.sequences.first().map_or(0, Vec::len);
|
||||
let n_genomes = alignment.genome_indices.len();
|
||||
|
||||
if args.fasta || !args.vcf {
|
||||
let path = path_for("fasta");
|
||||
let mut f = create(&path);
|
||||
for (&g, seq) in alignment.genome_indices.iter().zip(alignment.sequences.iter()) {
|
||||
obifastwrite::write_plain_record(seq, &labels[g], &mut f).unwrap();
|
||||
}
|
||||
info!("pseudo-alignment ({n_sites} site(s), {n_genomes} genome(s)) → {path}");
|
||||
}
|
||||
|
||||
if args.vcf {
|
||||
let path = path_for("vcf");
|
||||
let mut f = create(&path);
|
||||
let written = alignment.write_vcf(labels, !args.no_ambiguity, &mut f).unwrap_or_else(|e| {
|
||||
eprintln!("error writing {path}: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
f.flush().unwrap();
|
||||
info!("pseudo-alignment VCF ({written}/{n_sites} site(s), {n_genomes} genome(s)) → {path}");
|
||||
}
|
||||
}
|
||||
@@ -275,6 +275,19 @@ pub struct PhyloArgs {
|
||||
#[arg(long)]
|
||||
pub pseudo_alignment: bool,
|
||||
|
||||
/// Write the pseudo-alignment as FASTA (`<prefix>_alignment.fasta`) —
|
||||
/// the default format when neither `--fasta` nor `--vcf` is given. Implies
|
||||
/// `--pseudo-alignment`; combinable with `--vcf`.
|
||||
#[arg(long)]
|
||||
pub fasta: bool,
|
||||
|
||||
/// Write the pseudo-alignment as VCF (`<prefix>_alignment.vcf`): one
|
||||
/// contig `obikmer_<partition>_<layer>` per scanned layer, `POS` the
|
||||
/// family's index within it, `ID` the family's masked canonical k-mer.
|
||||
/// Implies `--pseudo-alignment`; combinable with `--fasta`.
|
||||
#[arg(long)]
|
||||
pub vcf: bool,
|
||||
|
||||
/// Number of variable sites to draw index-wide, or `all` for every site
|
||||
/// that passes the other filters (no sampling then). Mandatory for
|
||||
/// `--pseudo-alignment`/`--sankoff`; optional for a `snp-*`
|
||||
@@ -504,3 +517,11 @@ pub struct PhyloArgs {
|
||||
#[arg(short, long)]
|
||||
pub output: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl PhyloArgs {
|
||||
/// Whether a pseudo-alignment must be drawn and written (`--pseudo-alignment`,
|
||||
/// or any of its output-format flags).
|
||||
pub fn alignment_output(&self) -> bool {
|
||||
self.pseudo_alignment || self.fasta || self.vcf
|
||||
}
|
||||
}
|
||||
@@ -100,7 +100,14 @@ fn drop_ascertainment_noninformative(alignment: &SnpAlignment) -> SnpAlignment {
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
SnpAlignment { sequences, genome_indices: alignment.genome_indices.clone() }
|
||||
let sites = alignment
|
||||
.sites
|
||||
.iter()
|
||||
.zip(keep.iter())
|
||||
.filter(|&(_, &k)| k)
|
||||
.map(|(&site, _)| site)
|
||||
.collect();
|
||||
SnpAlignment { sequences, genome_indices: alignment.genome_indices.clone(), sites }
|
||||
}
|
||||
|
||||
/// Recode every occurrence of a byte in `symbols` to `-` — the same
|
||||
@@ -119,7 +126,7 @@ fn recode_symbols_as_absent(alignment: &SnpAlignment, symbols: &[u8]) -> SnpAlig
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
SnpAlignment { sequences, genome_indices: alignment.genome_indices.clone() }
|
||||
SnpAlignment { sequences, genome_indices: alignment.genome_indices.clone(), sites: alignment.sites.clone() }
|
||||
}
|
||||
|
||||
fn compact_alphabet(alignment: &SnpAlignment, free_loss: bool) -> CompactAlphabet {
|
||||
@@ -384,7 +391,7 @@ mod tests {
|
||||
|
||||
fn alignment(sequences: Vec<Vec<u8>>) -> SnpAlignment {
|
||||
let genome_indices = (0..sequences.len()).collect();
|
||||
SnpAlignment { sequences, genome_indices }
|
||||
SnpAlignment { sequences, genome_indices, sites: Vec::new() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
mod alignment_out;
|
||||
mod args;
|
||||
mod iqtree;
|
||||
mod phyg;
|
||||
@@ -19,6 +20,7 @@ use obikphylo::{Metrics, neighbor_joining, upgma};
|
||||
use obisys::{Reporter, Stage};
|
||||
use tracing::info;
|
||||
|
||||
use alignment_out::write_alignment_outputs;
|
||||
use args::{DistanceArg, NSitesArg, distance_to_compute};
|
||||
use iqtree::write_iqtree;
|
||||
use phyg::write_sankoff_phyg;
|
||||
@@ -285,13 +287,13 @@ pub fn run(args: PhyloArgs) {
|
||||
let sankoff_requested = args.sankoff || args.tnt || args.phyg || args.iqtree;
|
||||
let distance = distance_to_compute(args.distance, args.nj, args.upgma, args.shared_kmers);
|
||||
let snp_kind = distance.and_then(DistanceArg::as_snp);
|
||||
let need_alignment = args.pseudo_alignment || sankoff_requested;
|
||||
let need_alignment = args.alignment_output() || sankoff_requested;
|
||||
let need_pairwise = sankoff_requested || snp_kind.is_some();
|
||||
// `None` = every site (`--n-sites all`, or `--n-sites` omitted where it is optional)
|
||||
let target = args.n_sites.and_then(NSitesArg::target);
|
||||
|
||||
if args.pseudo_alignment && args.n_sites.is_none() {
|
||||
eprintln!("error: --pseudo-alignment requires --n-sites <N|all>");
|
||||
if args.alignment_output() && args.n_sites.is_none() {
|
||||
eprintln!("error: --pseudo-alignment/--fasta/--vcf require --n-sites <N|all>");
|
||||
std::process::exit(1);
|
||||
}
|
||||
if sankoff_requested && args.n_sites.is_none() {
|
||||
@@ -357,21 +359,9 @@ pub fn run(args: PhyloArgs) {
|
||||
let alignment = alignment_reducer.map(obikphylo::siblings::AlignmentReducer::finish);
|
||||
|
||||
// ── SNP pseudo-alignment (`--pseudo-alignment`) ─────────────────────────────
|
||||
if args.pseudo_alignment {
|
||||
if args.alignment_output() {
|
||||
let alignment = alignment.as_ref().expect("scanned above: need_alignment");
|
||||
|
||||
let path = args.output.as_ref()
|
||||
.map(|p| format!("{}_alignment.fasta", p.display()))
|
||||
.unwrap_or_else(|| "alignment.fasta".into());
|
||||
let mut f = BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|e| {
|
||||
eprintln!("error creating {path}: {e}");
|
||||
std::process::exit(1);
|
||||
}));
|
||||
let n_sites = alignment.sequences.first().map_or(0, Vec::len);
|
||||
for (&g, seq) in alignment.genome_indices.iter().zip(alignment.sequences.iter()) {
|
||||
obifastwrite::write_plain_record(seq, &labels[g], &mut f).unwrap();
|
||||
}
|
||||
info!("pseudo-alignment ({n_sites} site(s), {} genome(s)) → {path}", alignment.genome_indices.len());
|
||||
write_alignment_outputs(alignment, &labels, &args);
|
||||
}
|
||||
|
||||
// ── Sankoff cost-matrix calibration (`--sankoff`, `--tnt`, `--phyg`, `--iqtree`) ──
|
||||
|
||||
Reference in new issue
Block a user