コード例 #1
0
def make_network_nice(folder, projects, cols=None, fname="fig.svg"):
    prob_cut = 0.001

    lnk_genes = []
    anl_genes = []

    for project in projects:
        lnk_genes.append([])
        anl_genes.append(set())
        dist_file = op.join(folder, project + "_tetra_dists.txt")

        for l in open(dist_file, "r"):
            d = l.split(",")
            prob = float(d[2])  # statistical control
            # prob = float(d[3])  # biological control
            anl_genes[-1].update([d[0], d[1]])
            if prob < prob_cut:
                lnk_genes[-1].append([d[0], d[1], prob])

    if cols is None:
        cols = int(np.round(np.sqrt(len(projects))))

    # all genes compared
    tot_genes = set(i for j in anl_genes for i in j)
    # only genes that have links somewhere
    # tot_genes = set()
    # for l_genes in lnk_genes:
    #    for g1, g2, p in l_genes:
    #        tot_genes.update([g1, g2])

    # alternative A:
    # sorted_genes = sorted(tot_genes)

    # alternative B: manually order the genes to prevent confusion
    sorted_genes = [
        i.strip()
        for i in """
    rpoA,fdhA,soxA-allo,soxA-rhodo,dsrA,
    rpoB,frhB,soxY-allo,soxY-rhodo,dsrB,
    cdsA-allo,cdsA-geo,cdsA-rhodo,cdsA-synn,
    rpoC,soxZ-allo,soxZ-rhodo,ligE
    """.split(
            ","
        )
    ]
    stot_genes = [g for g in sorted_genes if g in tot_genes]
    tot_genes = stot_genes + sorted(tot_genes.difference(stot_genes))

    adj_f = 2 * np.pi / len(tot_genes)
    g_pos = {g: (np.sin(adj_f * i), np.cos(adj_f * i)) for i, g in enumerate(tot_genes)}
    g_ang = {g: 90 - 360 * i / len(tot_genes) for i, g in enumerate(tot_genes)}

    colormap.set_under(colormap(0))
    colormap.set_over(colormap(colormap.N))
    norm = mpl.colors.LogNorm(vmin=10e-10, vmax=prob_cut)
    p_val_to_c = lambda p: colormap(norm(p))

    fig = plt.figure(figsize=(2, 6))
    for proj, grey_labels, l_genes in zip(projects, anl_genes, lnk_genes):
        # ax = plt.subplot(gs[projects.index(proj)])
        ax = fig.add_subplot(int(np.ceil(len(projects) / cols)), cols, projects.index(proj) + 1)
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
        ax.set_xlim(-1.1, 1.1)
        ax.set_ylim(-1.2, 1.2)
        ax.set_frame_on(False)

        black_labels = set()
        for g1, g2, p in l_genes:
            black_labels.update([g1, g2])

        for g in grey_labels.intersection(tot_genes):
            ha, va, ang = text_params_from_ang(g_ang[g])
            ax.text(*g_pos[g], s=g, size=8, color="grey", va=va, ha=ha, rotation=ang)

        for g in black_labels:
            ha, va, ang = text_params_from_ang(g_ang[g])
            ax.text(*g_pos[g], s=g, size=8, color="black", va=va, ha=ha, rotation=ang)

        for g1, g2, p in l_genes:
            clr = p_val_to_c(p)
            arrow = FancyArrowPatch(
                g_pos[g1], g_pos[g2], color=clr, lw=0.3, arrowstyle="simple,head_length=8,head_width=4"
            )
            ax.add_patch(arrow)

        # TODO: turn off
        # ax.text(0.5, 0.5, proj, ha='center', va='center',
        #        transform=plt.gca().transAxes)
    cax = fig.add_axes([0.33, 0.05, 0.33, 0.010])
    mpl.colorbar.ColorbarBase(cax, cmap=colormap, norm=norm, orientation="horizontal")
    plt.savefig(fname, bbox_inches="tight")
    plt.show()
コード例 #2
0
    def get_mesh(self, attribute='color', cmap='nyu40'):
        """ Extract a mesh from the TSDF using marching cubes

        If TSDF also has atribute_vols, these are extracted as
        vertex_attributes. The mesh is also colored using the cmap 

        Args:
            attribute: which tsdf attribute is used to color the mesh
            cmap: colormap for converting the attribute to a color

        Returns:
            trimesh.Trimesh
        """

        tsdf_vol = self.tsdf_vol.detach().clone()

        # measure.marching_cubes() likes positive
        # values in front of surface
        tsdf_vol = -tsdf_vol

        # don't close surfaces using unknown-empty boundry
        tsdf_vol[tsdf_vol == -1] = 1

        tsdf_vol = tsdf_vol.clamp(-1, 1).cpu().numpy()

        if tsdf_vol.min() >= 0 or tsdf_vol.max() <= 0:
            return trimesh.Trimesh(vertices=np.zeros((0, 3)))

        verts, faces, _, _ = measure.marching_cubes(tsdf_vol, level=0)

        verts_ind = np.round(verts).astype(int)
        verts = verts * self.voxel_size + self.origin.cpu().numpy()

        vertex_attributes = {}
        # get vertex attributes
        if 'semseg' in self.attribute_vols:
            semseg_vol = self.attribute_vols['semseg'].detach().cpu().numpy()
            semseg = semseg_vol[verts_ind[:, 0], verts_ind[:, 1], verts_ind[:,
                                                                            2]]
            vertex_attributes['semseg'] = semseg

        if 'instance' in self.attribute_vols:
            instance_vol = self.attribute_vols['instance']
            instance_vol = instance_vol.detach().cpu().numpy()
            instance = instance_vol[verts_ind[:, 0], verts_ind[:, 1],
                                    verts_ind[:, 2]]
            vertex_attributes['instance'] = instance

        # color mesh
        if attribute == 'color' and 'color' in self.attribute_vols:
            color_vol = self.attribute_vols['color']
            color_vol = color_vol.detach().clamp(0, 255).byte().cpu().numpy()
            colors = color_vol[:, verts_ind[:, 0], verts_ind[:, 1],
                               verts_ind[:, 2]].T
        elif attribute == 'instance':
            label_viz = instance + 1
            n = label_viz.max()
            cmap = (colormap('jet')(np.linspace(0, 1, n))[:, :3] * 255).astype(
                np.uint8)
            cmap = cmap[np.random.permutation(n), :]
            cmap = np.insert(cmap, 0, [0, 0, 0], 0)
            colors = cmap[label_viz, :]
        elif attribute == 'semseg':
            if cmap == 'nyu40':
                cmap = np.array(
                    NYU40_COLORMAP)  # FIXME: support more general colormaps
            else:
                raise NotImplementedError('colormap %s' % cmap)
            label_viz = semseg.copy()
            label_viz[(label_viz < 0) | (label_viz >= len(cmap))] = 0
            colors = cmap[label_viz, :]
        else:
            colors = None

        mesh = trimesh.Trimesh(vertices=verts,
                               faces=faces,
                               vertex_colors=colors,
                               vertex_attributes=vertex_attributes,
                               process=False)
        return mesh
コード例 #3
0
#!/usr/bin/env python3

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.cm import jet as colormap
from matplotlib.ticker import NullFormatter, MultipleLocator

t, w, r = zip((0.1, 0.4, 1), (0.9, 0.3, 5), (1.7, 0.5, 7), (2.7, 0.6, 6), (3.5, 0.3, 3), (4.5, 0.4, 4), (5.3, 0.3, 7))

fig, ax = plt.subplots(subplot_kw = {'polar':True})
bars = ax.bar(t, r, width = w, bottom = 0.0, lw = 2, edgecolor = 'Black', zorder = 2)

for r, bar in zip(r, bars):
    bar.set_facecolor(colormap(r/9.0))
    bar.set_alpha(0.7)

ax.yaxis.set_major_locator(MultipleLocator(2))

for axis in (ax.xaxis, ax.yaxis):
    axis.set_major_formatter(NullFormatter())  #no tick labels

ax.set_ylim([0, 8])
ax.grid(True)

plt.show()