Chromosome Display

The function that displays a chromosome is a method named display_chromosome, defined in the PeakViewerApp class.

The method is called whenver the user clicks the left or right button next to the chromosome name or edits the chromosome name.

To break the code into manageable pieces there are two "helper methods":

  • _make_patches builds a list of rectangles for the "ribbon" display
  • _make_grid builds the column of blocks, interleaving graphical representations of the SNPs with a text view of the dataframe

display_chromosome

Update the chromosome display. Called whenever the chromosome ID changes. Shows a set of rectangular patches where the color is based on the region identified by the HMM. Below that is a grid with one row for each block of SNPs identifed by the peak finder. Draw a vertical line at the crossover location (if there is one).

Source code in src/xo/gui.py
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
def display_chromosome(self):
    '''
    Update the chromosome display.  Called whenever the chromosome ID changes.  Shows
    a set of rectangular patches where the color is based on the region identified by 
    the HMM.  Below that is a grid with one row for each block of SNPs identifed by
    the peak finder.  Draw a vertical line at the crossover location (if there is one).
    '''
    chr_id = self.chromosome_id.value
    chrom = self.intervals.get_group(chr_id)
    logging.info(f'peak {chr_id}, {len(chrom)} SNPs')

    graphic = pn.Column()
    if chr_id in self.peaks.groups:
        df = self.peaks.get_group(chr_id)
        res, self.summary = self.snp_filter.apply(df)
        if self.nco_switch.value:
            res = self.nco_filter.apply(res)
            self.blocks = res.groupby('blk_id')
            self.nco_blocks = { n for n, grp in self.blocks if grp.nco.max() == 2 }
        else:
            self.blocks = res.groupby('blk_id')
            self.nco_blocks = set()
        grid = self._make_grid()
        graphic.append(grid)

    rects = PatchCollection(self._make_patches(chrom, chr_id), match_original=True)
    fig, ax = plt.subplots(figsize=(12,1))
    plt.box(False)
    plt.yticks([])
    plt.xticks(ticks=np.linspace(0,20000000,5), labels=[f'{int(n*20)}Mbp' for n in np.linspace(0,1,5)])
    ax.xaxis.set_ticks_position('top')
    ax.add_collection(rects)
    if chr_id in self.crossovers.groups:
        for _, xo in self.crossovers.get_group(chr_id).iterrows():
            logging.info(f'crossover {xo.start} {xo.is_CO}')
            if xo.is_CO:
                plt.axvline(xo.start, color='green')
    plt.xlim(0,20000000)
    plt.ylim(0,2000000)
    plt.close(fig)
    graphic.insert(0,pn.pane.Matplotlib(fig, dpi=72, tight=True))

    self.chromosome_panel.pop(-1)
    self.chromosome_panel.append(graphic)

_make_patches

Create a horizontal bar as a collection of rectangular patches, with one patch for each row in the data frame. The rows have the starting coordinates lengths, and HMM states of chromosome regions, used to define the width and color of a patch. Add black dots to indicate the locations of blocks.

Source code in src/xo/gui.py
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
def _make_patches(self, df, chr_id):
    '''
    Create a horizontal bar as a collection of rectangular patches, with one
    patch for each row in the data frame.  The rows have the starting coordinates
    lengths, and HMM states of chromosome regions, used to define the width and
    color of a patch.  Add black dots to indicate the locations of blocks.
    '''
    pcolor = {
        'CB4856': 'dodgerblue',
        'N2': 'indianred'
    }
    res = []
    for _, r in df.iterrows():
        c = pcolor.get(r.hmm_state) or 'lightgray'
        res.append(Rectangle((r.start,500000), r.length, 1000000, color=c))
    if chr_id in self.peaks.groups:
        for blk_index, _ in self.summary.iterrows():
            _, blk_id = blk_index
            block = self.blocks.get_group(blk_id)
            x0 = block.iloc[0].position
            res.append(Circle((x0,750000), 50000, color='black'))
            if blk_id in self.nco_blocks:
                res.append(Circle((x0,1200000), 50000, color='yellow'))
    return res

_make_grid

Make a Column object that has a collection of figures, one for each block in a chromosome (saved in an instance var). The figures are saved in a grid. Below each figure is a text widget containing the data frame with the filtered SNPs in the block, i.e. the grid for a chromosome with N blocks as 2*N rows. The frames are initially hidden. The rows that have figures also have a toggle button; clicking this button will show or hide the frame.

Source code in src/xo/gui.py
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
def _make_grid(self):
    '''
    Make a Column object that has a collection of figures, one for each block 
    in a chromosome (saved in an instance var).  The figures are saved in a grid.
    Below each figure is a text widget containing the data frame with the filtered 
    SNPs in the block, i.e. the grid for a chromosome with N blocks as 2*N rows.
    The frames are initially hidden.  The rows that have figures also have a toggle
    button; clicking this button will show or hide the frame.
    '''
    pcolor = {
        'CB4856': 'dodgerblue',
        'N2': 'indianred',
        'uCB4856': 'lightsteelblue',
        'uN2': 'lightpink',
        'unknown': 'lightgray',
        'het': 'palegoldenrod',
    }
    nco_sym = {
        0: ' ',
        1: '✓',
        2: '★',
    }
    self.block_buttons = {}
    self.block_text = {}
    g = pn.Column()
    for blk_index, blk_stats in self.summary.iterrows():
        _, blk_id = blk_index
        block = self.blocks.get_group(blk_id)
        fig, ax = plt.subplots(figsize=(10,0.8))
        plt.box(False)
        plt.xlim(0,10)
        plt.ylim(0,0.8)
        plt.yticks([])
        x0 = block.iloc[0].position
        size = int(blk_stats.blk_size)
        length = int(blk_stats.blk_len)
        w = block.iloc[-1].position - x0
        plt.xticks(ticks=np.linspace(0,10,5), labels=[f'{int(n*w)}bp' for n in np.linspace(0,1,5)])
        plt.suptitle(f'Block #{blk_id}\nStart: {(x0/1000000):.1f}Mbp\nSize: {size} SNPs\nLength: {length}bp', x=0, y=0.75, size='medium',ha='left')
        res = []
        for _, snp in block.iterrows():
            p = ((snp.position - x0) / length) if length > 0 else 0
            x = p*10
            res.append(Circle((x,0.2),0.1,color=pcolor[snp.base_geno]))
        dots = PatchCollection(res, match_original=True)
        ax.add_collection(dots)
        plt.close(fig)
        self.block_buttons[blk_id] = pn.widgets.Button(name='>', align='center', tags=[blk_id])
        self.block_buttons[blk_id].on_click(self.toggle_text_cb)
        cols = ['position','base_geno','hmm_state1','reference','ref_reads','variant','var_reads','background','homozygosity']
        df = block[cols]
        if self.nco_switch.value:
            # df['nco'] = block.nco.map(lambda n: nco_sym[n])
            df = pd.concat([df, block.nco.map(lambda n: nco_sym[n])], axis=1)
        self.block_text[blk_id] = pn.pane.DataFrame(df, visible=False)
        if blk_id in self.open_blocks:
            self.block_text[blk_id].visible = True
            self.block_buttons[blk_id].name = '∨'
        g.append(pn.Row(
            self.block_buttons[blk_id],
            pn.pane.Matplotlib(fig, dpi=72, tight=True),
            styles={'background':'WhiteSmoke'},
        ))
        g.append(pn.Row(self.block_text[blk_id]))
    return g