docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Fetch the ensembl genes Args: build(str): ['37', '38']
def fetch_ensembl_exons(build='37'): LOG.info("Fetching ensembl exons build %s ...", build) if build == '37': url = 'http://grch37.ensembl.org' else: url = 'http://www.ensembl.org' dataset_name = 'hsapiens_gene_ensembl' dataset = pybiomart.Dataset(name=dataset_name, ho...
614,982
Fetch the necessary mim files using a api key Args: api_key(str): A api key necessary to fetch mim data Returns: mim_files(dict): A dictionary with the neccesary files
def fetch_hpo_files(hpogenes=False, hpoterms=False, phenotype_to_terms=False, hpodisease=False): LOG.info("Fetching HPO information from http://compbio.charite.de") base_url = ('http://compbio.charite.de/jenkins/job/hpo.annotations.monthly/' 'lastStableBuild/artifact/annotation/{}') hp...
614,985
Parse information about variants. - Adds information about compounds - Updates the information about compounds if necessary and 'update=True' Args: store(scout.adapter.MongoAdapter) institute_obj(scout.models.Institute) case_obj(scout.models.Case) variant_obj(scout.models.V...
def parse_variant(store, institute_obj, case_obj, variant_obj, update=False, genome_build='37', get_compounds = True): has_changed = False compounds = variant_obj.get('compounds', []) if compounds and get_compounds: # Check if we need to add compound information # If i...
614,995
Get variants info to be exported to file, one list (line) per variant. Args: store(scout.adapter.MongoAdapter) case_obj(scout.models.Case) variants_query: a list of variant objects, each one is a dictionary Returns: export_variants: a list of strings. Ea...
def variant_export_lines(store, case_obj, variants_query): export_variants = [] for variant in variants_query: variant_line = [] position = variant['position'] change = variant['reference']+'>'+variant['alternative'] variant_line.append(variant['rank_score']) varia...
614,996
Returns a header for the CSV file with the filtered variants to be exported. Args: case_obj(scout.models.Case) Returns: header: includes the fields defined in scout.constants.variants_export EXPORT_HEADER + AD_reference, AD_alternate, GT_quality for each sam...
def variants_export_header(case_obj): header = [] header = header + EXPORT_HEADER # Add fields specific for case samples for individual in case_obj['individuals']: display_name = str(individual['display_name']) header.append('AD_reference_'+display_name) # Add AD reference field for...
614,997
Pre-process case for the variant view. Adds information about files from case obj to variant Args: store(scout.adapter.MongoAdapter) case_obj(scout.models.Case) variant_obj(scout.models.Variant)
def variant_case(store, case_obj, variant_obj): case_obj['bam_files'] = [] case_obj['mt_bams'] = [] case_obj['bai_files'] = [] case_obj['mt_bais'] = [] case_obj['sample_names'] = [] for individual in case_obj['individuals']: bam_path = individual.get('bam_file') mt_bam = ind...
615,000
Compose link to COSMIC Database. Args: variant_obj(scout.models.Variant) Returns: url_template(str): Link to COSMIIC database if cosmic id is present
def cosmic_link(variant_obj): cosmic_ids = variant_obj.get('cosmic_ids') if not cosmic_ids: return None else: cosmic_id = cosmic_ids[0] url_template = ("https://cancer.sanger.ac.uk/cosmic/mutation/overview?id={}") return url_template.format(cosmic_id)
615,011
Gather the required data for creating the clinvar submission form Args: store(scout.adapter.MongoAdapter) institute_id(str): Institute ID case_name(str): case ID variant_id(str): variant._id Returns: a dictionary with all the required data (c...
def clinvar_export(store, institute_id, case_name, variant_id): institute_obj, case_obj = institute_and_case(store, institute_id, case_name) pinned = [store.variant(variant_id) or variant_id for variant_id in case_obj.get('suspects', [])] variant_obj = store.variant(variant_id) r...
615,020
Collects all variants from the clinvar submission collection with a specific submission_id Args: store(scout.adapter.MongoAdapter) institute_id(str): Institute ID case_name(str): case ID variant_id(str): variant._id submission_id(str): clinvar submiss...
def get_clinvar_submission(store, institute_id, case_name, variant_id, submission_id): institute_obj, case_obj = institute_and_case(store, institute_id, case_name) pinned = [store.variant(variant_id) or variant_id for variant_id in case_obj.get('suspects', [])] variant_obj = store.va...
615,021
Collect all verified variants in a list on institutes and save them to file Args: store(adapter.MongoAdapter) institute_list(list): a list of institute ids temp_excel_dir(os.Path): folder where the temp excel files are written to Returns: written_files(int): the number of files...
def verified_excel_file(store, institute_list, temp_excel_dir): document_lines = [] written_files = 0 today = datetime.datetime.now().strftime('%Y-%m-%d') LOG.info('Creating verified variant document..') for cust in institute_list: verif_vars = store.verified(institute_id=cust) ...
615,026
Build a hpo_term object Check that the information is correct and add the correct hgnc ids to the array of genes. Args: hpo_info(dict) Returns: hpo_obj(scout.models.HpoTerm): A dictionary with hpo information
def build_hpo_term(hpo_info): try: hpo_id = hpo_info['hpo_id'] except KeyError: raise KeyError("Hpo terms has to have a hpo_id") LOG.debug("Building hpo term %s", hpo_id) # Add description to HPO term try: description = hpo_info['description'] except KeyError:...
615,027
Get the clnsig information Args: acc(str): The clnsig accession number, raw from vcf sig(str): The clnsig significance score, raw from vcf revstat(str): The clnsig revstat, raw from vcf transcripts(iterable(dict)) Returns: clnsig_accsessions(list): A list with clnsig ac...
def parse_clnsig(acc, sig, revstat, transcripts): clnsig_accsessions = [] if acc: # New format of clinvar allways have integers as accession numbers try: acc = int(acc) except ValueError: pass # There are sometimes different separators so we need to chec...
615,029
Get a list with compounds objects for this variant. Arguments: compound_info(str): A Variant dictionary case_id (str): unique family id variant_type(str): 'research' or 'clinical' Returns: compounds(list(dict)): A list of compounds
def parse_compounds(compound_info, case_id, variant_type): # We need the case to construct the correct id compounds = [] if compound_info: for family_info in compound_info.split(','): splitted_entry = family_info.split(':') # This is the family id if splitted...
615,032
Parse individual information Args: sample (dict) Returns: { 'individual_id': str, 'father': str, 'mother': str, 'display_name': str, 'sex': str, 'phenotype': str, 'ba...
def parse_individual(sample): ind_info = {} if 'sample_id' not in sample: raise PedigreeError("One sample is missing 'sample_id'") sample_id = sample['sample_id'] # Check the sex if 'sex' not in sample: raise PedigreeError("Sample %s is missing 'sex'" % sample_id) sex = samp...
615,054
Parse the individual information Reformat sample information to proper individuals Args: samples(list(dict)) Returns: individuals(list(dict))
def parse_individuals(samples): individuals = [] if len(samples) == 0: raise PedigreeError("No samples could be found") ind_ids = set() for sample_info in samples: parsed_ind = parse_individual(sample_info) individuals.append(parsed_ind) ind_ids.add(parsed_ind['indi...
615,055
Parse case information from config or PED files. Args: config (dict): case config with detailed information Returns: dict: parsed case data
def parse_case(config): if 'owner' not in config: raise ConfigError("A case has to have a owner") if 'family' not in config: raise ConfigError("A case has to have a 'family'") individuals = parse_individuals(config['samples']) case_data = { 'owner': config['owner'], ...
615,056
Parse out minimal family information from a PED file. Args: ped_stream(iterable(str)) family_type(str): Format of the pedigree information Returns: family_id(str), samples(list[dict])
def parse_ped(ped_stream, family_type='ped'): pedigree = FamilyParser(ped_stream, family_type=family_type) if len(pedigree.families) != 1: raise PedigreeError("Only one case per ped file is allowed") family_id = list(pedigree.families.keys())[0] family = pedigree.families[family_id] ...
615,057
Build a evaluation object ready to be inserted to database Args: variant_specific(str): md5 string for the specific variant variant_id(str): md5 string for the common variant user_id(str) user_name(str) institute_id(str) case_id(str) classification(str): The ...
def build_evaluation(variant_specific, variant_id, user_id, user_name, institute_id, case_id, classification, criteria): criteria = criteria or [] evaluation_obj = dict( variant_specific = variant_specific, variant_id = variant_id, institute_id = institute_id, ...
615,058
Export all mitochondrial variants for each sample of a case and write them to an excel file Args: adapter(MongoAdapter) case_id(str) test(bool): True if the function is called for testing purposes outpath(str): path to output file Returns: ...
def mt_report(context, case_id, test, outpath=None): LOG.info('exporting mitochondrial variants for case "{}"'.format(case_id)) adapter = context.obj['adapter'] query = {'chrom':'MT'} case_obj = adapter.case(case_id=case_id) if not case_obj: LOG.warning('Could not find a scout case w...
615,059
Build a genotype call Args: gt_call(dict) Returns: gt_obj(dict) gt_call = dict( sample_id = str, display_name = str, genotype_call = str, allele_depths = list, # int read_depth = int, genotype_quality = int, )
def build_genotype(gt_call): gt_obj = dict( sample_id = gt_call['individual_id'], display_name = gt_call['display_name'], genotype_call = gt_call['genotype_call'], allele_depths = [gt_call['ref_depth'], gt_call['alt_depth']], read_depth = gt_call['read_depth'], g...
615,060
Use the algorithm described in ACMG paper to get a ACMG calssification Args: acmg_terms(set(str)): A collection of prediction terms Returns: prediction(int): 0 - Uncertain Significanse 1 - Benign 2 - Likely Benign 3 - Likely Patho...
def get_acmg(acmg_terms): prediction = 'uncertain_significance' # This variable indicates if Pathogenecity Very Strong exists pvs = False # Collection of terms with Pathogenecity Strong ps_terms = [] # Collection of terms with Pathogenecity moderate pm_terms = [] # Collection of ter...
615,064
Add extra information about genes from gene panels Args: variant_obj(dict): A variant from the database gene_panels(list(dict)): List of panels from database
def add_gene_info(self, variant_obj, gene_panels=None): gene_panels = gene_panels or [] # Add a variable that checks if there are any refseq transcripts variant_obj['has_refseq'] = False # We need to check if there are any additional information in the gene panels # e...
615,066
Return all variants with sanger information Args: institute_id(str) case_id(str) Returns: res(pymongo.Cursor): A Cursor with all variants with sanger activity
def sanger_variants(self, institute_id=None, case_id=None): query = {'validation': {'$exists': True}} if institute_id: query['institute_id'] = institute_id if case_id: query['case_id'] = case_id return self.variant_collection.find(query)
615,068
Returns the specified variant. Arguments: document_id : A md5 key that represents the variant or "variant_id" gene_panels(List[GenePanel]) case_id (str): case id (will search with "variant_id") Returns: variant_object(Variant): A odm va...
def variant(self, document_id, gene_panels=None, case_id=None): query = {} if case_id: # search for a variant in a case query['case_id'] = case_id query['variant_id'] = document_id else: # search with a unique id query['_id'] =...
615,069
Return all variants seen in a given gene. If skip not equal to 0 skip the first n variants. Arguments: query(dict): A dictionary with querys for the database, including variant_type: 'clinical', 'research' category(str): 'sv', 'str', 'snv' or 'cancer' nr...
def gene_variants(self, query=None, category='snv', variant_type=['clinical'], nr_of_variants=50, skip=0): mongo_variant_query = self.build_variant_query(query=query, category=category, variant_type=variant_type) sorting...
615,070
Return all verified variants for a given institute Args: institute_id(str): institute id Returns: res(list): a list with validated variants
def verified(self, institute_id): query = { 'verb' : 'validate', 'institute' : institute_id, } res = [] validate_events = self.event_collection.find(query) for validated in list(validate_events): case_id = validated['case'] ...
615,071
Return all causative variants for an institute Args: institute_id(str) case_id(str) Yields: str: variant document id
def get_causatives(self, institute_id, case_id=None): causatives = [] if case_id: case_obj = self.case_collection.find_one( {"_id": case_id} ) causatives = [causative for causative in case_obj['causatives']] elif institute_...
615,072
Check if there are any variants that are previously marked causative Loop through all variants that are marked 'causative' for an institute and check if any of the variants are present in the current case. Args: case_obj (dict): A Case object ...
def check_causatives(self, case_obj=None, institute_obj=None): institute_id = case_obj['owner'] if case_obj else institute_obj['_id'] institute_causative_variant_ids = self.get_causatives(institute_id) if len(institute_causative_variant_ids) == 0: return [] if case_...
615,073
Find the same variant in other cases marked causative. Args: case_obj(dict) variant_obj(dict) Yields: other_variant(dict)
def other_causatives(self, case_obj, variant_obj): # variant id without "*_[variant_type]" variant_id = variant_obj['display_name'].rsplit('_', 1)[0] institute_causatives = self.get_causatives(variant_obj['institute']) for causative_id in institute_causatives: other...
615,074
Delete variants of one type for a case This is used when a case is reanalyzed Args: case_id(str): The case id variant_type(str): 'research' or 'clinical' category(str): 'snv', 'sv' or 'cancer'
def delete_variants(self, case_id, variant_type, category=None): category = category or '' LOG.info("Deleting old {0} {1} variants for case {2}".format( variant_type, category, case_id)) query = {'case_id': case_id, 'variant_type': variant_type} if category: ...
615,075
Return overlapping variants. Look at the genes that a variant overlaps to. Then return all variants that overlap these genes. If variant_obj is sv it will return the overlapping snvs and oposite There is a problem when SVs are huge since there are to many overlapping variants. ...
def overlapping(self, variant_obj): #This is the category of the variants that we want to collect category = 'snv' if variant_obj['category'] == 'sv' else 'sv' query = { '$and': [ {'case_id': variant_obj['case_id']}, {'category': category}, ...
615,076
Returns variants that has been evaluated Return all variants, snvs/indels and svs from case case_id which have a entry for 'acmg_classification', 'manual_rank', 'dismiss_variant' or if they are commented. Args: case_id(str) Returns: variants(iterable(Va...
def evaluated_variants(self, case_id): # Get all variants that have been evaluated in some way for a case query = { '$and': [ {'case_id': case_id}, { '$or': [ {'acmg_classification': {'$exists': True}}, ...
615,077
Given a list of variants get variant objects found in a specific patient Args: variants(list): a list of variant ids sample_name(str): a sample display name category(str): 'snv', 'sv' .. Returns: result(iterable(Variant))
def sample_variants(self, variants, sample_name, category = 'snv'): LOG.info('Retrieving variants for subject : {0}'.format(sample_name)) has_allele = re.compile('1|2') # a non wild-type allele is called at least once in this sample query = { '$and': [ {'_id...
615,079
Creates a list of submission objects (variant and case-data) from the clinvar submission form in blueprints/variants/clinvar.html. Args: form_fields(dict): it's the submission form dictionary. Keys have the same names as CLINVAR_HEADER and CASEDATA_HEADER Returns: submission_...
def set_submission_objects(form_fields): variant_ids = get_submission_variants(form_fields) # A list of variant IDs present in the submitted form # Extract list of variant objects to be submitted variant_objs = get_objects_from_form(variant_ids, form_fields, 'variant') # Extract list of casedata ...
615,081
Extracts a list of variant ids from the clinvar submission form in blueprints/variants/clinvar.html (creation of a new clinvar submission). Args: form_fields(dict): it's the submission form dictionary. Keys have the same names as CLINVAR_HEADER and CASEDATA_HEADER Returns: cl...
def get_submission_variants(form_fields): clinvars = [] # if the html checkbox named 'all_vars' is checked in the html form, then all pinned variants from a case should be included in the clinvar submission file, # otherwise just the selected one. if 'all_vars' in form_fields: for field, ...
615,083
Determine which fields to include in csv header by checking a list of submission objects Args: submission_objs(list): a list of objects (variants or casedata) to include in a csv file csv_type(str) : 'variant_data' or 'case_data' Returns: custom_header(dict): A dict...
def clinvar_submission_header(submission_objs, csv_type): complete_header = {} # header containing all available fields custom_header = {} # header reflecting the real data included in the submission objects if csv_type == 'variant_data' : complete_header = CLINVAR_HEADER else: c...
615,084
Load all the transcripts Transcript information is from ensembl. Args: adapter(MongoAdapter) transcripts_lines(iterable): iterable with ensembl transcript lines build(str) ensembl_genes(dict): Map from ensembl_id -> HgncGene Returns: transcript_objs(list): A list w...
def load_transcripts(adapter, transcripts_lines=None, build='37', ensembl_genes=None): # Fetch all genes with ensemblid as keys ensembl_genes = ensembl_genes or adapter.ensembl_genes(build) if transcripts_lines is None: transcripts_lines = fetch_ensembl_transcripts(build=build) # Map with...
615,086
Build a Exon object object Args: exon_info(dict): Exon information Returns: exon_obj(Exon) "exon_id": str, # str(chrom-start-end) "chrom": str, "start": int, "end": int, "transcript": str, # ENST ID "hgnc_id": int,...
def build_exon(exon_info, build='37'): try: chrom = exon_info['chrom'] except KeyError: raise KeyError("Exons has to have a chromosome") try: start = int(exon_info['start']) except KeyError: raise KeyError("Exon has to have a start") except TypeError: r...
615,088
Extract all OMIM phenotypes available for the case Args: case_obj(dict): a scout case object Returns: disorders(list): a list of OMIM disorder objects
def omim_terms(case_obj): LOG.info("Collecting OMIM disorders for case {}".format(case_obj.get('display_name'))) disorders = [] case_disorders = case_obj.get('diagnosis_phenotypes') # array of OMIM terms if case_disorders: for disorder in case_disorders: disorder_obj = { ...
615,097
Updates a case after a submission to MatchMaker Exchange Args: case_obj(dict): a scout case object user_obj(dict): a scout user object mme_subm_obj(dict): contains MME submission params and server response Returns: updated_case(dict...
def case_mme_update(self, case_obj, user_obj, mme_subm_obj): created = None patient_ids = [] updated = datetime.now() if 'mme_submission' in case_obj and case_obj['mme_submission']: created = case_obj['mme_submission']['created_at'] else: created ...
615,106
Delete a MatchMaker submission from a case record and creates the related event. Args: case_obj(dict): a scout case object user_obj(dict): a scout user object Returns: updated_case(dict): the updated scout case
def case_mme_delete(self, case_obj, user_obj): institute_obj = self.institute(case_obj['owner']) # create events for subjects removal from Matchmaker this cas for individual in case_obj['individuals']: if individual['phenotype'] == 2: # affected # create even...
615,107
Build a institute object Args: internal_id(str) display_name(str) sanger_recipients(list(str)): List with email addresses Returns: institute_obj(scout.models.Institute)
def build_institute(internal_id, display_name, sanger_recipients=None, coverage_cutoff=None, frequency_cutoff=None): LOG.info("Building institute %s with display name %s", internal_id,display_name) institute_obj = Institute( internal_id=internal_id, display_name=displ...
615,108
Delete a event Arguments: event_id (str): The database key for the event
def delete_event(self, event_id): LOG.info("Deleting event{0}".format(event_id)) if not isinstance(event_id, ObjectId): event_id = ObjectId(event_id) self.event_collection.delete_one({'_id': event_id}) LOG.debug("Event {0} deleted".format(event_id))
615,109
Fetch events from the database. Args: institute (dict): A institute case (dict): A case variant_id (str, optional): global variant id level (str, optional): restrict comments to 'specific' or 'global' comments (bool, optional): restrict events to in...
def events(self, institute, case=None, variant_id=None, level=None, comments=False, panel=None): query = {} if variant_id: if comments: # If it's comment-related event collect global and variant-specific comment events LOG.debug("Fetc...
615,111
Add a new phenotype term to a case Create a phenotype term and event with the given information Args: institute (Institute): A Institute object case (Case): Case object user (User): A User object link (str): The url to be used in ...
def add_phenotype(self, institute, case, user, link, hpo_term=None, omim_term=None, is_group=False): hpo_results = [] try: if hpo_term: hpo_results = [hpo_term] elif omim_term: LOG.debug("Fetching info for mim term {0...
615,113
Remove an existing phenotype from a case Args: institute (dict): A Institute object case (dict): Case object user (dict): A User object link (dict): The url to be used in the event phenotype_id (str): A phenotype id Returns: updat...
def remove_phenotype(self, institute, case, user, link, phenotype_id, is_group=False): LOG.info("Removing HPO term from case {0}".format(case['display_name'])) if is_group: updated_case = self.case_collection.find_one_and_update( {'_id': cas...
615,114
Parse the genotype calls for a variant Args: variant(cyvcf2.Variant) individuals: List[dict] individual_positions(dict) Returns: genotypes(list(dict)): A list of genotypes
def parse_genotypes(variant, individuals, individual_positions): genotypes = [] for ind in individuals: pos = individual_positions[ind['individual_id']] genotypes.append(parse_genotype(variant, ind, pos)) return genotypes
615,116
Check if a variant is in the Pseudo Autosomal Region or not Args: chromosome(str) position(int) build(str): The genome build Returns: bool
def is_par(chromosome, position, build='37'): chrom_match = CHR_PATTERN.match(chromosome) chrom = chrom_match.group(2) # PAR regions are only on X and Y if not chrom in ['X','Y']: return False # Check if variant is in first PAR region if PAR_COORDINATES[build][chrom].search(pos...
615,118
Check if the variant is in the interval given by the coordinates Args: chromosome(str): Variant chromosome pos(int): Variant position coordinates(dict): Dictionary with the region of interest
def check_coordinates(chromosome, pos, coordinates): chrom_match = CHR_PATTERN.match(chromosome) chrom = chrom_match.group(2) if chrom != coordinates['chrom']: return False if (pos >= coordinates['start'] and pos <= coordinates['end']): return True return False
615,119
Export all genes in gene panels Exports the union of genes in one or several gene panels to a bed like format with coordinates. Args: adapter(scout.adapter.MongoAdapter) panels(iterable(str)): Iterable with panel ids bed(bool): If lines should be bed formated
def export_panels(adapter, panels, versions=None, build='37'): if versions and (len(versions) != len(panels)): raise SyntaxError("If version specify for each panel") headers = [] build_string = ("##genome_build={}") headers.append(build_string.format(build)) header_string = ("##ge...
615,120
Export the genes of a gene panel Takes a list of gene panel names and return the lines of the gene panels. Unlike export_panels this function only export the genes and extra information, not the coordinates. Args: adapter(MongoAdapter) panels(list(str)) version(float):...
def export_gene_panels(adapter, panels, version=None): if version and len(panels) > 1: raise SyntaxError("Version only possible with one panel") bed_string = ("{0}\t{1}\t{2}\t{3}\t{4}\t{5}") headers = [] # Dictionary with hgnc ids as keys and panel gene information as value. pane...
615,121
Build a user object Args: user_info(dict): A dictionary with user information Returns: user_obj(scout.models.User)
def build_user(user_info): try: email = user_info['email'] except KeyError as err: raise KeyError("A user has to have a email") try: name = user_info['name'] except KeyError as err: raise KeyError("A user has to have a name") user_obj = User(email=email...
615,133
Update an existing gene panel with genes. Args: store(scout.adapter.MongoAdapter) panel_name(str) csv_lines(iterable(str)): Stream with genes option(str): 'add' or 'replace' Returns: panel_obj(dict)
def update_panel(store, panel_name, csv_lines, option): new_genes= [] panel_obj = store.gene_panel(panel_name) if panel_obj is None: return None try: new_genes = parse_genes(csv_lines) # a list of gene dictionaries containing gene info except SyntaxError as error: flash(...
615,136
Create a new gene panel. Args: store(scout.adapter.MongoAdapter) institute_id(str) panel_name(str) display_name(str) csv_lines(iterable(str)): Stream with genes Returns: panel_id: the ID of the new panel document created or None
def new_panel(store, institute_id, panel_name, display_name, csv_lines): institute_obj = store.institute(institute_id) if institute_obj is None: flash("{}: institute not found".format(institute_id)) return None panel_obj = store.gene_panel(panel_name) if panel_obj: flash("p...
615,137
Export variants which have been verified for an institute and write them to an excel file. Args: collaborator(str): institute id test(bool): True if the function is called for testing purposes outpath(str): path to output file Returns: written_files(int): number of writ...
def verified(context, collaborator, test, outpath=None): written_files = 0 collaborator = collaborator or 'cust000' LOG.info('Exporting verified variants for cust {}'.format(collaborator)) adapter = context.obj['adapter'] verified_vars = adapter.verified(institute_id=collaborator) LOG.info...
615,156
Get vcf entry from variant object Args: variant_obj(dict) Returns: variant_string(str): string representing variant in vcf format
def get_vcf_entry(variant_obj, case_id=None): if variant_obj['category'] == 'snv': var_type = 'TYPE' else: var_type = 'SVTYPE' info_field = ';'.join( [ 'END='+str(variant_obj['end']), var_type+'='+variant_obj['sub_category'].upper() ...
615,158
Generate an md5-key from a list of arguments. Args: list_of_arguments: A list of strings Returns: A md5-key object generated from the list of strings.
def generate_md5_key(list_of_arguments): for arg in list_of_arguments: if not isinstance(arg, string_types): raise SyntaxError("Error in generate_md5_key: " "Argument: {0} is a {1}".format(arg, type(arg))) hash = hashlib.md5() hash.update(' '.join(list...
615,160
Parse the genetic models entry of a vcf Args: models_info(str): The raw vcf information case_id(str) Returns: genetic_models(list)
def parse_genetic_models(models_info, case_id): genetic_models = [] if models_info: for family_info in models_info.split(','): splitted_info = family_info.split(':') if splitted_info[0] == case_id: genetic_models = splitted_info[1].split('|') return gene...
615,169
Add a institute to the database Args: institute_obj(Institute)
def add_institute(self, institute_obj): internal_id = institute_obj['internal_id'] display_name = institute_obj['internal_id'] # Check if institute already exists if self.institute(institute_id=internal_id): raise IntegrityError("Institute {0} already exists in data...
615,171
Featch a single institute from the backend Args: institute_id(str) Returns: Institute object
def institute(self, institute_id): LOG.debug("Fetch institute {}".format(institute_id)) institute_obj = self.institute_collection.find_one({ '_id': institute_id }) if institute_obj is None: LOG.debug("Could not find institute {0}".format(institute_id)) ...
615,173
Fetch all institutes. Args: institute_ids(list(str)) Returns: res(pymongo.Cursor)
def institutes(self, institute_ids=None): query = {} if institute_ids: query['_id'] = {'$in': institute_ids} LOG.debug("Fetching all institutes") return self.institute_collection.find(query)
615,174
Check if a string is a valid date Args: date(str) Returns: bool
def match_date(date): date_pattern = re.compile("^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])") if re.match(date_pattern, date): return True return False
615,175
Return a datetime object if there is a valid date Raise exception if date is not valid Return todays date if no date where added Args: date(str) date_format(str) Returns: date_obj(datetime.datetime)
def get_date(date, date_format = None): date_obj = datetime.datetime.now() if date: if date_format: date_obj = datetime.datetime.strptime(date, date_format) else: if match_date(date): if len(date.split('-')) == 3: date = date.split...
615,176
Parse transcript information and get the gene information from there. Use hgnc_id as identifier for genes and ensembl transcript id to identify transcripts Args: transcripts(iterable(dict)) Returns: genes (list(dict)): A list with dictionaries that represents genes
def parse_genes(transcripts): # Dictionary to group the transcripts by hgnc_id genes_to_transcripts = {} # List with all genes and there transcripts genes = [] hgvs_identifier = None canonical_transcript = None exon = None # Group all transcripts by gene for transcript in ...
615,178
Parse the rank score Args: rank_score_entry(str): The raw rank score entry case_id(str) Returns: rank_score(float)
def parse_rank_score(rank_score_entry, case_id): rank_score = None if rank_score_entry: for family_info in rank_score_entry.split(','): splitted_info = family_info.split(':') if case_id == splitted_info[0]: rank_score = float(splitted_info[1]) return rank...
615,179
Parse transcript information from VCF variants Args: raw_transcripts(iterable(dict)): An iterable with raw transcript information Yields: transcript(dict) A dictionary with transcript information
def parse_transcripts(raw_transcripts, allele=None): for entry in raw_transcripts: transcript = {} # There can be several functional annotations for one variant functional_annotations = entry.get('CONSEQUENCE', '').split('&') transcript['functional_annotations'] = functional_ann...
615,181
Check if a connection could be made to the mongo process specified Args: host(str) port(int) username(str) password(str) authdb (str): database to to for authentication max_delay(int): Number of milliseconds to wait for connection Returns: bool: If conne...
def check_connection(host='localhost', port=27017, username=None, password=None, authdb=None, max_delay=1): #uri looks like: #mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]] if username and password: uri = ("mongodb://{...
615,182
Build a transcript object These represents the transcripts that are parsed from the VCF, not the transcript definitions that are collected from ensembl. Args: transcript(dict): Parsed transcript information Returns: transcript_obj(dict)
def build_transcript(transcript, build='37'): # Transcripts has to have an id transcript_id = transcript['transcript_id'] transcript_obj = dict( transcript_id = transcript_id ) # Transcripts has to belong to a gene transcript_obj['hgnc_id'] = transcript['hgnc_id'] if ...
615,187
Update an existing user. Args: user_obj(dict) Returns: updated_user(dict)
def update_user(self, user_obj): LOG.info("Updating user %s", user_obj['_id']) updated_user = self.user_collection.find_one_and_replace( {'_id': user_obj['_id']}, user_obj, return_document=pymongo.ReturnDocument.AFTER ) return updated_user
615,188
Add a user object to the database Args: user_obj(scout.models.User): A dictionary with user information Returns: user_info(dict): a copy of what was inserted
def add_user(self, user_obj): LOG.info("Adding user %s to the database", user_obj['email']) if not '_id' in user_obj: user_obj['_id'] = user_obj['email'] try: self.user_collection.insert_one(user_obj) LOG.debug("User inserted") except Dup...
615,189
Return all users from the database Args: institute(str): A institute_id Returns: res(pymongo.Cursor): A cursor with users
def users(self, institute=None): query = {} if institute: LOG.info("Fetching all users from institute %s", institute) query = {'institutes': {'$in': [institute]}} else: LOG.info("Fetching all users") res = self.user_collection.fin...
615,190
Fetch a user from the database. Args: email(str) Returns: user_obj(dict)
def user(self, email): LOG.info("Fetching user %s", email) user_obj = self.user_collection.find_one({'_id': email}) return user_obj
615,191
Delete a user from the database Args: email(str) Returns: user_obj(dict)
def delete_user(self, email): LOG.info("Deleting user %s", email) user_obj = self.user_collection.delete_one({'_id': email}) return user_obj
615,192
Load all the exons Transcript information is from ensembl. Check that the transcript that the exon belongs to exists in the database Args: adapter(MongoAdapter) exon_lines(iterable): iterable with ensembl exon lines build(str) ensembl_transcripts(dict): Existing ensembl...
def load_exons(adapter, exon_lines, build='37', ensembl_genes=None): # Fetch all genes with ensemblid as keys ensembl_genes = ensembl_genes or adapter.ensembl_genes(build) hgnc_id_transcripts = adapter.id_transcripts_by_gene(build=build) if isinstance(exon_lines, DataFrame): exons = pa...
615,198
Return a parsed variant Get all the necessary information to build a variant object Args: variant(cyvcf2.Variant) case(dict) variant_type(str): 'clinical' or 'research' rank_results_header(list) vep_header(list) individual_positions(dict): Explain what posit...
def parse_variant(variant, case, variant_type='clinical', rank_results_header=None, vep_header=None, individual_positions=None, category=None): # These are to display how the rank score is built rank_results_header = rank_results_header or [] # Vep information vep_...
615,199
Update a gene object with links Args: gene_obj(dict) build(int) Returns: gene_obj(dict): gene_obj updated with many links
def add_gene_links(gene_obj, build=37): try: build = int(build) except ValueError: build = 37 # Add links that use the hgnc_id hgnc_id = gene_obj['hgnc_id'] gene_obj['hgnc_link'] = genenames(hgnc_id) gene_obj['omim_link'] = omim(hgnc_id) # Add links that use ensembl_id ...
615,201
Parse an hgnc formated line Args: line(list): A list with hgnc gene info header(list): A list with the header info Returns: hgnc_info(dict): A dictionary with the relevant info
def parse_hgnc_line(line, header): hgnc_gene = {} line = line.rstrip().split('\t') raw_info = dict(zip(header, line)) # Skip all genes that have status withdrawn if 'Withdrawn' in raw_info['status']: return hgnc_gene hgnc_symbol = raw_info['symbol'] hgnc_gene['hgnc_symbol']...
615,206
Parse lines with hgnc formated genes This is designed to take a dump with genes from HGNC. This is downloaded from: ftp://ftp.ebi.ac.uk/pub/databases/genenames/new/tsv/hgnc_complete_set.txt Args: lines(iterable(str)): An iterable with HGNC formated genes Yields: ...
def parse_hgnc_genes(lines): header = [] logger.info("Parsing hgnc genes...") for index, line in enumerate(lines): if index == 0: header = line.split('\t') elif len(line) > 1: hgnc_gene = parse_hgnc_line(line=line, header=header) if hgnc_gene: ...
615,207
Create an open clinvar submission for a user and an institute Args: user_id(str): a user ID institute_id(str): an institute ID returns: submission(obj): an open clinvar submission object
def create_submission(self, user_id, institute_id): submission_obj = { 'status' : 'open', 'created_at' : datetime.now(), 'user_id' : user_id, 'institute_id' : institute_id } LOG.info("Creating a new clinvar submission for user '%s' and in...
615,211
Deletes a Clinvar submission object, along with all associated clinvar objects (variants and casedata) Args: submission_id(str): the ID of the submission to be deleted Returns: deleted_objects(int): the number of associated objects removed (variants and/or cased...
def delete_submission(self, submission_id): LOG.info("Deleting clinvar submission %s", submission_id) submission_obj = self.clinvar_submission_collection.find_one({ '_id' : ObjectId(submission_id)}) submission_variants = submission_obj.get('variant_data') submission_casedata = ...
615,212
Retrieve the database id of an open clinvar submission for a user and institute, if none is available then create a new submission and return it Args: user_id(str): a user ID institute_id(str): an institute ID Returns: submission(obj) : ...
def get_open_clinvar_submission(self, user_id, institute_id): LOG.info("Retrieving an open clinvar submission for user '%s' and institute %s", user_id, institute_id) query = dict(user_id=user_id, institute_id=institute_id, status='open') submission = self.clinvar_submission_collection....
615,213
saves an official clinvar submission ID in a clinvar submission object Args: clinvar_id(str): a string with a format: SUB[0-9]. It is obtained from clinvar portal when starting a new submission submission_id(str): submission_id(str) : id of the submission to be updated ...
def update_clinvar_id(self, clinvar_id, submission_id ): updated_submission = self.clinvar_submission_collection.find_one_and_update( {'_id': ObjectId(submission_id)}, { '$set' : {'clinvar_subm_id' : clinvar_id, 'updated_at': datetime.now()} }, upsert=True, return_document=pymongo.ReturnDocument.AFTER ...
615,214
Returns the official Clinvar submission ID for a submission object Args: submission_id(str): submission_id(str) : id of the submission Returns: clinvar_subm_id(str): a string with a format: SUB[0-9]. It is obtained from clinvar portal when starting a new submiss...
def get_clinvar_id(self, submission_id): submission_obj = self.clinvar_submission_collection.find_one({'_id': ObjectId(submission_id)}) clinvar_subm_id = submission_obj.get('clinvar_subm_id') # This key does not exist if it was not previously provided by user return clinvar_subm_id
615,215
Adds submission_objects to clinvar collection and update the coresponding submission object with their id Args: submission_id(str) : id of the submission to be updated submission_objects(tuple): a tuple of 2 elements coresponding to a list of variants and a list of case data...
def add_to_submission(self, submission_id, submission_objects): LOG.info("Adding new variants and case data to clinvar submission '%s'", submission_id) # Insert variant submission_objects into clinvar collection # Loop over the objects for var_obj in submission_objects[0]: ...
615,216
Set a clinvar submission ID to 'closed' Args: submission_id(str): the ID of the clinvar submission to close Return updated_submission(obj): the submission object with a 'closed' status
def update_clinvar_submission_status(self, user_id, submission_id, status): LOG.info('closing clinvar submission "%s"', submission_id) if status == 'open': # just close the submission its status does not affect the other submissions for this user # Close all other submissions for t...
615,217
Collect all open and closed clinvar submission created by a user for an institute Args: user_id(str): a user ID institute_id(str): an institute ID Returns: submissions(list): a list of clinvar submission objects
def clinvar_submissions(self, user_id, institute_id): LOG.info("Retrieving all clinvar submissions for user '%s', institute '%s'", user_id, institute_id) # get first all submission objects query = dict(user_id=user_id, institute_id=institute_id) results = list(self.clinvar_submi...
615,218
Get all variants included in clinvar submissions for a case Args: case_id(str): a case _id Returns: submission_variants(dict): keys are variant ids and values are variant submission objects
def case_to_clinVars(self, case_id): query = dict(case_id=case_id, csv_type='variant') clinvar_objs = list(self.clinvar_collection.find(query)) submitted_vars = {} for clinvar in clinvar_objs: submitted_vars[clinvar.get('local_id')] = clinvar return submitte...
615,221
Parse hpo phenotype Args: hpo_line(str): A iterable with hpo phenotype lines Yields: hpo_info(dict)
def parse_hpo_phenotype(hpo_line): hpo_line = hpo_line.rstrip().split('\t') hpo_info = {} hpo_info['hpo_id'] = hpo_line[0] hpo_info['description'] = hpo_line[1] hpo_info['hgnc_symbol'] = hpo_line[3] return hpo_info
615,222
Parse hpo gene information Args: hpo_line(str): A iterable with hpo phenotype lines Yields: hpo_info(dict)
def parse_hpo_gene(hpo_line): if not len(hpo_line) > 3: return {} hpo_line = hpo_line.rstrip().split('\t') hpo_info = {} hpo_info['hgnc_symbol'] = hpo_line[1] hpo_info['description'] = hpo_line[2] hpo_info['hpo_id'] = hpo_line[3] return hpo_info
615,223
Parse hpo disease line Args: hpo_line(str)
def parse_hpo_disease(hpo_line): hpo_line = hpo_line.rstrip().split('\t') hpo_info = {} disease = hpo_line[0].split(':') hpo_info['source'] = disease[0] hpo_info['disease_nr'] = int(disease[1]) hpo_info['hgnc_symbol'] = None hpo_info['hpo_term'] = None if len(hpo_line) >= ...
615,224
Parse hpo phenotypes Group the genes that a phenotype is associated to in 'genes' Args: hpo_lines(iterable(str)): A file handle to the hpo phenotypes file Returns: hpo_terms(dict): A dictionary with hpo_ids as keys and terms as values { <hpo_id>: {...
def parse_hpo_phenotypes(hpo_lines): hpo_terms = {} LOG.info("Parsing hpo phenotypes...") for index, line in enumerate(hpo_lines): if index > 0 and len(line) > 0: hpo_info = parse_hpo_phenotype(line) hpo_term = hpo_info['hpo_id'] hgnc_symbol = hpo_info['hgnc_...
615,225
Parse hpo disease phenotypes Args: hpo_lines(iterable(str)) Returns: diseases(dict): A dictionary with mim numbers as keys
def parse_hpo_diseases(hpo_lines): diseases = {} LOG.info("Parsing hpo diseases...") for index, line in enumerate(hpo_lines): # First line is a header if index == 0: continue # Skip empty lines if not len(line) > 3: continue # Parse the in...
615,226
Parse the map from hpo term to hgnc symbol Args: lines(iterable(str)): Yields: hpo_to_gene(dict): A dictionary with information on how a term map to a hgnc symbol
def parse_hpo_to_genes(hpo_lines): for line in hpo_lines: if line.startswith('#') or len(line) < 1: continue line = line.rstrip().split('\t') hpo_id = line[0] hgnc_symbol = line[3] yield { 'hpo_id': hpo_id, 'hgnc_symbol': hgnc...
615,227
Parse HPO gene information Args: hpo_lines(iterable(str)) Returns: diseases(dict): A dictionary with hgnc symbols as keys
def parse_hpo_genes(hpo_lines): LOG.info("Parsing HPO genes ...") genes = {} for index, line in enumerate(hpo_lines): # First line is header if index == 0: continue if len(line) < 5: continue gene_info = parse_hpo_gene(line) hgnc_symbol = ...
615,228
Get a set with all genes that have incomplete penetrance according to HPO Args: hpo_lines(iterable(str)) Returns: incomplete_penetrance_genes(set): A set with the hgnc symbols of all genes with incomplete penetrance
def get_incomplete_penetrance_genes(hpo_lines): genes = parse_hpo_genes(hpo_lines) incomplete_penetrance_genes = set() for hgnc_symbol in genes: if genes[hgnc_symbol].get('incomplete_penetrance'): incomplete_penetrance_genes.add(hgnc_symbol) return incomplete_penetrance_genes
615,229
Make sure that the gene panels exist in the database Also check if the default panels are defined in gene panels Args: adapter(MongoAdapter) panels(list(str)): A list with panel names Returns: panels_exists(bool)
def check_panels(adapter, panels, default_panels=None): default_panels = default_panels or [] panels_exist = True for panel in default_panels: if panel not in panels: log.warning("Default panels have to be defined in panels") panels_exist = False for panel in panels:...
615,234
Load all variants in a region defined by a HGNC id Args: adapter (MongoAdapter) case_id (str): Case id hgnc_id (int): If all variants from a gene should be uploaded chrom (str): If variants from coordinates should be uploaded start (int): Start position for region en...
def load_region(adapter, case_id, hgnc_id=None, chrom=None, start=None, end=None): if hgnc_id: gene_obj = adapter.hgnc_gene(hgnc_id) if not gene_obj: ValueError("Gene {} does not exist in database".format(hgnc_id)) chrom = gene_obj['chromosome'] start = gene_obj['sta...
615,235
Load a new case from a Scout config. Args: adapter(MongoAdapter) config(dict): loading info ped(Iterable(str)): Pedigree ingformation update(bool): If existing case should be updated
def load_scout(adapter, config, ped=None, update=False): log.info("Check that the panels exists") if not check_panels(adapter, config.get('gene_panels', []), config.get('default_gene_panels')): raise ConfigError("Some panel(s) does not exist in the database") case_obj = ...
615,236
Get the hgnc id for a gene The proprity order will be 1. if there is a hgnc id this one will be choosen 2. if the hgnc symbol matches a genes proper hgnc symbol 3. if the symbol ony matches aliases on several genes one will be choosen at random Args: gene...
def get_hgnc_id(gene_info, adapter): hgnc_id = gene_info.get('hgnc_id') hgnc_symbol = gene_info.get('hgnc_symbol') true_id = None if hgnc_id: true_id = int(hgnc_id) else: gene_result = adapter.hgnc_genes(hgnc_symbol) if gene_result.count() == 0: raise Excep...
615,240
Load the hpo terms and hpo diseases into database Args: adapter(MongoAdapter) disease_lines(iterable(str)): These are the omim genemap2 information hpo_lines(iterable(str)) disease_lines(iterable(str)) hpo_gene_lines(iterable(str))
def load_hpo(adapter, disease_lines, hpo_disease_lines=None, hpo_lines=None, hpo_gene_lines=None): # Create a map from gene aliases to gene objects alias_genes = adapter.genes_by_alias() # Fetch the hpo terms if no file if not hpo_lines: hpo_lines = fetch_hpo_terms() # Fetch the h...
615,244