Cn-Bioinf

 view release on metacpan or  search on metacpan

lib/Cn/Bioinf.pm  view on Meta::CPAN

				@row{ @{ $head } } = @{ $data[$i] };
				push @rows, \%row;
			}
		} else {
			croak "$sub: \"$what\" must be $shapes, not an array whose first row is " . _what($frame->[0]);
		}
		@labels = map { "row $_" } 1 .. @rows if $labelled;
	} elsif (ref $frame eq 'HASH') {
		my ($key, $first) = each %{ $frame };
		keys %{ $frame }; # resets the iterator that each left part-way
		croak "$sub: \"$what\" has no rows" unless defined $key;
		if (ref $first eq 'HASH') {
			if ($labelled) {
				my @keys = sort keys %{ $frame };
				@rows = @{ $frame }{@keys};
				@labels = map { "row \"$_\"" } @keys;
			} else {
				@rows = values %{ $frame };
			}
		} elsif (ref $first eq 'ARRAY') {
			# sorted, so that the column a length is compared with, and named
			# when it differs, is not the hash's order
			my @cols = sort keys %{ $frame };
			foreach my $c (@cols) {
				croak "$sub: column \"$c\" of \"$what\" must be an array ref, as \"$key\" is, not " . _what($frame->{$c})
					unless ref $frame->{$c} eq 'ARRAY';
				my $n = @{ $frame->{$c} };
				croak "$sub: column \"$c\" of \"$what\" has $n value" . ($n == 1 ? '' : 's') . ", and \"$cols[0]\" " . scalar(@{ $frame->{ $cols[0] } })
					unless $n == @{ $frame->{ $cols[0] } };
			}
			foreach my $i (0 .. $#{ $first }) {
				push @rows, { map { $_ => $frame->{$_}[$i] } @cols };
			}
			croak "$sub: \"$what\" has no rows" unless @rows;
			@labels = map { "row $_" } 1 .. @rows if $labelled;
		} else {
			croak "$sub: \"$what\" must be $shapes, not a hash whose \"$key\" is " . _what($first);
		}
	} else {
		croak "$sub: \"$what\" must be $shapes, not " . _what($frame);
	}
	foreach my $i (0 .. $#rows) {
		croak "$sub: row " . ($i + 1) . " of \"$what\" must be a hash ref, not " . _what($rows[$i]) unless ref $rows[$i] eq 'HASH';
	}
	$labelled ? (\@rows, \@labels) : \@rows;
}

# A chromosome's name as a VCF, PLINK 2 and a scoring file are compared on: in
# upper case, without UCSC's "chr" prefix (GRCh37's own names, and the PGS
# Catalog's, have none), with PLINK's numeric codes for the sex and
# mitochondrial chromosomes and UCSC's "M" named as Ensembl names them, and with
# X's pseudo-autosomal regions, which PLINK 2 names PAR1 and PAR2 (or XY, its
# 25) once --split-par has split them off, taken as X.
my %Chrom_alias = (23 => 'X', 24 => 'Y', 25 => 'X', 26 => 'MT', M => 'MT', PAR1 => 'X', PAR2 => 'X', XY => 'X');
sub _chrom {
	my $c = uc $_[0];
	$c =~ s/\ACHR//;
	$Chrom_alias{$c} // $c;
}

# A decimal number, as an effect_weight must be. Infinity and NaN, which
# looks_like_number would take, are left out, as either would make every score
# the same non-number.
my $Number = qr/\A[-+]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][-+]?[0-9]+)?\z/;

# The rows of the option $what ("weights" for pgs_score, "model" for
# trait_predict) one at a time, each a hash ref with how a message names it,
# and the column names: from a data frame (see _frame_rows), or read from a
# tab-separated file a line at a time, so that a score of millions of variants
# is never held whole. An empty field of a file is '', where read_table gives
# undef; every check below treats the two alike.
sub _weight_rows {
	my ($sub, $weights, $what) = @_;
	$what //= 'weights';
	if (ref $weights) {
		my ($rows, $labels) = _frame_rows($sub, $what, $weights, 1);
		my $i = 0;
		return (sub { $i < @{ $rows } ? ($rows->[$i], $labels->[$i++]) : () }, [keys %{ $rows->[0] }]);
	}
	croak "$sub: \"$what\" file \"$weights\" doesn't exist or isn't readable" unless -f $weights && -r _;
	my $fh;
	if ($weights =~ /\.gz\z/i) {
		require IO::Uncompress::Gunzip;
		$fh = IO::Uncompress::Gunzip->new($weights, MultiStream => 1)
			or croak "$sub: can't read $weights: $IO::Uncompress::Gunzip::GunzipError";
	} else {
		open $fh, '<:raw', $weights or croak "$sub: can't read $weights: $!";
	}
	my $n = 0; # rows read so far
	# IO::Uncompress::Gunzip ends a truncated or corrupt stream as if it were
	# the end of the file, and says so only in its error(), which reading a
	# .gz to the end therefore checks
	my $whole = sub {
		return unless ref $fh ne 'GLOB' && $fh->error;
		croak "$sub: \"$what\" file $weights ends early or is corrupt, " . ($n ? "after row $n" : 'before its first row') . ': ' . $fh->error;
	};
	my $head;
	while (defined(my $line = <$fh>)) {
		$line =~ s/\r?\n\z//;
		next if $line eq '' || $line =~ /\A#/;
		$head = $line;
		last;
	}
	$whole->() unless defined $head;
	croak "$sub: \"$what\" file $weights has no header line" unless defined $head;
	my @cols = split /\t/, $head, -1;
	my $next = sub {
		while (defined(my $line = <$fh>)) {
			$line =~ s/\r?\n\z//;
			next if $line eq '';
			my %row;
			@row{@cols} = split /\t/, $line, -1;
			return (\%row, 'row ' . ++$n);
		}
		$whole->();
		return;
	};
	($next, \@cols);
}

# The data frame $frame written to $file as a VCF of GT alone, for PLINK 2 to

lib/Cn/Bioinf.pm  view on Meta::CPAN

		foreach my $k (0 .. $#{ $panel }) {
			$genotype{ $column[$k] } = $d->[$k];
			push @missing, $panel->[$k]{rsid} unless defined $d->[$k];
		}
		my $can = _hirisplex_possible($panel, $d);
		$out{$s} = {
			genotype => \%genotype,
			missing  => \@missing,
			markers  => scalar @{ $panel },
			called   => scalar(@{ $panel }) - scalar(@missing),
			%{ $can },
		};
	}
	_hirisplex_csv($sub, $r{file}, $panel, \%out, $names) if defined $r{file};
	if ($r{report}) {
		print STDOUT _hirisplex_report($vcf, \%r, $panel, \%out, $names, \@absent) or croak "$sub: can't print the report: $!";
	}
	carp "$sub: \"vcf\" $vcf holds none of the " . scalar(@{ $panel }) . ' HIrisPlex-S markers'
		. ($r{match} eq 'id' ? '; it was matched by rs number, and a VCF whose ID column is "." matches nothing that way'
			: ", matched by position on $r{build}; check that it is the build the file is on")
		if @absent == @{ $panel };
	\%out;
}

# The marker that carries a category's intercept, in place of an rs number, in
# a "model" table. A marker can't be called this, so nothing is ambiguous.
my $Intercept = '(intercept)';

# The rows of "model" read into trait => category => { marker => beta }, with
# the intercept under $Intercept, and the traits and their categories in the
# order the table first names them, which is the order the report prints.
sub _trait_model {
	my ($sub, $model) = @_;
	my ($next, $cols) = _weight_rows($sub, $model, 'model');
	my %have = map { $_ => 1 } @{ $cols };
	my @absent = grep { !$have{$_} } qw(trait category marker beta);
	croak "$sub: \"model\" has no " . join(', ', map { "\"$_\"" } @absent) . ' column' . (@absent > 1 ? 's' : '')
		. '; a model table has trait, category, marker and beta' if @absent;
	my (%beta, @traits, %category);
	while (my ($row, $label) = $next->()) {
		my ($t, $c, $m, $b) = @{ $row }{qw(trait category marker beta)};
		foreach my $f (['trait', $t], ['category', $c], ['marker', $m]) {
			croak "$sub: $label of \"model\" has no $f->[0]" unless defined $f->[1] && length $f->[1];
		}
		croak "$sub: $label of \"model\" has beta " . _what($b) . ", which isn't a number"
			unless defined $b && !ref $b && $b =~ $Number;
		push @traits, $t unless $beta{$t};
		push @{ $category{$t} }, $c unless $beta{$t} && $beta{$t}{$c};
		croak "$sub: $label of \"model\" gives $t category \"$c\" a second beta for $m"
			if exists $beta{$t}{$c}{$m};
		$beta{$t}{$c}{$m} = $b;
	}
	croak "$sub: \"model\" has no rows" unless @traits;
	(\%beta, \@traits, \%category);
}

# exp() of each of @$eta, divided by their sum: the probabilities a multinomial
# logistic regression gives its categories. The largest is taken out first, so
# that a linear predictor big enough to overflow exp() (about 710 on an IEEE
# double, and larger on a long-double or quadmath perl) gives 1 and the rest 0
# rather than inf/inf, which is NaN.
sub _softmax {
	my ($eta) = @_;
	my $max = $eta->[0];
	foreach my $e (@{ $eta }) { $max = $e if $e > $max }
	my @exp = map { exp($_ - $max) } @{ $eta };
	my $sum = 0;
	$sum += $_ foreach @exp;
	[map { $_ / $sum } @exp];
}

# trait_predict's report on $out: a table of each sample's probabilities, one
# block for each trait, the categories in the model's order.
sub _trait_report {
	my ($r, $out, $order, $traits, $category) = @_;
	my $text = "trait_predict: " . scalar(@{ $order }) . ' sample' . (@{ $order } > 1 ? 's' : '')
		. ', ' . scalar(@{ $traits }) . ' trait' . (@{ $traits } > 1 ? 's' : '')
		. "; a marker the sample has no genotype for counts as 0 copies"
		. ($r->{force} ? ', and a prediction the HIrisPlex-S rules refuse is made anyway ("force")' : '') . "\n";
	foreach my $t (@{ $traits }) {
		my @head = ('sample', 'call', @{ $category->{$t} }, 'called');
		my @rows = map {
			my $p = $out->{$_}{$t};
			[$_, $p->{call} // '-', (map { defined $p->{p}{$_} ? sprintf('%.3f', $p->{p}{$_}) : '-' } @{ $category->{$t} }),
				"$p->{called}/$p->{markers}"]
		} @{ $order };
		my @w = map { length $head[$_] } 0 .. $#head;
		foreach my $row (@rows) {
			foreach my $i (0 .. $#head) {
				$w[$i] = length $row->[$i] if length $row->[$i] > $w[$i];
			}
		}
		my $line = sub { join('  ', map { $_ == 0 ? sprintf('%-*s', $w[$_], $_[$_]) : sprintf('%*s', $w[$_], $_[$_]) } 0 .. $#head) . "\n" };
		$text .= "\n$t\n" . $line->(@head) . join('', map { $line->(@{ $_ }) } @rows);
		my @refused = grep { defined $out->{$_}{$t}{refused} } @{ $order };
		$text .= join '', map { "  $_: no $t prediction: $out->{$_}{$t}{refused}\n" } @refused;
	}
	$text;
}

sub trait_predict {
	my $sub = 'trait_predict';
	my $args = _args(\@_, $sub, [qw(genotypes model)], [qw(force report)]);
	my %r;
	$r{force} = $args->{force} // 0; # 0 = a trait the genotypes say can't be predicted isn't; 1 = predict it anyway
	croak "$sub: \"force\" must be 0 or 1, not " . _what($r{force}) unless !ref $r{force} && ($r{force} eq '0' || $r{force} eq '1');
	$r{report} = $args->{report} // 1; # 1 = print a table of the samples to STDOUT; 0 = only return them
	croak "$sub: \"report\" must be 0 or 1, not " . _what($r{report}) unless !ref $r{report} && ($r{report} eq '0' || $r{report} eq '1');
	my $g = $args->{genotypes};
	croak "$sub: \"genotypes\" must be a hash ref of sample => genotypes, as hirisplex_genotypes returns, not " . _what($g)
		unless ref $g eq 'HASH';
	croak "$sub: \"genotypes\" has no samples" unless keys %{ $g };
	my ($beta, $traits, $category) = _trait_model($sub, $args->{model});

	# Which markers each trait's categories use between them: the same for every
	# sample, so it is worked out once rather than once per sample.
	my %uses;
	foreach my $t (@{ $traits }) {
		foreach my $c (@{ $category->{$t} }) {
			$uses{$t}{$_} = 1 foreach grep { $_ ne $Intercept } keys %{ $beta->{$t}{$c} };
		}

lib/Cn/Bioinf.pm  view on Meta::CPAN


A genotype is counted only when the call is diploid and complete: a C<./.>, a
C<./1>, a haploid call (the panel is autosomal) or one below C<min_depth> leaves
the marker without a genotype. A site split into one record per ALT is counted
from whichever record carries the counted allele, in either order, and a record
at a marker's position whose REF is longer than one base is some other variant
and is passed over.

C<hirisplex_genotypes> warns when the file holds none of the 41 markers, which
usually means the wrong build or an ID column of C<.>.

Reading the markers is done in XS, in one pass, keeping one byte per sample per
marker, so a whole-genome VCF costs no more memory than a small one. A
275,879-record exome of 22 MB gzipped took 0.86 s (perl 5.44.0, 2026-10-20).

Most of the panel is intronic or intergenic, so an exome carries little of it:
that same exome held 9 of the 41 markers. A whole-genome VCF, a genotyping
array that covers the panel, or the SNaPshot assay the panel was designed for
is what the prediction expects, and C<missing> and C<called> are returned so that
a prediction made from a handful of markers can be seen for what it is.

=head2 trait_predict(%args)

Applies a multinomial logistic regression -- which is what the HIrisPlex-S,
HIrisPlex and IrisPlex models are -- to genotypes, and returns a probability
for each category of each trait:

 use Cn::Bioinf qw(hirisplex_genotypes trait_predict);

 my $g = hirisplex_genotypes(vcf => 'genome.vcf.gz', report => 0);
 my $p = trait_predict(genotypes => $g, model => 'my_model.tsv');
 print $p->{NA12878}{eye}{call};          # the most probable category
 print $p->{NA12878}{eye}{p}{blue};       # its probability

The model is yours to supply: see C<hirisplex_genotypes> above for why this
distribution ships none. Any model written in the form below works, so this is
not limited to pigmentation.

=head3 The model table

A tab-separated file (optionally gzipped), or a data frame as
C<Stats::LikeR>'s C<read_table> returns, with four columns:

 trait    category    marker    beta
 eye    blue    (intercept)    3.94
 eye    blue    rs12913832_T    -4.81
 eye    brown    (intercept)    0

C<marker> is a key of the C<genotype> hash C<hirisplex_genotypes> returns, which
is C<< E<lt>rs numberE<gt>_E<lt>input alleleE<gt> >>, or the literal C<(intercept)> for the
category's intercept. A category whose only row is an intercept of 0 is the
reference category, which is how a model of I<k> categories is written with
I<k> - 1 sets of betas; every category that should appear in the result needs at
least one row. Traits and their categories come out in the order the table
first names them. A frame's rows and columns must be of one length, as
C<pgs_score>'s must, and a gzipped file that ends early dies.

For each category the linear predictor is its intercept plus the sum of its
betas times the genotypes, and the probabilities are C<exp> of those over their
sum. The largest is taken out before C<exp>, so a linear predictor large enough
to overflow gives 1 rather than a NaN.

=head3 Arguments

=over

=item * C<genotypes> (required): what C<hirisplex_genotypes> returned, or a plain hash
ref of sample => { marker => 0, 1 or 2 }. A dosage may be any number from 0
to 2, as imputation gives, and C<undef> is no genotype; anything else, C<NA>
included, dies naming the sample and the marker. Only the markers the model
uses are looked at.

=item * C<model> (required): the table above, as a file name or a data frame.

=item * C<force>: 0 (the default) makes no prediction for a trait that the genotypes
say cannot be predicted -- that is, where C<hirisplex_genotypes> set C<eye>,
C<hair> or C<skin> to 0; 1 predicts it anyway. A trait the genotypes say
nothing about is always predicted.

=item * C<report>: 1 (the default) prints a table of the samples to STDOUT; 0 returns
them only.

=back

=head3 What it returns

A hash ref keyed by sample and then by trait, each holding:

=over

=item * C<p>: a hash ref of category => probability, which sum to 1; empty when the
prediction was refused.

=item * C<call>: the most probable category, or C<undef> when it was refused. A tie is
broken by the category's name, so the answer does not depend on hash order.

=item * C<markers> and C<called>: how many markers the trait's categories use between
them, and how many this sample has a genotype for.

=item * C<missing>: an array ref of the markers the model names and the sample has no
genotype for.

=item * C<refused>: C<undef>, or why no prediction was made.

=back

A marker the sample has no genotype for drops out of the sum, which is the same
as counting it 0 copies of the counted allele. That is a choice, not something
the HIrisPlex-S authors specify, and it biases the result towards whatever 0
copies means for that marker; C<missing> and C<called> are returned so that a
prediction made from few markers can be reported as such. The webtool reports a
loss in AUC for exactly this reason.

=head2 plot_msa(%args)

Aligns sequences with Clustal Omega and draws the alignment. Returns a hash ref
of the files made: C<filename>, C<msa_file>, C<python_file> (see C<fh> and
C<execute> below), and C<tree_file> if it was given. Once the image is written it
prints C<wrote> and its file name to STDOUT, the name in black on yellow when
STDOUT is a terminal; with C<< execute =E<gt> 0 >> it prints C<will write> instead.



( run in 0.623 second using v1.01-cache-2.11-cpan-60884a8df76 )