def panels(): """Show all panels for a case.""" if request.method == 'POST': # add new panel csv_file = request.files['csv_file'] lines = csv_file.stream.read().decode().split('\r') panel_genes = parse_panel(lines) try: panel_obj = build_panel( adapter=store, institute_id=request.form['institute_id'], panel_name=request.form['panel_name'], display_name=request.form['display_name'], version=float(request.form['version']) if request.form.get('version') else 1.0, panel_genes=panel_genes, ) except ValueError as error: flash(error.args[0], 'warning') return redirect(request.referrer) store.add_gene_panel(panel_obj) flash("new gene panel added: {}".format(panel_obj['panel_name']), 'info') panel_groups = [] for institute_obj in user_institutes(store, current_user): institute_panels = store.gene_panels(institute_id=institute_obj['_id']) panel_groups.append((institute_obj, institute_panels)) return dict(panel_groups=panel_groups, institutes=user_institutes(store, current_user))
def institutes(): """Display a list of all user institutes.""" institute_objs = user_institutes(store, current_user) institutes = [] for ins_obj in institute_objs: sanger_recipients = [] for user_mail in ins_obj.get('sanger_recipients', []): user_obj = store.user(user_mail) if not user_obj: continue sanger_recipients.append(user_obj['name']) institutes.append({ 'display_name': ins_obj['display_name'], 'internal_id': ins_obj['_id'], 'coverage_cutoff': ins_obj.get('coverage_cutoff', 'None'), 'sanger_recipients': sanger_recipients, 'frequency_cutoff': ins_obj.get('frequency_cutoff', 'None'), 'phenotype_groups': ins_obj.get('phenotype_groups', PHENOTYPE_GROUPS) }) data = dict(institutes=institutes) return render_template('overview/institutes.html', **data)
def institutes(): """Display a list of all user institutes.""" institute_objs = user_institutes(store, current_user) institutes = [] for ins_obj in institute_objs: sanger_recipients = [] for user_mail in ins_obj.get("sanger_recipients", []): user_obj = store.user(user_mail) if not user_obj: continue sanger_recipients.append(user_obj["name"]) institutes.append({ "display_name": ins_obj["display_name"], "internal_id": ins_obj["_id"], "coverage_cutoff": ins_obj.get("coverage_cutoff", "None"), "sanger_recipients": sanger_recipients, "frequency_cutoff": ins_obj.get("frequency_cutoff", "None"), "phenotype_groups": ins_obj.get("phenotype_groups", PHENOTYPE_GROUPS), "case_count": sum(1 for i in store.cases(collaborator=ins_obj["_id"])), }) data = dict(institutes=institutes) return render_template("overview/institutes.html", **data)
def add_managed_variant(request): """Add a managed variant. Args: request(werkzeug.local.LocalProxy): request containing form data """ add_form = ManagedVariantAddForm(request.form) institutes = list(user_institutes(store, current_user)) current_user_id = current_user._id managed_variant_obj = build_managed_variant( dict( chromosome=add_form["chromosome"].data, position=add_form["position"].data, end=add_form["end"].data, reference=add_form["reference"].data, alternative=add_form["alternative"].data, institutes=institutes, maintainer=[current_user_id], category=add_form["category"].data, sub_category=add_form["sub_category"].data, description=add_form["description"].data, )) return store.upsert_managed_variant(managed_variant_obj)
def institutes(): """Returns institutes info available for a user Returns: data(list): a list of institute dictionaries """ institute_objs = user_institutes(store, current_user) institutes = [] for ins_obj in institute_objs: sanger_recipients = [] for user_mail in ins_obj.get("sanger_recipients", []): user_obj = store.user(user_mail) if not user_obj: continue sanger_recipients.append(user_obj["name"]) institutes.append({ "display_name": ins_obj["display_name"], "internal_id": ins_obj["_id"], "coverage_cutoff": ins_obj.get("coverage_cutoff", "None"), "sanger_recipients": sanger_recipients, "frequency_cutoff": ins_obj.get("frequency_cutoff", "None"), "phenotype_groups": ins_obj.get("phenotype_groups", PHENOTYPE_GROUPS), "case_count": sum(1 for i in store.cases(collaborator=ins_obj["_id"])), }) return institutes
def institutes(): """Display a list of all user institutes.""" institute_objs = user_institutes(store, current_user) institutes = [] for ins_obj in institute_objs: sanger_recipients = [] for user_mail in ins_obj.get('sanger_recipients',[]): user_obj = store.user(user_mail) if not user_obj: continue sanger_recipients.append(user_obj['name']) institutes.append( { 'display_name': ins_obj['display_name'], 'internal_id': ins_obj['_id'], 'coverage_cutoff': ins_obj.get('coverage_cutoff', 'None'), 'sanger_recipients': sanger_recipients, 'frequency_cutoff': ins_obj.get('frequency_cutoff', 'None'), 'phenotype_groups': ins_obj.get('phenotype_groups', PHENOTYPE_GROUPS) } ) data = dict(institutes=institutes) return render_template( 'overview/institutes.html', **data)
def managed_variants(): page = int(request.form.get("page", 1)) institutes = list(user_institutes(store, current_user)) filters_form = ManagedVariantsFilterForm(request.form) add_form = ManagedVariantAddForm() modify_form = ManagedVariantModifyForm() category = request.form.get("category", "snv") query_options = {} for option in [ "chromosome", "sub_category", "position", "end", "description" ]: if request.form.get(option, None): query_options[option] = request.form.get(option) managed_variants_query = store.managed_variants( category=category, query_options=query_options) data = controllers.managed_variants(store, managed_variants_query, page) return dict( filters_form=filters_form, add_form=add_form, modify_form=modify_form, page=page, **data, )
def upload_managed_variants(): institutes = list(user_institutes(store, current_user)) csv_file = request.files["csv_file"] content = csv_file.stream.read() lines = None try: if b"\n" in content: lines = content.decode("utf-8-sig", "ignore").split("\n") else: lines = content.decode("windows-1252").split("\r") except Exception as err: flash( "Something went wrong while parsing the panel CSV file! ({})". format(err), "danger", ) return redirect(request.referrer) LOG.debug("Loading lines %s", lines) result = controllers.upload_managed_variants(store, lines, institutes, current_user._id) flash( "In total {} new variants out of {} in file added".format( result[0], result[1]), "success") return redirect(request.referrer)
def gene_variants(store, pymongo_cursor, variant_count, institute_id, page=1, per_page=50): """Pre-process list of variants.""" skip_count = per_page * max(page - 1, 0) more_variants = True if variant_count > (skip_count + per_page) else False variant_res = pymongo_cursor.skip(skip_count).limit(per_page) my_institutes = set(inst["_id"] for inst in user_institutes(store, current_user)) variants = [] for variant_obj in variant_res: # 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 # hide other institutes for now other_institutes = set([variant_case_obj.get("owner")]) other_institutes.update(set(variant_case_obj.get("collaborators", []))) if my_institutes.isdisjoint(other_institutes): # If the user does not have access to the information we skip it continue genome_build = get_genome_build(variant_case_obj) variant_genes = variant_obj.get("genes") gene_object = update_HGNC_symbols(store, variant_genes, genome_build) # Populate variant HGVS and predictions variant_genes = variant_obj.get("genes") hgvs_c = [] hgvs_p = [] if variant_genes is not None: for gene_obj in variant_genes: hgnc_id = gene_obj["hgnc_id"] gene_symbol = gene(store, hgnc_id)["symbol"] gene_symbols = [gene_symbol] # gather HGVS info from gene transcripts (hgvs_nucleotide, hgvs_protein) = get_hgvs(gene_obj) hgvs_c.append(hgvs_nucleotide) hgvs_p.append(hgvs_protein) if len(gene_symbols) == 1: variant_obj["hgvs"] = hgvs_str(gene_symbols, hgvs_p, hgvs_c) # populate variant predictions for display variant_obj.update(predictions(variant_genes)) variants.append(variant_obj) return {"variants": variants, "more_variants": more_variants}
def index(): """Display a list of all user institutes.""" institute_objs = user_institutes(store, current_user) institutes_count = ((institute_obj, store.cases( collaborator=institute_obj["_id"]).count()) for institute_obj in institute_objs if institute_obj) return dict(institutes=institutes_count)
def add_managed_variant(): add_form = ManagedVariantAddForm(request.form) LOG.debug("Adding managed variant with form %s", add_form) institutes = list(user_institutes(store, current_user)) current_user_id = current_user._id controllers.add_managed_variant(store, add_form, institutes, current_user_id) return redirect(request.referrer)
def panels(): """Show all panels for a case.""" if request.method == 'POST': # update an existing panel csv_file = request.files['csv_file'] content = csv_file.stream.read() if b'\n' in content: lines = content.decode().split('\n') else: lines = content.decode('windows-1252').split('\r') new_panel_name = request.form.get('new_panel_name') if new_panel_name: panel_obj = controllers.new_panel( store=store, institute_id=request.form['institute'], panel_name=new_panel_name, display_name=request.form['display_name'], csv_lines=lines, ) if panel_obj is None: return redirect(request.referrer) flash("new gene panel added: {}!".format(panel_obj['panel_name'])) else: panel_obj = controllers.update_panel(store, request.form['panel_name'], lines) if panel_obj is None: return abort( 404, "gene panel not found: {}".format( request.form['panel_name'])) return redirect(url_for('panels.panel', panel_id=panel_obj['_id'])) institutes = list(user_institutes(store, current_user)) panel_names = [ name for institute in institutes for name in store.gene_panels( institute_id=institute['_id']).distinct('panel_name') ] panel_versions = {} for name in panel_names: panel_versions[name] = store.gene_panels(panel_id=name) panel_groups = [] for institute_obj in institutes: institute_panels = store.latest_panels(institute_obj['_id']) panel_groups.append((institute_obj, institute_panels)) return dict(panel_groups=panel_groups, panel_names=panel_names, panel_versions=panel_versions, institutes=institutes)
def institute_select_choices(): """Return a list of tuples with institute _id, institute names to populate a form select. Returns: institute_choices(list). Example:[(cust000, "Institute 1"), ..] """ institute_choices = [("All", "All institutes")] if current_user.is_admin else [] # Collect only institutes available to the user institute_objs = user_institutes(store, current_user) for inst in institute_objs: institute_choices.append((inst["_id"], inst["display_name"])) return institute_choices
def gene_variants(institute_id): """Display a list of SNV variants.""" page = int(request.form.get("page", 1)) result_size = None institute_obj = institute_and_case(store, institute_id) data = {} if request.method == "GET": form = GeneVariantFiltersForm(request.args) else: # POST form = GeneVariantFiltersForm(request.form) if form.variant_type.data == []: form.variant_type.data = ["clinical"] variant_type = form.data.get("variant_type") update_form_hgnc_symbols(store=store, case_obj=None, form=form) # If no valid gene is provided, redirect to form if not form.hgnc_symbols.data: flash( "Provided gene symbols could not be used in variants' search", "warning") return redirect(request.referrer) variants_query = store.build_variant_query( query=form.data, institute_ids=[ inst["_id"] for inst in user_institutes(store, current_user) ], category="snv", variant_type=variant_type, ) # This is the actual query dictionary, not the cursor with results results = store.variant_collection.find(variants_query).sort([ ("rank_score", DESCENDING) ]) # query results result_size = store.variant_collection.count_documents(variants_query) data = controllers.gene_variants( store, results, result_size, page) # decorated variant results, max 50 in a page return dict(institute=institute_obj, form=form, page=page, result_size=result_size, **data)
def get_loqusdb_obs_cases(store, variant_obj, category, obs_families=[]): """Get a list of cases where variant observations occurred. These are only the cases the user has access to. Args: store (scout.adapter.MongoAdapter) variant_obj(scout.models.Variant) it's the variant the loqusdb stats are computer for category(str) obs_families(list). List of all cases in loqusdb where variant occurred Returns: obs_cases(list). """ obs_cases = [] user_institutes_ids = set([inst["_id"] for inst in user_institutes(store, current_user)]) for i, case_id in enumerate(obs_families): if len(obs_cases) == 10: break if case_id == variant_obj["case_id"]: continue # other case might belong to same institute, collaborators or other institutes other_case = store.case(case_id) if not other_case: # Case could have been removed LOG.debug("Case %s could not be found in database", case_id) continue other_institutes = set([other_case.get("owner")]) other_institutes.update(set(other_case.get("collaborators", []))) if user_institutes_ids.isdisjoint(other_institutes): # If the user does not have access to the information we skip it. Admins allowed by user_institutes. continue other_variant = store.variant( case_id=other_case["_id"], document_id=variant_obj["variant_id"] ) # IF variant is SV variant, look for variants with different sub_category occurring at the same coordinates if other_variant is None and category == "sv": other_variant = store.overlapping_sv_variant(other_case["_id"], variant_obj) obs_cases.append(dict(case=other_case, variant=other_variant)) return obs_cases
def panels(): """Show all panels for a user""" if request.method == "POST": # Edit/create a new panel and redirect to its page redirect_panel_id = controllers.panel_create_or_update(store, request) if redirect_panel_id: return redirect(url_for("panels.panel", panel_id=redirect_panel_id)) return redirect(url_for("panels.panels")) institutes = list(user_institutes(store, current_user)) panel_names = [ name for institute in institutes for name in store.gene_panels(institute_id=institute["_id"], include_hidden=True).distinct("panel_name") ] panel_versions = {} for name in panel_names: panels = store.gene_panels(panel_id=name, include_hidden=True) panel_versions[name] = [ panel_obj for panel_obj in panels if controllers.shall_display_panel(panel_obj, current_user) ] panel_groups = [] for institute_obj in institutes: institute_panels = ( panel_obj for panel_obj in store.latest_panels(institute_obj["_id"], include_hidden=True) if controllers.shall_display_panel(panel_obj, current_user)) panel_groups.append((institute_obj, institute_panels)) return dict( panel_groups=panel_groups, panel_names=panel_names, panel_versions=panel_versions, institutes=institutes, )
def panels(): """Show all panels for a case.""" if request.method == 'POST': # update an existing panel csv_file = request.files['csv_file'] content = csv_file.stream.read() lines = None try: if b'\n' in content: lines = content.decode('utf-8', 'ignore').split('\n') else: lines = content.decode('windows-1252').split('\r') except Exception as err: flash('Something went wrong while parsing the panel CSV file! ({})'.format(err), 'danger') return redirect(request.referrer) new_panel_name = request.form.get('new_panel_name') if new_panel_name: #create a new panel new_panel_id = controllers.new_panel( store=store, institute_id=request.form['institute'], panel_name=new_panel_name, display_name=request.form['display_name'], csv_lines=lines, ) if new_panel_id is None: flash('Something went wrong and the panel list was not updated!','warning') return redirect(request.referrer) else: flash("new gene panel added, {}!".format(new_panel_name),'success') return redirect(url_for('panels.panel', panel_id=new_panel_id)) else: # modify an existing panel update_option = request.form['modify_option'] panel_obj= controllers.update_panel( store=store, panel_name=request.form['panel_name'], csv_lines=lines, option=update_option ) if panel_obj is None: return abort(404, "gene panel not found: {}".format(request.form['panel_name'])) else: return redirect(url_for('panels.panel', panel_id=panel_obj['_id'])) institutes = list(user_institutes(store, current_user)) panel_names = [name for institute in institutes for name in store.gene_panels(institute_id=institute['_id']).distinct('panel_name')] panel_versions = {} for name in panel_names: panel_versions[name]=store.gene_panels(panel_id=name) panel_groups = [] for institute_obj in institutes: institute_panels = store.latest_panels(institute_obj['_id']) panel_groups.append((institute_obj, institute_panels)) return dict(panel_groups=panel_groups, panel_names=panel_names, panel_versions=panel_versions, institutes=institutes)
variant_obj["comments"] = store.events( institute_obj, case=case_obj, variant_id=variant_id, comments=True ) # Adds information about other causative variants other_causatives = [] if add_other: other_causatives = [ causative for causative in store.other_causatives(case_obj, variant_obj) ] managed_variant = store.find_managed_variant_id(variant_obj["variant_id"]) if variant_obj.get("category") == "cancer": variant_obj["matching_tiered"] = store.matching_tiered( variant_obj, user_institutes(store, current_user) ) # Gather display information for the genes variant_obj.update(predictions(variant_obj.get("genes", []))) # Prepare classification information for visualisation classification = variant_obj.get("acmg_classification") if isinstance(classification, int): acmg_code = ACMG_MAP[variant_obj["acmg_classification"]] variant_obj["acmg_classification"] = ACMG_COMPLETE_MAP[acmg_code] # sort compounds on combined rank score compounds = variant_obj.get("compounds", []) if compounds: # Gather display information for the compounds
def panels(): """Show all panels for a case.""" if request.method == "POST": # update an existing panel csv_file = request.files["csv_file"] content = csv_file.stream.read() lines = None try: if b"\n" in content: lines = content.decode("utf-8-sig", "ignore").split("\n") else: lines = content.decode("windows-1252").split("\r") except Exception as err: flash( "Something went wrong while parsing the panel CSV file! ({})". format(err), "danger", ) return redirect(request.referrer) new_panel_name = request.form.get("new_panel_name") if new_panel_name: # create a new panel new_panel_id = controllers.new_panel( store=store, institute_id=request.form["institute"], panel_name=new_panel_name, display_name=request.form["display_name"], description=request.form["description"], csv_lines=lines, ) if new_panel_id is None: flash( "Something went wrong and the panel list was not updated!", "warning", ) return redirect(request.referrer) else: flash("new gene panel added, {}!".format(new_panel_name), "success") return redirect(url_for("panels.panel", panel_id=new_panel_id)) else: # modify an existing panel update_option = request.form["modify_option"] panel_obj = controllers.update_panel( store=store, panel_name=request.form["panel_name"], csv_lines=lines, option=update_option, ) if panel_obj is None: return abort( 404, "gene panel not found: {}".format( request.form["panel_name"])) else: return redirect( url_for("panels.panel", panel_id=panel_obj["_id"])) institutes = list(user_institutes(store, current_user)) panel_names = [ name for institute in institutes for name in store.gene_panels( institute_id=institute["_id"]).distinct("panel_name") ] panel_versions = {} for name in panel_names: panel_versions[name] = store.gene_panels(panel_id=name) panel_groups = [] for institute_obj in institutes: institute_panels = store.latest_panels(institute_obj["_id"]) panel_groups.append((institute_obj, institute_panels)) return dict( panel_groups=panel_groups, panel_names=panel_names, panel_versions=panel_versions, institutes=institutes, )
def observations(store, loqusdb, case_obj, variant_obj): """Query observations for a variant. Check if variant_obj have been observed before ni the loqusdb instance. If not return empty dictionary. We need to add links to the variant in other cases where the variant has been observed. First we need to make sure that the user has access to these cases. The user_institute_ids holds information about what institutes the user has access to. Loop over the case ids from loqusdb and check if they exist in the scout instance. Also make sure that we do not link to the observation that is the current variant. Args: store (scout.adapter.MongoAdapter) loqusdb (scout.server.extensions.LoqusDB) case_obj (scout.models.Case) variant_obj (scout.models.Variant) Returns: obs_data(dict) """ chrom = variant_obj["chromosome"] pos = variant_obj["position"] ref = variant_obj["reference"] alt = variant_obj["alternative"] var_case_id = variant_obj["case_id"] var_type = variant_obj.get("variant_type", "clinical") composite_id = "{0}_{1}_{2}_{3}".format(chrom, pos, ref, alt) variant_query = { "_id": composite_id, "chrom": chrom, "end_chrom": variant_obj.get("end_chrom", chrom), "pos": pos, "end": variant_obj["end"], "length": variant_obj.get("length", 0), "variant_type": variant_obj.get("sub_category", "").upper(), "category": variant_obj["category"], } institute_id = variant_obj["institute"] institute_obj = store.institute(institute_id) obs_data = loqusdb.get_variant( variant_query, loqusdb_id=institute_obj.get("loqusdb_id")) or {} if not obs_data: LOG.debug("Could not find any observations for %s", composite_id) obs_data["total"] = loqusdb.case_count() return obs_data user_institutes_ids = set( [inst["_id"] for inst in user_institutes(store, current_user)]) obs_data["cases"] = [] for i, case_id in enumerate(obs_data.get("families", [])): if i > 10: break if case_id == var_case_id: continue # other case might belong to same institute, collaborators or other institutes other_case = store.case(case_id) if not other_case: # Case could have been removed LOG.debug("Case %s could not be found in database", case_id) continue other_institutes = set([other_case.get("owner")]) other_institutes.update(set(other_case.get("collaborators", []))) if user_institutes_ids.isdisjoint(other_institutes): # If the user does not have access to the information we skip it continue document_id = parse_document_id(chrom, str(pos), ref, alt, var_type, case_id) other_variant = store.variant(document_id=document_id) # If the other variant is not loaded we skip it if not other_variant: continue obs_data["cases"].append(dict(case=other_case, variant=other_variant)) return obs_data
def panels(): """Show all panels for a case.""" if request.method == 'POST': # update an existing panel csv_file = request.files['csv_file'] content = csv_file.stream.read() lines = None try: if b'\n' in content: lines = content.decode('utf-8', 'ignore').split('\n') else: lines = content.decode('windows-1252').split('\r') except Exception as err: flash('Something went wrong while parsing the panel CSV file! ({})'.format(err), 'danger') return redirect(request.referrer) new_panel_name = request.form.get('new_panel_name') if new_panel_name: #create a new panel new_panel_id = controllers.new_panel( store=store, institute_id=request.form['institute'], panel_name=new_panel_name, display_name=request.form['display_name'], description=request.form['description'], csv_lines=lines, ) if new_panel_id is None: flash('Something went wrong and the panel list was not updated!','warning') return redirect(request.referrer) else: flash("new gene panel added, {}!".format(new_panel_name),'success') return redirect(url_for('panels.panel', panel_id=new_panel_id)) else: # modify an existing panel update_option = request.form['modify_option'] panel_obj= controllers.update_panel( store=store, panel_name=request.form['panel_name'], csv_lines=lines, option=update_option ) if panel_obj is None: return abort(404, "gene panel not found: {}".format(request.form['panel_name'])) else: return redirect(url_for('panels.panel', panel_id=panel_obj['_id'])) institutes = list(user_institutes(store, current_user)) panel_names = [name for institute in institutes for name in store.gene_panels(institute_id=institute['_id']).distinct('panel_name')] panel_versions = {} for name in panel_names: panel_versions[name]=store.gene_panels(panel_id=name) panel_groups = [] for institute_obj in institutes: institute_panels = store.latest_panels(institute_obj['_id']) panel_groups.append((institute_obj, institute_panels)) return dict(panel_groups=panel_groups, panel_names=panel_names, panel_versions=panel_versions, institutes=institutes)
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, }
def gene_variants(store, variants_query, institute_id, page=1, per_page=50): """Pre-process list of variants.""" # We need to call variants_collection.count_documents here 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 = set(inst["_id"] for inst in user_institutes(store, current_user)) variants = [] for variant_obj in variant_res: # 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 # hide other institutes for now other_institutes = set([variant_case_obj.get("owner")]) other_institutes.update(set(variant_case_obj.get("collaborators", []))) if my_institutes.isdisjoint(other_institutes): # If the user does not have access to the information we skip it continue 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(predictions(variant_genes)) variants.append(variant_obj) return {"variants": variants, "more_variants": more_variants}
def index(): """Display a list of all user institutes.""" institute_objs = user_institutes(store, current_user) institutes_count = ((institute_obj, store.cases(collaborator=institute_obj['_id']).count()) for institute_obj in institute_objs if institute_obj) return dict(institutes=institutes_count)
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, }