Example #1
0
def variant_page(variant_id):
    db = get_db()
    try:
        _log()
        variant = lookups.get_variant_by_variant_id(
            db, variant_id, default_to_boring_variant=False)
        if not variant:
            return not_found_page(
                'The requested variant {!s} could not be found.'.format(
                    variant_id))

        pop_names = {
            k + '_AF': '1000G ' + v
            for k, v in {
                'AFR': 'African',
                'AMR': 'American',
                'EAS': 'East Asian',
                'EUR': 'European',
                'SAS': 'South Asian'
            }.items()
        }
        if 'pop_afs' in variant:
            variant['pop_afs'] = {
                pop_names.get(k, k): v
                for k, v in variant['pop_afs'].items()
            }
        else:
            variant['pop_afs'] = {x: None for x in pop_names.itervalues()}
        variant['pop_afs'][app.config['DATASET_NAME']] = variant['allele_freq']

        consequence_drilldown = ConsequenceDrilldown.from_variant(variant)
        gene_for_top_csq, top_HGVSs = ConsequenceDrilldown.get_top_gene_and_HGVSs(
            consequence_drilldown)
        consequence_drilldown_columns = ConsequenceDrilldown.split_into_two_columns(
            consequence_drilldown)

        base_coverage = get_coverage_handler().get_coverage_for_intervalset(
            IntervalSet.from_xstart_xstop(
                variant['xpos'], variant['xpos'] + len(variant['ref']) - 1))

        metrics = lookups.get_metrics(db)
        variant['quality_metrics']['QUAL'] = variant['site_quality']

        lookups.remove_some_extraneous_information(variant)

        return render_template(
            'variant.html',
            variant=variant,
            base_coverage=base_coverage,
            consequences=consequence_drilldown,
            consequence_columns=consequence_drilldown_columns,
            any_covered=bool(base_coverage),
            metrics=metrics,
            top_HGVSs=top_HGVSs,
            gene_for_top_csq=gene_for_top_csq,
        )
    except:
        _err()
        abort(500)
Example #2
0
def variant_page(variant_str):
    db = get_db()
    try:
        chrom, pos, ref, alt = variant_str.split('-')
        pos = int(pos)
        # pos, ref, alt = get_minimal_representation(pos, ref, alt)
        xpos = xbrowse.get_xpos(chrom, pos)
        variant = lookups.get_variant(db, xpos, ref, alt)

        if variant is None:
            variant = {
                'chrom': chrom,
                'pos': pos,
                'xpos': xpos,
                'ref': ref,
                'alt': alt
            }
        consequences = None
        ordered_csqs = None
        if 'vep_annotations' in variant:
            variant['vep_annotations'] = order_vep_by_csq(
                variant['vep_annotations'])  # Adds major_consequence
            ordered_csqs = [
                x['major_consequence'] for x in variant['vep_annotations']
            ]
            ordered_csqs = reduce(
                lambda x, y: ','.join([x, y]) if y not in x else x,
                ordered_csqs, '').split(',')  # Close but not quite there
            consequences = defaultdict(lambda: defaultdict(list))
            for annotation in variant['vep_annotations']:
                annotation['HGVS'] = get_proper_hgvs(annotation)
                consequences[annotation['major_consequence']][
                    annotation['Gene']].append(annotation)
        base_coverage = lookups.get_coverage_for_bases(db, xpos,
                                                       xpos + len(ref) - 1)
        any_covered = any([x['has_coverage'] for x in base_coverage])
        metrics = lookups.get_metrics(db, variant)

        print 'Rendering variant: %s' % variant_str
        return render_template('variant.html',
                               variant=variant,
                               base_coverage=base_coverage,
                               consequences=consequences,
                               any_covered=any_covered,
                               ordered_csqs=ordered_csqs,
                               metrics=metrics)
    except Exception, e:
        print 'Failed on variant:', variant_str, '; Error=', traceback.format_exc(
        )
        abort(404)
Example #3
0
def variant_data(variant_str, source):
    db = get_db()
    chrom, pos, ref, alt = variant_str.split('-')
    pos = int(pos)
    # pos, ref, alt = get_minimal_representation(pos, ref, alt)
    xpos = get_xpos(chrom, pos)
    variant = lookups.get_variant(db, source, xpos, ref, alt)

    if variant is None:
        variant = {
            'chrom': chrom,
            'pos': pos,
            'xpos': xpos,
            'ref': ref,
            'alt': alt
        }
    consequences = OrderedDict()
    if 'vep_annotations' in variant:
        add_consequence_to_variant(variant)
        variant['vep_annotations'] = remove_extraneous_vep_annotations(variant['vep_annotations'])
        variant['vep_annotations'] = order_vep_by_csq(variant['vep_annotations'])  # Adds major_consequence
        for annotation in variant['vep_annotations']:
            annotation['HGVS'] = get_proper_hgvs(annotation)
            consequences.setdefault(annotation['major_consequence'], {}).setdefault(annotation['Gene'], []).append(annotation)
    base_coverage = lookups.get_coverage_for_bases(db, 'base_coverage', xpos, xpos + len(ref) - 1)
    any_covered = any([x['has_coverage'] for x in base_coverage])
    metrics = lookups.get_metrics(db, variant)

    # check the appropriate sqlite db to get the *expected* number of
    # available bams and *actual* number of available bams for this variant
    sqlite_db_path = os.path.join(
        app.config["READ_VIZ_DIR"],
        "combined_bams",
        chrom,
        "combined_chr%s_%03d.db" % (chrom, pos % 1000))
    logging.info(sqlite_db_path)
    try:
        read_viz_db = sqlite3.connect(sqlite_db_path)
        n_het = read_viz_db.execute("select n_expected_samples, n_available_samples from t "
                                    "where chrom=? and pos=? and ref=? and alt=? and het_or_hom_or_hemi=?", (chrom, pos, ref, alt, 'het')).fetchone()
        n_hom = read_viz_db.execute("select n_expected_samples, n_available_samples from t "
                                    "where chrom=? and pos=? and ref=? and alt=? and het_or_hom_or_hemi=?", (chrom, pos, ref, alt, 'hom')).fetchone()
        n_hemi = read_viz_db.execute("select n_expected_samples, n_available_samples from t "
                                     "where chrom=? and pos=? and ref=? and alt=? and het_or_hom_or_hemi=?", (chrom, pos, ref, alt, 'hemi')).fetchone()
        read_viz_db.close()
    except Exception, e:
        logging.error("Error when accessing sqlite db: %s - %s", sqlite_db_path, e)
        n_het = n_hom = n_hemi = None
Example #4
0
def variant_page(variant_str):
    db = get_db()
    try:
        chrom, pos, ref, alt = variant_str.split('-')
        pos = int(pos)
        # pos, ref, alt = get_minimal_representation(pos, ref, alt)
        xpos = xbrowse.get_xpos(chrom, pos)
        variant = lookups.get_variant(db, xpos, ref, alt)

        if variant is None:
            variant = {
                'chrom': chrom,
                'pos': pos,
                'xpos': xpos,
                'ref': ref,
                'alt': alt
            }
        consequences = None
        ordered_csqs = None
        if 'vep_annotations' in variant:
            variant['vep_annotations'] = order_vep_by_csq(variant['vep_annotations'])  # Adds major_consequence
            ordered_csqs = [x['major_consequence'] for x in variant['vep_annotations']]
            ordered_csqs = reduce(lambda x, y: ','.join([x, y]) if y not in x else x, ordered_csqs, '').split(',') # Close but not quite there
            consequences = defaultdict(lambda: defaultdict(list))
            for annotation in variant['vep_annotations']:
                annotation['HGVS'] = get_proper_hgvs(annotation)
                consequences[annotation['major_consequence']][annotation['Gene']].append(annotation)
        base_coverage = lookups.get_coverage_for_bases(db, xpos, xpos + len(ref) - 1)
        any_covered = any([x['has_coverage'] for x in base_coverage])
        metrics = lookups.get_metrics(db, variant)

        print 'Rendering variant: %s' % variant_str
        return render_template(
            'variant.html',
            variant=variant,
            base_coverage=base_coverage,
            consequences=consequences,
            any_covered=any_covered,
            ordered_csqs=ordered_csqs,
            metrics=metrics
        )
    except Exception, e:
        print 'Failed on variant:', variant_str, '; Error=', traceback.format_exc()
        abort(404)
Example #5
0
def variant_page(variant_str):
    db = get_db()
    try:
        chrom, pos, ref, alt = variant_str.split("-")
        pos = int(pos)
        # pos, ref, alt = get_minimal_representation(pos, ref, alt)
        xpos = get_xpos(chrom, pos)
        variant = lookups.get_variant(db, xpos, ref, alt)

        if variant is None:
            variant = {"chrom": chrom, "pos": pos, "xpos": xpos, "ref": ref, "alt": alt}
        consequences = None
        ordered_csqs = None
        if "vep_annotations" in variant:
            variant["vep_annotations"] = order_vep_by_csq(variant["vep_annotations"])  # Adds major_consequence
            ordered_csqs = [x["major_consequence"] for x in variant["vep_annotations"]]
            ordered_csqs = reduce(lambda x, y: ",".join([x, y]) if y not in x else x, ordered_csqs, "").split(
                ","
            )  # Close but not quite there
            consequences = defaultdict(lambda: defaultdict(list))
            for annotation in variant["vep_annotations"]:
                annotation["HGVS"] = get_proper_hgvs(annotation)
                consequences[annotation["major_consequence"]][annotation["Gene"]].append(annotation)
        base_coverage = lookups.get_coverage_for_bases(db, xpos, xpos + len(ref) - 1)
        any_covered = any([x["has_coverage"] for x in base_coverage])
        metrics = lookups.get_metrics(db, variant)

        print "Rendering variant: %s" % variant_str
        return render_template(
            "variant.html",
            variant=variant,
            base_coverage=base_coverage,
            consequences=consequences,
            any_covered=any_covered,
            ordered_csqs=ordered_csqs,
            metrics=metrics,
        )
    except Exception, e:
        print "Failed on variant:", variant_str, "; Error=", traceback.format_exc()
        abort(404)
Example #6
0
def variant_page(variant_str):
    db = get_db()
    try:
        chrom, pos, ref, alt = variant_str.split('-')
        pos = int(pos)
        # pos, ref, alt = get_minimal_representation(pos, ref, alt)
        xpos = get_xpos(chrom, pos)
        variant = lookups.get_variant(db, xpos, ref, alt)

        if variant is None:
            variant = {
                'chrom': chrom,
                'pos': pos,
                'xpos': xpos,
                'ref': ref,
                'alt': alt
            }
        consequences = OrderedDict()
        if 'vep_annotations' in variant:
            add_consequence_to_variant(variant)
            variant['vep_annotations'] = remove_extraneous_vep_annotations(variant['vep_annotations'])
            variant['vep_annotations'] = order_vep_by_csq(variant['vep_annotations'])  # Adds major_consequence
            for annotation in variant['vep_annotations']:
                annotation['HGVS'] = get_proper_hgvs(annotation)
                consequences.setdefault(annotation['major_consequence'], {}).setdefault(annotation['Gene'], []).append(annotation)
        base_coverage = lookups.get_coverage_for_bases(db, xpos, xpos + len(ref) - 1)
        any_covered = any([x['has_coverage'] for x in base_coverage])
        metrics = lookups.get_metrics(db, variant)

        # check the appropriate sqlite db to get the *expected* number of
        # available bams and *actual* number of available bams for this variant
        sqlite_db_path = os.path.join(
            app.config["READ_VIZ_DIR"],            
            "combined_bams", 
            chrom,
            "combined_chr%s_%03d.db" % (chrom, pos % 1000))
        logging.info(sqlite_db_path)
        try:
            read_viz_db = sqlite3.connect(sqlite_db_path)
            n_het = read_viz_db.execute("select n_expected_samples, n_available_samples from t "
                                        "where chrom=? and pos=? and ref=? and alt=? and het_or_hom_or_hemi=?", (chrom, pos, ref, alt, 'het')).fetchone()
            n_hom = read_viz_db.execute("select n_expected_samples, n_available_samples from t "
                                        "where chrom=? and pos=? and ref=? and alt=? and het_or_hom_or_hemi=?", (chrom, pos, ref, alt, 'hom')).fetchone()
            n_hemi = read_viz_db.execute("select n_expected_samples, n_available_samples from t "
                                         "where chrom=? and pos=? and ref=? and alt=? and het_or_hom_or_hemi=?", (chrom, pos, ref, alt, 'hemi')).fetchone()
            read_viz_db.close()
        except Exception, e:
            logging.error("Error when accessing sqlite db: %s - %s", sqlite_db_path, e)
            n_het = n_hom = n_hemi = None

        read_viz_dict = {
            'het': {'n_expected': n_het[0] if n_het is not None and n_het[0] is not None else 0, 
                    'n_available': n_het[1] if n_het is not None and n_het[1] is not None else 0,},
            'hom': {'n_expected': n_hom[0] if n_hom is not None and n_hom[0] is not None else 0, 
                    'n_available': n_hom[1] if n_hom is not None  and n_hom[1] is not None else 0,},
            'hemi': {'n_expected': n_hemi[0] if n_hemi is not None and n_hemi[0] is not None else 0, 
                     'n_available': n_hemi[1] if n_hemi is not None and n_hemi[1] is not None else 0,},
        }

        total_available = 0
        total_expected = 0
        for het_or_hom_or_hemi in ('het', 'hom', 'hemi'):
            total_available += read_viz_dict[het_or_hom_or_hemi]['n_available']
            total_expected += read_viz_dict[het_or_hom_or_hemi]['n_expected']

            read_viz_dict[het_or_hom_or_hemi]['readgroups'] = [
                '%(chrom)s-%(pos)s-%(ref)s-%(alt)s_%(het_or_hom_or_hemi)s%(i)s' % locals()
                    for i in range(read_viz_dict[het_or_hom_or_hemi]['n_available'])

            ]   #eg. '1-157768000-G-C_hom1',

            read_viz_dict[het_or_hom_or_hemi]['urls'] = [
                #os.path.join('combined_bams', chrom, 'combined_chr%s_%03d.bam' % (chrom, pos % 1000))
                os.path.join('combined_bams', chrom, 'combined_chr%s_%03d.bam' % (chrom, pos % 1000))
                    for i in range(read_viz_dict[het_or_hom_or_hemi]['n_available'])
            ]

        read_viz_dict['total_available'] = total_available
        read_viz_dict['total_expected'] = total_expected


        print 'Rendering variant: %s' % variant_str
        return render_template(
            'variant.html',
            variant=variant,
            base_coverage=base_coverage,
            consequences=consequences,
            any_covered=any_covered,
            metrics=metrics,
            read_viz=read_viz_dict,
        )
Example #7
0
def variant_page(variant_str):
    db = get_db()
    try:
        chrom, pos, ref, alt = variant_str.split('-')
        pos = int(pos)
        # pos, ref, alt = get_minimal_representation(pos, ref, alt)
        xpos = get_xpos(chrom, pos)
        variant = lookups.get_variant(db, xpos, ref, alt)

        if variant is None:
            variant = {
                'chrom': chrom,
                'pos': pos,
                'xpos': xpos,
                'ref': ref,
                'alt': alt
            }
        consequences = OrderedDict()
        if 'vep_annotations' in variant:
            add_consequence_to_variant(variant)
            variant['vep_annotations'] = remove_extraneous_vep_annotations(
                variant['vep_annotations'])
            variant['vep_annotations'] = order_vep_by_csq(
                variant['vep_annotations'])  # Adds major_consequence
            for annotation in variant['vep_annotations']:
                annotation['HGVS'] = get_proper_hgvs(annotation)
                consequences.setdefault(annotation['major_consequence'],
                                        {}).setdefault(annotation['Gene'],
                                                       []).append(annotation)
        base_coverage = lookups.get_coverage_for_bases(db, xpos,
                                                       xpos + len(ref) - 1)
        any_covered = any([x['has_coverage'] for x in base_coverage])
        metrics = lookups.get_metrics(db, variant)

        # check the appropriate sqlite db to get the *expected* number of
        # available bams and *actual* number of available bams for this variant
        sqlite_db_path = os.path.join(
            app.config["READ_VIZ_DIR"], "combined_bams", chrom,
            "combined_chr%s_%03d.db" % (chrom, pos % 1000))
        logging.info(sqlite_db_path)
        try:
            read_viz_db = sqlite3.connect(sqlite_db_path)
            n_het = read_viz_db.execute(
                "select n_expected_samples, n_available_samples from t "
                "where chrom=? and pos=? and ref=? and alt=? and het_or_hom_or_hemi=?",
                (chrom, pos, ref, alt, 'het')).fetchone()
            n_hom = read_viz_db.execute(
                "select n_expected_samples, n_available_samples from t "
                "where chrom=? and pos=? and ref=? and alt=? and het_or_hom_or_hemi=?",
                (chrom, pos, ref, alt, 'hom')).fetchone()
            n_hemi = read_viz_db.execute(
                "select n_expected_samples, n_available_samples from t "
                "where chrom=? and pos=? and ref=? and alt=? and het_or_hom_or_hemi=?",
                (chrom, pos, ref, alt, 'hemi')).fetchone()
            read_viz_db.close()
        except Exception, e:
            logging.error("Error when accessing sqlite db: %s - %s",
                          sqlite_db_path, e)
            n_het = n_hom = n_hemi = None

        read_viz_dict = {
            'het': {
                'n_expected':
                n_het[0] if n_het is not None and n_het[0] is not None else 0,
                'n_available':
                n_het[1] if n_het is not None and n_het[1] is not None else 0,
            },
            'hom': {
                'n_expected':
                n_hom[0] if n_hom is not None and n_hom[0] is not None else 0,
                'n_available':
                n_hom[1] if n_hom is not None and n_hom[1] is not None else 0,
            },
            'hemi': {
                'n_expected':
                n_hemi[0]
                if n_hemi is not None and n_hemi[0] is not None else 0,
                'n_available':
                n_hemi[1]
                if n_hemi is not None and n_hemi[1] is not None else 0,
            },
        }

        total_available = 0
        total_expected = 0
        for het_or_hom_or_hemi in ('het', 'hom', 'hemi'):
            total_available += read_viz_dict[het_or_hom_or_hemi]['n_available']
            total_expected += read_viz_dict[het_or_hom_or_hemi]['n_expected']

            read_viz_dict[het_or_hom_or_hemi]['readgroups'] = [
                '%(chrom)s-%(pos)s-%(ref)s-%(alt)s_%(het_or_hom_or_hemi)s%(i)s'
                % locals() for i in range(read_viz_dict[het_or_hom_or_hemi]
                                          ['n_available'])
            ]  #eg. '1-157768000-G-C_hom1',

            read_viz_dict[het_or_hom_or_hemi]['urls'] = [
                #os.path.join('combined_bams', chrom, 'combined_chr%s_%03d.bam' % (chrom, pos % 1000))
                os.path.join('combined_bams', chrom,
                             'combined_chr%s_%03d.bam' % (chrom, pos % 1000))
                for i in range(read_viz_dict[het_or_hom_or_hemi]
                               ['n_available'])
            ]

        read_viz_dict['total_available'] = total_available
        read_viz_dict['total_expected'] = total_expected

        print 'Rendering variant: %s' % variant_str
        return render_template(
            'variant.html',
            variant=variant,
            base_coverage=base_coverage,
            consequences=consequences,
            any_covered=any_covered,
            metrics=metrics,
            read_viz=read_viz_dict,
        )
def variant_page(variant_str):
    db = get_db()
    try:
        chrom, pos, ref, alt = variant_str.split('-')
        pos = int(pos)
        # pos, ref, alt = get_minimal_representation(pos, ref, alt)
        xpos = get_xpos(chrom, pos)
        variant = lookups.get_variant(db, xpos, ref, alt)

        if variant is None:
            variant = {
                'chrom': chrom,
                'pos': pos,
                'xpos': xpos,
                'ref': ref,
                'alt': alt
            }
        consequences = None
        ordered_csqs = None
        if 'vep_annotations' in variant:
            variant['vep_annotations'] = order_vep_by_csq(
                variant['vep_annotations'])  # Adds major_consequence
            ordered_csqs = [
                x['major_consequence'] for x in variant['vep_annotations']
            ]
            ordered_csqs = reduce(
                lambda x, y: ','.join([x, y]) if y not in x else x,
                ordered_csqs, '').split(',')  # Close but not quite there
            consequences = defaultdict(lambda: defaultdict(list))
            for annotation in variant['vep_annotations']:
                annotation['HGVS'] = get_proper_hgvs(annotation)
                consequences[annotation['major_consequence']][
                    annotation['Gene']].append(annotation)
        base_coverage = lookups.get_coverage_for_bases(db, xpos,
                                                       xpos + len(ref) - 1)
        any_covered = any([x['has_coverage'] for x in base_coverage])
        metrics = lookups.get_metrics(db, variant)

        # check the appropriate sqlite db to get the *expected* number of
        # available bams and *actual* number of available bams for this variant
        sqlite_db_path = os.path.join(
            app.config["READ_VIZ_DIR"], "combined_bams", chrom,
            "combined_chr%s_%03d.db" % (chrom, pos % 1000))
        print(sqlite_db_path)
        try:
            read_viz_db = sqlite3.connect(sqlite_db_path)
            n_het = read_viz_db.execute(
                "select n_expected_samples, n_available_samples from t "
                "where chrom=? and pos=? and ref=? and alt=? and het_or_hom=?",
                (chrom, pos, ref, alt, 'het')).fetchone()
            n_hom = read_viz_db.execute(
                "select n_expected_samples, n_available_samples from t "
                "where chrom=? and pos=? and ref=? and alt=? and het_or_hom=?",
                (chrom, pos, ref, alt, 'hom')).fetchone()
            read_viz_db.close()
        except Exception, e:
            logging.debug("Error when accessing sqlite db: %s - %s",
                          sqlite_db_path, e)
            n_het = n_hom = None

        read_viz_dict = {
            'het': {
                'n_expected':
                n_het[0] if n_het is not None and n_het[0] is not None else -1,
                'n_available':
                n_het[1] if n_het and n_het[1] else 0,
            },
            'hom': {
                'n_expected':
                n_hom[0] if n_hom is not None and n_hom[0] is not None else -1,
                'n_available':
                n_hom[1] if n_hom and n_hom[1] else 0,
            },
        }

        for het_or_hom in (
                'het',
                'hom',
        ):
            #read_viz_dict[het_or_hom]['some_samples_missing'] = (read_viz_dict[het_or_hom]['n_expected'] > 0)    and (read_viz_dict[het_or_hom]['n_expected'] - read_viz_dict[het_or_hom]['n_available'] > 0)
            read_viz_dict[het_or_hom]['all_samples_missing'] = (
                read_viz_dict[het_or_hom]['n_expected'] !=
                0) and (read_viz_dict[het_or_hom]['n_available'] == 0)
            read_viz_dict[het_or_hom]['readgroups'] = [
                '%(chrom)s-%(pos)s-%(ref)s-%(alt)s_%(het_or_hom)s%(i)s' %
                locals()
                for i in range(read_viz_dict[het_or_hom]['n_available'])
            ]  #eg. '1-157768000-G-C_hom1',

            read_viz_dict[het_or_hom]['urls'] = [
                os.path.join('combined_bams', chrom,
                             'combined_chr%s_%03d.bam' % (chrom, pos % 1000))
                for i in range(read_viz_dict[het_or_hom]['n_available'])
            ]

        print 'Rendering variant: %s' % variant_str
        return render_template(
            'variant.html',
            variant=variant,
            base_coverage=base_coverage,
            consequences=consequences,
            any_covered=any_covered,
            ordered_csqs=ordered_csqs,
            metrics=metrics,
            read_viz=read_viz_dict,
        )
Example #9
0
def variant_page(variant_str):
    db = get_db()
    try:
        chrom, pos, ref, alt = variant_str.split("-")
        pos = int(pos)
        # pos, ref, alt = get_minimal_representation(pos, ref, alt)
        xpos = get_xpos(chrom, pos)
        variant = lookups.get_variant(db, xpos, ref, alt)

        if variant is None:
            variant = {"chrom": chrom, "pos": pos, "xpos": xpos, "ref": ref, "alt": alt}
        consequences = None
        ordered_csqs = None
        if "vep_annotations" in variant:
            variant["vep_annotations"] = order_vep_by_csq(variant["vep_annotations"])  # Adds major_consequence
            ordered_csqs = [x["major_consequence"] for x in variant["vep_annotations"]]
            ordered_csqs = reduce(lambda x, y: ",".join([x, y]) if y not in x else x, ordered_csqs, "").split(
                ","
            )  # Close but not quite there
            consequences = defaultdict(lambda: defaultdict(list))
            for annotation in variant["vep_annotations"]:
                annotation["HGVS"] = get_proper_hgvs(annotation)
                consequences[annotation["major_consequence"]][annotation["Gene"]].append(annotation)
        base_coverage = lookups.get_coverage_for_bases(db, xpos, xpos + len(ref) - 1)
        any_covered = any([x["has_coverage"] for x in base_coverage])
        metrics = lookups.get_metrics(db, variant)

        # check the appropriate sqlite db to get the *expected* number of
        # available bams and *actual* number of available bams for this variant
        sqlite_db_path = os.path.join(
            app.config["READ_VIZ_DIR"], "combined_bams", chrom, "combined_chr%s_%03d.db" % (chrom, pos % 1000)
        )
        print (sqlite_db_path)
        try:
            read_viz_db = sqlite3.connect(sqlite_db_path)
            n_het = read_viz_db.execute(
                "select n_expected_samples, n_available_samples from t "
                "where chrom=? and pos=? and ref=? and alt=? and het_or_hom=?",
                (chrom, pos, ref, alt, "het"),
            ).fetchone()
            n_hom = read_viz_db.execute(
                "select n_expected_samples, n_available_samples from t "
                "where chrom=? and pos=? and ref=? and alt=? and het_or_hom=?",
                (chrom, pos, ref, alt, "hom"),
            ).fetchone()
            read_viz_db.close()
        except Exception, e:
            logging.debug("Error when accessing sqlite db: %s - %s", sqlite_db_path, e)
            n_het = n_hom = None

        read_viz_dict = {
            "het": {
                "n_expected": n_het[0] if n_het is not None and n_het[0] is not None else -1,
                "n_available": n_het[1] if n_het and n_het[1] else 0,
            },
            "hom": {
                "n_expected": n_hom[0] if n_hom is not None and n_hom[0] is not None else -1,
                "n_available": n_hom[1] if n_hom and n_hom[1] else 0,
            },
        }

        for het_or_hom in ("het", "hom"):
            # read_viz_dict[het_or_hom]['some_samples_missing'] = (read_viz_dict[het_or_hom]['n_expected'] > 0)    and (read_viz_dict[het_or_hom]['n_expected'] - read_viz_dict[het_or_hom]['n_available'] > 0)
            read_viz_dict[het_or_hom]["all_samples_missing"] = (read_viz_dict[het_or_hom]["n_expected"] != 0) and (
                read_viz_dict[het_or_hom]["n_available"] == 0
            )
            read_viz_dict[het_or_hom]["readgroups"] = [
                "%(chrom)s-%(pos)s-%(ref)s-%(alt)s_%(het_or_hom)s%(i)s" % locals()
                for i in range(read_viz_dict[het_or_hom]["n_available"])
            ]  # eg. '1-157768000-G-C_hom1',

            read_viz_dict[het_or_hom]["urls"] = [
                os.path.join("combined_bams", chrom, "combined_chr%s_%03d.bam" % (chrom, pos % 1000))
                for i in range(read_viz_dict[het_or_hom]["n_available"])
            ]

        print "Rendering variant: %s" % variant_str
        return render_template(
            "variant.html",
            variant=variant,
            base_coverage=base_coverage,
            consequences=consequences,
            any_covered=any_covered,
            ordered_csqs=ordered_csqs,
            metrics=metrics,
            read_viz=read_viz_dict,
        )
Example #10
0
def variant_page(variant_str):
    db = get_db()
    try:
        chrom, pos, ref, alt = variant_str.split('-')
        pos = int(pos)
        # pos, ref, alt = get_minimal_representation(pos, ref, alt)
        xpos = get_xpos(chrom, pos)
        variant = lookups.get_variant(db, xpos, ref, alt)

        if variant is None:
            variant = {
                'chrom': chrom,
                'pos': pos,
                'xpos': xpos,
                'ref': ref,
                'alt': alt
            }
        consequences = None
        ordered_csqs = None
        if 'vep_annotations' in variant:
            variant['vep_annotations'] = order_vep_by_csq(variant['vep_annotations'])  # Adds major_consequence
            ordered_csqs = [x['major_consequence'] for x in variant['vep_annotations']]
            ordered_csqs = reduce(lambda x, y: ','.join([x, y]) if y not in x else x, ordered_csqs, '').split(',') # Close but not quite there
            consequences = defaultdict(lambda: defaultdict(list))
            for annotation in variant['vep_annotations']:
                annotation['HGVS'] = get_proper_hgvs(annotation)
                consequences[annotation['major_consequence']][annotation['Gene']].append(annotation)
        base_coverage = lookups.get_coverage_for_bases(db, xpos, xpos + len(ref) - 1)
        any_covered = any([x['has_coverage'] for x in base_coverage])
        metrics = lookups.get_metrics(db, variant)

        # check the appropriate sqlite db to get the *expected* number of
        # available bams and *actual* number of available bams for this variant
        sqlite_db_path = os.path.join(
            app.config["READ_VIZ_DIR"],
            "combined_bams",
            chrom,
            "combined_chr%s_%03d.db" % (chrom, pos % 1000))
        print(sqlite_db_path)
        try:
            read_viz_db = sqlite3.connect(sqlite_db_path)
            n_het = read_viz_db.execute("select n_expected_samples, n_available_samples from t "
                "where chrom=? and pos=? and ref=? and alt=? and het_or_hom=?", (chrom, pos, ref, alt, 'het')).fetchone()
            n_hom = read_viz_db.execute("select n_expected_samples, n_available_samples from t "
                "where chrom=? and pos=? and ref=? and alt=? and het_or_hom=?", (chrom, pos, ref, alt, 'hom')).fetchone()
            read_viz_db.close()
        except Exception, e:
            logging.debug("Error when accessing sqlite db: %s - %s", sqlite_db_path, e)
            n_het = n_hom = None

        read_viz_dict = {
            'het': {'n_expected': n_het[0] if n_het is not None and n_het[0] is not None else -1, 'n_available': n_het[1] if n_het and n_het[1] else 0,},
            'hom': {'n_expected': n_hom[0] if n_hom is not None and n_hom[0] is not None else -1, 'n_available': n_hom[1] if n_hom and n_hom[1] else 0,},
        }

        for het_or_hom in ('het', 'hom',):
            #read_viz_dict[het_or_hom]['some_samples_missing'] = (read_viz_dict[het_or_hom]['n_expected'] > 0)    and (read_viz_dict[het_or_hom]['n_expected'] - read_viz_dict[het_or_hom]['n_available'] > 0)
            read_viz_dict[het_or_hom]['all_samples_missing'] = (read_viz_dict[het_or_hom]['n_expected'] != 0) and (read_viz_dict[het_or_hom]['n_available'] == 0)
            read_viz_dict[het_or_hom]['readgroups'] = [
                '%(chrom)s-%(pos)s-%(ref)s-%(alt)s_%(het_or_hom)s%(i)s' % locals()
                    for i in range(read_viz_dict[het_or_hom]['n_available'])
            ]   #eg. '1-157768000-G-C_hom1',

            read_viz_dict[het_or_hom]['urls'] = [
                os.path.join('combined_bams', chrom, 'combined_chr%s_%03d.bam' % (chrom, pos % 1000))
                    for i in range(read_viz_dict[het_or_hom]['n_available'])
            ]


        print 'Rendering variant: %s' % variant_str
        return render_template(
            'variant.html',
            variant=variant,
            base_coverage=base_coverage,
            consequences=consequences,
            any_covered=any_covered,
            ordered_csqs=ordered_csqs,
            metrics=metrics,
            read_viz=read_viz_dict,
        )