Beispiel #1
0
def direction_colour_getter(direction_colours=DIRECTION_COLOURS,
                            vmin=None,
                            vmax=None):
    """
    Generate a direction colour getters, which returns a hexadecimal colour code when called with a direction.
    :param direction_colours: Various inputs supported
    string: The name of a matplotlib colourmap. Must specify vmin and vmax.
    dict: Must be keyed by 'up' and 'down', this is used to create a binary colourmap. No need to specify vmin or vmax.
    array of hex strings: Used to generate a discrete colourmap between the specified vmin and vmax values.
    :param vmin, vmax: The min and max values used for the scalar colour mapping.
    :return: Function that takes a single scalar input and returns a hex colour.
    """
    if isinstance(direction_colours, str):
        if vmin is None or vmax is None:
            raise AttributeError(
                "When supplying the name of a matplotlib colourmap, must also supply vmin and vmax."
            )
        return common.continuous_cmap(vmin, vmax, cmap=direction_colours)
    elif isinstance(direction_colours, dict):
        if len({'up', 'down'}.intersection(direction_colours.keys())) != 2:
            raise ValueError(
                "When supplying a dictionary, it must contain the keys 'up' and 'down'."
            )
        return lambda x: direction_colours['up' if x > 0 else 'down']
    elif hasattr(direction_colours, '__iter__'):
        if vmin is None or vmax is None:
            raise AttributeError(
                "When supplying an iterable of colours, must also supply vmin and vmax."
            )
        norm = common.Normalize(vmin=vmin, vmax=vmax)
        lsm = colors.LinearSegmentedColormap.from_list(direction_colours)
        sm = plt.cm.ScalarMappable(norm=norm, cmap=lsm)
        return lambda x: colors.to_hex(sm.to_rgba(x))
    elif callable(direction_colours):
        return direction_colours
    else:
        ## TODO: support ColorMap objects from matplotlib??
        raise NotImplementedError("Unsupported direction_colours object.")
Beispiel #2
0
    this.columns = ['-logp', 'ratio', 'z', 'genes']
    # add ngenes column
    this.index = [x.decode('utf-8') for x in this.index]
    # NaN in the z attribute will cause a parsing error
    this.drop('z', axis=1, inplace=True)

    this = this.loc[this['-logp'] > plogalpha_relevant]

    cy_session = cyto.CytoscapeSession()
    gg = ipa.nx_graph_from_ipa_single(this,
                                      name='PC1 mean logFC',
                                      min_edge_count=min_edge_count)

    # add fill colours, deliberately saturating late to avoid deepest shade
    vmax = this['-logp'].max() * 1.2
    node_cmap = common.continuous_cmap(plogalpha_relevant, vmax, cmap='Reds')
    for k, n in gg.nodes.items():
        n['fill_colour'] = node_cmap(n['-logp'])

    this_net = cy_session.add_networkx_graph(gg, name=gg.name)
    cyto_nets[gg.name] = this_net

    # formatting
    this_net.passthrough_node_label('name')
    this_net.passthrough_node_size_linear('n_genes')
    # this_net.passthrough_edge_width_linear('gene_count', xmin=1., ymin=0.2, ymax=5)
    this_net.passthrough_edge_width_linear('n_genes',
                                           xmin=1.,
                                           ymin=0.2,
                                           ymax=5)
    this_net.set_node_border_width(0.)
    # comments (DGIdb)
    comments = dgi_db_df.groupby('ensembl_gene_id').apply(lambda x: '\n'.join([
        t['name'] + ("" if t.interaction_type == "" else " (%s)" % t.
                     interaction_type) for _, t in x.iterrows()
    ]))
    col_letter = excel.get_column_letter(single_de_dm_df,
                                         'num_DGIdb_interactions')
    for ix, row in single_de_dm_df[
            single_de_dm_df['num_DGIdb_interactions'] > 0].iterrows():
        row_letter = excel.get_row_number(single_de_dm_df, ix)
        worksheet.write_comment('%s%s' % (col_letter, row_letter),
                                comments.loc[row['ensembl_gene_id']])

    # shading (logFC)
    green_cmap = common.continuous_cmap(-8, 0, 'Greens_r')
    red_cmap = common.continuous_cmap(0, 8, 'Reds')

    breaks_de = list(zip(range(-5, 5), range(-4, 6)))
    breaks_de[0] = (None, breaks_de[0][1])
    breaks_de[-1] = (breaks_de[-1][0], None)
    cmap_de_formats = []
    for lo, hi in breaks_de:
        if lo is None or lo < 0:
            this_fmt_dict = {'bg_color': green_cmap(hi - 0.5)}
            this_fmt_name = '{}_{}'.format(lo or 'LOW', hi)
            formatter.add_format(this_fmt_name, this_fmt_dict)
            cmap_de_formats.append(this_fmt_name)
        else:
            this_fmt_dict = {'bg_color': red_cmap(lo + 0.5)}
            this_fmt_name = '{}_{}'.format(lo, hi or 'HIGH')
Beispiel #4
0
        # we're going to use passthrough mapping to customise the node colour
        # we'll define 3 colourmaps, with -log10(p) assigning the shade:
        # greyscale for syn. and ref.
        # reds for ref. only
        # blues for syn. only
        # colours are defined by HEX values? Add these to the nodes
        logp_syn = -np.log10(res_syn.fdr + eps)
        logp_r1 = -np.log10(res_r1.fdr + eps)
        logp_r2 = -np.log10(res_r2.fdr + eps)
        vmax = max(
            logp_syn.max(),
            logp_r1.max(),
            logp_r2.max(),
        )

        cmap_both_func = common.continuous_cmap(0, vmax, cmap='Greys')
        cmap_syn_func = common.continuous_cmap(0, vmax, cmap='Blues')
        cmap_ref_func = common.continuous_cmap(0, vmax, cmap='Reds')
        vs, _ = setops.venn_from_arrays(
            *[t.index for t in (res_syn, res_r1, res_r2)])

        node_colours = {}
        for pth in vs['111'] + vs['101'] + vs['110']:
            node_colours[pth] = cmap_both_func(logp_syn[pth])
        for pth in vs['100']:
            node_colours[pth] = cmap_syn_func(logp_syn[pth])
        for pth in vs['011']:
            # mean P for refs
            node_colours[pth] = cmap_ref_func(0.5 *
                                              (logp_r1[pth] + logp_r2[pth]))
        for pth in vs['010']:
Beispiel #5
0
    # add descriptor
    our_gic_obj.meta.insert(1, 'descriptor', 'In vitro GIC')
    our_ffpe_obj.meta.insert(1, 'descriptor', 'Bulk GBM')
    pdx_bulk.meta.insert(1, 'descriptor', 'Bulk PDX')
    gic_late_desc = pd.Series('In vitro GIC', index=gic_late.meta.index)
    gic_late_desc.loc[gic_late_desc.index.str.contains('PDX')] = 'Ex vivo GIC'
    gic_late.meta.insert(1, 'descriptor', gic_late_desc)

    # combine into a single object with compatible probes
    obj = loader.loader.MultipleBatchLoader(
        [our_gic_obj, our_ffpe_obj, pdx_bulk, gic_late])

    # colours for dendrogram / PCA
    n_desc = len(obj.meta.descriptor.unique())
    descriptor_cmap = common.continuous_cmap(0, n_desc - 1, cmap='Greys')
    descriptor_colours = dict(
        zip(obj.meta.descriptor.unique(),
            [descriptor_cmap(i) for i in range(n_desc)]))
    pid_colours = consts.PATIENT_COLOURS

    # convert to M values
    mdat = process.m_from_beta(obj.data)
    mdat_019 = mdat.loc[:, obj.meta.patient_id == '019']

    # extract meta for convenience
    meta = obj.meta
    meta_019 = obj.meta.loc[mdat_019.columns]

    row_colours_all = pd.DataFrame('white',
                                   index=mdat.columns,