INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
vcf2cytosure CGH file for inidividual.
def vcf2cytosure(store, institute_id, case_name, individual_id): """vcf2cytosure CGH file for inidividual.""" institute_obj, case_obj = institute_and_case(store, institute_id, case_name) for individual in case_obj['individuals']: if individual['individual_id'] == individual_id: individual_obj = individual return (individual_obj['display_name'], individual_obj['vcf2cytosure'])
Pre - process list of variants.
def gene_variants(store, variants_query, page=1, per_page=50): """Pre-process list of variants.""" variant_count = variants_query.count() skip_count = per_page * max(page - 1, 0) more_variants = True if variant_count > (skip_count + per_page) else False variant_res = variants_query.skip(skip_count).limit(per_page) my_institutes = list(inst['_id'] for inst in user_institutes(store, current_user)) variants = [] for variant_obj in variant_res: # hide other institutes for now if variant_obj['institute'] not in my_institutes: LOG.warning("Institute {} not allowed.".format(variant_obj['institute'])) continue # Populate variant case_display_name variant_case_obj = store.case(case_id=variant_obj['case_id']) if not variant_case_obj: # A variant with missing case was encountered continue case_display_name = variant_case_obj.get('display_name') variant_obj['case_display_name'] = case_display_name genome_build = variant_case_obj.get('genome_build', '37') if genome_build not in ['37','38']: genome_build = '37' # Update the HGNC symbols if they are not set variant_genes = variant_obj.get('genes') if variant_genes is not None: for gene_obj in variant_genes: # If there is no hgnc id there is nothin we can do if not gene_obj['hgnc_id']: continue # Else we collect the gene object and check the id if gene_obj.get('hgnc_symbol') is None or gene_obj.get('description') is None: hgnc_gene = store.hgnc_gene(gene_obj['hgnc_id'], build=genome_build) if not hgnc_gene: continue gene_obj['hgnc_symbol'] = hgnc_gene['hgnc_symbol'] gene_obj['description'] = hgnc_gene['description'] # Populate variant HGVS and predictions gene_ids = [] gene_symbols = [] hgvs_c = [] hgvs_p = [] variant_genes = variant_obj.get('genes') if variant_genes is not None: functional_annotation = '' for gene_obj in variant_genes: hgnc_id = gene_obj['hgnc_id'] gene_symbol = gene(store, hgnc_id)['symbol'] gene_ids.append(hgnc_id) gene_symbols.append(gene_symbol) hgvs_nucleotide = '-' # gather HGVS info from gene transcripts transcripts_list = gene_obj.get('transcripts') for transcript_obj in transcripts_list: if transcript_obj.get('is_canonical') and transcript_obj.get('is_canonical') is True: hgvs_nucleotide = str(transcript_obj.get('coding_sequence_name')) hgvs_protein = str(transcript_obj.get('protein_sequence_name')) hgvs_c.append(hgvs_nucleotide) hgvs_p.append(hgvs_protein) if len(gene_symbols) == 1: if(hgvs_p[0] != "None"): hgvs = hgvs_p[0] elif(hgvs_c[0] != "None"): hgvs = hgvs_c[0] else: hgvs = "-" variant_obj['hgvs'] = hgvs # populate variant predictions for display variant_obj.update(get_predictions(variant_genes)) variants.append(variant_obj) return { 'variants': variants, 'more_variants': more_variants, }
Find MultiQC report for the case.
def multiqc(store, institute_id, case_name): """Find MultiQC report for the case.""" institute_obj, case_obj = institute_and_case(store, institute_id, case_name) return dict( institute=institute_obj, case=case_obj, )
Get all variants for an institute having Sanger validations ordered but still not evaluated
def get_sanger_unevaluated(store, institute_id, user_id): """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, varID_2, .., varID_n]} ], where the keys are case_ids and the values are lists of variants with Sanger ordered but not yet validated """ # 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_id, user_id) unevaluated = [] # for each object where key==case and value==[variant_id with Sanger ordered] for item in sanger_ordered_by_case: case_id = item['_id'] # Get the case to collect display name case_obj = store.case(case_id=case_id) if not case_obj: # the case might have been removed continue case_display_name = case_obj.get('display_name') # List of variant document ids varid_list = item['vars'] unevaluated_by_case = {} unevaluated_by_case[case_display_name] = [] for var_id in varid_list: # For each variant with sanger validation ordered variant_obj = store.variant(document_id=var_id, case_id=case_id) # Double check that Sanger was ordered (and not canceled) for the variant if variant_obj is None or variant_obj.get('sanger_ordered') is None or variant_obj.get('sanger_ordered') is False: continue validation = variant_obj.get('validation', 'not_evaluated') # Check that the variant is not evaluated if validation in ['True positive', 'False positive']: continue unevaluated_by_case[case_display_name].append(variant_obj['_id']) # If for a case there is at least one Sanger validation to evaluate add the object to the unevaluated objects list if len(unevaluated_by_case[case_display_name]) > 0: unevaluated.append(unevaluated_by_case) return unevaluated
Add a patient to MatchMaker server
def mme_add(store, user_obj, case_obj, add_gender, add_features, add_disorders, genes_only, mme_base_url, mme_accepts, mme_token): """Add a patient to MatchMaker server Args: store(adapter.MongoAdapter) user_obj(dict) a scout user object (to be added as matchmaker contact) case_obj(dict) a scout case object add_gender(bool) if True case gender will be included in matchmaker add_features(bool) if True HPO features will be included in matchmaker add_disorders(bool) if True OMIM diagnoses will be included in matchmaker genes_only(bool) if True only genes and not variants will be shared mme_base_url(str) base url of the MME server mme_accepts(str) request content accepted by MME server mme_token(str) auth token of the MME server Returns: submitted_info(dict) info submitted to MatchMaker and its responses """ if not mme_base_url or not mme_accepts or not mme_token: return 'Please check that Matchmaker connection parameters are valid' url = ''.join([mme_base_url, '/patient/add']) features = [] # this is the list of HPO terms disorders = [] # this is the list of OMIM diagnoses g_features = [] # create contact dictionary contact_info = { 'name' : user_obj['name'], 'href' : ''.join( ['mailto:',user_obj['email']] ), 'institution' : 'Scout software user, Science For Life Laboratory, Stockholm, Sweden' } if add_features: # create features dictionaries features = hpo_terms(case_obj) if add_disorders: # create OMIM disorders dictionaries disorders = omim_terms(case_obj) # send a POST request and collect response for each affected individual in case server_responses = [] submitted_info = { 'contact' : contact_info, 'sex' : add_gender, 'features' : features, 'disorders' : disorders, 'genes_only' : genes_only, 'patient_id' : [] } for individual in case_obj.get('individuals'): if not individual['phenotype'] in [2, 'affected']: # include only affected individuals continue patient = { 'contact' : contact_info, 'id' : '.'.join([case_obj['_id'], individual.get('individual_id')]), # This is a required field form MME 'label' : '.'.join([case_obj['display_name'], individual.get('display_name')]), 'features' : features, 'disorders' : disorders } if add_gender: if individual['sex'] == '1': patient['sex'] = 'MALE' else: patient['sex'] = 'FEMALE' if case_obj.get('suspects'): g_features = genomic_features(store, case_obj, individual.get('display_name'), genes_only) patient['genomicFeatures'] = g_features # send add request to server and capture response resp = matchmaker_request(url=url, token=mme_token, method='POST', content_type=mme_accepts, accept='application/json', data={'patient':patient}) server_responses.append({ 'patient': patient, 'message': resp.get('message'), 'status_code' : resp.get('status_code') }) submitted_info['server_responses'] = server_responses return submitted_info
Delete all affected samples for a case from MatchMaker
def mme_delete(case_obj, mme_base_url, mme_token): """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: { 'patient_id': patient_id 'message': server_message, 'status_code': server_status_code } """ 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']: # send delete request to server and capture server's response patient_id = patient['id'] url = ''.join([mme_base_url, '/patient/delete/', patient_id]) resp = matchmaker_request(url=url, token=mme_token, method='DELETE', ) server_responses.append({ 'patient_id': patient_id, 'message': resp.get('message'), 'status_code': resp.get('status_code') }) return server_responses
Show Matchmaker submission data for a sample and eventual matches.
def mme_matches(case_obj, institute_obj, mme_base_url, mme_token): """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 display in the html template """ 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_submission'): return None for patient in case_obj['mme_submission']['patients']: patient_id = patient['id'] matches[patient_id] = None url = ''.join([ mme_base_url, '/matches/', patient_id]) server_resp = matchmaker_request(url=url, token=mme_token, method='GET') if 'status_code' in server_resp: # the server returned a valid response # and this will be a list of match objects sorted by desc date pat_matches = [] if server_resp.get('matches'): pat_matches = parse_matches(patient_id, server_resp['matches']) matches[patient_id] = pat_matches else: LOG.warning('Server returned error message: {}'.format(server_resp['message'])) data['server_errors'].append(server_resp['message']) data['matches'] = matches return data
Initiate a MatchMaker match against either other Scout patients or external nodes
def mme_match(case_obj, match_type, mme_base_url, mme_token, nodes=None, mme_accepts=None): """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 mme_accepts(str): request content accepted by MME server (only for internal matches) Returns: matches(list): a list of eventual matches """ 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': url = ''.join([mme_base_url,'/match']) for patient in query_patients: json_resp = matchmaker_request(url=url, token=mme_token, method='POST', content_type=mme_accepts, accept=mme_accepts, data={'patient':patient}) resp_obj = { 'server' : 'Local MatchMaker node', 'patient_id' : patient['id'], 'results' : json_resp.get('results'), 'status_code' : json_resp.get('status_code'), 'message' : json_resp.get('message') # None if request was successful } server_responses.append(resp_obj) else: # external matching # external matching requires only patient ID query_patients = [ patient['id'] for patient in query_patients] node_ids = [ node['id'] for node in nodes ] if match_type in node_ids: # match is against a specific external node node_ids = [match_type] # Match every affected patient for patient in query_patients: # Against every node for node in node_ids: url = ''.join([mme_base_url,'/match/external/', patient, '?node=', node]) json_resp = matchmaker_request(url=url, token=mme_token, method='POST') resp_obj = { 'server' : node, 'patient_id' : patient, 'results' : json_resp.get('results'), 'status_code' : json_resp.get('status_code'), 'message' : json_resp.get('message') # None if request was successful } server_responses.append(resp_obj) return server_responses
Build a variant object based on parsed information
def build_variant(variant, institute_id, gene_to_panels = None, hgncid_to_gene=None, sample_info=None): """Build a variant object based on parsed information Args: variant(dict) institute_id(str) gene_to_panels(dict): A dictionary with {<hgnc_id>: { 'panel_names': [<panel_name>, ..], 'disease_associated_transcripts': [<transcript_id>, ..] } . . } hgncid_to_gene(dict): A dictionary with {<hgnc_id>: <hgnc_gene info> . . } sample_info(dict): A dictionary with info about samples. Strictly for cancer to tell which is tumor Returns: variant_obj(dict) variant = dict( # document_id is a md5 string created by institute_genelist_caseid_variantid: _id = str, # required, same as document_id document_id = str, # required # variant_id is a md5 string created by chrom_pos_ref_alt (simple_id) variant_id = str, # required # display name is variant_id (no md5) display_name = str, # required # chrom_pos_ref_alt simple_id = str, # The variant can be either research or clinical. # For research variants we display all the available information while # the clinical variants have limited annotation fields. variant_type = str, # required, choices=('research', 'clinical')) category = str, # choices=('sv', 'snv', 'str') sub_category = str, # choices=('snv', 'indel', 'del', 'ins', 'dup', 'inv', 'cnv', 'bnd') mate_id = str, # For SVs this identifies the other end case_id = str, # case_id is a string like owner_caseid chromosome = str, # required position = int, # required end = int, # required length = int, # required reference = str, # required alternative = str, # required rank_score = float, # required variant_rank = int, # required rank_score_results = list, # List if dictionaries variant_rank = int, # required institute = str, # institute_id, required sanger_ordered = bool, validation = str, # Sanger validation, choices=('True positive', 'False positive') quality = float, filters = list, # list of strings samples = list, # list of dictionaries that are <gt_calls> genetic_models = list, # list of strings choices=GENETIC_MODELS compounds = list, # sorted list of <compound> ordering='combined_score' genes = list, # list with <gene> dbsnp_id = str, # Gene ids: hgnc_ids = list, # list of hgnc ids (int) hgnc_symbols = list, # list of hgnc symbols (str) panels = list, # list of panel names that the variant ovelapps # Frequencies: thousand_genomes_frequency = float, thousand_genomes_frequency_left = float, thousand_genomes_frequency_right = float, exac_frequency = float, max_thousand_genomes_frequency = float, max_exac_frequency = float, local_frequency = float, local_obs_old = int, local_obs_hom_old = int, local_obs_total_old = int, # default=638 # Predicted deleteriousness: cadd_score = float, clnsig = list, # list of <clinsig> spidex = float, missing_data = bool, # default False # STR specific information str_repid = str, repeat id generally corresponds to gene symbol str_ru = str, used e g in PanelApp naming of STRs str_ref = int, reference copy number str_len = int, number of repeats found in case str_status = str, this indicates the severity of the expansion level # Callers gatk = str, # choices=VARIANT_CALL, default='Not Used' samtools = str, # choices=VARIANT_CALL, default='Not Used' freebayes = str, # choices=VARIANT_CALL, default='Not Used' # Conservation: phast_conservation = list, # list of str, choices=CONSERVATION gerp_conservation = list, # list of str, choices=CONSERVATION phylop_conservation = list, # list of str, choices=CONSERVATION # Database options: gene_lists = list, manual_rank = int, # choices=[0, 1, 2, 3, 4, 5] dismiss_variant = list, acmg_evaluation = str, # choices=ACMG_TERMS ) """ gene_to_panels = gene_to_panels or {} hgncid_to_gene = hgncid_to_gene or {} sample_info = sample_info or {} #LOG.debug("Building variant %s", variant['ids']['document_id']) variant_obj = dict( _id = variant['ids']['document_id'], document_id=variant['ids']['document_id'], variant_id=variant['ids']['variant_id'], display_name=variant['ids']['display_name'], variant_type=variant['variant_type'], case_id=variant['case_id'], chromosome=variant['chromosome'], reference=variant['reference'], alternative=variant['alternative'], institute=institute_id, ) variant_obj['missing_data'] = False variant_obj['position'] = int(variant['position']) variant_obj['rank_score'] = float(variant['rank_score']) end = variant.get('end') if end: variant_obj['end'] = int(end) length = variant.get('length') if length: variant_obj['length'] = int(length) variant_obj['simple_id'] = variant['ids'].get('simple_id') variant_obj['quality'] = float(variant['quality']) if variant['quality'] else None variant_obj['filters'] = variant['filters'] variant_obj['dbsnp_id'] = variant.get('dbsnp_id') variant_obj['cosmic_ids'] = variant.get('cosmic_ids') variant_obj['category'] = variant['category'] variant_obj['sub_category'] = variant.get('sub_category') if 'mate_id' in variant: variant_obj['mate_id'] = variant['mate_id'] if 'cytoband_start' in variant: variant_obj['cytoband_start'] = variant['cytoband_start'] if 'cytoband_end' in variant: variant_obj['cytoband_end'] = variant['cytoband_end'] if 'end_chrom' in variant: variant_obj['end_chrom'] = variant['end_chrom'] ############ Str specific ############ if 'str_ru' in variant: variant_obj['str_ru'] = variant['str_ru'] if 'str_repid' in variant: variant_obj['str_repid'] = variant['str_repid'] if 'str_ref' in variant: variant_obj['str_ref'] = variant['str_ref'] if 'str_len' in variant: variant_obj['str_len'] = variant['str_len'] if 'str_status' in variant: variant_obj['str_status'] = variant['str_status'] gt_types = [] for sample in variant.get('samples', []): gt_call = build_genotype(sample) gt_types.append(gt_call) if sample_info: sample_id = sample['individual_id'] if sample_info[sample_id] == 'case': key = 'tumor' else: key = 'normal' variant_obj[key] = { 'alt_depth': sample['alt_depth'], 'ref_depth': sample['ref_depth'], 'read_depth': sample['read_depth'], 'alt_freq': sample['alt_frequency'], 'ind_id': sample_id } variant_obj['samples'] = gt_types if 'genetic_models' in variant: variant_obj['genetic_models'] = variant['genetic_models'] # Add the compounds compounds = [] for compound in variant.get('compounds', []): compound_obj = build_compound(compound) compounds.append(compound_obj) if compounds: variant_obj['compounds'] = compounds # Add the genes with transcripts genes = [] for index, gene in enumerate(variant.get('genes', [])): if gene.get('hgnc_id'): gene_obj = build_gene(gene, hgncid_to_gene) genes.append(gene_obj) if index > 30: # avoid uploading too much data (specifically for SV variants) # mark variant as missing data variant_obj['missing_data'] = True break if genes: variant_obj['genes'] = genes # To make gene searches more effective if 'hgnc_ids' in variant: variant_obj['hgnc_ids'] = [hgnc_id for hgnc_id in variant['hgnc_ids'] if hgnc_id] # Add the hgnc symbols from the database genes hgnc_symbols = [] for hgnc_id in variant_obj['hgnc_ids']: gene_obj = hgncid_to_gene.get(hgnc_id) if gene_obj: hgnc_symbols.append(gene_obj['hgnc_symbol']) # else: # LOG.warn("missing HGNC symbol for: %s", hgnc_id) if hgnc_symbols: variant_obj['hgnc_symbols'] = hgnc_symbols # link gene panels panel_names = set() for hgnc_id in variant_obj['hgnc_ids']: gene_panels = gene_to_panels.get(hgnc_id, set()) panel_names = panel_names.union(gene_panels) if panel_names: variant_obj['panels'] = list(panel_names) # Add the clnsig ocbjects clnsig_objects = [] for entry in variant.get('clnsig', []): clnsig_obj = build_clnsig(entry) clnsig_objects.append(clnsig_obj) if clnsig_objects: variant_obj['clnsig'] = clnsig_objects # Add the callers call_info = variant.get('callers', {}) for caller in call_info: if call_info[caller]: variant_obj[caller] = call_info[caller] # Add the conservation conservation_info = variant.get('conservation', {}) if conservation_info.get('phast'): variant_obj['phast_conservation'] = conservation_info['phast'] if conservation_info.get('gerp'): variant_obj['gerp_conservation'] = conservation_info['gerp'] if conservation_info.get('phylop'): variant_obj['phylop_conservation'] = conservation_info['phylop'] # Add autozygosity calls if variant.get('azlength'): variant_obj['azlength'] = variant['azlength'] if variant.get('azqual'): variant_obj['azqual'] = variant['azqual'] # Add the frequencies frequencies = variant.get('frequencies', {}) if frequencies.get('thousand_g'): variant_obj['thousand_genomes_frequency'] = float(frequencies['thousand_g']) if frequencies.get('thousand_g_max'): variant_obj['max_thousand_genomes_frequency'] = float(frequencies['thousand_g_max']) if frequencies.get('exac'): variant_obj['exac_frequency'] = float(frequencies['exac']) if frequencies.get('exac_max'): variant_obj['max_exac_frequency'] = float(frequencies['exac_max']) if frequencies.get('gnomad'): variant_obj['gnomad_frequency'] = float(frequencies['gnomad']) if frequencies.get('gnomad_max'): variant_obj['max_gnomad_frequency'] = float(frequencies['gnomad_max']) if frequencies.get('thousand_g_left'): variant_obj['thousand_genomes_frequency_left'] = float(frequencies['thousand_g_left']) if frequencies.get('thousand_g_right'): variant_obj['thousand_genomes_frequency_right'] = float(frequencies['thousand_g_right']) # add the local observation counts from the old archive if variant.get('local_obs_old'): variant_obj['local_obs_old'] = variant['local_obs_old'] if variant.get('local_obs_hom_old'): variant_obj['local_obs_hom_old'] = variant['local_obs_hom_old'] # Add the sv counts: if frequencies.get('clingen_cgh_benign'): variant_obj['clingen_cgh_benign'] = frequencies['clingen_cgh_benign'] if frequencies.get('clingen_cgh_pathogenic'): variant_obj['clingen_cgh_pathogenic'] = frequencies['clingen_cgh_pathogenic'] if frequencies.get('clingen_ngi'): variant_obj['clingen_ngi'] = frequencies['clingen_ngi'] if frequencies.get('swegen'): variant_obj['swegen'] = frequencies['swegen'] # Decipher is never a frequency, it will ony give 1 if variant exists in decipher # Check if decipher exists if frequencies.get('decipher'): variant_obj['decipher'] = frequencies['decipher'] # If not check if field decipherAF exists elif frequencies.get('decipherAF'): variant_obj['decipher'] = frequencies['decipherAF'] # Add the severity predictors if variant.get('cadd_score'): variant_obj['cadd_score'] = variant['cadd_score'] if variant.get('spidex'): variant_obj['spidex'] = variant['spidex'] # Add the rank score results rank_results = [] for category in variant.get('rank_result', []): rank_result = { 'category': category, 'score': variant['rank_result'][category] } rank_results.append(rank_result) if rank_results: variant_obj['rank_score_results'] = rank_results # Cancer specific if variant.get('mvl_tag'): variant_obj['mvl_tag'] = True return variant_obj
Load the hgnc aliases to the mongo database.
def genes(context, build, api_key): """ Load the hgnc aliases to the mongo database. """ LOG.info("Running scout update genes") adapter = context.obj['adapter'] # Fetch the omim information api_key = api_key or context.obj.get('omim_api_key') if not api_key: LOG.warning("Please provide a omim api key to load the omim gene panel") context.abort() try: mim_files = fetch_mim_files(api_key, mim2genes=True, morbidmap=True, genemap2=True) except Exception as err: LOG.warning(err) context.abort() LOG.warning("Dropping all gene information") adapter.drop_genes(build) LOG.info("Genes dropped") LOG.warning("Dropping all transcript information") adapter.drop_transcripts(build) LOG.info("transcripts dropped") hpo_genes = fetch_hpo_genes() if build: builds = [build] else: builds = ['37', '38'] hgnc_lines = fetch_hgnc() exac_lines = fetch_exac_constraint() for build in builds: ensembl_genes = fetch_ensembl_genes(build=build) # load the genes hgnc_genes = load_hgnc_genes( adapter=adapter, ensembl_lines=ensembl_genes, hgnc_lines=hgnc_lines, exac_lines=exac_lines, mim2gene_lines=mim_files['mim2genes'], genemap_lines=mim_files['genemap2'], hpo_lines=hpo_genes, build=build, ) ensembl_genes = {} for gene_obj in hgnc_genes: ensembl_id = gene_obj['ensembl_id'] ensembl_genes[ensembl_id] = gene_obj # Fetch the transcripts from ensembl ensembl_transcripts = fetch_ensembl_transcripts(build=build) transcripts = load_transcripts(adapter, ensembl_transcripts, build, ensembl_genes) adapter.update_indexes() LOG.info("Genes, transcripts and Exons loaded")
Parse how the different variant callers have performed
def parse_callers(variant, category='snv'): """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>} """ 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': for caller in callers: callers[caller] = 'Filtered' elif call == 'Intersection': for caller in callers: callers[caller] = 'Pass' elif 'filterIn' in call: for caller in callers: if caller in call: callers[caller] = 'Filtered' elif call in set(callers.keys()): callers[call] = 'Pass' # The following is parsing of a custom made merge other_info = variant.INFO.get('FOUND_IN') if other_info: for info in other_info.split(','): called_by = info.split('|')[0] callers[called_by] = 'Pass' return callers
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): """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 """ description = description.strip('"') keyword = 'Format:' before_keyword, keyword, after_keyword = description.partition(keyword) return after_keyword.strip()
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): """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) """ 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
Build a hgnc_transcript object
def build_transcript(transcript_info, build='37'): """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 refseq_id: str, chrom: str, required start: int, required end: int, required is_primary: bool } """ 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 = transcript_info.get('refseq_id') refseq_identifiers = transcript_info.get('refseq_identifiers') try: chrom = transcript_info['chrom'] except KeyError: raise KeyError("Transcript has to have a chromosome") try: start = int(transcript_info['transcript_start']) except KeyError: raise KeyError("Transcript has to have start") except TypeError: raise TypeError("Transcript start has to be integer") try: end = int(transcript_info['transcript_end']) except KeyError: raise KeyError("Transcript has to have end") except TypeError: raise TypeError("Transcript end has to be integer") try: hgnc_id = int(transcript_info['hgnc_id']) except KeyError: raise KeyError("Transcript has to have a hgnc id") except TypeError: raise TypeError("hgnc id has to be integer") transcript_obj = HgncTranscript( transcript_id=transcript_id, hgnc_id=hgnc_id, chrom=chrom, start=start, end=end, is_primary=is_primary, refseq_id=refseq_id, refseq_identifiers=refseq_identifiers, build=build ) # Remove unnessesary keys for key in list(transcript_obj): if transcript_obj[key] is None: transcript_obj.pop(key) return transcript_obj
Load a institute into the database
def load_institute(adapter, internal_id, display_name, sanger_recipients=None): """Load a institute into the database Args: adapter(MongoAdapter) internal_id(str) display_name(str) sanger_recipients(list(email)) """ 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}" \ " into database".format(internal_id, display_name)) adapter.add_institute(institute_obj)
Check if the cadd phred score is annotated
def parse_cadd(variant, transcripts): """Check if the cadd phred score is annotated""" cadd = 0 cadd_keys = ['CADD', 'CADD_PHRED'] for key in cadd_keys: cadd = variant.INFO.get(key, 0) if cadd: return float(cadd) for transcript in transcripts: cadd_entry = transcript.get('cadd') if (cadd_entry and cadd_entry > cadd): cadd = cadd_entry return cadd
Load a case into the database.
def case(context, vcf, vcf_sv, vcf_cancer, vcf_str, owner, ped, update, config, no_variants, peddy_ped, peddy_sex, peddy_check): """Load a case into the database. A case can be loaded without specifying vcf files and/or bam files """ adapter = context.obj['adapter'] if config is None and ped is None: LOG.warning("Please provide either scout config or ped file") context.abort() # Scout needs a config object with the neccessary information # If no config is used create a dictionary config_raw = yaml.load(config) if config else {} try: config_data = parse_case_data( config=config_raw, ped=ped, owner=owner, vcf_snv=vcf, vcf_sv=vcf_sv, vcf_str=vcf_str, vcf_cancer=vcf_cancer, peddy_ped=peddy_ped, peddy_sex=peddy_sex, peddy_check=peddy_check ) except SyntaxError as err: LOG.warning(err) context.abort() LOG.info("Use family %s" % config_data['family']) try: case_obj = adapter.load_case(config_data, update) except Exception as err: LOG.error("Something went wrong during loading") LOG.warning(err) context.abort()
Update one variant document in the database.
def update_variant(self, variant_obj): """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) """ 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 ) return new_variant
Updates the manual rank for all variants in a case
def update_variant_rank(self, case_obj, variant_type='clinical', category='snv'): """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) """ # Get all variants sorted by rank score variants = self.variant_collection.find({ 'case_id': case_obj['_id'], 'category': category, 'variant_type': variant_type, }).sort('rank_score', pymongo.DESCENDING) LOG.info("Updating variant_rank for all variants") requests = [] for index, var_obj in enumerate(variants): if len(requests) > 5000: try: self.variant_collection.bulk_write(requests, ordered=False) requests = [] except BulkWriteError as err: LOG.warning("Updating variant rank failed") raise err operation = pymongo.UpdateOne( {'_id': var_obj['_id']}, { '$set': { 'variant_rank': index + 1, } }) requests.append(operation) #Update the final bulk try: self.variant_collection.bulk_write(requests, ordered=False) except BulkWriteError as err: LOG.warning("Updating variant rank failed") raise err LOG.info("Updating variant_rank done")
Update compounds for a variant.
def update_variant_compounds(self, variant, variant_objs = None): """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(dict)): A dictionary with updated compound objects. """ compound_objs = [] for compound in variant.get('compounds', []): not_loaded = True gene_objs = [] # Check if the compound variant exists if variant_objs: variant_obj = variant_objs.get(compound['variant']) else: variant_obj = self.variant_collection.find_one({'_id': compound['variant']}) if variant_obj: # If the variant exosts we try to collect as much info as possible not_loaded = False compound['rank_score'] = variant_obj['rank_score'] for gene in variant_obj.get('genes', []): gene_obj = { 'hgnc_id': gene['hgnc_id'], 'hgnc_symbol': gene.get('hgnc_symbol'), 'region_annotation': gene.get('region_annotation'), 'functional_annotation': gene.get('functional_annotation'), } gene_objs.append(gene_obj) compound['genes'] = gene_objs compound['not_loaded'] = not_loaded compound_objs.append(compound) return compound_objs
Update the compounds for a set of variants.
def update_compounds(self, variants): """Update the compounds for a set of variants. Args: variants(dict): A dictionary with _ids as keys and variant objs as values """ 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, variants) variant_obj['compounds'] = updated_compounds LOG.debug("Compounds updated") return variants
Update the compound information for a bulk of variants in the database
def update_mongo_compound_variants(self, bulk): """Update the compound information for a bulk of variants in the database Args: bulk(dict): {'_id': scout.models.Variant} """ 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( {'_id': var_obj['_id']}, { '$set': { 'compounds': var_obj['compounds'] } }) requests.append(operation) if not requests: return try: self.variant_collection.bulk_write(requests, ordered=False) except BulkWriteError as err: LOG.warning("Updating compounds failed") raise err
Update the compounds for a case
def update_case_compounds(self, case_obj, build='37'): """Update the compounds for a case Loop over all coding intervals to get coordinates for all potential compound positions. Update all variants within a gene with a bulk operation. """ case_id = case_obj['_id'] # Possible categories 'snv', 'sv', 'str', 'cancer': categories = set() # Possible variant types 'clinical', 'research': variant_types = set() for file_type in FILE_TYPE_MAP: if case_obj.get('vcf_files',{}).get(file_type): categories.add(FILE_TYPE_MAP[file_type]['category']) variant_types.add(FILE_TYPE_MAP[file_type]['variant_type']) coding_intervals = self.get_coding_intervals(build=build) # Loop over all intervals for chrom in CHROMOSOMES: intervals = coding_intervals.get(chrom, IntervalTree()) for var_type in variant_types: for category in categories: LOG.info("Updating compounds on chromosome:{0}, type:{1}, category:{2} for case:{3}".format( chrom, var_type, category, case_id)) # Fetch all variants from a chromosome query = { 'variant_type': var_type, 'chrom': chrom, } # Get all variants from the database of the specific type variant_objs = self.variants( case_id=case_id, query=query, category=category, nr_of_variants=-1, sort_key='position' ) # Initiate a bulk bulk = {} current_region = None special = False # Loop over the variants and check if they are in a coding region for var_obj in variant_objs: var_id = var_obj['_id'] var_chrom = var_obj['chromosome'] var_start = var_obj['position'] var_end = var_obj['end'] + 1 update_bulk = True new_region = None # Check if the variant is in a coding region genomic_regions = coding_intervals.get(var_chrom, IntervalTree()).search(var_start, var_end) # If the variant is in a coding region if genomic_regions: # We know there is data here so get the interval id new_region = genomic_regions.pop().data if new_region and (new_region == current_region): # If the variant is in the same region as previous # we add it to the same bulk update_bulk = False current_region = new_region # If the variant is not in a current region we update the compounds # from the previous region, if any. Otherwise continue if update_bulk and bulk: self.update_compounds(bulk) self.update_mongo_compound_variants(bulk) bulk = {} if new_region: bulk[var_id] = var_obj if not bulk: continue self.update_compounds(bulk) self.update_mongo_compound_variants(bulk) LOG.info("All compounds updated") return
Load a variant object
def load_variant(self, variant_obj): """Load a variant object Args: variant_obj(dict) Returns: inserted_id """ # 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['_id']) return result
Load a variant object if the object already exists update compounds.
def upsert_variant(self, variant_obj): """Load a variant object, if the object already exists update compounds. Args: variant_obj(dict) Returns: result """ 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']) result = self.variant_collection.find_one_and_update( {'_id': variant_obj['_id']}, { '$set': { 'compounds': variant_obj.get('compounds',[]) } } ) variant = self.variant_collection.find_one({'_id': variant_obj['_id']}) return result
Load a bulk of variants
def load_variant_bulk(self, variants): """Load a bulk of variants Args: variants(iterable(scout.models.Variant)) Returns: object_ids """ 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 wrong there are probably some variants already existing # In the database. So insert each variant for var_obj in variants: try: self.upsert_variant(var_obj) except IntegrityError as err: pass return
Perform the loading of variants
def _load_variants(self, variants, variant_type, case_obj, individual_positions, rank_threshold, institute_id, build=None, rank_results_header=None, vep_header=None, category='snv', sample_info = None): """Perform the loading of variants This is the function that loops over the variants, parse them and build the variant objects so they are ready to be inserted into the database. """ build = build or '37' genes = [gene_obj for gene_obj in self.all_genes(build=build)] gene_to_panels = self.gene_to_panels(case_obj) hgncid_to_gene = self.hgncid_to_gene(genes=genes) genomic_intervals = self.get_coding_intervals(genes=genes) LOG.info("Start inserting {0} {1} variants into database".format(variant_type, category)) start_insertion = datetime.now() start_five_thousand = datetime.now() # These are the number of parsed varaints nr_variants = 0 # These are the number of variants that meet the criteria and gets inserted nr_inserted = 0 # This is to keep track of blocks of inserted variants inserted = 1 nr_bulks = 0 # We want to load batches of variants to reduce the number of network round trips bulk = {} current_region = None for nr_variants, variant in enumerate(variants): # All MT variants are loaded mt_variant = 'MT' in variant.CHROM rank_score = parse_rank_score(variant.INFO.get('RankScore'), case_obj['_id']) # Check if the variant should be loaded at all # if rank score is None means there are no rank scores annotated, all variants will be loaded # Otherwise we load all variants above a rank score treshold # Except for MT variants where we load all variants if (rank_score is None) or (rank_score > rank_threshold) or mt_variant: nr_inserted += 1 # Parse the vcf variant parsed_variant = parse_variant( variant=variant, case=case_obj, variant_type=variant_type, rank_results_header=rank_results_header, vep_header=vep_header, individual_positions=individual_positions, category=category, ) # Build the variant object variant_obj = build_variant( variant=parsed_variant, institute_id=institute_id, gene_to_panels=gene_to_panels, hgncid_to_gene=hgncid_to_gene, sample_info=sample_info ) # Check if the variant is in a genomic region var_chrom = variant_obj['chromosome'] var_start = variant_obj['position'] # We need to make sure that the interval has a length > 0 var_end = variant_obj['end'] + 1 var_id = variant_obj['_id'] # If the bulk should be loaded or not load = True new_region = None genomic_regions = genomic_intervals.get(var_chrom, IntervalTree()).search(var_start, var_end) # If the variant is in a coding region if genomic_regions: # We know there is data here so get the interval id new_region = genomic_regions.pop().data # If the variant is in the same region as previous # we add it to the same bulk if new_region == current_region: load = False # This is the case where the variant is intergenic else: # If the previous variant was also intergenic we add the variant to the bulk if not current_region: load = False # We need to have a max size of the bulk if len(bulk) > 10000: load = True # Load the variant object if load: # If the variant bulk contains coding variants we want to update the compounds if current_region: self.update_compounds(bulk) try: # Load the variants self.load_variant_bulk(list(bulk.values())) nr_bulks += 1 except IntegrityError as error: pass bulk = {} current_region = new_region bulk[var_id] = variant_obj if (nr_variants != 0 and nr_variants % 5000 == 0): LOG.info("%s variants parsed", str(nr_variants)) LOG.info("Time to parse variants: %s", (datetime.now() - start_five_thousand)) start_five_thousand = datetime.now() if (nr_inserted != 0 and (nr_inserted * inserted) % (1000 * inserted) == 0): LOG.info("%s variants inserted", nr_inserted) inserted += 1 # If the variants are in a coding region we update the compounds if current_region: self.update_compounds(bulk) # Load the final variant bulk self.load_variant_bulk(list(bulk.values())) nr_bulks += 1 LOG.info("All variants inserted, time to insert variants: {0}".format( datetime.now() - start_insertion)) if nr_variants: nr_variants += 1 LOG.info("Nr variants parsed: %s", nr_variants) LOG.info("Nr variants inserted: %s", nr_inserted) LOG.debug("Nr bulks inserted: %s", nr_bulks) return nr_inserted
Load variants for a case into scout.
def load_variants(self, case_obj, variant_type='clinical', category='snv', rank_threshold=None, chrom=None, start=None, end=None, gene_obj=None, build='37'): """Load variants for a case into scout. Load the variants for a specific analysis type and category into scout. If no region is specified, load all variants above rank score threshold If region or gene is specified, load all variants from that region disregarding variant rank(if not specified) Args: case_obj(dict): A case from the scout database variant_type(str): 'clinical' or 'research'. Default: 'clinical' category(str): 'snv', 'str' or 'sv'. Default: 'snv' rank_threshold(float): Only load variants above this score. Default: 0 chrom(str): Load variants from a certain chromosome start(int): Specify the start position end(int): Specify the end position gene_obj(dict): A gene object from the database Returns: nr_inserted(int) """ # We need the institute object institute_id = self.institute(institute_id=case_obj['owner'])['_id'] nr_inserted = 0 variant_file = None if variant_type == 'clinical': if category == 'snv': variant_file = case_obj['vcf_files'].get('vcf_snv') elif category == 'sv': variant_file = case_obj['vcf_files'].get('vcf_sv') elif category == 'str': LOG.debug('Attempt to load STR VCF.') variant_file = case_obj['vcf_files'].get('vcf_str') elif category == 'cancer': # Currently this implies a paired tumor normal variant_file = case_obj['vcf_files'].get('vcf_cancer') elif variant_type == 'research': if category == 'snv': variant_file = case_obj['vcf_files'].get('vcf_snv_research') elif category == 'sv': variant_file = case_obj['vcf_files'].get('vcf_sv_research') elif category == 'cancer': variant_file = case_obj['vcf_files'].get('vcf_cancer_research') if not variant_file: raise SyntaxError("Vcf file does not seem to exist") # Check if there are any variants in file try: vcf_obj = VCF(variant_file) var = next(vcf_obj) except StopIteration as err: LOG.warning("Variant file %s does not include any variants", variant_file) return nr_inserted # We need to reload the file vcf_obj = VCF(variant_file) # Parse the neccessary headers from vcf file rank_results_header = parse_rank_results_header(vcf_obj) vep_header = parse_vep_header(vcf_obj) # This is a dictionary to tell where ind are in vcf individual_positions = {} for i, ind in enumerate(vcf_obj.samples): individual_positions[ind] = i # Dictionary for cancer analysis sample_info = {} if category == 'cancer': for ind in case_obj['individuals']: if ind['phenotype'] == 2: sample_info[ind['individual_id']] = 'case' else: sample_info[ind['individual_id']] = 'control' # Check if a region scould be uploaded region = "" if gene_obj: chrom = gene_obj['chromosome'] # Add same padding as VEP start = max(gene_obj['start'] - 5000, 0) end = gene_obj['end'] + 5000 if chrom: # We want to load all variants in the region regardless of rank score rank_threshold = rank_threshold or -1000 if not (start and end): raise SyntaxError("Specify chrom start and end") region = "{0}:{1}-{2}".format(chrom, start, end) else: rank_threshold = rank_threshold or 0 variants = vcf_obj(region) try: nr_inserted = self._load_variants( variants=variants, variant_type=variant_type, case_obj=case_obj, individual_positions=individual_positions, rank_threshold=rank_threshold, institute_id=institute_id, build=build, rank_results_header=rank_results_header, vep_header=vep_header, category=category, sample_info = sample_info ) except Exception as error: LOG.exception('unexpected error') LOG.warning("Deleting inserted variants") self.delete_variants(case_obj['_id'], variant_type) raise error self.update_variant_rank(case_obj, variant_type, category=category) return nr_inserted
Assign a user to a case.
def assign(self, institute, case, user, link): """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 link (str): The url to be used in the event Returns: updated_case(dict) """ 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=link, category='case', verb='assign', subject=case['display_name'] ) LOG.info("Updating {0} to be assigned with {1}" .format(case['display_name'], user['name'])) updated_case = self.case_collection.find_one_and_update( {'_id': case['_id']}, {'$addToSet': {'assignees': user['_id']}}, return_document=pymongo.ReturnDocument.AFTER ) return updated_case
Share a case with a new institute.
def share(self, institute, case, collaborator_id, user, link): """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_case """ if collaborator_id in case.get('collaborators', []): raise ValueError('new customer is already a collaborator') self.create_event( institute=institute, case=case, user=user, link=link, category='case', verb='share', subject=collaborator_id ) updated_case = self.case_collection.find_one_and_update( {'_id': case['_id']}, { '$push': {'collaborators': collaborator_id} }, return_document=pymongo.ReturnDocument.AFTER ) LOG.debug("Case updated") return updated_case
Diagnose a case using OMIM ids.
def diagnose(self, institute, case, user, link, level, omim_id, remove=False): """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: updated_case """ if level == 'phenotype': case_key = 'diagnosis_phenotypes' elif level == 'gene': case_key = 'diagnosis_genes' else: raise TypeError('wrong level') diagnosis_list = case.get(case_key, []) omim_number = int(omim_id.split(':')[-1]) updated_case = None if remove and omim_number in diagnosis_list: updated_case = self.case_collection.find_one_and_update( {'_id': case['_id']}, {'$pull': {case_key: omim_number}}, return_document=pymongo.ReturnDocument.AFTER ) elif omim_number not in diagnosis_list: updated_case = self.case_collection.find_one_and_update( {'_id': case['_id']}, {'$push': {case_key: omim_number}}, return_document=pymongo.ReturnDocument.AFTER ) if updated_case: self.create_event( institute=institute, case=case, user=user, link=link, category='case', verb='update_diagnosis', subject=case['display_name'], content=omim_id ) return updated_case
Mark a case as checked from an analysis point of view.
def mark_checked(self, institute, case, user, link, unmark=False): """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 Return: updated_case """ LOG.info("Updating checked status of {}" .format(case['display_name'])) status = 'not checked' if unmark else 'checked' self.create_event( institute=institute, case=case, user=user, link=link, category='case', verb='check_case', subject=status ) LOG.info("Updating {0}'s checked status {1}" .format(case['display_name'], status)) analysis_checked = False if unmark else True updated_case = self.case_collection.find_one_and_update( {'_id': case['_id']}, { '$set': {'analysis_checked': analysis_checked} }, return_document=pymongo.ReturnDocument.AFTER ) LOG.debug("Case updated") return updated_case
Update default panels for a case.
def update_default_panels(self, institute_obj, case_obj, user_obj, link, panel_objs): """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: updated_case(dict) """ self.create_event( institute=institute_obj, case=case_obj, user=user_obj, link=link, category='case', verb='update_default_panels', subject=case_obj['display_name'], ) LOG.info("Update default panels for {}".format(case_obj['display_name'])) panel_ids = [panel['_id'] for panel in panel_objs] for existing_panel in case_obj['panels']: if existing_panel['panel_id'] in panel_ids: existing_panel['is_default'] = True else: existing_panel['is_default'] = False updated_case = self.case_collection.find_one_and_update( {'_id': case_obj['_id']}, { '$set': {'panels': case_obj['panels']} }, return_document=pymongo.ReturnDocument.AFTER ) LOG.debug("Case updated") return updated_case
Create an event for a variant verification for a variant and an event for a variant verification for a case
def order_verification(self, institute, case, user, link, variant): """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 variant (dict): A variant object Returns: updated_variant(dict) """ 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']}, {'$set': {'sanger_ordered': True}}, return_document=pymongo.ReturnDocument.AFTER ) self.create_event( institute=institute, case=case, user=user, link=link, category='variant', verb='sanger', variant=variant, subject=variant['display_name'], ) LOG.info("Creating event for ordering sanger for case" \ " {0}".format(case['display_name'])) self.create_event( institute=institute, case=case, user=user, link=link, category='case', verb='sanger', variant=variant, subject=variant['display_name'], ) return updated_variant
Get all variants with validations ever ordered.
def sanger_ordered(self, institute_id=None, user_id=None): """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 """ query = {'$match': { '$and': [ {'verb': 'sanger'}, ], }} if institute_id: query['$match']['$and'].append({'institute': institute_id}) if user_id: query['$match']['$and'].append({'user_id': user_id}) # Get all sanger ordered variants grouped by case_id results = self.event_collection.aggregate([ query, {'$group': { '_id': "$case", 'vars': {'$addToSet' : '$variant_id'} }} ]) sanger_ordered = [item for item in results] return sanger_ordered
Mark validation status for a variant.
def validate(self, institute, case, user, link, variant, validate_type): """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 outcome of validation. choices=('True positive', 'False positive') Returns: updated_variant(dict) """ 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 = self.variant_collection.find_one_and_update( {'_id': variant['_id']}, {'$set': {'validation': validate_type}}, return_document=pymongo.ReturnDocument.AFTER ) self.create_event( institute=institute, case=case, user=user, link=link, category='variant', verb='validate', variant=variant, subject=variant['display_name'], ) return updated_variant
Create an event for marking a variant causative.
def mark_causative(self, institute, case, user, link, variant): """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: updated_case(dict) """ 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( case['display_name'])) LOG.info("Marking case {0} as solved".format( case['display_name'])) updated_case = self.case_collection.find_one_and_update( {'_id': case['_id']}, { '$push': {'causatives': variant['_id']}, '$set': {'status': 'solved'} }, return_document=pymongo.ReturnDocument.AFTER ) LOG.info("Creating case event for marking {0}" \ " causative".format(variant['display_name'])) self.create_event( institute=institute, case=case, user=user, link=link, category='case', verb='mark_causative', variant=variant, subject=variant['display_name'], ) LOG.info("Creating variant event for marking {0}" \ " causative".format(case['display_name'])) self.create_event( institute=institute, case=case, user=user, link=link, category='variant', verb='mark_causative', variant=variant, subject=variant['display_name'], ) return updated_case
Create an event for updating the manual dismiss variant entry
def update_dismiss_variant(self, institute, case, user, link, variant, dismiss_variant): """Create an event for updating the manual dismiss variant entry This function will create a event and update the dismiss variant field of the 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 dismiss_variant (list): The new dismiss variant list Return: updated_variant """ LOG.info("Creating event for updating dismiss variant for " "variant {0}".format(variant['display_name'])) self.create_event( institute=institute, case=case, user=user, link=link, category='variant', verb='dismiss_variant', variant=variant, subject=variant['display_name'], ) if dismiss_variant: LOG.info("Setting dismiss variant to {0} for variant {1}" .format(dismiss_variant, variant['display_name'])) action = '$set' else: LOG.info("Reset dismiss variant from {0} for variant {1}" .format(variant['dismiss_variant'], variant['display_name'])) action = '$unset' updated_variant = self.variant_collection.find_one_and_update( {'_id': variant['_id']}, {action: {'dismiss_variant': dismiss_variant}}, return_document=pymongo.ReturnDocument.AFTER ) LOG.debug("Variant updated") return updated_variant
Create an event for updating the ACMG classification of a variant.
def update_acmg(self, institute_obj, case_obj, user_obj, link, variant_obj, acmg_str): """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 variant object acmg_str (str): The new ACMG classification string Returns: updated_variant """ self.create_event( institute=institute_obj, case=case_obj, user=user_obj, link=link, category='variant', verb='acmg', variant=variant_obj, subject=variant_obj['display_name'], ) LOG.info("Setting ACMG to {} for: {}".format(acmg_str, variant_obj['display_name'])) if acmg_str is None: updated_variant = self.variant_collection.find_one_and_update( {'_id': variant_obj['_id']}, {'$unset': {'acmg_classification': 1}}, return_document=pymongo.ReturnDocument.AFTER ) else: updated_variant = self.variant_collection.find_one_and_update( {'_id': variant_obj['_id']}, {'$set': {'acmg_classification': REV_ACMG_MAP[acmg_str]}}, return_document=pymongo.ReturnDocument.AFTER ) LOG.debug("Variant updated") return updated_variant
Construct the necessary ids for a variant
def parse_ids(chrom, pos, ref, alt, case_id, variant_type): """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): Dictionary with the relevant ids """ 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) ids['document_id'] = parse_document_id(chrom, pos, ref, alt, variant_type, case_id) return ids
Parse the simple id for a variant
def parse_simple_id(chrom, pos, ref, alt): """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 """ return '_'.join([chrom, pos, ref, alt])
Parse the variant id for a variant
def parse_variant_id(chrom, pos, ref, alt, variant_type): """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: variant_id(str): The variant id converted to md5 string """ return generate_md5_key([chrom, pos, ref, alt, variant_type])
Parse the variant id for a variant
def parse_display_name(chrom, pos, ref, alt, variant_type): """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 """ return '_'.join([chrom, pos, ref, alt, variant_type])
Parse the unique document id for a variant.
def parse_document_id(chrom, pos, ref, alt, variant_type, case_id): """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 document id in an md5 string """ return generate_md5_key([chrom, pos, ref, alt, variant_type, case_id])
Convert a gene panel with hgnc symbols to a new one with hgnc ids.
def convert(context, panel): """Convert a gene panel with hgnc symbols to a new one with hgnc ids.""" adapter = context.obj['adapter'] new_header = ["hgnc_id","hgnc_symbol","disease_associated_transcripts", "reduced_penetrance", "genetic_disease_models", "mosaicism", "database_entry_version"] genes = parse_genes(panel) adapter.add_hgnc_id(genes) click.echo("#{0}".format('\t'.join(new_header))) for gene in genes: if gene.get('hgnc_id'): print_info = [] for head in new_header: print_info.append(str(gene[head]) if gene.get(head) else '') click.echo('\t'.join(print_info))
Create a new variant id.
def get_variantid(variant_obj, family_id): """Create a new variant id. Args: variant_obj(dict) family_id(str) Returns: new_id(str): The new variant 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, ) return new_id
Fetches all cases from the backend.
def cases(self, owner=None, collaborator=None, query=None, skip_assigned=False, has_causatives=False, reruns=False, finished=False, research_requested=False, is_research=False, status=None, phenotype_terms=False, pinned=False, cohort=False, name_query=None, yield_query=False): """Fetches all cases from the backend. Args: collaborator(str): If collaborator should be considered owner(str): Query cases for specified case owner only query(dict): If a specific query is used skip_assigned(bool) has_causatives(bool) reruns(bool) finished(bool) research_requested(bool) is_research(bool) status(str) phenotype_terms(bool): Fetch all cases with phenotype terms pinned(bool): Fetch all cases with pinned variants name_query(str): Could be hpo term, HPO-group, user, part of display name, part of inds or part of synopsis yield_query(bool): If true, only return mongo query dict for use in compound querying. Returns: Cases ordered by date. If yield_query is True, does not pose query to db; instead returns corresponding query dict that can be reused in compound queries or for testing. """ LOG.debug("Fetch all cases") query = query or {} # Prioritize when both owner and collaborator params are present if collaborator and owner: collaborator = None if collaborator: LOG.debug("Use collaborator {0}".format(collaborator)) query['collaborators'] = collaborator if owner: LOG.debug("Use owner {0}".format(owner)) query['owner'] = owner if skip_assigned: query['assignees'] = {'$exists': False} if has_causatives: query['causatives'] = {'$exists': True, '$ne': []} if reruns: query['rerun_requested'] = True if status: query['status'] = status elif finished: query['status'] = {'$in': ['solved', 'archived']} if research_requested: query['research_requested'] = True if is_research: query['is_research'] = {'$exists': True, '$eq': True} if phenotype_terms: query['phenotype_terms'] = {'$exists': True, '$ne': []} if pinned: query['suspects'] = {'$exists': True, '$ne': []} if cohort: query['cohorts'] = {'$exists': True, '$ne': []} if name_query: name_value = name_query.split(':')[-1] # capture ant value provided after query descriptor users = self.user_collection.find({'name': {'$regex': name_query, '$options': 'i'}}) if users.count() > 0: query['assignees'] = {'$in': [user['email'] for user in users]} elif name_query.startswith('HP:'): LOG.debug("HPO case query") if name_value: query['phenotype_terms.phenotype_id'] = name_query else: # query for cases with no HPO terms query['$or'] = [ {'phenotype_terms' : {'$size' : 0}}, {'phenotype_terms' : {'$exists' : False}} ] elif name_query.startswith('PG:'): LOG.debug("PG case query") if name_value: phenotype_group_query = name_query.replace('PG:', 'HP:') query['phenotype_groups.phenotype_id'] = phenotype_group_query else: # query for cases with no phenotype groups query['$or'] = [ {'phenotype_groups' : {'$size' : 0}}, {'phenotype_groups' : {'$exists' : False}} ] elif name_query.startswith('synopsis:'): if name_value: query['$text']={'$search':name_value} else: # query for cases with missing synopsis query['synopsis'] = '' elif name_query.startswith('cohort:'): query['cohorts'] = name_value elif name_query.startswith('panel:'): query['panels'] = {'$elemMatch': {'panel_name': name_value, 'is_default': True }} elif name_query.startswith('status:'): status_query = name_query.replace('status:','') query['status'] = status_query elif name_query.startswith('is_research'): query['is_research'] = {'$exists': True, '$eq': True} else: query['$or'] = [ {'display_name': {'$regex': name_query}}, {'individuals.display_name': {'$regex': name_query}}, ] if yield_query: return query LOG.info("Get cases with query {0}".format(query)) return self.case_collection.find(query).sort('updated_at', -1)
Return the number of cases
def nr_cases(self, institute_id=None): """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) """ 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
Update the dynamic gene list for a case
def update_dynamic_gene_list(self, case, hgnc_symbols=None, hgnc_ids=None, phenotype_ids=None, build='37'): """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 hgnc_symbols (iterable): A list of hgnc_symbols hgnc_ids (iterable): A list of hgnc_ids Returns: updated_case(dict) """ dynamic_gene_list = [] res = [] if hgnc_ids: LOG.info("Fetching genes by hgnc id") res = self.hgnc_collection.find({'hgnc_id': {'$in': hgnc_ids}, 'build': build}) elif hgnc_symbols: LOG.info("Fetching genes by hgnc symbols") res = [] for symbol in hgnc_symbols: for gene_obj in self.gene_by_alias(symbol=symbol, build=build): res.append(gene_obj) for gene_obj in res: dynamic_gene_list.append( { 'hgnc_symbol': gene_obj['hgnc_symbol'], 'hgnc_id': gene_obj['hgnc_id'], 'description': gene_obj['description'], } ) LOG.info("Update dynamic gene panel for: %s", case['display_name']) updated_case = self.case_collection.find_one_and_update( {'_id': case['_id']}, {'$set': {'dynamic_gene_list': dynamic_gene_list, 'dynamic_panel_phenotypes': phenotype_ids or []}}, return_document=pymongo.ReturnDocument.AFTER ) LOG.debug("Case updated") return updated_case
Fetches a single case from database
def case(self, case_id=None, institute_id=None, display_name=None): """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 """ 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 both institute_id and display_name") LOG.info("Fetching case %s institute %s", display_name, institute_id) query['owner'] = institute_id query['display_name'] = display_name return self.case_collection.find_one(query)
Delete a single case from database
def delete_case(self, case_id=None, institute_id=None, display_name=None): """Delete a single case from database Args: institute_id(str) case_id(str) Returns: case_obj(dict): The case that was deleted """ 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 provide both institute_id and display_name") LOG.info("Deleting case %s institute %s", display_name, institute_id) query['owner'] = institute_id query['display_name'] = display_name result = self.case_collection.delete_one(query) return result
Load a case into the database
def load_case(self, config_data, update=False): """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) """ # 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 the case information parsed_case = parse_case(config=config_data) # Build the case object case_obj = build_case(parsed_case, self) # Check if case exists with old case id old_caseid = '-'.join([case_obj['owner'], case_obj['display_name']]) old_case = self.case(old_caseid) if old_case: LOG.info("Update case id for existing case: %s -> %s", old_caseid, case_obj['_id']) self.update_caseid(old_case, case_obj['_id']) update = True # Check if case exists in database existing_case = self.case(case_obj['_id']) if existing_case and not update: raise IntegrityError("Case %s already exists in database" % case_obj['_id']) files = [ {'file_name': 'vcf_snv', 'variant_type': 'clinical', 'category': 'snv'}, {'file_name': 'vcf_sv', 'variant_type': 'clinical', 'category': 'sv'}, {'file_name': 'vcf_cancer', 'variant_type': 'clinical', 'category': 'cancer'}, {'file_name': 'vcf_str', 'variant_type': 'clinical', 'category': 'str'} ] try: for vcf_file in files: # Check if file exists if not case_obj['vcf_files'].get(vcf_file['file_name']): LOG.debug("didn't find {}, skipping".format(vcf_file['file_name'])) continue variant_type = vcf_file['variant_type'] category = vcf_file['category'] if update: self.delete_variants( case_id=case_obj['_id'], variant_type=variant_type, category=category ) self.load_variants( case_obj=case_obj, variant_type=variant_type, category=category, rank_threshold=case_obj.get('rank_score_threshold', 0), ) except (IntegrityError, ValueError, ConfigError, KeyError) as error: LOG.warning(error) if existing_case and update: self.update_case(case_obj) else: LOG.info('Loading case %s into database', case_obj['display_name']) self._add_case(case_obj) return case_obj
Add a case to the database If the case already exists exception is raised
def _add_case(self, case_obj): """Add a case to the database If the case already exists exception is raised Args: case_obj(Case) """ 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)
Update a case in the database
def update_case(self, case_obj): """Update a case in the database The following will be updated: - collaborators: If new collaborators these will be added to the old ones - analysis_date: Is updated to the new date - analyses: The new analysis date will be added to old runs - individuals: There could be new individuals - updated_at: When the case was updated in the database - rerun_requested: Is set to False since that is probably what happened - panels: The new gene panels are added - genome_build: If there is a new genome build - genome_version: - || - - rank_model_version: If there is a new rank model - madeline_info: If there is a new pedigree - vcf_files: paths to the new files - has_svvariants: If there are new svvariants - has_strvariants: If there are new strvariants - multiqc: If there's an updated multiqc report location - mme_submission: If case was submitted to MatchMaker Exchange Args: case_obj(dict): The new case information Returns: updated_case(dict): The updated case information """ # Todo: rename to match the intended purpose LOG.info("Updating case {0}".format(case_obj['_id'])) old_case = self.case_collection.find_one( {'_id': case_obj['_id']} ) updated_case = self.case_collection.find_one_and_update( {'_id': case_obj['_id']}, { '$addToSet': { 'collaborators': {'$each': case_obj['collaborators']}, 'analyses': { 'date': old_case['analysis_date'], 'delivery_report': old_case.get('delivery_report') } }, '$set': { 'analysis_date': case_obj['analysis_date'], 'delivery_report': case_obj.get('delivery_report'), 'individuals': case_obj['individuals'], 'updated_at': datetime.datetime.now(), 'rerun_requested': False, 'panels': case_obj.get('panels', []), 'genome_build': case_obj.get('genome_build', '37'), 'genome_version': case_obj.get('genome_version'), 'rank_model_version': case_obj.get('rank_model_version'), 'madeline_info': case_obj.get('madeline_info'), 'vcf_files': case_obj.get('vcf_files'), 'has_svvariants': case_obj.get('has_svvariants'), 'has_strvariants': case_obj.get('has_strvariants'), 'is_research': case_obj.get('is_research', False), 'research_requested': case_obj.get('research_requested', False), 'multiqc': case_obj.get('multiqc'), 'mme_submission': case_obj.get('mme_submission'), } }, return_document=pymongo.ReturnDocument.AFTER ) LOG.info("Case updated") return updated_case
Replace a existing case with a new one
def replace_case(self, case_obj): """Replace a existing case with a new one Keeps the object id Args: case_obj(dict) Returns: updated_case(dict) """ # 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(), updated_case = self.case_collection.find_one_and_replace( {'_id': case_obj['_id']}, case_obj, return_document=pymongo.ReturnDocument.AFTER ) return updated_case
Update case id for a case across the database.
def update_caseid(self, case_obj, family_id): """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 """ 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, []): case_variant = self.variant(variant_id) if not case_variant: continue new_variantid = get_variantid(case_variant, family_id) new_variantids.append(new_variantid) new_case[case_variants] = new_variantids # update ACMG for acmg_obj in self.acmg_collection.find({'case_id': case_obj['_id']}): LOG.info("update ACMG classification: %s", acmg_obj['classification']) acmg_variant = self.variant(acmg_obj['variant_specific']) new_specific_id = get_variantid(acmg_variant, family_id) self.acmg_collection.find_one_and_update( {'_id': acmg_obj['_id']}, {'$set': {'case_id': family_id, 'variant_specific': new_specific_id}}, ) # update events institute_obj = self.institute(case_obj['owner']) for event_obj in self.events(institute_obj, case=case_obj): LOG.info("update event: %s", event_obj['verb']) self.event_collection.find_one_and_update( {'_id': event_obj['_id']}, {'$set': {'case': family_id}}, ) # insert the updated case self.case_collection.insert_one(new_case) # delete the old case self.case_collection.find_one_and_delete({'_id': case_obj['_id']}) return new_case
Submit an evaluation to the database
def submit_evaluation(self, variant_obj, user_obj, institute_obj, case_obj, link, criteria): """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)): [ { 'term': str, 'comment': str, 'links': list(str) }, . . ] """ 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_obj['_id'] case_id = case_obj['_id'] evaluation_terms = [evluation_info['term'] for evluation_info in criteria] classification = get_acmg(evaluation_terms) evaluation_obj = build_evaluation( variant_specific=variant_specific, variant_id=variant_id, user_id=user_id, user_name=user_name, institute_id=institute_id, case_id=case_id, classification=classification, criteria=criteria ) self._load_evaluation(evaluation_obj) # Update the acmg classification for the variant: self.update_acmg(institute_obj, case_obj, user_obj, link, variant_obj, classification) return classification
Return all evaluations for a certain variant.
def get_evaluations(self, variant_obj): """Return all evaluations for a certain variant. Args: variant_obj (dict): variant dict from the database Returns: pymongo.cursor: database cursor """ query = dict(variant_id=variant_obj['variant_id']) res = self.acmg_collection.find(query).sort([('created_at', pymongo.DESCENDING)]) return res
Parse and massage the transcript information
def parse_transcripts(transcript_lines): """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 iterable with strings or a pandas.DataFrame Returns: parsed_transcripts(dict): Map from enstid -> transcript info """ 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 = parse_ensembl_transcripts(transcript_lines) # Since there can be multiple lines with information about the same transcript # we store transcript information in a dictionary for now parsed_transcripts = {} # Loop over the parsed transcripts for tx in transcripts: tx_id = tx['ensembl_transcript_id'] ens_gene_id = tx['ensembl_gene_id'] # Check if the transcript has been added # If not, create a new transcript if not tx_id in parsed_transcripts: tx_info = { 'chrom': tx['chrom'], 'transcript_start': tx['transcript_start'], 'transcript_end': tx['transcript_end'], 'mrna': set(), 'mrna_predicted': set(), 'nc_rna': set(), 'ensembl_gene_id': ens_gene_id, 'ensembl_transcript_id': tx_id, } parsed_transcripts[tx_id] = tx_info tx_info = parsed_transcripts[tx_id] # Add the ref seq information if tx.get('refseq_mrna_predicted'): tx_info['mrna_predicted'].add(tx['refseq_mrna_predicted']) if tx.get('refseq_mrna'): tx_info['mrna'].add(tx['refseq_mrna']) if tx.get('refseq_ncrna'): tx_info['nc_rna'].add(tx['refseq_ncrna']) return parsed_transcripts
Parse a dataframe with ensembl gene information
def parse_ensembl_gene_request(result): """Parse a dataframe with ensembl gene information Args: res(pandas.DataFrame) Yields: gene_info(dict) """ 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 genes without hgnc information continue ensembl_info['chrom'] = row['chromosome_name'] ensembl_info['gene_start'] = int(row['start_position']) ensembl_info['gene_end'] = int(row['end_position']) ensembl_info['ensembl_gene_id'] = row['ensembl_gene_id'] ensembl_info['hgnc_symbol'] = row['hgnc_symbol'] hgnc_id = row['hgnc_id'] if type(hgnc_id) is float: hgnc_id = int(hgnc_id) else: hgnc_id = int(hgnc_id.split(':')[-1]) ensembl_info['hgnc_id'] = hgnc_id yield ensembl_info
Parse a dataframe with ensembl transcript information
def parse_ensembl_transcript_request(result): """Parse a dataframe with ensembl transcript information Args: res(pandas.DataFrame) Yields: transcript_info(dict) """ LOG.info("Parsing transcripts from request") keys = [ 'chrom', 'ensembl_gene_id', 'ensembl_transcript_id', 'transcript_start', 'transcript_end', 'refseq_mrna', 'refseq_mrna_predicted', 'refseq_ncrna', ] # for res in result.itertuples(): for index, row in result.iterrows(): ensembl_info = {} ensembl_info['chrom'] = str(row['chromosome_name']) ensembl_info['ensembl_gene_id'] = row['ensembl_gene_id'] ensembl_info['ensembl_transcript_id'] = row['ensembl_transcript_id'] ensembl_info['transcript_start'] = int(row['transcript_start']) ensembl_info['transcript_end'] = int(row['transcript_end']) # Check if refseq data is annotated # Pandas represent missing data with nan for key in keys[-3:]: if type(row[key]) is float: ensembl_info[key] = None else: ensembl_info[key] = row[key] yield ensembl_info
Parse an ensembl formated line
def parse_ensembl_line(line, header): """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 """ 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 word: ensembl_info['chrom'] = value if 'gene' in word: if 'id' in word: ensembl_info['ensembl_gene_id'] = value elif 'start' in word: ensembl_info['gene_start'] = int(value) elif 'end' in word: ensembl_info['gene_end'] = int(value) if 'hgnc symbol' in word: ensembl_info['hgnc_symbol'] = value if "gene name" in word: ensembl_info['hgnc_symbol'] = value if 'hgnc id' in word: ensembl_info['hgnc_id'] = int(value.split(':')[-1]) if 'transcript' in word: if 'id' in word: ensembl_info['ensembl_transcript_id'] = value elif 'start' in word: ensembl_info['transcript_start'] = int(value) elif 'end' in word: ensembl_info['transcript_end'] = int(value) if 'exon' in word: if 'start' in word: ensembl_info['exon_start'] = int(value) elif 'end' in word: ensembl_info['exon_end'] = int(value) elif 'rank' in word: ensembl_info['exon_rank'] = int(value) if 'utr' in word: if 'start' in word: if '5' in word: ensembl_info['utr_5_start'] = int(value) elif '3' in word: ensembl_info['utr_3_start'] = int(value) elif 'end' in word: if '5' in word: ensembl_info['utr_5_end'] = int(value) elif '3' in word: ensembl_info['utr_3_end'] = int(value) if 'strand' in word: ensembl_info['strand'] = int(value) if 'refseq' in word: if 'mrna' in word: if 'predicted' in word: ensembl_info['refseq_mrna_predicted'] = value else: ensembl_info['refseq_mrna'] = value if 'ncrna' in word: ensembl_info['refseq_ncrna'] = value return ensembl_info
Parse lines with ensembl formated genes
def parse_ensembl_genes(lines): """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: ensembl_gene(dict): A dictionary with the relevant information """ 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 represents a gene yield parse_ensembl_line(line, header)
Parse lines with ensembl formated exons
def parse_ensembl_exons(lines): """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 the relevant information """ 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, header) chrom = exon_info['chrom'] start = exon_info['exon_start'] end = exon_info['exon_end'] transcript = exon_info['ensembl_transcript_id'] gene = exon_info['ensembl_gene_id'] rank = exon_info['exon_rank'] strand = exon_info['strand'] # Recalculate start and stop (taking UTR regions into account for end exons) if strand == 1: # highest position: start of exon or end of 5' UTR # If no 5' UTR make sure exon_start is allways choosen start = max(start, exon_info.get('utr_5_end') or -1) # lowest position: end of exon or start of 3' UTR end = min(end, exon_info.get('utr_3_start') or float('inf')) elif strand == -1: # highest position: start of exon or end of 3' UTR start = max(start, exon_info.get('utr_3_end') or -1) # lowest position: end of exon or start of 5' UTR end = min(end, exon_info.get('utr_5_start') or float('inf')) exon_id = "-".join([chrom, str(start), str(end)]) if start > end: raise ValueError("ERROR: %s" % exon_id) data = { "exon_id": exon_id, "chrom": chrom, "start": start, "end": end, "transcript": transcript, "gene": gene, "rank": rank, } yield data
Parse a dataframe with ensembl exon information
def parse_ensembl_exon_request(result): """Parse a dataframe with ensembl exon information Args: res(pandas.DataFrame) Yields: gene_info(dict) """ 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' ] # for res in result.itertuples(): for res in zip(result['Chromosome/scaffold name'], result['Gene stable ID'], result['Transcript stable ID'], result['Exon stable ID'], result['Exon region start (bp)'], result['Exon region end (bp)'], result["5' UTR start"], result["5' UTR end"], result["3' UTR start"], result["3' UTR end"], result["Strand"], result["Exon rank in transcript"]): ensembl_info = dict(zip(keys, res)) # Recalculate start and stop (taking UTR regions into account for end exons) if ensembl_info['strand'] == 1: # highest position: start of exon or end of 5' UTR # If no 5' UTR make sure exon_start is allways choosen start = max(ensembl_info['exon_chrom_start'], ensembl_info['5_utr_end'] or -1) # lowest position: end of exon or start of 3' UTR end = min(ensembl_info['exon_chrom_end'], ensembl_info['3_utr_start'] or float('inf')) elif ensembl_info['strand'] == -1: # highest position: start of exon or end of 3' UTR start = max(ensembl_info['exon_chrom_start'], ensembl_info['3_utr_end'] or -1) # lowest position: end of exon or start of 5' UTR end = min(ensembl_info['exon_chrom_end'], ensembl_info['5_utr_start'] or float('inf')) ensembl_info['start'] = start ensembl_info['end'] = end yield ensembl_info
Initializes the log file in the proper format.
def init_log(logger, filename=None, loglevel=None): """ 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. """ 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 = logging.StreamHandler() console.setLevel('WARNING') console.setFormatter(formatter) if filename: file_handler = logging.FileHandler(filename, encoding='utf-8') if loglevel: file_handler.setLevel(getattr(logging, loglevel)) file_handler.setFormatter(formatter) logger.addHandler(file_handler) # If no logfile is provided we print all log messages that the user has # defined to stderr else: if loglevel: console.setLevel(getattr(logging, loglevel)) logger.addHandler(console)
docstring for parse_omim_2_line
def parse_omim_line(line, header): """docstring for parse_omim_2_line""" omim_info = dict(zip(header, line.split('\t'))) return omim_info
Parse the omim source file called genemap2. txt Explanation of Phenotype field: Brackets [ ] indicate nondiseases mainly genetic variations that lead to apparently abnormal laboratory test values.
def parse_genemap2(lines): """Parse the omim source file called genemap2.txt Explanation of Phenotype field: Brackets, "[ ]", indicate "nondiseases," mainly genetic variations that lead to apparently abnormal laboratory test values. Braces, "{ }", indicate mutations that contribute to susceptibility to multifactorial disorders (e.g., diabetes, asthma) or to susceptibility to infection (e.g., malaria). A question mark, "?", before the phenotype name indicates that the relationship between the phenotype and gene is provisional. More details about this relationship are provided in the comment field of the map and in the gene and phenotype OMIM entries. The number in parentheses after the name of each disorder indicates the following: (1) the disorder was positioned by mapping of the wildtype gene; (2) the disease phenotype itself was mapped; (3) the molecular basis of the disorder is known; (4) the disorder is a chromosome deletion or duplication syndrome. Args: lines(iterable(str)) Yields: parsed_entry(dict) """ LOG.info("Parsing the omim genemap2") header = [] for i,line in enumerate(lines): line = line.rstrip() if line.startswith('#'): if i < 10: if line.startswith('# Chromosome'): header = line[2:].split('\t') continue if len(line) < 5: continue parsed_entry = parse_omim_line(line, header) parsed_entry['mim_number'] = int(parsed_entry['Mim Number']) parsed_entry['raw'] = line # This is the approved symbol for the entry hgnc_symbol = parsed_entry.get("Approved Symbol") # If no approved symbol could be found choose the first of # the gene symbols gene_symbols = [] if parsed_entry.get('Gene Symbols'): gene_symbols = [symbol.strip() for symbol in parsed_entry['Gene Symbols'].split(',')] parsed_entry['hgnc_symbols'] = gene_symbols if not hgnc_symbol and gene_symbols: hgnc_symbol = gene_symbols[0] parsed_entry['hgnc_symbol'] = hgnc_symbol # Gene inheritance is a construct. It is the union of all inheritance # patterns found in the associated phenotypes gene_inheritance = set() parsed_phenotypes = [] # Information about the related phenotypes # Each related phenotype is separated by ';' for phenotype_info in parsed_entry.get('Phenotypes', '').split(';'): if not phenotype_info: continue phenotype_info = phenotype_info.lstrip() # First symbol in description indicates phenotype status # If no special symbol is used the phenotype is 'established' phenotype_status = OMIM_STATUS_MAP.get(phenotype_info[0], 'established') # Skip phenotype entries that not associated to disease if phenotype_status == 'nondisease': continue phenotype_description = "" # We will try to save the description splitted_info = phenotype_info.split(',') for i, text in enumerate(splitted_info): # Everything before ([1,2,3]) # We check if we are in the part where the mim number exists match = entry_pattern.search(text) if not match: phenotype_description += text else: # If we find the end of the entry mimnr_match = mimnr_pattern.search(phenotype_info) # Then if the entry have a mim number we choose that if mimnr_match: phenotype_mim = int(mimnr_match.group()) else: phenotype_mim = parsed_entry['mim_number'] phenotype_description += text[:-4] break # Find the inheritance inheritance = set() inheritance_text = ','.join(splitted_info[i:]) for term in mim_inheritance_terms: if term in inheritance_text: inheritance.add(TERMS_MAPPER[term]) gene_inheritance.add(TERMS_MAPPER[term]) parsed_phenotypes.append( { 'mim_number':phenotype_mim, 'inheritance': inheritance, 'description': phenotype_description.strip('?\{\}'), 'status': phenotype_status, } ) parsed_entry['phenotypes'] = parsed_phenotypes parsed_entry['inheritance'] = gene_inheritance yield parsed_entry
Parse the file called mim2gene This file describes what type ( s ) the different mim numbers have. The different entry types are: gene gene/ phenotype moved/ removed phenotype predominantly phenotypes Where: gene: Is a gene entry gene/ phenotype: This entry describes both a phenotype and a gene moved/ removed: No explanation needed phenotype: Describes a phenotype predominantly phenotype: Not clearly established ( probably phenotype ) Args: lines ( iterable ( str )): The mim2gene lines Yields: parsed_entry ( dict ) { mim_number: int entry_type: str entrez_gene_id: int hgnc_symbol: str ensembl_gene_id: str ensembl_transcript_id: str }
def parse_mim2gene(lines): """Parse the file called mim2gene This file describes what type(s) the different mim numbers have. The different entry types are: 'gene', 'gene/phenotype', 'moved/removed', 'phenotype', 'predominantly phenotypes' Where: gene: Is a gene entry gene/phenotype: This entry describes both a phenotype and a gene moved/removed: No explanation needed phenotype: Describes a phenotype predominantly phenotype: Not clearly established (probably phenotype) Args: lines(iterable(str)): The mim2gene lines Yields: parsed_entry(dict) { "mim_number": int, "entry_type": str, "entrez_gene_id": int, "hgnc_symbol": str, "ensembl_gene_id": str, "ensembl_transcript_id": str, } """ LOG.info("Parsing mim2gene") header = ["mim_number", "entry_type", "entrez_gene_id", "hgnc_symbol", "ensembl_gene_id"] for i, line in enumerate(lines): if line.startswith('#'): continue if not len(line) > 0: continue line = line.rstrip() parsed_entry = parse_omim_line(line, header) parsed_entry['mim_number'] = int(parsed_entry['mim_number']) parsed_entry['raw'] = line if 'hgnc_symbol' in parsed_entry: parsed_entry['hgnc_symbol'] = parsed_entry['hgnc_symbol'] if parsed_entry.get('entrez_gene_id'): parsed_entry['entrez_gene_id'] = int(parsed_entry['entrez_gene_id']) if parsed_entry.get('ensembl_gene_id'): ensembl_info = parsed_entry['ensembl_gene_id'].split(',') parsed_entry['ensembl_gene_id'] = ensembl_info[0].strip() if len(ensembl_info) > 1: parsed_entry['ensembl_transcript_id'] = ensembl_info[1].strip() yield parsed_entry
docstring for parse_omim_morbid
def parse_omim_morbid(lines): """docstring for parse_omim_morbid""" header = [] for i,line in enumerate(lines): line = line.rstrip() if line.startswith('#'): if i < 10: if line.startswith('# Phenotype'): header = line[2:].split('\t') else: yield parse_omim_line(line, header)
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: parsed_entry ( dict ) { mim_number: int # The mim number for entry preferred_title: str # the preferred title for a entry }
def parse_mim_titles(lines): """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: parsed_entry(dict) { 'mim_number': int, # The mim number for entry 'preferred_title': str, # the preferred title for a entry } """ 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_number'] = int(parsed_entry['mim_number']) parsed_entry['preferred_title'] = parsed_entry['preferred_title'].split(';')[0] yield parsed_entry
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): """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 """ 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_nr += 1 if not 'hgnc_symbol' in entry: no_hgnc += 1 else: genes[mim_nr] = entry LOG.info("Number of genes without hgnc symbol %s", str(no_hgnc)) for entry in parse_genemap2(genemap_lines): mim_number = entry['mim_number'] inheritance = entry['inheritance'] phenotype_info = entry['phenotypes'] hgnc_symbol = entry['hgnc_symbol'] hgnc_symbols = entry['hgnc_symbols'] if mim_number in genes: genes[mim_number]['inheritance'] = inheritance genes[mim_number]['phenotypes'] = phenotype_info genes[mim_number]['hgnc_symbols'] = hgnc_symbols for mim_nr in genes: gene_info = genes[mim_nr] hgnc_symbol = gene_info['hgnc_symbol'] if hgnc_symbol in hgnc_genes: existing_info = hgnc_genes[hgnc_symbol] if not existing_info['phenotypes']: hgnc_genes[hgnc_symbol] = gene_info else: hgnc_genes[hgnc_symbol] = gene_info return hgnc_genes
Get a dictionary with phenotypes Use the mim numbers for phenotypes as keys and phenotype information as values.
def get_mim_phenotypes(genemap_lines): """Get a dictionary with phenotypes Use the mim numbers for phenotypes as keys and phenotype information as values. Args: genemap_lines(iterable(str)) Returns: phenotypes_found(dict): A dictionary with mim_numbers as keys and dictionaries with phenotype information as values. { 'description': str, # Description of the phenotype 'hgnc_symbols': set(), # Associated hgnc symbols 'inheritance': set(), # Associated phenotypes 'mim_number': int, # mim number of phenotype } """ # Set with all omim numbers that are phenotypes # Parsed from mim2gene.txt phenotype_mims = set() phenotypes_found = {} # Genemap is a file with one entry per gene. # Each line hold a lot of information and in specific it # has information about the phenotypes that a gene is associated with # From this source we collect inheritane patterns and what hgnc symbols # a phenotype is associated with for entry in parse_genemap2(genemap_lines): hgnc_symbol = entry['hgnc_symbol'] for phenotype in entry['phenotypes']: mim_nr = phenotype['mim_number'] if mim_nr in phenotypes_found: phenotype_entry = phenotypes_found[mim_nr] phenotype_entry['inheritance'] = phenotype_entry['inheritance'].union(phenotype['inheritance']) phenotype_entry['hgnc_symbols'].add(hgnc_symbol) else: phenotype['hgnc_symbols'] = set([hgnc_symbol]) phenotypes_found[mim_nr] = phenotype return phenotypes_found
Parse the omim files
def cli(context, morbid, genemap, mim2gene, mim_titles, phenotypes): """Parse the omim files""" # if not (morbid and genemap and mim2gene, mim_titles): # print("Please provide all files") # context.abort() from scout.utils.handle import get_file_handle from pprint import pprint as pp print("Morbid file: %s" % morbid) print("Genemap file: %s" % genemap) print("mim2gene file: %s" % mim2gene) print("MimTitles file: %s" % mim_titles) if morbid: morbid_handle = get_file_handle(morbid) if genemap: genemap_handle = get_file_handle(genemap) if mim2gene: mim2gene_handle = get_file_handle(mim2gene) if mim_titles: mimtitles_handle = get_file_handle(mim_titles) mim_genes = get_mim_genes(genemap_handle, mim2gene_handle) for entry in mim_genes: if entry == 'C10orf11': pp(mim_genes[entry]) context.abort() if phenotypes: if not genemap: click.echo("Please provide the genemap file") context.abort() phenotypes = get_mim_phenotypes(genemap_handle) for i,mim_term in enumerate(phenotypes): # pp(phenotypes[mim_term]) pass print("Number of phenotypes found: %s" % i) context.abort() # hgnc_genes = get_mim_genes(genemap_handle, mim2gene_handle) # for hgnc_symbol in hgnc_genes: # pp(hgnc_genes[hgnc_symbol]) # phenotypes = get_mim_phenotypes(genemap_handle, mim2gene_handle, mimtitles_handle) # for mim_nr in phenotypes: # pp(phenotypes[mim_nr]) genes = get_mim_genes(genemap_handle, mim2gene_handle) for hgnc_symbol in genes: if hgnc_symbol == 'OPA1': print(genes[hgnc_symbol])
Convert a string to number If int convert to int otherwise float If not possible return None
def convert_number(string): """Convert a string to number If int convert to int otherwise float If not possible return None """ res = None if isint(string): res = int(string) elif isfloat(string): res = float(string) return res
Update a case in the database
def case(context, case_id, case_name, institute, collaborator, vcf, vcf_sv, vcf_cancer, vcf_research, vcf_sv_research, vcf_cancer_research, peddy_ped, reupload_sv, rankscore_treshold, rankmodel_version): """ Update a case in the database """ adapter = context.obj['adapter'] if not case_id: if not (case_name and institute): LOG.info("Please specify which case to update.") context.abort case_id = "{0}-{1}".format(institute, case_name) # Check if the case exists case_obj = adapter.case(case_id) if not case_obj: LOG.warning("Case %s could not be found", case_id) context.abort() case_changed = False if collaborator: if not adapter.institute(collaborator): LOG.warning("Institute %s could not be found", collaborator) context.abort() if not collaborator in case_obj['collaborators']: case_changed = True case_obj['collaborators'].append(collaborator) LOG.info("Adding collaborator %s", collaborator) if vcf: LOG.info("Updating 'vcf_snv' to %s", vcf) case_obj['vcf_files']['vcf_snv'] = vcf case_changed = True if vcf_sv: LOG.info("Updating 'vcf_sv' to %s", vcf_sv) case_obj['vcf_files']['vcf_sv'] = vcf_sv case_changed = True if vcf_cancer: LOG.info("Updating 'vcf_cancer' to %s", vcf_cancer) case_obj['vcf_files']['vcf_cancer'] = vcf_cancer case_changed = True if vcf_research: LOG.info("Updating 'vcf_research' to %s", vcf_research) case_obj['vcf_files']['vcf_research'] = vcf_research case_changed = True if vcf_sv_research: LOG.info("Updating 'vcf_sv_research' to %s", vcf_sv_research) case_obj['vcf_files']['vcf_sv_research'] = vcf_sv_research case_changed = True if vcf_cancer_research: LOG.info("Updating 'vcf_cancer_research' to %s", vcf_cancer_research) case_obj['vcf_files']['vcf_cancer_research'] = vcf_cancer_research case_changed = True if case_changed: adapter.update_case(case_obj) if reupload_sv: LOG.info("Set needs_check to True for case %s", case_id) updates = {'needs_check': True} if rankscore_treshold: updates['sv_rank_model_version'] = rankmodel_version if vcf_sv: updates['vcf_files.vcf_sv'] = vcf_sv if vcf_sv: updates['vcf_files.vcf_sv_research'] = vcf_sv_research updated_case = adapter.case_collection.find_one_and_update( {'_id':case_id}, {'$set': updates }, return_document=pymongo.ReturnDocument.AFTER ) rankscore_treshold = rankscore_treshold or updated_case.get("rank_score_threshold", 5) # Delete and reload the clinical SV variants if updated_case['vcf_files'].get('vcf_sv'): adapter.delete_variants(case_id, variant_type='clinical', category='sv') adapter.load_variants(updated_case, variant_type='clinical', category='sv', rank_threshold=rankscore_treshold) # Delete and reload research SV variants if updated_case['vcf_files'].get('vcf_sv_research'): adapter.delete_variants(case_id, variant_type='research', category='sv') if updated_case.get('is_research'): adapter.load_variants(updated_case, variant_type='research', category='sv', rank_threshold=rankscore_treshold)
docstring for setup_scout
def setup_scout(adapter, institute_id='cust000', user_name='Clark Kent', user_mail='clark.kent@mail.com', api_key=None, demo=False): """docstring for setup_scout""" ########################## Delete previous information ########################## LOG.info("Deleting previous database") for collection_name in adapter.db.collection_names(): if not collection_name.startswith('system'): LOG.info("Deleting collection %s", collection_name) adapter.db.drop_collection(collection_name) LOG.info("Database deleted") ########################## Add a institute ########################## ##################################################################### # Build a institute with id institute_name institute_obj = build_institute( internal_id=institute_id, display_name=institute_id, sanger_recipients=[user_mail] ) # Add the institute to database adapter.add_institute(institute_obj) ########################## Add a User ############################### ##################################################################### # Build a user obj user_obj = dict( _id=user_mail, email=user_mail, name=user_name, roles=['admin'], institutes=[institute_id] ) adapter.add_user(user_obj) ### Get the mim information ### if not demo: # Fetch the mim files try: mim_files = fetch_mim_files(api_key, mim2genes=True, morbidmap=True, genemap2=True) except Exception as err: LOG.warning(err) raise err mim2gene_lines = mim_files['mim2genes'] genemap_lines = mim_files['genemap2'] # Fetch the genes to hpo information hpo_gene_lines = fetch_hpo_genes() # Fetch the latest version of the hgnc information hgnc_lines = fetch_hgnc() # Fetch the latest exac pli score information exac_lines = fetch_exac_constraint() else: mim2gene_lines = [line for line in get_file_handle(mim2gene_reduced_path)] genemap_lines = [line for line in get_file_handle(genemap2_reduced_path)] # Fetch the genes to hpo information hpo_gene_lines = [line for line in get_file_handle(hpogenes_reduced_path)] # Fetch the reduced hgnc information hgnc_lines = [line for line in get_file_handle(hgnc_reduced_path)] # Fetch the latest exac pli score information exac_lines = [line for line in get_file_handle(exac_reduced_path)] builds = ['37', '38'] ################## Load Genes and transcripts ####################### ##################################################################### for build in builds: # Fetch the ensembl information if not demo: ensembl_genes = fetch_ensembl_genes(build=build) else: ensembl_genes = get_file_handle(genes37_reduced_path) # load the genes hgnc_genes = load_hgnc_genes( adapter=adapter, ensembl_lines=ensembl_genes, hgnc_lines=hgnc_lines, exac_lines=exac_lines, mim2gene_lines=mim2gene_lines, genemap_lines=genemap_lines, hpo_lines=hpo_gene_lines, build=build, ) # Create a map from ensembl ids to gene objects ensembl_genes = {} for gene_obj in hgnc_genes: ensembl_id = gene_obj['ensembl_id'] ensembl_genes[ensembl_id] = gene_obj # Fetch the transcripts from ensembl if not demo: ensembl_transcripts = fetch_ensembl_transcripts(build=build) else: ensembl_transcripts = get_file_handle(transcripts37_reduced_path) # Load the transcripts for a certain build transcripts = load_transcripts(adapter, ensembl_transcripts, build, ensembl_genes) hpo_terms_handle = None hpo_to_genes_handle = None hpo_disease_handle = None if demo: hpo_terms_handle = get_file_handle(hpoterms_reduced_path) hpo_to_genes_handle = get_file_handle(hpo_to_genes_reduced_path) hpo_disease_handle = get_file_handle(hpo_phenotype_to_terms_reduced_path) load_hpo( adapter=adapter, hpo_lines=hpo_terms_handle, hpo_gene_lines=hpo_to_genes_handle, disease_lines=genemap_lines, hpo_disease_lines=hpo_disease_handle ) # If demo we load a gene panel and some case information if demo: parsed_panel = parse_gene_panel( path=panel_path, institute='cust000', panel_id='panel1', version=1.0, display_name='Test panel' ) adapter.load_panel(parsed_panel) case_handle = get_file_handle(load_path) case_data = yaml.load(case_handle) adapter.load_case(case_data) LOG.info("Creating indexes") adapter.load_indexes() LOG.info("Scout instance setup successful")
Export all transcripts from the database Args: adapter ( scout. adapter. MongoAdapter ) build ( str ) Yields: transcript ( scout. models. Transcript )
def export_transcripts(adapter, build='37'): """Export all transcripts from the database Args: adapter(scout.adapter.MongoAdapter) build(str) Yields: transcript(scout.models.Transcript) """ LOG.info("Exporting all transcripts") for tx_obj in adapter.transcripts(build=build): yield tx_obj
Return a formatted month as a table.
def formatmonth(self, theyear, themonth, withyear=True, net=None, qs=None, template='happenings/partials/calendar/month_table.html'): """Return a formatted month as a table.""" context = self.get_context() context['month_start_date'] = date(self.yr, self.mo, 1) context['week_rows'] = [] for week in self.monthdays2calendar(theyear, themonth): week_row = [] for day, weekday in week: week_row.append(self.formatday(day, weekday)) context['week_rows'].append(week_row) nxt, prev = get_next_and_prev(net) extra_qs = ('&' + '&'.join(qs)) if qs else '' context['prev_qs'] = mark_safe('?cal_prev=%d%s' % (prev, extra_qs)) context['next_qs'] = mark_safe('?cal_next=%d%s' % (nxt, extra_qs)) context['withyear'] = withyear return render_to_string(template, context)
Return a day as a table cell.
def formatday( self, day, weekday, day_template='happenings/partials/calendar/day_cell.html', noday_template='happenings/partials/calendar/day_noday_cell.html', popover_template='happenings/partials/calendar/popover.html', ): """Return a day as a table cell.""" super(EventCalendar, self).formatday(day, weekday) now = get_now() context = self.get_context() context['events'] = [] context['day'] = day context['day_url'] = self.get_day_url(day) context['month_start_date'] = date(self.yr, self.mo, 1) context['weekday'] = weekday context['cssclass'] = self.cssclasses[weekday] context['popover_template'] = popover_template context['num_events'] = len(self.count.get(day, [])), try: processed_date = date(self.yr, self.mo, day) except ValueError: # day is out of range for month processed_date = None context['month_start_date'] = date(self.yr, self.mo, 1) if day == 0: template = noday_template else: template = day_template if now.date() == processed_date: context['is_current_day'] = True if processed_date and (day in self.count): for item in self.count[day]: self.pk = item[1] self.title = item[0] for event in self.events: if event.pk == self.pk: event.check_if_cancelled(processed_date) # allow to use event.last_check_if_cancelled and populate event.title.extra context['events'].append(event) return render_to_string(template, context)
Return a day as a table cell.
def formatday(self, day, weekday): """Return a day as a table cell.""" return super(MiniEventCalendar, self).formatday( day, weekday, day_template='happenings/partials/calendar/mini_day_cell.html', popover_template='happenings/partials/calendar/mini_popover.html', )
Set some commonly used variables.
def formatday(self, day, weekday): """Set some commonly used variables.""" self.wkday_not_today = '<td class="%s"><div class="td-inner">' % ( self.cssclasses[weekday]) self.wkday_today = ( '<td class="%s calendar-today"><div class="td-inner">' % ( self.cssclasses[weekday]) ) if URLS_NAMESPACE: url_name = '%s:day_list' % (URLS_NAMESPACE) else: url_name = 'day_list' self.day_url = reverse(url_name, args=(self.yr, self.mo, day)) self.day = day self.anch = '<a href="%s">%d</a>' % ( self.day_url, day ) self.end = '</div></td>'
Change colspan to 5 add today button and return a month name as a table row.
def formatmonthname(self, theyear, themonth, withyear=True): """ Change colspan to "5", add "today" button, and return a month name as a table row. """ display_month = month_name[themonth] if isinstance(display_month, six.binary_type) and self.encoding: display_month = display_month.decode(self.encoding) if withyear: s = u'%s %s' % (display_month, theyear) else: s = u'%s' % display_month return ('<tr><th colspan="5" class="month">' '<button id="cal-today-btn" class="btn btn-small">' 'Today</button> %s</th></tr>' % s)
Populate variables used to build popovers.
def popover_helper(self): """Populate variables used to build popovers.""" # when display_month = month_name[self.mo] if isinstance(display_month, six.binary_type) and self.encoding: display_month = display_month.decode('utf-8') self.when = ('<p><b>When:</b> ' + display_month + ' ' + str(self.day) + ', ' + self.event.l_start_date.strftime( LEGACY_CALENDAR_TIME_FORMAT).lstrip('0') + ' - ' + self.event.l_end_date.strftime(LEGACY_CALENDAR_TIME_FORMAT).lstrip('0') + '</p>') if self.event.location.exists(): # where self.where = '<p><b>Where:</b> ' for l in self.event.location.all(): self.where += l.name self.where += '</p>' else: self.where = '' # description self.desc = '<p><b>Description:</b> ' + self.event.description[:100] self.desc += ('...</p>' if len(self.event.description) > 100 else '</p>') self.event_url = self.event.get_absolute_url() # url t = LEGACY_CALENDAR_TIME_FORMAT if self.event.l_start_date.minute else LEGACY_CALENDAR_HOUR_FORMAT self.title2 = (self.event.l_start_date.strftime(t).lstrip('0') + ' ' + self.title)
Return a day as a table cell.
def formatday(self, day, weekday): """Return a day as a table cell.""" super(EventCalendar, self).formatday(day, weekday) now = get_now() self.day = day out = '' if day == 0: return '<td class="noday">&nbsp;</td>' # day outside month elif now.month == self.mo and now.year == self.yr and day == now.day: if day in self.count: # don't return just yet out = self.wkday_today + self.anch else: return self.wkday_today + self.anch + self.end elif day in self.count: # don't return just yet out = self.wkday_not_today + self.anch else: return self.wkday_not_today + self.anch + self.end detail = "%s%s%s<br><a href='%s'>View details</a>" extras = ('<div title="%s" data-content="%s" data-container="body"' ' data-toggle="popover" class="calendar-event"%s>') common = ' style=background:%s;color:%s;' # inject style and extras into calendar html for item in self.count[day]: self.pk = item[1] self.title = item[0] for event in self.events: if event.pk == self.pk: self.event = event self.check_if_cancelled() # self.add_occurrence self.popover_helper() bg, fnt = self.event.get_colors() out += ('<a class="event-anch" href="' + self.event_url + '">' + extras % ( self.title, detail % ( self.when, self.where, self.desc, self.event_url ), common % (bg, fnt) ) + self.title2 + '</div></a>') return out + self.end
Return a day as a table cell.
def formatday(self, day, weekday): """Return a day as a table cell.""" super(MiniEventCalendar, self).formatday(day, weekday) now = get_now() self.day = day if day == 0: return '<td class="noday">&nbsp;</td>' # day outside month elif now.month == self.mo and now.year == self.yr and day == now.day: if day in self.count: self.popover_helper() return self.wkday_today + self.anch + self.cal_event + self.end else: return self.wkday_today + self.anch + self.end elif day in self.count: self.popover_helper() return self.wkday_not_today + self.anch + self.cal_event + self.end else: return self.wkday_not_today + self.anch + self.end
Parse metadata for a gene panel
def get_panel_info(panel_lines=None, panel_id=None, institute=None, version=None, date=None, display_name=None): """Parse metadata for a gene panel For historical reasons it is possible to include all information about a gene panel in the header of a panel file. This function parses the header. Args: panel_lines(iterable(str)) Returns: panel_info(dict): Dictionary with panel information """ panel_info = { 'panel_id': panel_id, 'institute': institute, 'version': version, 'date': date, 'display_name': display_name, } if panel_lines: for line in panel_lines: line = line.rstrip() if not line.startswith('##'): break info = line[2:].split('=') field = info[0] value = info[1] if not panel_info.get(field): panel_info[field] = value panel_info['date'] = get_date(panel_info['date']) return panel_info
Parse a gene line with information from a panel file
def parse_gene(gene_info): """Parse a gene line with information from a panel file Args: gene_info(dict): dictionary with gene info Returns: gene(dict): A dictionary with the gene information { 'hgnc_id': int, 'hgnc_symbol': str, 'disease_associated_transcripts': list(str), 'inheritance_models': list(str), 'mosaicism': bool, 'reduced_penetrance': bool, 'database_entry_version': str, } """ gene = {} # This is either hgnc id or hgnc symbol identifier = None hgnc_id = None try: if 'hgnc_id' in gene_info: hgnc_id = int(gene_info['hgnc_id']) elif 'hgnc_idnumber' in gene_info: hgnc_id = int(gene_info['hgnc_idnumber']) elif 'hgncid' in gene_info: hgnc_id = int(gene_info['hgncid']) except ValueError as e: raise SyntaxError("Invalid hgnc id: {0}".format(hgnc_id)) gene['hgnc_id'] = hgnc_id identifier = hgnc_id hgnc_symbol = None if 'hgnc_symbol' in gene_info: hgnc_symbol = gene_info['hgnc_symbol'] elif 'hgncsymbol' in gene_info: hgnc_symbol = gene_info['hgncsymbol'] elif 'symbol' in gene_info: hgnc_symbol = gene_info['symbol'] gene['hgnc_symbol'] = hgnc_symbol if not identifier: if hgnc_symbol: identifier = hgnc_symbol else: raise SyntaxError("No gene identifier could be found") gene['identifier'] = identifier # Disease associated transcripts is a ','-separated list of # manually curated transcripts transcripts = "" if 'disease_associated_transcripts' in gene_info: transcripts = gene_info['disease_associated_transcripts'] elif 'disease_associated_transcript' in gene_info: transcripts = gene_info['disease_associated_transcript'] elif 'transcripts' in gene_info: transcripts = gene_info['transcripts'] gene['transcripts'] = [ transcript.strip() for transcript in transcripts.split(',') if transcript ] # Genetic disease models is a ','-separated list of manually curated # inheritance patterns that are followed for a gene models = "" if 'genetic_disease_models' in gene_info: models = gene_info['genetic_disease_models'] elif 'genetic_disease_model' in gene_info: models = gene_info['genetic_disease_model'] elif 'inheritance_models' in gene_info: models = gene_info['inheritance_models'] elif 'genetic_inheritance_models' in gene_info: models = gene_info['genetic_inheritance_models'] gene['inheritance_models'] = [ model.strip() for model in models.split(',') if model.strip() in VALID_MODELS ] # If a gene is known to be associated with mosaicism this is annotated gene['mosaicism'] = True if gene_info.get('mosaicism') else False # If a gene is known to have reduced penetrance this is annotated gene['reduced_penetrance'] = True if gene_info.get('reduced_penetrance') else False # The database entry version is a way to track when a a gene was added or # modified, optional gene['database_entry_version'] = gene_info.get('database_entry_version') return gene
Parse a file with genes and return the hgnc ids
def parse_genes(gene_lines): """Parse a file with genes and return the hgnc ids Args: gene_lines(iterable(str)): Stream with genes Returns: genes(list(dict)): Dictionaries with relevant gene info """ genes = [] header = [] hgnc_identifiers = set() delimiter = '\t' # This can be '\t' or ';' delimiters = ['\t', ' ', ';'] # There are files that have '#' to indicate headers # There are some files that start with a header line without # any special symbol for i,line in enumerate(gene_lines): line = line.rstrip() if not len(line) > 0: continue if line.startswith('#'): if not line.startswith('##'): # We need to try delimiters # We prefer ';' or '\t' byt should accept ' ' line_length = 0 delimiter = None for alt in delimiters: head_line = line.split(alt) if len(head_line) > line_length: line_length = len(head_line) delimiter = alt header = [word.lower() for word in line[1:].split(delimiter)] else: # If no header symbol(#) assume first line is header if i == 0: line_length = 0 for alt in delimiters: head_line = line.split(alt) if len(head_line) > line_length: line_length = len(head_line) delimiter = alt if ('hgnc' in line or 'HGNC' in line): header = [word.lower() for word in line.split(delimiter)] continue # If first line is not a header try to sniff what the first # columns holds if line.split(delimiter)[0].isdigit(): header = ['hgnc_id'] else: header = ['hgnc_symbol'] splitted_line = line.split(delimiter) gene_info = dict(zip(header, splitted_line)) # There are cases when excel exports empty lines that looks like # ;;;;;;;. This is a exception to handle these info_found = False for key in gene_info: if gene_info[key]: info_found = True break # If no info was found we skip that line if not info_found: continue try: gene = parse_gene(gene_info) except Exception as e: LOG.warning(e) raise SyntaxError("Line {0} is malformed".format(i + 1)) identifier = gene.pop('identifier') if not identifier in hgnc_identifiers: hgnc_identifiers.add(identifier) genes.append(gene) return genes
Parse the panel info and return a gene panel
def parse_gene_panel(path, institute='cust000', panel_id='test', panel_type='clinical', date=datetime.now(), version=1.0, display_name=None, genes = None): """Parse the panel info and return a gene panel Args: path(str): Path to panel file institute(str): Name of institute that owns the panel panel_id(str): Panel id date(datetime.datetime): Date of creation version(float) full_name(str): Option to have a long name Returns: gene_panel(dict) """ LOG.info("Parsing gene panel %s", panel_id) gene_panel = {} gene_panel['path'] = path gene_panel['type'] = panel_type gene_panel['date'] = date gene_panel['panel_id'] = panel_id gene_panel['institute'] = institute version = version or 1.0 gene_panel['version'] = float(version) gene_panel['display_name'] = display_name or panel_id if not path: panel_handle = genes else: panel_handle = get_file_handle(gene_panel['path']) gene_panel['genes'] = parse_genes(gene_lines=panel_handle) return gene_panel
Parse a panel app formated gene Args: app_gene ( dict ): Dict with panel app info hgnc_map ( dict ): Map from hgnc_symbol to hgnc_id Returns: gene_info ( dict ): Scout infromation
def parse_panel_app_gene(app_gene, hgnc_map): """Parse a panel app formated gene Args: app_gene(dict): Dict with panel app info hgnc_map(dict): Map from hgnc_symbol to hgnc_id Returns: gene_info(dict): Scout infromation """ gene_info = {} confidence_level = app_gene['LevelOfConfidence'] # Return empty gene if not confident gene if not confidence_level == 'HighEvidence': return gene_info hgnc_symbol = app_gene['GeneSymbol'] # Returns a set of hgnc ids hgnc_ids = get_correct_ids(hgnc_symbol, hgnc_map) if not hgnc_ids: LOG.warning("Gene %s does not exist in database. Skipping gene...", hgnc_symbol) return gene_info if len(hgnc_ids) > 1: LOG.warning("Gene %s has unclear identifier. Choose random id", hgnc_symbol) gene_info['hgnc_symbol'] = hgnc_symbol for hgnc_id in hgnc_ids: gene_info['hgnc_id'] = hgnc_id gene_info['reduced_penetrance'] = INCOMPLETE_PENETRANCE_MAP.get(app_gene['Penetrance']) inheritance_models = [] for model in MODELS_MAP.get(app_gene['ModeOfInheritance'],[]): inheritance_models.append(model) gene_info['inheritance_models'] = inheritance_models return gene_info
Parse a PanelApp panel Args: panel_info ( dict ) hgnc_map ( dict ): Map from symbol to hgnc ids institute ( str ) panel_type ( str ) Returns: gene_panel ( dict )
def parse_panel_app_panel(panel_info, hgnc_map, institute='cust000', panel_type='clinical'): """Parse a PanelApp panel Args: panel_info(dict) hgnc_map(dict): Map from symbol to hgnc ids institute(str) panel_type(str) Returns: gene_panel(dict) """ date_format = "%Y-%m-%dT%H:%M:%S.%f" gene_panel = {} gene_panel['version'] = float(panel_info['version']) gene_panel['date'] = get_date(panel_info['Created'][:-1], date_format=date_format) gene_panel['display_name'] = panel_info['SpecificDiseaseName'] gene_panel['institute'] = institute gene_panel['panel_type'] = panel_type LOG.info("Parsing panel %s", gene_panel['display_name']) gene_panel['genes'] = [] nr_low_confidence = 1 nr_genes = 0 for nr_genes, gene in enumerate(panel_info['Genes'],1): gene_info = parse_panel_app_gene(gene, hgnc_map) if not gene_info: nr_low_confidence += 1 continue gene_panel['genes'].append(gene_info) LOG.info("Number of genes in panel %s", nr_genes) LOG.info("Number of low confidence genes in panel %s", nr_low_confidence) return gene_panel
Return all genes that should be included in the OMIM - AUTO panel Return the hgnc symbols Genes that have at least one established or provisional phenotype connection are included in the gene panel Args: genemap2_lines ( iterable ) mim2gene_lines ( iterable ) alias_genes ( dict ): A dictionary that maps hgnc_symbol to hgnc_id Yields: hgnc_symbol ( str )
def get_omim_panel_genes(genemap2_lines, mim2gene_lines, alias_genes): """Return all genes that should be included in the OMIM-AUTO panel Return the hgnc symbols Genes that have at least one 'established' or 'provisional' phenotype connection are included in the gene panel Args: genemap2_lines(iterable) mim2gene_lines(iterable) alias_genes(dict): A dictionary that maps hgnc_symbol to hgnc_id Yields: hgnc_symbol(str) """ parsed_genes = get_mim_genes(genemap2_lines, mim2gene_lines) STATUS_TO_ADD = set(['established', 'provisional']) for hgnc_symbol in parsed_genes: try: gene = parsed_genes[hgnc_symbol] keep = False for phenotype_info in gene.get('phenotypes',[]): if phenotype_info['status'] in STATUS_TO_ADD: keep = True break if keep: hgnc_id_info = alias_genes.get(hgnc_symbol) if not hgnc_id_info: for symbol in gene.get('hgnc_symbols', []): if symbol in alias_genes: hgnc_id_info = alias_genes[symbol] break if hgnc_id_info: yield { 'hgnc_id': hgnc_id_info['true'], 'hgnc_symbol': hgnc_symbol, } else: LOG.warning("Gene symbol %s does not exist", hgnc_symbol) except KeyError: pass
Show all diseases in the database
def diseases(context): """Show all diseases in the database""" LOG.info("Running scout view diseases") adapter = context.obj['adapter'] disease_objs = adapter.disease_terms() nr_diseases = disease_objs.count() if nr_diseases == 0: click.echo("No diseases found") else: click.echo("Disease") for disease_obj in adapter.disease_terms(): click.echo("{0}".format(disease_obj['_id'])) LOG.info("{0} diseases found".format(nr_diseases))
Update the hpo terms in the database. Fetch the latest release and update terms.
def hpo(context): """ Update the hpo terms in the database. Fetch the latest release and update terms. """ LOG.info("Running scout update hpo") adapter = context.obj['adapter'] LOG.info("Dropping HPO terms") adapter.hpo_term_collection.drop() LOG.debug("HPO terms dropped") load_hpo_terms(adapter)
Repeats an event and returns num ( or fewer ) upcoming events from now.
def get_upcoming_events(self): """ Repeats an event and returns 'num' (or fewer) upcoming events from 'now'. """ if self.event.repeats('NEVER'): has_ended = False now_gt_start = self.now > self.event.l_start_date now_gt_end = self.now > self.event.end_date if now_gt_end or now_gt_start: has_ended = True has_not_started = self.event.l_start_date > self.finish if has_ended or has_not_started: return self.events self.events.append((self.event.l_start_date, self.event)) return self.events if self.event.repeats('WEEKDAY'): self._weekday() elif self.event.repeats('MONTHLY'): self._monthly() elif self.event.repeats('YEARLY'): self._yearly() else: self._others() return self.events
Checks start to see if we should stop collecting upcoming events. start should be a datetime. datetime start_ should be the same as start but it should be a datetime. date to allow comparison w/ end_repeat.
def we_should_stop(self, start, start_): """ Checks 'start' to see if we should stop collecting upcoming events. 'start' should be a datetime.datetime, 'start_' should be the same as 'start', but it should be a datetime.date to allow comparison w/ end_repeat. """ if start > self.finish or \ self.event.end_repeat is not None and \ start_ > self.event.end_repeat: return True else: return False
Display a list of all users and which institutes they belong to.
def users(store): """Display a list of all users and which institutes they belong to.""" user_objs = list(store.users()) total_events = store.user_events().count() for user_obj in user_objs: if user_obj.get('institutes'): user_obj['institutes'] = [store.institute(inst_id) for inst_id in user_obj.get('institutes')] else: user_obj['institutes'] = [] user_obj['events'] = store.user_events(user_obj).count() user_obj['events_rank'] = event_rank(user_obj['events']) return dict( users=sorted(user_objs, key=lambda user: -user['events']), total_events=total_events, )
Parse the conservation predictors
def parse_conservations(variant): """Parse the conservation predictors Args: variant(dict): A variant dictionary Returns: conservations(dict): A dictionary with the conservations """ conservations = {} conservations['gerp'] = parse_conservation( variant, 'dbNSFP_GERP___RS' ) conservations['phast'] = parse_conservation( variant, 'dbNSFP_phastCons100way_vertebrate' ) conservations['phylop'] = parse_conservation( variant, 'dbNSFP_phyloP100way_vertebrate' ) return conservations
Get the conservation prediction
def parse_conservation(variant, info_key): """Get the conservation prediction Args: variant(dict): A variant dictionary info_key(str) Returns: conservations(list): List of censervation terms """ raw_score = variant.INFO.get(info_key) conservations = [] if raw_score: if isinstance(raw_score, numbers.Number): raw_score = (raw_score,) for score in raw_score: if score >= CONSERVATION[info_key]['conserved_min']: conservations.append('Conserved') else: conservations.append('NotConserved') return conservations