docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Load the hpo terms into the database
Parse the hpo lines, build the objects and add them to the database
Args:
adapter(MongoAdapter)
hpo_lines(iterable(str))
hpo_gene_lines(iterable(str)) | def load_hpo_terms(adapter, hpo_lines=None, hpo_gene_lines=None, alias_genes=None):
# Store the hpo terms
hpo_terms = {}
# Fetch the hpo terms if no file
if not hpo_lines:
hpo_lines = fetch_hpo_terms()
# Fetch the hpo gene information if no file
if not hpo_gene_lines:... | 615,245 |
Load the omim phenotypes into the database
Parse the phenotypes from genemap2.txt and find the associated hpo terms
from ALL_SOURCES_ALL_FREQUENCIES_diseases_to_genes_to_phenotypes.txt.
Args:
adapter(MongoAdapter)
genemap_lines(iterable(str))
genes(dict): Dictionary with all ge... | def load_disease_terms(adapter, genemap_lines, genes=None, hpo_disease_lines=None):
# Get a map with hgnc symbols to hgnc ids from scout
if not genes:
genes = adapter.genes_by_alias()
# Fetch the disease terms from omim
disease_terms = get_mim_phenotypes(genemap_lines=genemap_lines)
i... | 615,246 |
Add the frequencies to a variant
Frequencies are parsed either directly from keys in info fieds or from the
transcripts is they are annotated there.
Args:
variant(cyvcf2.Variant): A parsed vcf variant
transcripts(iterable(dict)): Parsed transcripts
Returns:
frequencies(dict): ... | def parse_frequencies(variant, transcripts):
frequencies = {}
# These lists could be extended...
thousand_genomes_keys = ['1000GAF']
thousand_genomes_max_keys = ['1000G_MAX_AF']
exac_keys = ['EXACAF']
exac_max_keys = ['ExAC_MAX_AF', 'EXAC_MAX_AF']
gnomad_keys = ['GNOMADAF', 'GNOMAD_AF... | 615,247 |
Parse any frequency from the info dict
Args:
variant(cyvcf2.Variant)
info_key(str)
Returns:
frequency(float): or None if frequency does not exist | def parse_frequency(variant, info_key):
raw_annotation = variant.INFO.get(info_key)
raw_annotation = None if raw_annotation == '.' else raw_annotation
frequency = float(raw_annotation) if raw_annotation else None
return frequency | 615,248 |
Parsing of some custom sv frequencies
These are very specific at the moment, this will hopefully get better over time when the
field of structural variants is more developed.
Args:
variant(cyvcf2.Variant)
Returns:
sv_frequencies(dict) | def parse_sv_frequencies(variant):
frequency_keys = [
'clingen_cgh_benignAF',
'clingen_cgh_benign',
'clingen_cgh_pathogenicAF',
'clingen_cgh_pathogenic',
'clingen_ngi',
'clingen_ngiAF',
'swegen',
'swegenAF',
'decipherAF',
'decipher... | 615,249 |
Load a case into the database
If the case already exists the function will exit.
If the user want to load a case that is already in the database
'update' has to be 'True'
Args:
adapter (MongoAdapter): connection to the database
case_obj (dict): case object to persist to the database
... | def load_case(adapter, case_obj, update=False):
logger.info('Loading case {} into database'.format(case_obj['display_name']))
# Check if case exists in database
existing_case = adapter.case(case_obj['_id'])
if existing_case:
if update:
adapter.update_case(case_obj)
els... | 615,251 |
Check if the latest version of OMIM differs from the most recent in database
Return all genes that where not in the previous version.
Args:
existing_panel(dict)
new_panel(dict)
Returns:
new_genes(set(str)) | def compare_mim_panels(self, existing_panel, new_panel):
existing_genes = set([gene['hgnc_id'] for gene in existing_panel['genes']])
new_genes = set([gene['hgnc_id'] for gene in new_panel['genes']])
return new_genes.difference(existing_genes) | 615,256 |
Set the correct version for each gene
Loop over the genes in the new panel
Args:
new_genes(set(str)): Set with the new gene symbols
new_panel(dict) | def update_mim_version(self, new_genes, new_panel, old_version):
LOG.info('Updating versions for new genes')
version = new_panel['version']
for gene in new_panel['genes']:
gene_symbol = gene['hgnc_id']
# If the gene is new we add the version
if gene_s... | 615,257 |
Add a gene panel to the database
Args:
panel_obj(dict) | def add_gene_panel(self, panel_obj):
panel_name = panel_obj['panel_name']
panel_version = panel_obj['version']
display_name = panel_obj.get('display_name', panel_name)
if self.gene_panel(panel_name, panel_version):
raise IntegrityError("Panel {0} with version {1} al... | 615,258 |
Fetch a gene panel by '_id'.
Args:
panel_id (str, ObjectId): str or ObjectId of document ObjectId
Returns:
dict: panel object or `None` if panel not found | def panel(self, panel_id):
if not isinstance(panel_id, ObjectId):
panel_id = ObjectId(panel_id)
panel_obj = self.panel_collection.find_one({'_id': panel_id})
return panel_obj | 615,259 |
Delete a panel by '_id'.
Args:
panel_obj(dict)
Returns:
res(pymongo.DeleteResult) | def delete_panel(self, panel_obj):
res = self.panel_collection.delete_one({'_id': panel_obj['_id']})
LOG.warning("Deleting panel %s, version %s" % (panel_obj['panel_name'], panel_obj['version']))
return res | 615,260 |
Fetch a gene panel.
If no panel is sent return all panels
Args:
panel_id (str): unique id for the panel
version (str): version of the panel. If 'None' latest version will be returned
Returns:
gene_panel: gene panel object | def gene_panel(self, panel_id, version=None):
query = {'panel_name': panel_id}
if version:
LOG.info("Fetch gene panel {0}, version {1} from database".format(
panel_id, version
))
query['version'] = version
return self.panel_collect... | 615,261 |
Return all gene panels
If panel_id return all versions of panels by that panel name
Args:
panel_id(str)
Returns:
cursor(pymongo.cursor) | def gene_panels(self, panel_id=None, institute_id=None, version=None):
query = {}
if panel_id:
query['panel_name'] = panel_id
if version:
query['version'] = version
if institute_id:
query['institute'] = institute_id
return sel... | 615,262 |
Fetch all gene panels and group them by gene
Args:
case_obj(scout.models.Case)
Returns:
gene_dict(dict): A dictionary with gene as keys and a set of
panel names as value | def gene_to_panels(self, case_obj):
LOG.info("Building gene to panels")
gene_dict = {}
for panel_info in case_obj.get('panels', []):
panel_name = panel_info['panel_name']
panel_version = panel_info['version']
panel_obj = self.gene_panel(panel_name, v... | 615,263 |
Replace a existing gene panel with a new one
Keeps the object id
Args:
panel_obj(dict)
version(float)
date_obj(datetime.datetime)
Returns:
updated_panel(dict) | def update_panel(self, panel_obj, version=None, date_obj=None):
LOG.info("Updating panel %s", panel_obj['panel_name'])
# update date of panel to "today"
date = panel_obj['date']
if version:
LOG.info("Updating version from {0} to version {1}".format(
p... | 615,264 |
Apply the pending changes to an existing gene panel or create a new version of the same panel.
Args:
panel_obj(dict): panel in database to update
version(double): panel version to update
Returns:
inserted_id(str): id of updated panel or the new one | def apply_pending(self, panel_obj, version):
updates = {}
new_panel = deepcopy(panel_obj)
new_panel['pending'] = []
new_panel['date'] = dt.datetime.now()
info_fields = ['disease_associated_transcripts', 'inheritance_models', 'reduced_penetrance',
'mosaicism'... | 615,266 |
Return a list with the current indexes
Skip the mandatory _id_ indexes
Args:
collection(str)
Returns:
indexes(list) | def indexes(self, collection=None):
indexes = []
for collection_name in self.collections():
if collection and collection != collection_name:
continue
for index_name in self.db[collection_name].index_information():
if index_name !... | 615,271 |
Add clinsig filter values to the mongo query object
Args:
query(dict): a dictionary of query filters specified by the users
mongo_query(dict): the query that is going to be submitted to the database
Returns:
clinsig_query(dict): a dictionary with... | def clinsig_query(self, query, mongo_query):
LOG.debug('clinsig is a query parameter')
trusted_revision_level = ['mult', 'single', 'exp', 'guideline']
rank = []
str_rank = []
clnsig_query = {}
for item in query['clinsig']:
rank.append(int(item))
... | 615,277 |
Adds genomic coordinated-related filters to the query object
Args:
query(dict): a dictionary of query filters specified by the users
mongo_query(dict): the query that is going to be submitted to the database
Returns:
mongo_query(dict): returned object contains coord... | def coordinate_filter(self, query, mongo_query):
LOG.debug('Adding genomic coordinates to the query')
chromosome = query['chrom']
mongo_query['chromosome'] = chromosome
if (query.get('start') and query.get('end')):
mongo_query['position'] = {'$lte': int(query['end']... | 615,278 |
Adds gene-related filters to the query object
Args:
query(dict): a dictionary of query filters specified by the users
mongo_query(dict): the query that is going to be submitted to the database
Returns:
mongo_query(dict): returned object contains gene and panel-relat... | def gene_filter(self, query, mongo_query):
LOG.debug('Adding panel and genes-related parameters to the query')
gene_query = []
if query.get('hgnc_symbols') and query.get('gene_panels'):
gene_query.append({'hgnc_symbols': {'$in': query['hgnc_symbols']}})
gene_qu... | 615,279 |
Creates a secondary query object based on secondary parameters specified by user
Args:
query(dict): a dictionary of query filters specified by the users
mongo_query(dict): the query that is going to be submitted to the database
Returns:
mongo_sec... | def secondary_query(self, query, mongo_query, secondary_filter=None):
LOG.debug('Creating a query object with secondary parameters')
mongo_secondary_query = []
# loop over secondary query criteria
for criterion in SECONDARY_CRITERIA:
if not query.get(criterion):
... | 615,280 |
Load a bulk of hgnc gene objects
Raises IntegrityError if there are any write concerns
Args:
gene_objs(iterable(scout.models.hgnc_gene))
Returns:
result (pymongo.results.InsertManyResult) | def load_hgnc_bulk(self, gene_objs):
LOG.info("Loading gene bulk with length %s", len(gene_objs))
try:
result = self.hgnc_collection.insert_many(gene_objs)
except (DuplicateKeyError, BulkWriteError) as err:
raise IntegrityError(err)
return result | 615,284 |
Load a bulk of transcript objects to the database
Arguments:
transcript_objs(iterable(scout.models.hgnc_transcript)) | def load_transcript_bulk(self, transcript_objs):
LOG.info("Loading transcript bulk")
try:
result = self.transcript_collection.insert_many(transcript_objs)
except (DuplicateKeyError, BulkWriteError) as err:
raise IntegrityError(err)
return result | 615,285 |
Load a bulk of exon objects to the database
Arguments:
exon_objs(iterable(scout.models.hgnc_exon)) | def load_exon_bulk(self, exon_objs):
try:
result = self.exon_collection.insert_many(transcript_objs)
except (DuplicateKeyError, BulkWriteError) as err:
raise IntegrityError(err)
return result | 615,286 |
Fetch a hgnc gene
Args:
hgnc_identifier(int)
Returns:
gene_obj(HgncGene) | def hgnc_gene(self, hgnc_identifier, build='37'):
if not build in ['37', '38']:
build = '37'
query = {}
try:
# If the identifier is a integer we search for hgnc_id
hgnc_identifier = int(hgnc_identifier)
query['hgnc_id'] = hgnc_identifier
... | 615,287 |
Query the genes with a hgnc symbol and return the hgnc id
Args:
hgnc_symbol(str)
build(str)
Returns:
hgnc_id(int) | def hgnc_id(self, hgnc_symbol, build='37'):
#LOG.debug("Fetching gene %s", hgnc_symbol)
query = {'hgnc_symbol':hgnc_symbol, 'build':build}
projection = {'hgnc_id':1, '_id':0}
res = self.hgnc_collection.find(query, projection)
if res.count() > 0:
return res[0... | 615,288 |
Fetch all hgnc genes that match a hgnc symbol
Check both hgnc_symbol and aliases
Args:
hgnc_symbol(str)
build(str): The build in which to search
search(bool): if partial searching should be used
Returns:
result() | def hgnc_genes(self, hgnc_symbol, build='37', search=False):
LOG.debug("Fetching genes with symbol %s" % hgnc_symbol)
if search:
# first search for a full match
full_query = self.hgnc_collection.find({
'$or': [
{'aliases': hgnc_symbol}... | 615,289 |
Return a dictionary with ensembl ids as keys and transcripts as value.
Args:
build(str)
Returns:
ensembl_transcripts(dict): {<enst_id>: transcripts_obj, ...} | def ensembl_transcripts(self, build='37'):
ensembl_transcripts = {}
LOG.info("Fetching all transcripts")
for transcript_obj in self.transcript_collection.find({'build':build}):
enst_id = transcript_obj['transcript_id']
ensembl_transcripts[enst_id] = transcript_ob... | 615,295 |
Return a dictionary with hgnc_symbol as key and gene_obj as value
The result will have ONE entry for each gene in the database.
(For a specific build)
Args:
build(str)
genes(iterable(scout.models.HgncGene)):
Returns:
hgnc_dict(dict): {<hgnc_symbol(s... | def hgncsymbol_to_gene(self, build='37', genes=None):
hgnc_dict = {}
LOG.info("Building hgncsymbol_to_gene")
if not genes:
genes = self.hgnc_collection.find({'build':build})
for gene_obj in genes:
hgnc_dict[gene_obj['hgnc_symbol']] = gene_obj
LOG... | 615,296 |
Return a iterable with hgnc_genes.
If the gene symbol is listed as primary the iterable will only have
one result. If not the iterable will include all hgnc genes that have
the symbol as an alias.
Args:
symbol(str)
build(str)
Returns:
res(py... | def gene_by_alias(self, symbol, build='37'):
res = self.hgnc_collection.find({'hgnc_symbol': symbol, 'build':build})
if res.count() == 0:
res = self.hgnc_collection.find({'aliases': symbol, 'build':build})
return res | 615,297 |
Return a dictionary with hgnc symbols as keys and a list of hgnc ids
as value.
If a gene symbol is listed as primary the list of ids will only consist
of that entry if not the gene can not be determined so the result is a list
of hgnc_ids
Args:
build(str)
... | def genes_by_alias(self, build='37', genes=None):
LOG.info("Fetching all genes by alias")
# Collect one entry for each alias symbol that exists
alias_genes = {}
# Loop over all genes
if not genes:
genes = self.hgnc_collection.find({'build':build})
fo... | 615,298 |
Return a set with identifier transcript(s)
Choose all refseq transcripts with NM symbols, if none where found choose ONE with NR,
if no NR choose ONE with XM. If there are no RefSeq transcripts identifiers choose the
longest ensembl transcript.
Args:
hgnc_id(int)
... | def get_id_transcripts(self, hgnc_id, build='37'):
transcripts = self.transcripts(build=build, hgnc_id=hgnc_id)
identifier_transcripts = set()
longest = None
nr = []
xm = []
for tx in transcripts:
enst_id = tx['transcript_id']
# Should we... | 615,299 |
Return a dictionary with hgnc_id as keys and a list of transcripts as value
Args:
build(str)
Returns:
hgnc_transcripts(dict) | def transcripts_by_gene(self, build='37'):
hgnc_transcripts = {}
LOG.info("Fetching all transcripts")
for transcript in self.transcript_collection.find({'build':build}):
hgnc_id = transcript['hgnc_id']
if not hgnc_id in hgnc_transcripts:
hgnc_tran... | 615,300 |
Return a dictionary with hgnc_id as keys and a set of id transcripts as value
Args:
build(str)
Returns:
hgnc_id_transcripts(dict) | def id_transcripts_by_gene(self, build='37'):
hgnc_id_transcripts = {}
LOG.info("Fetching all id transcripts")
for gene_obj in self.hgnc_collection.find({'build': build}):
hgnc_id = gene_obj['hgnc_id']
id_transcripts = self.get_id_transcripts(hgnc_id=hgnc_id, bui... | 615,301 |
Return a dictionary with ensembl ids as keys and gene objects as value.
Args:
build(str)
Returns:
genes(dict): {<ensg_id>: gene_obj, ...} | def ensembl_genes(self, build='37'):
genes = {}
LOG.info("Fetching all genes")
for gene_obj in self.hgnc_collection.find({'build':build}):
ensg_id = gene_obj['ensembl_id']
hgnc_id = gene_obj['hgnc_id']
genes[ensg_id] = gene_obj
... | 615,302 |
Return all transcripts.
If a gene is specified return all transcripts for the gene
Args:
build(str)
hgnc_id(int)
Returns:
iterable(transcript) | def transcripts(self, build='37', hgnc_id=None):
query = {'build': build}
if hgnc_id:
query['hgnc_id'] = hgnc_id
return self.transcript_collection.find(query) | 615,303 |
Check if a hgnc symbol is an alias
Return the correct hgnc symbol, if not existing return None
Args:
hgnc_alias(str)
Returns:
hgnc_symbol(str) | def to_hgnc(self, hgnc_alias, build='37'):
result = self.hgnc_genes(hgnc_symbol=hgnc_alias, build=build)
if result:
for gene in result:
return gene['hgnc_symbol']
else:
return None | 615,304 |
Add the correct hgnc id to a set of genes with hgnc symbols
Args:
genes(list(dict)): A set of genes with hgnc symbols only | def add_hgnc_id(self, genes):
genes_by_alias = self.genes_by_alias()
for gene in genes:
id_info = genes_by_alias.get(gene['hgnc_symbol'])
if not id_info:
LOG.warning("Gene %s does not exist in scout", gene['hgnc_symbol'])
continue
... | 615,305 |
Return a dictionary with chromosomes as keys and interval trees as values
Each interval represents a coding region of overlapping genes.
Args:
build(str): The genome build
genes(iterable(scout.models.HgncGene)):
Returns:
intervals(dict): A dictionary with c... | def get_coding_intervals(self, build='37', genes=None):
intervals = {}
if not genes:
genes = self.all_genes(build=build)
LOG.info("Building interval trees...")
for i,hgnc_obj in enumerate(genes):
chrom = hgnc_obj['chromosome']
start = max((hgn... | 615,306 |
Create exon objects and insert them into the database
Args:
exons(iterable(dict)) | def load_exons(self, exons, genes=None, build='37'):
genes = genes or self.ensembl_genes(build)
for exon in exons:
exon_obj = build_exon(exon, genes)
if not exon_obj:
continue
res = self.exon_collection.insert_one(exon_obj) | 615,307 |
Return all exons
Args:
hgnc_id(int)
transcript_id(str)
build(str)
Returns:
exons(iterable(dict)) | def exons(self, hgnc_id=None, transcript_id=None, build=None):
query = {}
if build:
query['build'] = build
if hgnc_id:
query['hgnc_id'] = hgnc_id
if transcript_id:
query['transcript_id'] = transcript_id
return self.exon_colle... | 615,308 |
Preprocess case objects.
Add the necessary information to display the 'cases' view
Args:
store(adapter.MongoAdapter)
case_query(pymongo.Cursor)
limit(int): Maximum number of cases to display
Returns:
data(dict): includes the cases, how many there are and the limit. | def cases(store, case_query, limit=100):
case_groups = {status: [] for status in CASE_STATUSES}
for case_obj in case_query.limit(limit):
analysis_types = set(ind['analysis_type'] for ind in case_obj['individuals'])
case_obj['analysis_types'] = list(analysis_types)
case_obj['assign... | 615,344 |
Preprocess a single case.
Prepare the case to be displayed in the case view.
Args:
store(adapter.MongoAdapter)
institute_obj(models.Institute)
case_obj(models.Case)
Returns:
data(dict): includes the cases, how many there are and the limit. | def case(store, institute_obj, case_obj):
# Convert individual information to more readable format
case_obj['individual_ids'] = []
for individual in case_obj['individuals']:
try:
sex = int(individual.get('sex', 0))
except ValueError as err:
sex = 0
indivi... | 615,345 |
Gather contents to be visualized in a case report
Args:
store(adapter.MongoAdapter)
institute_obj(models.Institute)
case_obj(models.Case)
Returns:
data(dict) | def case_report_content(store, institute_obj, case_obj):
variant_types = {
'causatives_detailed': 'causatives',
'suspects_detailed': 'suspects',
'classified_detailed': 'acmg_classification',
'tagged_detailed': 'manual_rank',
'dismissed_detailed': 'dismiss_variant',
... | 615,346 |
Posts a request to chanjo-report and capture the body of the returned response to include it in case report
Args:
store(adapter.MongoAdapter)
institute_obj(models.Institute)
case_obj(models.Case)
base_url(str): base url of server
Returns:
coverage_data(str): string rend... | def coverage_report_contents(store, institute_obj, case_obj, base_url):
request_data = {}
# extract sample ids from case_obj and add them to the post request object:
request_data['sample_id'] = [ ind['individual_id'] for ind in case_obj['individuals'] ]
# extract default panel names and default g... | 615,347 |
Collect MT variants and format line of a MT variant report
to be exported in excel format
Args:
store(adapter.MongoAdapter)
case_obj(models.Case)
temp_excel_dir(os.Path): folder where the temp excel files are written to
Returns:
written_files(int): the number of files writt... | def mt_excel_files(store, case_obj, temp_excel_dir):
today = datetime.datetime.now().strftime('%Y-%m-%d')
samples = case_obj.get('individuals')
query = {'chrom':'MT'}
mt_variants = list(store.variants(case_id=case_obj['_id'], query=query, nr_of_variants= -1, sort_key='position'))
written_file... | 615,349 |
Return the list of HGNC symbols that match annotated HPO terms.
Args:
username (str): username to use for phenomizer connection
password (str): password to use for phenomizer connection
Returns:
query_result: a generator of dictionaries on the form
{
'p_value': floa... | def hpo_diseases(username, password, hpo_ids, p_value_treshold=1):
# skip querying Phenomizer unless at least one HPO terms exists
try:
results = query_phenomizer.query(username, password, *hpo_ids)
diseases = [result for result in results
if result['p_value'] <= p_value... | 615,351 |
Get all variants for an institute having Sanger validations ordered but still not evaluated
Args:
store(scout.adapter.MongoAdapter)
institute_id(str)
Returns:
unevaluated: a list that looks like this: [ {'case1': [varID_1, varID_2, .., varID_n]}, {'case2' : [varID_1... | def get_sanger_unevaluated(store, institute_id, user_id):
# Retrieve a list of ids for variants with Sanger ordered grouped by case from the 'event' collection
# This way is much faster than querying over all variants in all cases of an institute
sanger_ordered_by_case = store.sanger_ordered(institute... | 615,357 |
Delete all affected samples for a case from MatchMaker
Args:
case_obj(dict) a scout case object
mme_base_url(str) base url of the MME server
mme_token(str) auth token of the MME server
Returns:
server_responses(list): a list of object of this type:
{
... | def mme_delete(case_obj, mme_base_url, mme_token):
server_responses = []
if not mme_base_url or not mme_token:
return 'Please check that Matchmaker connection parameters are valid'
# for each patient of the case in matchmaker
for patient in case_obj['mme_submission']['patients']:
... | 615,359 |
Show Matchmaker submission data for a sample and eventual matches.
Args:
case_obj(dict): a scout case object
institute_obj(dict): an institute object
mme_base_url(str) base url of the MME server
mme_token(str) auth token of the MME server
Returns:
data(dict): data to di... | def mme_matches(case_obj, institute_obj, mme_base_url, mme_token):
data = {
'institute' : institute_obj,
'case' : case_obj,
'server_errors' : []
}
matches = {}
# loop over the submitted samples and get matches from the MatchMaker server
if not case_obj.get('mme_submissio... | 615,360 |
Initiate a MatchMaker match against either other Scout patients or external nodes
Args:
case_obj(dict): a scout case object already submitted to MME
match_type(str): 'internal' or 'external'
mme_base_url(str): base url of the MME server
mme_token(str): auth token of the MME server
... | def mme_match(case_obj, match_type, mme_base_url, mme_token, nodes=None, mme_accepts=None):
query_patients = []
server_responses = []
url = None
# list of patient dictionaries is required for internal matching
query_patients = case_obj['mme_submission']['patients']
if match_type=='internal'... | 615,361 |
Parse how the different variant callers have performed
Args:
variant (cyvcf2.Variant): A variant object
Returns:
callers (dict): A dictionary on the format
{'gatk': <filter>,'freebayes': <filter>,'samtools': <filter>} | def parse_callers(variant, category='snv'):
relevant_callers = CALLERS[category]
callers = {caller['id']: None for caller in relevant_callers}
raw_info = variant.INFO.get('set')
if raw_info:
info = raw_info.split('-')
for call in info:
if call == 'FilteredInAll':
... | 615,364 |
Get the format from a vcf header line description
If format begins with white space it will be stripped
Args:
description(str): Description from a vcf header line
Return:
format(str): The format information from description | def parse_header_format(description):
description = description.strip('"')
keyword = 'Format:'
before_keyword, keyword, after_keyword = description.partition(keyword)
return after_keyword.strip() | 615,365 |
Return a list with the VEP header
The vep header is collected from CSQ in the vcf file
All keys are capitalized
Args:
vcf_obj(cyvcf2.VCF)
Returns:
vep_header(list) | def parse_vep_header(vcf_obj):
vep_header = []
if 'CSQ' in vcf_obj:
# This is a dictionary
csq_info = vcf_obj['CSQ']
format_info = parse_header_format(csq_info['Description'])
vep_header = [key.upper() for key in format_info.split('|')]
return vep_header | 615,366 |
Build a hgnc_transcript object
Args:
transcript_info(dict): Transcript information
Returns:
transcript_obj(HgncTranscript)
{
transcript_id: str, required
hgnc_id: int, required
build: str, required
refs... | def build_transcript(transcript_info, build='37'):
try:
transcript_id = transcript_info['ensembl_transcript_id']
except KeyError:
raise KeyError("Transcript has to have ensembl id")
build = build
is_primary = transcript_info.get('is_primary', False)
refseq_id = transcr... | 615,367 |
Load a institute into the database
Args:
adapter(MongoAdapter)
internal_id(str)
display_name(str)
sanger_recipients(list(email)) | def load_institute(adapter, internal_id, display_name, sanger_recipients=None):
institute_obj = build_institute(
internal_id=internal_id,
display_name=display_name,
sanger_recipients=sanger_recipients
)
log.info("Loading institute {0} with display name {1}" \
" int... | 615,368 |
Update one variant document in the database.
This means that the variant in the database will be replaced by variant_obj.
Args:
variant_obj(dict)
Returns:
new_variant(dict) | def update_variant(self, variant_obj):
LOG.debug('Updating variant %s', variant_obj.get('simple_id'))
new_variant = self.variant_collection.find_one_and_replace(
{'_id': variant_obj['_id']},
variant_obj,
return_document=pymongo.ReturnDocument.AFTER
)... | 615,371 |
Updates the manual rank for all variants in a case
Add a variant rank based on the rank score
Whenever variants are added or removed from a case we need to update the variant rank
Args:
case_obj(Case)
variant_type(str) | def update_variant_rank(self, case_obj, variant_type='clinical', category='snv'):
# Get all variants sorted by rank score
variants = self.variant_collection.find({
'case_id': case_obj['_id'],
'category': category,
'variant_type': variant_type,
}).sort... | 615,372 |
Update compounds for a variant.
This will add all the necessary information of a variant on a compound object.
Args:
variant(scout.models.Variant)
variant_objs(dict): A dictionary with _ids as keys and variant objs as values.
Returns:
compound_objs(list(dic... | def update_variant_compounds(self, variant, variant_objs = None):
compound_objs = []
for compound in variant.get('compounds', []):
not_loaded = True
gene_objs = []
# Check if the compound variant exists
if variant_objs:
variant_obj... | 615,373 |
Update the compounds for a set of variants.
Args:
variants(dict): A dictionary with _ids as keys and variant objs as values | def update_compounds(self, variants):
LOG.debug("Updating compound objects")
for var_id in variants:
variant_obj = variants[var_id]
if not variant_obj.get('compounds'):
continue
updated_compounds = self.update_variant_compounds(variant_obj, ... | 615,374 |
Update the compound information for a bulk of variants in the database
Args:
bulk(dict): {'_id': scout.models.Variant} | def update_mongo_compound_variants(self, bulk):
requests = []
for var_id in bulk:
var_obj = bulk[var_id]
if not var_obj.get('compounds'):
continue
# Add a request to update compounds
operation = pymongo.UpdateOne(
{... | 615,375 |
Load a variant object
Args:
variant_obj(dict)
Returns:
inserted_id | def load_variant(self, variant_obj):
# LOG.debug("Loading variant %s", variant_obj['_id'])
try:
result = self.variant_collection.insert_one(variant_obj)
except DuplicateKeyError as err:
raise IntegrityError("Variant %s already exists in database", variant_obj['_i... | 615,377 |
Load a variant object, if the object already exists update compounds.
Args:
variant_obj(dict)
Returns:
result | def upsert_variant(self, variant_obj):
LOG.debug("Upserting variant %s", variant_obj['_id'])
try:
result = self.variant_collection.insert_one(variant_obj)
except DuplicateKeyError as err:
LOG.debug("Variant %s already exists in database", variant_obj['_id'])
... | 615,378 |
Load a bulk of variants
Args:
variants(iterable(scout.models.Variant))
Returns:
object_ids | def load_variant_bulk(self, variants):
if not len(variants) > 0:
return
LOG.debug("Loading variant bulk")
try:
result = self.variant_collection.insert_many(variants)
except (DuplicateKeyError, BulkWriteError) as err:
# If the bulk write is wr... | 615,379 |
Assign a user to a case.
This function will create an Event to log that a person has been assigned
to a case. Also the user will be added to case "assignees".
Arguments:
institute (dict): A institute
case (dict): A case
user (dict): A User object
... | def assign(self, institute, case, user, link):
LOG.info("Creating event for assigning {0} to {1}"
.format(user['name'].encode('utf-8'), case['display_name']))
self.create_event(
institute=institute,
case=case,
user=user,
link=... | 615,382 |
Share a case with a new institute.
Arguments:
institute (dict): A Institute object
case (dict): Case object
collaborator_id (str): A instute id
user (dict): A User object
link (str): The url to be used in the event
Return:
updated... | def share(self, institute, case, collaborator_id, user, link):
if collaborator_id in case.get('collaborators', []):
raise ValueError('new customer is already a collaborator')
self.create_event(
institute=institute,
case=case,
user=user,
... | 615,383 |
Diagnose a case using OMIM ids.
Arguments:
institute (dict): A Institute object
case (dict): Case object
user (dict): A User object
link (str): The url to be used in the event
level (str): choices=('phenotype','gene')
Return:
upda... | def diagnose(self, institute, case, user, link, level, omim_id, remove=False):
if level == 'phenotype':
case_key = 'diagnosis_phenotypes'
elif level == 'gene':
case_key = 'diagnosis_genes'
else:
raise TypeError('wrong level')
diagnosis_list =... | 615,384 |
Mark a case as checked from an analysis point of view.
Arguments:
institute (dict): A Institute object
case (dict): Case object
user (dict): A User object
link (str): The url to be used in the event
unmark (bool): If case should ve unmarked
R... | def mark_checked(self, institute, case, user, link,
unmark=False):
LOG.info("Updating checked status of {}"
.format(case['display_name']))
status = 'not checked' if unmark else 'checked'
self.create_event(
institute=institute,
... | 615,385 |
Update default panels for a case.
Arguments:
institute_obj (dict): A Institute object
case_obj (dict): Case object
user_obj (dict): A User object
link (str): The url to be used in the event
panel_objs (list(dict)): List of panel objs
Return:
... | def update_default_panels(self, institute_obj, case_obj, user_obj, link, panel_objs):
self.create_event(
institute=institute_obj,
case=case_obj,
user=user_obj,
link=link,
category='case',
verb='update_default_panels',
s... | 615,386 |
Create an event for a variant verification for a variant
and an event for a variant verification for a case
Arguments:
institute (dict): A Institute object
case (dict): Case object
user (dict): A User object
link (str): The url to be used in the event
... | def order_verification(self, institute, case, user, link, variant):
LOG.info("Creating event for ordering validation for variant" \
" {0}".format(variant['display_name']))
updated_variant = self.variant_collection.find_one_and_update(
{'_id': variant['_id']},
... | 615,387 |
Get all variants with validations ever ordered.
Args:
institute_id(str) : The id of an institute
user_id(str) : The id of an user
Returns:
sanger_ordered(list) : a list of dictionaries, each with "case_id" as keys and list of variant ids as values | def sanger_ordered(self, institute_id=None, user_id=None):
query = {'$match': {
'$and': [
{'verb': 'sanger'},
],
}}
if institute_id:
query['$match']['$and'].append({'institute': institute_id})
if user_id:
... | 615,388 |
Mark validation status for a variant.
Arguments:
institute (dict): A Institute object
case (dict): Case object
user (dict): A User object
link (str): The url to be used in the event
variant (dict): A variant object
validate_type(str): The ... | def validate(self, institute, case, user, link, variant, validate_type):
if not validate_type in SANGER_OPTIONS:
LOG.warning("Invalid validation string: %s", validate_type)
LOG.info("Validation options: %s", ', '.join(SANGER_OPTIONS))
return
updated_variant ... | 615,389 |
Create an event for marking a variant causative.
Arguments:
institute (dict): A Institute object
case (dict): Case object
user (dict): A User object
link (str): The url to be used in the event
variant (variant): A variant object
Returns:
up... | def mark_causative(self, institute, case, user, link, variant):
display_name = variant['display_name']
LOG.info("Mark variant {0} as causative in the case {1}".format(
display_name, case['display_name']))
LOG.info("Adding variant to causatives in case {0}".format(
... | 615,390 |
Create an event for updating the ACMG classification of a variant.
Arguments:
institute_obj (dict): A Institute object
case_obj (dict): Case object
user_obj (dict): A User object
link (str): The url to be used in the event
variant_obj (dict): A varian... | def update_acmg(self, institute_obj, case_obj, user_obj, link, variant_obj, acmg_str):
self.create_event(
institute=institute_obj,
case=case_obj,
user=user_obj,
link=link,
category='variant',
verb='acmg',
variant=varian... | 615,392 |
Construct the necessary ids for a variant
Args:
chrom(str): Variant chromosome
pos(int): Variant position
ref(str): Variant reference
alt(str): Variant alternative
case_id(str): Unique case id
variant_type(str): 'clinical' or 'research'
Returns:
ids(dict... | def parse_ids(chrom, pos, ref, alt, case_id, variant_type):
ids = {}
pos = str(pos)
ids['simple_id'] = parse_simple_id(chrom, pos, ref, alt)
ids['variant_id'] = parse_variant_id(chrom, pos, ref, alt, variant_type)
ids['display_name'] = parse_display_name(chrom, pos, ref, alt, variant_type)
... | 615,393 |
Parse the simple id for a variant
Simple id is used as a human readable reference for a position, it is
in no way unique.
Args:
chrom(str)
pos(str)
ref(str)
alt(str)
Returns:
simple_id(str): The simple human readable variant id | def parse_simple_id(chrom, pos, ref, alt):
return '_'.join([chrom, pos, ref, alt]) | 615,394 |
Parse the variant id for a variant
variant_id is used to identify variants within a certain type of
analysis. It is not human readable since it is a md5 key.
Args:
chrom(str)
pos(str)
ref(str)
alt(str)
variant_type(str): 'clinical' or 'research'
Returns:
... | def parse_variant_id(chrom, pos, ref, alt, variant_type):
return generate_md5_key([chrom, pos, ref, alt, variant_type]) | 615,395 |
Parse the variant id for a variant
This is used to display the variant in scout.
Args:
chrom(str)
pos(str)
ref(str)
alt(str)
variant_type(str): 'clinical' or 'research'
Returns:
variant_id(str): The variant id in human readable format | def parse_display_name(chrom, pos, ref, alt, variant_type):
return '_'.join([chrom, pos, ref, alt, variant_type]) | 615,396 |
Parse the unique document id for a variant.
This will always be unique in the database.
Args:
chrom(str)
pos(str)
ref(str)
alt(str)
variant_type(str): 'clinical' or 'research'
case_id(str): unqiue family id
Returns:
document_id(str): The unique docu... | def parse_document_id(chrom, pos, ref, alt, variant_type, case_id):
return generate_md5_key([chrom, pos, ref, alt, variant_type, case_id]) | 615,397 |
Create a new variant id.
Args:
variant_obj(dict)
family_id(str)
Returns:
new_id(str): The new variant id | def get_variantid(variant_obj, family_id):
new_id = parse_document_id(
chrom=variant_obj['chromosome'],
pos=str(variant_obj['position']),
ref=variant_obj['reference'],
alt=variant_obj['alternative'],
variant_type=variant_obj['variant_type'],
case_id=family_id,
... | 615,401 |
Return the number of cases
This function will change when we migrate to 3.7.1
Args:
collaborator(str): Institute id
Returns:
nr_cases(int) | def nr_cases(self, institute_id=None):
query = {}
if institute_id:
query['collaborators'] = institute_id
LOG.debug("Fetch all cases with query {0}".format(query))
nr_cases = self.case_collection.find(query).count()
return nr_cases | 615,403 |
Update the dynamic gene list for a case
Adds a list of dictionaries to case['dynamic_gene_list'] that looks like
{
hgnc_symbol: str,
hgnc_id: int,
description: str
}
Arguments:
case (dict): The case that should be updated
hgn... | def update_dynamic_gene_list(self, case, hgnc_symbols=None, hgnc_ids=None,
phenotype_ids=None, build='37'):
dynamic_gene_list = []
res = []
if hgnc_ids:
LOG.info("Fetching genes by hgnc id")
res = self.hgnc_collection.find({'hgnc_... | 615,404 |
Fetches a single case from database
Use either the _id or combination of institute_id and display_name
Args:
case_id(str): _id for a caes
institute_id(str):
display_name(str)
Yields:
A single Case | def case(self, case_id=None, institute_id=None, display_name=None):
query = {}
if case_id:
query['_id'] = case_id
LOG.info("Fetching case %s", case_id)
else:
if not (institute_id and display_name):
raise ValueError("Have to provide bot... | 615,405 |
Delete a single case from database
Args:
institute_id(str)
case_id(str)
Returns:
case_obj(dict): The case that was deleted | def delete_case(self, case_id=None, institute_id=None, display_name=None):
query = {}
if case_id:
query['_id'] = case_id
LOG.info("Deleting case %s", case_id)
else:
if not (institute_id and display_name):
raise ValueError("Have to prov... | 615,406 |
Load a case into the database
Check if the owner and the institute exists.
Args:
config_data(dict): A dictionary with all the necessary information
update(bool): If existing case should be updated
Returns:
case_obj(dict) | def load_case(self, config_data, update=False):
# Check that the owner exists in the database
institute_obj = self.institute(config_data['owner'])
if not institute_obj:
raise IntegrityError("Institute '%s' does not exist in database" % config_data['owner'])
# Parse ... | 615,407 |
Add a case to the database
If the case already exists exception is raised
Args:
case_obj(Case) | def _add_case(self, case_obj):
if self.case(case_obj['_id']):
raise IntegrityError("Case %s already exists in database" % case_obj['_id'])
return self.case_collection.insert_one(case_obj) | 615,408 |
Replace a existing case with a new one
Keeps the object id
Args:
case_obj(dict)
Returns:
updated_case(dict) | def replace_case(self, case_obj):
# Todo: Figure out and describe when this method destroys a case if invoked instead of
# update_case
LOG.info("Saving case %s", case_obj['_id'])
# update updated_at of case to "today"
case_obj['updated_at'] = datetime.datetime.now(),
... | 615,410 |
Update case id for a case across the database.
This function is used when a case is a rerun or updated for another reason.
Args:
case_obj(dict)
family_id(str): The new family id
Returns:
new_case(dict): The updated case object | def update_caseid(self, case_obj, family_id):
new_case = deepcopy(case_obj)
new_case['_id'] = family_id
# update suspects and causatives
for case_variants in ['suspects', 'causatives']:
new_variantids = []
for variant_id in case_obj.get(case_variants, []... | 615,411 |
Submit an evaluation to the database
Get all the relevant information, build a evaluation_obj
Args:
variant_obj(dict)
user_obj(dict)
institute_obj(dict)
case_obj(dict)
link(str): variant url
criteria(list(dict)):
... | def submit_evaluation(self, variant_obj, user_obj, institute_obj, case_obj, link, criteria):
variant_specific = variant_obj['_id']
variant_id = variant_obj['variant_id']
user_id = user_obj['_id']
user_name = user_obj.get('name', user_obj['_id'])
institute_id = institute_... | 615,412 |
Return all evaluations for a certain variant.
Args:
variant_obj (dict): variant dict from the database
Returns:
pymongo.cursor: database cursor | def get_evaluations(self, variant_obj):
query = dict(variant_id=variant_obj['variant_id'])
res = self.acmg_collection.find(query).sort([('created_at', pymongo.DESCENDING)])
return res | 615,413 |
Parse and massage the transcript information
There could be multiple lines with information about the same transcript.
This is why it is necessary to parse the transcripts first and then return a dictionary
where all information has been merged.
Args:
transcript_lines(): This could be an itera... | def parse_transcripts(transcript_lines):
LOG.info("Parsing transcripts")
# Parse the transcripts, we need to check if it is a request or a file handle
if isinstance(transcript_lines, DataFrame):
transcripts = parse_ensembl_transcript_request(transcript_lines)
else:
transcripts = par... | 615,414 |
Parse a dataframe with ensembl gene information
Args:
res(pandas.DataFrame)
Yields:
gene_info(dict) | def parse_ensembl_gene_request(result):
LOG.info("Parsing genes from request")
for index, row in result.iterrows():
# print(index, row)
ensembl_info = {}
# Pandas represents missing data with nan which is a float
if type(row['hgnc_symbol']) is float:
# Skip gen... | 615,415 |
Parse a dataframe with ensembl transcript information
Args:
res(pandas.DataFrame)
Yields:
transcript_info(dict) | def parse_ensembl_transcript_request(result):
LOG.info("Parsing transcripts from request")
keys = [
'chrom',
'ensembl_gene_id',
'ensembl_transcript_id',
'transcript_start',
'transcript_end',
'refseq_mrna',
'refseq_mrna_predicted',
'refseq_ncr... | 615,416 |
Parse an ensembl formated line
Args:
line(list): A list with ensembl gene info
header(list): A list with the header info
Returns:
ensembl_info(dict): A dictionary with the relevant info | def parse_ensembl_line(line, header):
line = line.rstrip().split('\t')
header = [head.lower() for head in header]
raw_info = dict(zip(header, line))
ensembl_info = {}
for word in raw_info:
value = raw_info[word]
if not value:
continue
if 'chromosome' in w... | 615,417 |
Parse lines with ensembl formated genes
This is designed to take a biomart dump with genes from ensembl.
Mandatory columns are:
'Gene ID' 'Chromosome' 'Gene Start' 'Gene End' 'HGNC symbol
Args:
lines(iterable(str)): An iterable with ensembl formated genes
Yields:
... | def parse_ensembl_genes(lines):
LOG.info("Parsing ensembl genes from file")
header = []
for index, line in enumerate(lines):
# File allways start with a header line
if index == 0:
header = line.rstrip().split('\t')
continue
# After that each line represe... | 615,418 |
Parse lines with ensembl formated exons
This is designed to take a biomart dump with exons from ensembl.
Check documentation for spec for download
Args:
lines(iterable(str)): An iterable with ensembl formated exons
Yields:
ensembl_gene(dict): A dictionary with t... | def parse_ensembl_exons(lines):
header = []
LOG.debug("Parsing ensembl exons...")
for index, line in enumerate(lines):
# File allways start with a header line
if index == 0:
header = line.rstrip().split('\t')
continue
exon_info = parse_ensembl_line(line... | 615,419 |
Parse a dataframe with ensembl exon information
Args:
res(pandas.DataFrame)
Yields:
gene_info(dict) | def parse_ensembl_exon_request(result):
keys = [
'chrom',
'gene',
'transcript',
'exon_id',
'exon_chrom_start',
'exon_chrom_end',
'5_utr_start',
'5_utr_end',
'3_utr_start',
'3_utr_end',
'strand',
'rank'
]
# ... | 615,420 |
Initializes the log file in the proper format.
Arguments:
filename (str): Path to a file. Or None if logging is to
be disabled.
loglevel (str): Determines the level of the log output. | def init_log(logger, filename=None, loglevel=None):
template = '[%(asctime)s] %(levelname)-8s: %(name)-25s: %(message)s'
formatter = logging.Formatter(template)
if loglevel:
logger.setLevel(getattr(logging, loglevel))
# We will always print warnings and higher to stderr
console = logg... | 615,421 |
Parse the mimTitles.txt file
This file hold information about the description for each entry in omim.
There is not information about entry type.
parse_mim_titles collects the preferred title and maps it to the mim number.
Args:
lines(iterable): lines from mimTitles file
Yields... | def parse_mim_titles(lines):
header = ['prefix', 'mim_number', 'preferred_title', 'alternative_title', 'included_title']
for i,line in enumerate(lines):
line = line.rstrip()
if not line.startswith('#'):
parsed_entry = parse_omim_line(line, header)
parsed_entry['mim_n... | 615,426 |
Get a dictionary with genes and their omim information
Args:
genemap_lines(iterable(str))
mim2gene_lines(iterable(str))
Returns.
hgnc_genes(dict): A dictionary with hgnc_symbol as keys | def get_mim_genes(genemap_lines, mim2gene_lines):
LOG.info("Get the mim genes")
genes = {}
hgnc_genes = {}
gene_nr = 0
no_hgnc = 0
for entry in parse_mim2gene(mim2gene_lines):
if 'gene' in entry['entry_type']:
mim_nr = entry['mim_number']
gene_... | 615,427 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.