Plot using the pydot graphics engine.
331582
def _plt_pydot(self, fout_img):
        """"""
        dag = self._get_pydot_graph()
        img_fmt = os.path.splitext(fout_img)[1][1:]
        dag.write(fout_img, format=img_fmt)
        self.log.write("  {GO_USR:>3} usr {GO_ALL:>3} GOs  WROTE: {F}\n".format(
            F=fout_img,
            GO_USR=len(self.godag.go_sources),
            GO_ALL=len(self.godag.go2obj)))
396881
def plot(self):
    
    plt.ion()
    plt.show()
    x = numpy.linspace(0, 15, 100)
    y = numpy.zeros(x.shape)
    y = self.excite(y, x)
    plt.plot(x, y)
    plt.xlabel('Input')
    plt.ylabel('Persistence')
    plt.title('Sigmoid Activation Function')
615359
def plot_ortho_stack(images, overlays=None, reorient=True,
    # xyz arguments
    xyz=None, xyz_lines=False, xyz_color='red', xyz_alpha=0.6, xyz_linewidth=2, xyz_pad=5,
    # base image arguments
    cmap='Greys_r', alpha=1,
    # overlay arguments
    overlay_cmap='jet', overlay_alpha=0.9, 
    # background arguments
    black_bg=True, bg_thresh_quant=0.01, bg_val_quant=0.99, 
    # scale/crop/domain arguments
    crop=False, scale=False, domain_image_map=None, 
    # title arguments
    title=None, titlefontsize=24, title_dx=0, title_dy=0, 
    # 4th panel text arguemnts
    text=None, textfontsize=24, textfontcolor='white', text_dx=0, text_dy=0,
    # save & size arguments
    filename=None, dpi=500, figsize=1., colpad=0, rowpad=0,
    transpose=False, transparent=True):
    
    def mirror_matrix(x):
        return x[::-1,:]
    def rotate270_matrix(x):
        return mirror_matrix(x.T)
    def reorient_slice(x, axis):
        return rotate270_matrix(x)

    # need this hack because of a weird NaN warning from matplotlib with overlays
    warnings.simplefilter('ignore')

    n_images = len(images)

    # handle `image` argument
    for i in range(n_images):
        if isinstance(images[i], str):
            images[i] = iio2.image_read(images[i])
        if not isinstance(images[i], iio.ANTsImage):
            raise ValueError('image argument must be an ANTsImage')
        if images[i].dimension != 3:
            raise ValueError('Input image must have 3 dimensions!')

    if overlays is None:
        overlays = [None]*n_images
    # handle `overlay` argument
    for i in range(n_images):
        if overlays[i] is not None:
            if isinstance(overlays[i], str):
                overlays[i] = iio2.image_read(overlays[i])
            if not isinstance(overlays[i], iio.ANTsImage):
                raise ValueError('overlay argument must be an ANTsImage')
            if overlays[i].dimension != 3:
                raise ValueError('Overlay image must have 3 dimensions!')

            if not iio.image_physical_space_consistency(images[i], overlays[i]):
                overlays[i] = reg.resample_image_to_target(overlays[i], images[i], interp_type='linear')

    for i in range(1,n_images):
        if not iio.image_physical_space_consistency(images[0], images[i]):
            images[i] = reg.resample_image_to_target(images[0], images[i], interp_type='linear')

    # reorient images
    if reorient != False:
        if reorient == True:
            reorient = 'RPI'
        
        for i in range(n_images):
            images[i] = images[i].reorient_image2(reorient)
        
        if overlays[i] is not None:
            overlays[i] = overlays[i].reorient_image2(reorient)

    # handle `slices` argument
    if xyz is None:
        xyz = [int(s/2) for s in images[0].shape]
    for i in range(3):
        if xyz[i] is None:
            xyz[i] = int(images[0].shape[i]/2)

    # resample image if spacing is very unbalanced
    spacing = [s for i,s in enumerate(images[0].spacing)]
    if (max(spacing) / min(spacing)) > 3.:
        new_spacing = (1,1,1)
        for i in range(n_images):
            images[i] = images[i].resample_image(tuple(new_spacing))
        if overlays[i] is not None:
            overlays[i] = overlays[i].resample_image(tuple(new_spacing))
        xyz = [int(sl*(sold/snew)) for sl,sold,snew in zip(xyz,spacing,new_spacing)]

    # potentially crop image
    if crop:
        for i in range(n_images):
            plotmask = images[i].get_mask(cleanup=0)
            if plotmask.max() == 0:
                plotmask += 1
            images[i] = images[i].crop_image(plotmask)
            if overlays[i] is not None:
                overlays[i] = overlays[i].crop_image(plotmask)
                
    # pad images
    for i in range(n_images):
        if i == 0:
            images[i], lowpad, uppad = images[i].pad_image(return_padvals=True)
        else:
            images[i] = images[i].pad_image()
        if overlays[i] is not None:
            overlays[i] = overlays[i].pad_image()
    xyz = [v+l for v,l in zip(xyz,lowpad)]

    # handle `domain_image_map` argument
    if domain_image_map is not None:
        if isinstance(domain_image_map, iio.ANTsImage):
            tx = tio2.new_ants_transform(precision='float', transform_type='AffineTransform',
                                         dimension=3)
            for i in range(n_images):
                images[i] = tio.apply_ants_transform_to_image(tx, images[i], domain_image_map)
            
                if overlays[i] is not None:
                    overlays[i] = tio.apply_ants_transform_to_image(tx, overlays[i], 
                                                            domain_image_map, 
                                                            interpolation='linear')       
        elif isinstance(domain_image_map, (list, tuple)):
            # expect an image and transformation
            if len(domain_image_map) != 2:
                raise ValueError('domain_image_map list or tuple must have length == 2')
            
            dimg = domain_image_map[0]
            if not isinstance(dimg, iio.ANTsImage):
                raise ValueError('domain_image_map first entry should be ANTsImage')

            tx = domain_image_map[1]
            for i in range(n_images):
                images[i] = reg.apply_transforms(dimg, images[i], transform_list=tx)
                if overlays[i] is not None:
                    overlays[i] = reg.apply_transforms(dimg, overlays[i], transform_list=tx,
                                                   interpolator='linear')

    # potentially find dynamic range
    if scale == True:
        vmins = []
        vmaxs = []
        for i in range(n_images):
            vmin, vmax = images[i].quantile((0.05,0.95))
            vmins.append(vmin)
            vmaxs.append(vmax)
    elif isinstance(scale, (list,tuple)):
        if len(scale) != 2:
            raise ValueError('scale argument must be boolean or list/tuple with two values')
        vmins = []
        vmaxs = []
        for i in range(n_images):
            vmin, vmax = images[i].quantile(scale)
            vmins.append(vmin)
            vmaxs.append(vmax)
    else:
        vmin = None
        vmax = None

    if not transpose:
        nrow = n_images
        ncol = 3
    else:
        nrow = 3
        ncol = n_images

    fig = plt.figure(figsize=((ncol+1)*2.5*figsize, (nrow+1)*2.5*figsize))
    if title is not None:
        basey = 0.93
        basex = 0.5
        fig.suptitle(title, fontsize=titlefontsize, x=basex+title_dx, y=basey+title_dy)

    if (colpad > 0) and (rowpad > 0):
        bothgridpad = max(colpad, rowpad)
        colpad = 0
        rowpad = 0
    else:
        bothgridpad = 0.0

    gs = gridspec.GridSpec(nrow, ncol, wspace=bothgridpad, hspace=0.0,
                 top=1.-0.5/(nrow+1), bottom=0.5/(nrow+1) + colpad, 
                 left=0.5/(ncol+1) + rowpad, right=1-0.5/(ncol+1))

    # pad image to have isotropic array dimensions
    for i in range(n_images):
        images[i] = images[i].numpy()
        if overlays[i] is not None:
            overlays[i] = overlays[i].numpy()
            overlays[i][np.abs(overlays[i]) == 0] = np.nan

    ####################
    ####################
    for i in range(n_images):
        yz_slice = reorient_slice(images[i][xyz[0],:,:],0)
        if not transpose:
            ax = plt.subplot(gs[i,0])
        else:
            ax = plt.subplot(gs[0,i])
        ax.imshow(yz_slice, cmap=cmap, vmin=vmin, vmax=vmax)
        if overlays[i] is not None:
            yz_overlay = reorient_slice(overlays[i][xyz[0],:,:],0)
            ax.imshow(yz_overlay, alpha=overlay_alpha, cmap=overlay_cmap)
        if xyz_lines:
            # add lines
            l = mlines.Line2D([yz_slice.shape[0]-xyz[1],yz_slice.shape[0]-xyz[1]], 
                              [xyz_pad,yz_slice.shape[0]-xyz_pad],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
            l = mlines.Line2D([xyz_pad,yz_slice.shape[1]-xyz_pad], 
                              [yz_slice.shape[1]-xyz[2],yz_slice.shape[1]-xyz[2]],
                color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
        ax.axis('off')
        ####################
        ####################

        xz_slice = reorient_slice(images[i][:,xyz[1],:],1)
        if not transpose:
            ax = plt.subplot(gs[i,1])
        else:
            ax = plt.subplot(gs[1,i])
        ax.imshow(xz_slice, cmap=cmap, vmin=vmin, vmax=vmax)
        if overlays[i] is not None:
            xz_overlay = reorient_slice(overlays[i][:,xyz[1],:],1)
            ax.imshow(xz_overlay, alpha=overlay_alpha, cmap=overlay_cmap)
        if xyz_lines:
            # add lines
            l = mlines.Line2D([xz_slice.shape[0]-xyz[0],xz_slice.shape[0]-xyz[0]], 
                              [xyz_pad,xz_slice.shape[0]-xyz_pad],
                               color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
            l = mlines.Line2D([xyz_pad,xz_slice.shape[1]-xyz_pad], 
                              [xz_slice.shape[1]-xyz[2],xz_slice.shape[1]-xyz[2]],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
        ax.axis('off')

        ####################
        ####################
        xy_slice = reorient_slice(images[i][:,:,xyz[2]],2)
        if not transpose:
            ax = plt.subplot(gs[i,2])
        else:
            ax = plt.subplot(gs[2,i])
        ax.imshow(xy_slice, cmap=cmap, vmin=vmin, vmax=vmax)
        if overlays[i] is not None:
            xy_overlay = reorient_slice(overlays[i][:,:,xyz[2]],2)
            ax.imshow(xy_overlay, alpha=overlay_alpha, cmap=overlay_cmap)
        if xyz_lines:
            # add lines
            l = mlines.Line2D([xy_slice.shape[0]-xyz[0],xy_slice.shape[0]-xyz[0]], 
                              [xyz_pad,xy_slice.shape[0]-xyz_pad],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
            l = mlines.Line2D([xyz_pad,xy_slice.shape[1]-xyz_pad], 
                              [xy_slice.shape[1]-xyz[1],xy_slice.shape[1]-xyz[1]],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
        ax.axis('off')

    ####################
    ####################

    if filename is not None:
        plt.savefig(filename, dpi=dpi, transparent=transparent)
        plt.close(fig)
    else:
        plt.show()

    # turn warnings back to default
    warnings.simplefilter('default')
580391
def plot_dop(bands, int_max, dop, hund_cu, name):
    """"""
    data = ssplt.calc_z(bands, dop, np.arange(0, int_max, 0.1), hund_cu, name)
    ssplt.plot_curves_z(data, name)
589773
def plothist(self,fig=None,**kwargs):
        
        setfig(fig)
        plt.hist(self.samples,bins=self.bins,**kwargs)
457214
def plot_goid2goobj(fout_png, goid2goobj, *args, **kws):
    """"""
    engine = kws['engine'] if 'engine' in kws else 'pydot'
    godagsmall = OboToGoDagSmall(goid2goobj=goid2goobj).godag
    godagplot = GODagSmallPlot(godagsmall, *args, **kws)
    godagplot.plt(fout_png, engine)
252374
def _plot(x, mph, mpd, threshold, edge, valley, ax, ind):
    """"""
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        print('matplotlib is not available.')
    else:
        if ax is None:
            _, ax = plt.subplots(1, 1, figsize=(8, 4))

        ax.plot(x, 'b', lw=1)
        if ind.size:
            label = 'valley' if valley else 'peak'
            label = label + 's' if ind.size > 1 else label
            ax.plot(ind, x[ind], '+', mfc=None, mec='r', mew=2, ms=8,
                    label='%d %s' % (ind.size, label))
            ax.legend(loc='best', framealpha=.5, numpoints=1)
        ax.set_xlim(-.02*x.size, x.size*1.02-1)
        ymin, ymax = x[np.isfinite(x)].min(), x[np.isfinite(x)].max()
        yrange = ymax - ymin if ymax > ymin else 1
        ax.set_ylim(ymin - 0.1*yrange, ymax + 0.1*yrange)
        ax.set_xlabel('Data #', fontsize=14)
        ax.set_ylabel('Amplitude', fontsize=14)
        mode = 'Valley detection' if valley else 'Peak detection'
        ax.set_title("%s (mph=%s, mpd=%d, threshold=%s, edge='%s')"
                     % (mode, str(mph), mpd, str(threshold), edge))
484487
def plt_dag(self, fout_img, engine="pydot"):
        """"""
        if engine == "pydot":
            self._plt_pydot(fout_img)
        else:
            raise RuntimeError("ENGINE NOT IMPLEMENTED({E})".format(E=engine))
1208344
def plot_2d(self, X, labels=None, s=20, marker='o',
                dimensions=(0, 1), ax=None, colors=None,
                fignum=None, cmap=None, # @UndefinedVariable
                ** kwargs):
        
        if cmap is None:
            cmap = matplotlib.cm.jet
        if ax is None:
            fig = pylab.figure(fignum)
            ax = fig.add_subplot(111)
        if labels is None:
            labels = numpy.zeros(X.shape[0])
        ulabels = []
        for lab in labels:
            if not lab in ulabels:
                ulabels.append(lab)
        nlabels = len(ulabels)
        if colors is None:
            colors = iter([cmap(float(i) / nlabels) for i in range(nlabels)])
        else:
            colors = iter(colors)
        X_ = self.project(X, self.Q)[:,dimensions]
        kwargs.update(dict(s=s))
        plots = list()
        for i, l in enumerate(ulabels):
            kwargs.update(dict(color=next(colors), marker=marker[i % len(marker)]))
            plots.append(ax.scatter(*X_[labels == l, :].T, label=str(l), **kwargs))
        ax.set_xlabel(r"PC$_1$")
        ax.set_ylabel(r"PC$_2$")
        try:
            pylab.tight_layout()
        except:
            pass
        return plots
766337
def displayplot(data, plinds, plottype, scaling, fileroot, url_path='http://www.aoc.nrao.edu/~claw/plots'):
    

    plotdict = {'dmt': plotdmt, 'norm': plotnorm,
               'loc': plotloc, 'stat': plotstat,
               'all': plotall}
    sizedict = {'dmt': [900,500], 'norm': [700, 700], 'loc': [700,700],
                'stat': [700,700]}

    sortinds = sorted(set(plinds['cir'] + plinds['cro'] + plinds['edg']))
    sizesrc, plaw = scaling.split('_')
    data['sizes'] = calcsize(data[sizesrc], inds=sortinds, plaw=int(plaw))

    if plottype != 'all':
        wid, hei = sizedict[plottype]
        pl = plotdict[plottype](data, circleinds=plinds['cir'], crossinds=plinds['cro'],
                                edgeinds=plinds['edg'], url_path=url_path,
                                fileroot=fileroot, plot_width=wid, plot_height=hei)
    else:
        pl = plotall(data, circleinds=plinds['cir'], crossinds=plinds['cro'],
                                 edgeinds=plinds['edg'], url_path=url_path,
                                 fileroot=fileroot)
    hdl = show(pl)
785149
def plot(self, overlay=True, **labels): # pragma: no cover
        ''''''
        pylab = LazyImport.pylab()
        colours = list('rgbymc')
        colours_len = len(colours)
        colours_pos = 0
        plots = len(self.groups)
        for name, series in self.groups.iteritems():
            colour = colours[colours_pos % colours_len]
            colours_pos += 1
            if not overlay:
                pylab.subplot(plots, 1, colours_pos)
            kwargs = {}
            if name in labels:
                name = labels[name]
            if name is not None:
                kwargs['label'] = name
            pylab.plot(series.dates, series.values, '%s-' % colour, **kwargs)
            if name is not None:
                pylab.legend()
        pylab.show()
699520
def plot(
        self, ax: GeoAxesSubplot, cmap: str = "inferno", s: int = 5, **kwargs
    ) -> Artist:
        """"""
        return ax.scatter(
            self.df.longitude,
            self.df.latitude,
            s=s,
            transform=PlateCarree(),
            c=-self.df.altitude,
            cmap=cmap,
            **kwargs,
        )
1245357
def plot(self, bins=250, **kwargs):
        """"""
        # Data #
        counts = [sum(map(len, b.contigs)) for b in self.parent.bins]
        # Linear bins in logarithmic space #
        if 'log' in kwargs.get('x_scale', ''):
            start, stop = numpy.log10(1), numpy.log10(max(counts))
            bins = list(numpy.logspace(start=start, stop=stop, num=bins))
            bins.insert(0, 0)
        # Plot #
        fig = pyplot.figure()
        pyplot.hist(counts, bins=bins, color='gray')
        axes = pyplot.gca()
        # Information #
        title = 'Distribution of the total nucleotide count in the bins'
        axes.set_title(title)
        axes.set_xlabel('Number of nucleotides in a bin')
        axes.set_ylabel('Number of bins with that many nucleotides in them')
        # Save it #
        self.save_plot(fig, axes, **kwargs)
        pyplot.close(fig)
        # For convenience #
        return self
847583
def make_graph_pydot(self, recs, nodecolor,
                     edgecolor, dpi,
                     draw_parents=True, draw_children=True):
        """"""
        import pydot
        G = pydot.Dot(graph_type='digraph', dpi="{}".format(dpi)) # Directed Graph
        edgeset = set()
        usr_ids = [rec.id for rec in recs]
        for rec in recs:
            if draw_parents:
                edgeset.update(rec.get_all_parent_edges())
            if draw_children:
                edgeset.update(rec.get_all_child_edges())

        lw = self._label_wrap
        rec_id_set = set([rec_id for endpts in edgeset for rec_id in endpts])
        nodes = {str(ID):pydot.Node(
              lw(ID).replace("GO:",""),  # Node name
              shape="box",
              style="rounded, filled",
              # Highlight query terms in plum:
              fillcolor="beige" if ID not in usr_ids else "plum",
              color=nodecolor)
                for ID in rec_id_set}

        # add nodes explicitly via add_node
        for rec_id, node in nodes.items():
            G.add_node(node)

        for src, target in edgeset:
            # default layout in graphviz is top->bottom, so we invert
            # the direction and plot using dir="back"
            G.add_edge(pydot.Edge(nodes[target], nodes[src],
              shape="normal",
              color=edgecolor,
              label="is_a",
              dir="back"))

        return G
813280
def plot(self, x, y, color="black"):
        
        p = Point(x, y)
        p.fill(color)
        p.draw(self)
141946
def _plot(self):
        """"""
        squares = self._squares()
        sq_dimensions = self.add_squares(squares)

        for index, serie in enumerate(self.series):
            current_square = self._current_square(squares, index)
            self.gaugify(serie, squares, sq_dimensions, current_square)
1152464
def snpplot(args):
    
    p = OptionParser(snpplot.__doc__)
    opts, args, iopts = p.set_image_options(args, format="png")

    if len(args) != 1:
        sys.exit(not p.print_help())

    datafile, = args
    # Read in CDT file
    fp = open(datafile)
    next(fp)
    next(fp)
    data = []
    for row in fp:
        atoms = row.split()[4:]
        nval = len(atoms)
        values = [float(x) for x in atoms]
        # normalize
        values = [x * 1. / sum(values) for x in values]
        data.append(values)

    pf = datafile.rsplit(".", 1)[0]
    fig = plt.figure(1, (iopts.w, iopts.h))
    root = fig.add_axes([0, 0, 1, 1])
    xmin, xmax = .1, .9
    ymin, ymax = .1, .9
    yinterval = (ymax - ymin) / len(data)
    colors = "rbg" if nval == 3 else ["lightgray"] + list("rbg")
    ystart = ymax
    for d in data:
        xstart = xmin
        for dd, c in zip(d, colors):
            xend = xstart + (xmax - xmin) * dd
            root.plot((xstart, xend), (ystart, ystart), "-", color=c)
            xstart = xend
        ystart -= yinterval

    root.text(.05, .5, "{0} LMD50 SNPs".format(len(data)),
              ha="center", va="center", rotation=90, color="lightslategray")

    for x, t, c in zip((.3, .5, .7), ("REF", "ALT", "HET"), "rbg"):
        root.text(x, .95, t, color=c, ha="center", va="center")
    normalize_axes(root)

    image_name = pf + "." + iopts.format
    savefig(image_name, dpi=iopts.dpi, iopts=iopts)