Skip to main content

GcFragModel

Struct GcFragModel 

Source
pub struct GcFragModel { /* private fields */ }
Expand description

(condBins × numGCBins) table of fragment-GC counts (then a normalized distribution / ratio after normalize / gc_ratio).

Implementations§

Source§

impl GcFragModel

Source

pub fn new(cond_bins: usize, gc_bins: usize) -> Self

Examples found in repository?
examples/conv_bench.rs (line 59)
33fn main() {
34    let args: Vec<String> = std::env::args().collect();
35    let n: usize = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(100_000);
36    let passes: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(3);
37
38    let mut rng = Lcg(0x9E3779B97F4A7C15);
39
40    // Build a realistic transcript-length distribution: log-normal-ish around
41    // ~1.5 kb with a long tail, clamped to [80, 15000] — close to GRCh38 cDNA.
42    let bases = [b'A', b'C', b'G', b'T'];
43    let mut seqs: Vec<Vec<u8>> = Vec::with_capacity(n);
44    let mut prefixes: Vec<Vec<u32>> = Vec::with_capacity(n);
45    for _ in 0..n {
46        let u = rng.next_f64();
47        // exp of a normal-ish variate -> heavy right tail
48        let len = (7.3 + 0.9 * (u - 0.5) * 4.0).exp() as usize;
49        let len = len.clamp(80, 15_000);
50        let seq: Vec<u8> = (0..len)
51            .map(|_| bases[(rng.next_u32() & 3) as usize])
52            .collect();
53        prefixes.push(gc_prefix(&seq));
54        seqs.push(seq);
55    }
56
57    // A normalized 3×25 GC ratio model (the shape doesn't matter for timing; we
58    // exercise the same binning + lookup the real run does).
59    let mut obs = GcFragModel::new(DEFAULT_COND_BINS, DEFAULT_GC_BINS);
60    let mut exp = GcFragModel::new(DEFAULT_COND_BINS, DEFAULT_GC_BINS);
61    for ctx in 0..=100 {
62        for gc in 0..=100 {
63            obs.inc(gc, ctx, 1.0 + 0.3 * ((gc + ctx) as f64).sin());
64            exp.inc(gc, ctx, 1.0);
65        }
66    }
67    let gc_model = gc_ratio(&mut obs, &mut exp, 1000.0);
68
69    // Fragment-length CDF: gaussian-ish pmf around mean 250, sd 40, over 0..1000.
70    let fld_max = 1000usize;
71    let mean = 250.0f64;
72    let sd = 40.0f64;
73    let pmf: Vec<f64> = (0..=fld_max)
74        .map(|l| {
75            let z = (l as f64 - mean) / sd;
76            (-0.5 * z * z).exp()
77        })
78        .collect();
79    let (cdf, fld_low, fld_high) = salmon_model::seqbias::fld_cdf_and_bounds(&pmf);
80
81    let mut acc = 0.0f64;
82    let mut best = f64::INFINITY;
83    for p in 0..passes {
84        let t = Instant::now();
85        for (seq, prefix) in seqs.iter().zip(&prefixes) {
86            let ref_len = seq.len() as f64;
87            let elen = (ref_len - 200.0).max(1.0); // ensure unprocessed > 0
88            let bias = BiasInputs {
89                seq: None,
90                gc: Some((&gc_model, salmon_model::GcView::Dense(prefix.as_slice()))),
91                pos: None,
92            };
93            acc += corrected_effective_length_full(
94                seq,
95                &cdf,
96                fld_low,
97                fld_high,
98                &bias,
99                elen,
100                GC_SAMP_STRIDE,
101                false,
102            );
103        }
104        let dt = t.elapsed().as_secs_f64();
105        best = best.min(dt);
106        eprintln!(
107            "pass {p}: {:.3}s  ({:.2} µs/transcript)  acc={}",
108            dt,
109            dt * 1e6 / n as f64,
110            black_box(acc)
111        );
112    }
113    eprintln!(
114        "BEST: {:.3}s over {} transcripts ({:.2} µs/transcript)",
115        best,
116        n,
117        best * 1e6 / n as f64
118    );
119}
Source

pub fn default_model() -> Self

salmon’s default 3 × 101 model.

Source

pub fn dump(&self) -> &[f64]

The flattened cond_bins × gc_bins table (counts[ctx * gc_bins + gc], row-major), for dumping to the aux bias files.

Source

pub fn inc(&mut self, gc_frac: i32, ctx_frac: i32, weight: f64)

Accumulate weight for a fragment with the given GC and context fractions.

Examples found in repository?
examples/conv_bench.rs (line 63)
33fn main() {
34    let args: Vec<String> = std::env::args().collect();
35    let n: usize = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(100_000);
36    let passes: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(3);
37
38    let mut rng = Lcg(0x9E3779B97F4A7C15);
39
40    // Build a realistic transcript-length distribution: log-normal-ish around
41    // ~1.5 kb with a long tail, clamped to [80, 15000] — close to GRCh38 cDNA.
42    let bases = [b'A', b'C', b'G', b'T'];
43    let mut seqs: Vec<Vec<u8>> = Vec::with_capacity(n);
44    let mut prefixes: Vec<Vec<u32>> = Vec::with_capacity(n);
45    for _ in 0..n {
46        let u = rng.next_f64();
47        // exp of a normal-ish variate -> heavy right tail
48        let len = (7.3 + 0.9 * (u - 0.5) * 4.0).exp() as usize;
49        let len = len.clamp(80, 15_000);
50        let seq: Vec<u8> = (0..len)
51            .map(|_| bases[(rng.next_u32() & 3) as usize])
52            .collect();
53        prefixes.push(gc_prefix(&seq));
54        seqs.push(seq);
55    }
56
57    // A normalized 3×25 GC ratio model (the shape doesn't matter for timing; we
58    // exercise the same binning + lookup the real run does).
59    let mut obs = GcFragModel::new(DEFAULT_COND_BINS, DEFAULT_GC_BINS);
60    let mut exp = GcFragModel::new(DEFAULT_COND_BINS, DEFAULT_GC_BINS);
61    for ctx in 0..=100 {
62        for gc in 0..=100 {
63            obs.inc(gc, ctx, 1.0 + 0.3 * ((gc + ctx) as f64).sin());
64            exp.inc(gc, ctx, 1.0);
65        }
66    }
67    let gc_model = gc_ratio(&mut obs, &mut exp, 1000.0);
68
69    // Fragment-length CDF: gaussian-ish pmf around mean 250, sd 40, over 0..1000.
70    let fld_max = 1000usize;
71    let mean = 250.0f64;
72    let sd = 40.0f64;
73    let pmf: Vec<f64> = (0..=fld_max)
74        .map(|l| {
75            let z = (l as f64 - mean) / sd;
76            (-0.5 * z * z).exp()
77        })
78        .collect();
79    let (cdf, fld_low, fld_high) = salmon_model::seqbias::fld_cdf_and_bounds(&pmf);
80
81    let mut acc = 0.0f64;
82    let mut best = f64::INFINITY;
83    for p in 0..passes {
84        let t = Instant::now();
85        for (seq, prefix) in seqs.iter().zip(&prefixes) {
86            let ref_len = seq.len() as f64;
87            let elen = (ref_len - 200.0).max(1.0); // ensure unprocessed > 0
88            let bias = BiasInputs {
89                seq: None,
90                gc: Some((&gc_model, salmon_model::GcView::Dense(prefix.as_slice()))),
91                pos: None,
92            };
93            acc += corrected_effective_length_full(
94                seq,
95                &cdf,
96                fld_low,
97                fld_high,
98                &bias,
99                elen,
100                GC_SAMP_STRIDE,
101                false,
102            );
103        }
104        let dt = t.elapsed().as_secs_f64();
105        best = best.min(dt);
106        eprintln!(
107            "pass {p}: {:.3}s  ({:.2} µs/transcript)  acc={}",
108            dt,
109            dt * 1e6 / n as f64,
110            black_box(acc)
111        );
112    }
113    eprintln!(
114        "BEST: {:.3}s over {} transcripts ({:.2} µs/transcript)",
115        best,
116        n,
117        best * 1e6 / n as f64
118    );
119}
Source

pub fn get(&self, gc_frac: i32, ctx_frac: i32) -> f64

Value at a (context, GC) cell (a normalized density after normalize, or a clamped ratio for a model produced by gc_ratio).

Source

pub fn combine_counts(&mut self, other: &GcFragModel)

Merge another (compatible) model’s counts. Both must be pre-normalization.

Source

pub fn normalize(&mut self)

Normalize each conditioning row into a distribution over GC bins, with a pseudocount prior (salmon’s default 0.1). Idempotent.

Trait Implementations§

Source§

impl Clone for GcFragModel

Source§

fn clone(&self) -> GcFragModel

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for GcFragModel

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more