-
Notifications
You must be signed in to change notification settings - Fork 24
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Moving karyotype
to anoph
#702
Open
jonbrenas
wants to merge
6
commits into
master
Choose a base branch
from
698-move-karyotype
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
cdda0a2
Moved karyotype to anoph
jonbrenas 19e99bc
Added tests
jonbrenas 64eb5ea
Changed the error for Af
jonbrenas 6649eca
Linting
jonbrenas f87e0da
Addressing comments
jonbrenas abcd9f8
Merge branch 'master' into 698-move-karyotype
jonbrenas File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
import pandas as pd # type: ignore | ||
from pandas import CategoricalDtype | ||
import numpy as np # type: ignore | ||
import allel # type: ignore | ||
|
||
from numpydoc_decorator import doc | ||
from ..util import check_types | ||
from . import base_params | ||
from typing import Optional | ||
|
||
from .snp_data import AnophelesSnpData | ||
from .karyotype_params import inversion_param | ||
|
||
|
||
def _karyotype_tags_n_alt(gt, alts, inversion_alts): | ||
# could be Numba'd for speed but was already quick (not many inversion tag snps) | ||
n_sites = gt.shape[0] | ||
n_samples = gt.shape[1] | ||
|
||
# create empty array | ||
inv_n_alt = np.empty((n_sites, n_samples), dtype=np.int8) | ||
|
||
# for every site | ||
for i in range(n_sites): | ||
# find the index of the correct tag snp allele | ||
tagsnp_index = np.where(alts[i] == inversion_alts[i])[0] | ||
|
||
for j in range(n_samples): | ||
# count alleles which == tag snp allele and store | ||
n_tag_alleles = np.sum(gt[i, j] == tagsnp_index[0]) | ||
inv_n_alt[i, j] = n_tag_alleles | ||
|
||
return inv_n_alt | ||
|
||
|
||
class AnophelesKaryotypeAnalysis(AnophelesSnpData): | ||
def __init__( | ||
self, | ||
inversion_tag_path: Optional[str] = None, | ||
**kwargs, | ||
): | ||
# N.B., this class is designed to work cooperatively, and | ||
# so it's important that any remaining parameters are passed | ||
# to the superclass constructor. | ||
super().__init__(**kwargs) | ||
|
||
self._inversion_tag_path = inversion_tag_path | ||
|
||
@check_types | ||
@doc( | ||
summary="Load tag SNPs for a given inversion.", | ||
) | ||
def load_inversion_tags(self, inversion: inversion_param) -> pd.DataFrame: | ||
# needs to be modified depending on where we are hosting | ||
import importlib.resources | ||
from .. import resources | ||
|
||
if not self._inversion_tag_path: | ||
raise FileNotFoundError( | ||
"The file containing the inversion tags is missing." | ||
) | ||
else: | ||
with importlib.resources.path(resources, self._inversion_tag_path) as path: | ||
df_tag_snps = pd.read_csv(path, sep=",") | ||
return df_tag_snps.query(f"inversion == '{inversion}'").reset_index() | ||
|
||
@check_types | ||
@doc( | ||
summary="Infer karyotype from tag SNPs for a given inversion in Ag.", | ||
jonbrenas marked this conversation as resolved.
Show resolved
Hide resolved
|
||
) | ||
def karyotype( | ||
self, | ||
inversion: inversion_param, | ||
sample_sets: Optional[base_params.sample_sets] = None, | ||
sample_query: Optional[base_params.sample_query] = None, | ||
sample_query_options: Optional[base_params.sample_query_options] = None, | ||
) -> pd.DataFrame: | ||
# load tag snp data | ||
df_tagsnps = self.load_inversion_tags(inversion=inversion) | ||
inversion_pos = df_tagsnps["position"] | ||
inversion_alts = df_tagsnps["alt_allele"] | ||
contig = inversion[0:2] | ||
|
||
# get snp calls for inversion region | ||
start, end = np.min(inversion_pos), np.max(inversion_pos) | ||
region = f"{contig}:{start}-{end}" | ||
|
||
ds_snps = self.snp_calls( | ||
region=region, | ||
sample_sets=sample_sets, | ||
sample_query=sample_query, | ||
sample_query_options=sample_query_options, | ||
) | ||
|
||
with self._spinner("Inferring karyotype from tag SNPs"): | ||
# access variables we need | ||
geno = allel.GenotypeDaskArray(ds_snps["call_genotype"].data) | ||
pos = allel.SortedIndex(ds_snps["variant_position"].values) | ||
samples = ds_snps["sample_id"].values | ||
alts = ds_snps["variant_allele"].values.astype(str) | ||
|
||
# subset to position of inversion tags | ||
mask = pos.locate_intersection(inversion_pos)[0] | ||
alts = alts[mask] | ||
geno = geno.compress(mask, axis=0).compute() | ||
|
||
# infer karyotype | ||
gn_alt = _karyotype_tags_n_alt( | ||
gt=geno, alts=alts, inversion_alts=inversion_alts | ||
) | ||
is_called = geno.is_called() | ||
|
||
# calculate mean genotype for each sample whilst masking missing calls | ||
av_gts = np.mean(np.ma.MaskedArray(gn_alt, mask=~is_called), axis=0) | ||
total_sites = np.sum(is_called, axis=0) | ||
|
||
df = pd.DataFrame( | ||
{ | ||
"sample_id": samples, | ||
"inversion": inversion, | ||
f"karyotype_{inversion}_mean": av_gts, | ||
# round the genotypes then convert to int | ||
f"karyotype_{inversion}": av_gts.round().astype(int), | ||
"total_tag_snps": total_sites, | ||
}, | ||
) | ||
# Allow filling missing values with "<NA>" visible placeholder. | ||
kt_dtype = CategoricalDtype(categories=[0, 1, 2, "<NA>"], ordered=True) | ||
df[f"karyotype_{inversion}"] = df[f"karyotype_{inversion}"].astype(kt_dtype) | ||
|
||
return df |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
"""Parameter definitions for karyotype analysis functions.""" | ||
|
||
|
||
from typing_extensions import Annotated, TypeAlias | ||
|
||
inversion_param: TypeAlias = Annotated[ | ||
str, | ||
"Name of inversion to infer karyotype for.", | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
FileNotFoundError
isn't quite the right exception class here.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I have been of two minds about this one: on one hand, it is true that we have not generated the tags for
Af1
and one could argue thatNotImplementedError
is a more appropriate error for work that is still to be done; on the other hand, the code itself would (I think) work if the file actually existed and it is thus less an issue of missing code and more an issue of a missing input. Also, I can imagine a situation where someone created tags for an inversion and would want to try to use their local file (it is not currently possible, the path that is used is hard-coded in bothAg3
andAf1
) in which case the error would come from the path being incorrect (though, an error message referring to the actual path inputed would be more helpful if we want to offer this option).