Cn-Bioinf
view release on metacpan or search on metacpan
UV *called;// each sample's called genotypes
} admix_reader;
static void admix_header(pTHX_ vcf_reader *r) {
admix_reader *t = (admix_reader*)r;
Newxz(t->called, r->n, UV);
SAVEFREEPV(t->called);// at the caller's LEAVE, croak or not; see vcf_read()'s block
}
/*The record p..e, kept when it is on an autosome and biallelic: one ALT,
which is not "." (no ALT) or "*" (a deletion's overlap), as PLINK 2's
--max-alleles 2 --min-alleles 2 keeps them, which is what made t/admixture.t's
reference input. A call of one allele, or of none, is missing.*/
static void admix_record(pTHX_ vcf_reader *r, const char *p, const char *e) {
admix_reader *t = (admix_reader*)r;
const char *f = vcf_field_end(p, e);
const unsigned short int chrom = vcf_chrom(p, f);
if (chrom == 0 || chrom > 22) return;
const char *col[9];
const char *format_end = vcf_columns(aTHX_ r, p, f, e, col);
const char *alt = col[4], *alt_end = col[5] - 1;
if (alt == alt_end || memchr(alt, ',', (size_t)(alt_end - alt)) || (alt_end - alt == 1 && (*alt == '.' || *alt == '*'))) return;
size_t gt, dp;
vcf_format(col[8], format_end, >, &dp);
if (gt == VCF_ABSENT) return;
const STRLEN at = SvCUR(t->g);
if ((STRLEN)r->n > ((STRLEN)-1 - at) / 2 - 1) croak("%s: %s has too many genotypes to hold, at line %" UVuf, __func__, r->name, r->line);
// doubled when full, so that the bytes are copied O(log variants) times, not once a record
if (SvLEN(t->g) < at + r->n + 1) SvGROW(t->g, 2 * (at + r->n) + 1);
unsigned char *row = (unsigned char*)SvPVX(t->g) + at;// not restrict: perl's buffer
p = format_end + 1;
for (size_t i = 0; i < r->n; i++) {
const char *se = vcf_sample(aTHX_ r, p, e, i);
unsigned short int alleles = 0, alts = 0;
const bool call = vcf_call(r, p, se, gt, dp, &alleles, &alts) == VCF_CALL && alleles == 2;
row[i] = call ? (unsigned char)alts : ADMIX_MISSING;
if (call) t->called[i]++;
p = se + 1;
}
vcf_samples_end(aTHX_ r, p, e);
SvCUR_set(t->g, at + r->n);
av_push(t->variants, newSVpvf("%.*s\t%.*s\t%.*s\t%.*s\t%.*s", (int)(col[1] - 1 - col[0]), col[0], (int)(col[2] - 1 - col[1]), col[1],
(int)(col[3] - 1 - col[2]), col[2], (int)(col[4] - 1 - col[3]), col[3], (int)(alt_end - alt), alt));
}
typedef struct {
const unsigned char *g;// m rows of n genotype bytes; perl's buffer, not written
size_t n, m, k;// samples, variants, ancestral populations
NV *twice;// each sample's called genotypes, twice: the alleles its q is a share of
NV *num, *den;// k each, admix_em()'s sums for one variant
} admix_fit;
/*The parameters, q (n rows of k) and then p (m rows of k), held to the
bounds: each q row clamped and made to sum to 1 again, each p clamped.*/
static void admix_bound(const admix_fit *a, NV *th) {
const size_t k = a->k;
for (size_t i = 0; i < a->n; i++) {
NV *q = th + i * k;
NV sum = 0;
for (size_t l = 0; l < k; l++) {
if (!(q[l] >= ADMIX_BOUND)) q[l] = ADMIX_BOUND;// also NaN, which an extrapolation can make
else if (q[l] > 1 - ADMIX_BOUND) q[l] = 1 - ADMIX_BOUND;
sum += q[l];
}
for (size_t l = 0; l < k; l++) q[l] /= sum;
}
NV *p = th + a->n * k;
for (size_t x = 0; x < a->m * k; x++) {
if (!(p[x] >= ADMIX_BOUND)) p[x] = ADMIX_BOUND;
else if (p[x] > 1 - ADMIX_BOUND) p[x] = 1 - ADMIX_BOUND;
}
}
static NV admix_loglik(const admix_fit *a, const NV *th) {
const size_t n = a->n, k = a->k;
const NV *q = th, *p = th + n * k;
NV ll = 0;
for (size_t j = 0; j < a->m; j++) {
const unsigned char *row = a->g + j * n;
const NV *pj = p + j * k;
for (size_t i = 0; i < n; i++) {
const unsigned char c = row[i];
if (c == ADMIX_MISSING) continue;
const NV *qi = q + i * k;
NV f = 0;
for (size_t l = 0; l < k; l++) f += qi[l] * pj[l];
if (c) ll += (NV)c * nv_log(f);
if (c < 2) ll += (NV)(2 - c) * nv_log(1 - f);
}
}
return ll;
}
/*One EM step from th into out, both laid out as admix_bound() describes.*/
static void admix_em(const admix_fit *a, const NV *th, NV *out) {
const size_t n = a->n, k = a->k;
const NV *q = th, *p = th + n * k;
NV *q2 = out, *p2 = out + n * k;
Zero(q2, n * k, NV);
for (size_t j = 0; j < a->m; j++) {
const unsigned char *row = a->g + j * n;
const NV *pj = p + j * k;
Zero(a->num, k, NV);
Zero(a->den, k, NV);
for (size_t i = 0; i < n; i++) {
const unsigned char c = row[i];
if (c == ADMIX_MISSING) continue;
const NV *qi = q + i * k;
NV f = 0;
for (size_t l = 0; l < k; l++) f += qi[l] * pj[l];
const NV x = c ? (NV)c / f : 0, y = c < 2 ? (NV)(2 - c) / (1 - f) : 0;
NV *q2i = q2 + i * k;
for (size_t l = 0; l < k; l++) {
const NV alt = x * qi[l] * pj[l], ref = y * qi[l] * (1 - pj[l]);
q2i[l] += alt + ref;
a->num[l] += alt;
a->den[l] += alt + ref;
}
}
for (size_t l = 0; l < k; l++) p2[j * k + l] = a->den[l] > 0 ? a->num[l] / a->den[l] : pj[l];
}
}
admix_bound(a, out);
}
/*The next of the 64-bit numbers that *s seeds, by SplitMix64 (Steele, Lea
and Flood 2014; the constants of Sebastiano Vigna's public-domain
splitmix64.c, prng.di.unimi.it), which gives the same numbers on every
platform, where rand() and perl's own do not.*/
static uint64_t admix_rand(uint64_t *s) {
uint64_t z = (*s += UINT64_C(0x9E3779B97F4A7C15));
z = (z ^ (z >> 30)) * UINT64_C(0xBF58476D1CE4E5B9);
z = (z ^ (z >> 27)) * UINT64_C(0x94D049BB133111EB);
return z ^ (z >> 31);
}
/*A random start from seed: each q row uniform numbers made to sum to 1, and
each p uniform, then held to the bounds. The top 53 bits of each number are
used, which a double holds exactly, so that the start is the same on a
long-double perl.*/
static void admix_start(const admix_fit *a, NV *th, uint64_t seed) {
const NV unit = (NV)1 / (NV)UINT64_C(9007199254740992);// 2^-53
for (size_t x = 0; x < (a->n + a->m) * a->k; x++) th[x] = (NV)(admix_rand(&seed) >> 11) * unit;
admix_bound(a, th);
}
/*Fits from the start in th, leaving the fit there; returns its
log-likelihood, with the iterations in *iterations, and whether it converged
(the log-likelihood rose by less than tol in the last) in *converged. Each
iteration is a SQUAREM cycle of three EM steps.*/
static NV admix_run(pTHX_ const admix_fit *a, NV *th, UV max_iterations, NV tol, UV *iterations, bool *converged) {
const size_t len = (a->n + a->m) * a->k;
NV *t1, *t2, *t3;
Newx(t1, len, NV);
SAVEFREEPV(t1);
Newx(t2, len, NV);
SAVEFREEPV(t2);
Newx(t3, len, NV);
SAVEFREEPV(t3);
NV ll = admix_loglik(a, th);
*converged = FALSE;
*iterations = 0;
while (*iterations < max_iterations) {
++*iterations;
admix_em(a, th, t1);
admix_em(a, t1, t2);
NV sr = 0, sv = 0;
for (size_t x = 0; x < len; x++) {
const NV r = t1[x] - th[x], v = t2[x] - 2 * t1[x] + th[x];
sr += r * r;
sv += v * v;
}
NV next;
const NV *keep = t2;// the parameters this iteration ends at
if (sv > 0) {
NV alpha = -nv_sqrt(sr / sv);
if (alpha > -1) alpha = -1;
for (size_t x = 0; x < len; x++) t3[x] = th[x] - 2 * alpha * (t1[x] - th[x]) + alpha * alpha * (t2[x] - 2 * t1[x] + th[x]);
admix_bound(a, t3);
admix_em(a, t3, t1);// t1 is not needed again
next = admix_loglik(a, t1);
if (next >= ll) keep = t1;// not NaN, and no lower
else next = admix_loglik(a, t2);
} else {
next = admix_loglik(a, t2);
}
Copy(keep, th, len, NV);
const NV rise = next - ll;
ll = next;
if (rise < tol) {
*converged = TRUE;
break;
}
}
return ll;
}
MODULE = Cn::Bioinf PACKAGE = Cn::Bioinf
PROTOTYPES: DISABLE
SV *
_read_fasta(fh, key, name, order = NULL)
PerlIO *fh
SV *key
const char *name
AV *order
CODE:
RETVAL = read_fasta(aTHX_ fh, SvOK(key) ? key : NULL, name, order);
OUTPUT:
RETVAL
void
_write_fasta(fh, h, order, width)
PerlIO *fh
HV *h
AV *order
UV width
CODE:
write_fasta(aTHX_ fh, h, order, (STRLEN)width);
void
_fai_build(fh)
PerlIO *fh
PPCODE:
fai_state s;
Zero(&s, 1, fai_state);
s.text = sv_2mortal(newSVpvs(""));
s.seen = (HV*)sv_2mortal((SV*)newHV());
s.dups = (AV*)sv_2mortal((SV*)newAV());
s.def = sv_2mortal(newSVpvs(""));
s.name = sv_2mortal(newSVpvs(""));
char *restrict buf;
Newx(buf, FASTA_BLOCK, char);
SAVEFREEPV(buf);// freed at this call's LEAVE, croak or not
fai_scan(aTHX_ fh, &s, buf);
EXTEND(SP, 6);
PUSHs(s.text);
PUSHs(sv_2mortal(newRV_inc((SV*)s.dups)));
PUSHs(s.error ? sv_2mortal(newSVpv(s.error, 0)) : &PL_sv_undef);
PUSHs(sv_2mortal(fai_number(aTHX_ s.line)));
PUSHs(s.named ? s.name : &PL_sv_undef);
PUSHs(s.error && strEQ(s.error, "read") ? sv_2mortal(newSVpv(Strerror(s.read_errno), 0)) : &PL_sv_undef);
( run in 0.888 second using v1.01-cache-2.11-cpan-60884a8df76 )