Plot the memory occupation
504630
def plot_memory(calc_id=-1):
    
    dstore = util.read(calc_id)
    plots = []
    for task_name in dstore['task_info']:
        mem = dstore['task_info/' + task_name]['mem_gb']
        plots.append((task_name, mem))
    plt = make_figure(plots)
    plt.show()
1304283
def plot_lr(self, show_text=True, show_moms=True):
        """"""
        phase_limits = [0]
        for nb_batch, phase in zip(self.nb_batches, self.phases):
            phase_limits.append(phase_limits[-1] + nb_batch * phase.epochs)
        if not in_ipynb():
            plt.switch_backend('agg')
        np_plts = 2 if show_moms else 1
        fig, axs = plt.subplots(1,np_plts,figsize=(6*np_plts,4))
        if not show_moms: axs = [axs]
        for i in range(np_plts): axs[i].set_xlabel('iterations')
        axs[0].set_ylabel('learning rate')
        axs[0].plot(self.iterations,self.lrs)
        if show_moms:
            axs[1].set_ylabel('momentum')
            axs[1].plot(self.iterations,self.momentums)
        if show_text:   
            for i, phase in enumerate(self.phases):
                text = phase.opt_fn.__name__
                if phase.wds is not None: text+='\nwds='+str(phase.wds)
                if phase.beta is not None: text+='\nbeta='+str(phase.beta)
                for k in range(np_plts):
                    if i < len(self.phases)-1:
                        draw_line(axs[k], phase_limits[i+1])
                    draw_text(axs[k], (phase_limits[i]+phase_limits[i+1])/2, text) 
        if not in_ipynb():
            plt.savefig(os.path.join(self.save_path, 'lr_plot.png'))
799891
def plot_loss_history(history, figsize=(15, 8)):
    

    plt.figure(figsize=figsize)

    plt.plot(history.history["loss"])
    plt.plot(history.history["val_loss"])

    plt.xlabel("# Epochs")
    plt.ylabel("Loss")
    plt.legend(["Training", "Validation"])
    plt.title("Loss over time")

    plt.show()
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
25602
def profile(self, frame, event, arg): #PYCHOK arg requ. to match signature
        """"""
        if (self.events == None) or (event in self.events):
            frame_info = inspect.getframeinfo(frame)
            cp = (frame_info[0], frame_info[2], frame_info[1])
            if self.codepoint_included(cp):
                objects = muppy.get_objects()
                size = muppy.get_size(objects)
                if cp not in self.memories:
                    self.memories[cp] = [0,0,0,0]
                    self.memories[cp][0] = 1
                    self.memories[cp][1] = size
                    self.memories[cp][2] = size
                else:
                    self.memories[cp][0] += 1
                    if self.memories[cp][1] > size:
                        self.memories[cp][1] = size
                    if self.memories[cp][2] < size:
                        self.memories[cp][2] = size
1308555
def plot(self, qubit_subset=None):
        
        import matplotlib.pyplot as plt
        prob_dict = self.get_outcome_probs()
        if qubit_subset:
            sub_dict = {}
            qubit_num = len(self)
            for i in qubit_subset:
                if i > (2**qubit_num - 1):
                    raise IndexError("Index {} too large for {} qubits.".format(i, qubit_num))
                else:
                    sub_dict[get_bitstring_from_index(i, qubit_num)] = prob_dict[get_bitstring_from_index(i, qubit_num)]
            prob_dict = sub_dict
        plt.bar(range(len(prob_dict)), prob_dict.values(), align='center', color='#6CAFB7')
        plt.xticks(range(len(prob_dict)), prob_dict.keys())
        plt.show()
802831
def get_plot_dims(signal, ann_samp):
    ""
    if signal is not None:
        if signal.ndim == 1:
            sig_len = len(signal)
            n_sig = 1
        else:
            sig_len = signal.shape[0]
            n_sig = signal.shape[1]
    else:
        sig_len = 0
        n_sig = 0

    if ann_samp is not None:
        n_annot = len(ann_samp)
    else:
        n_annot = 0

    return sig_len, n_sig, n_annot, max(n_sig, n_annot)
464318
def plot(self, df_data, center=False, save=False,
             save_name=None, save_path='saved', dated=True, notebook=True):
        ""
        data = df_data.to_json(orient='records')
        options = self.to_dict()
        return plot(data, options, center=center, save=save,
                    save_name=save_name, save_path=save_path, dated=dated, notebook=notebook)
1236232
def plot(data: Dict[str, np.array], fields: List[str] = None, *args, **kwargs):
    
    if plt is None:
        return

    if fields is None:
        fields = ['x', 'y', 'm', 'c']
    labels = []
    lines = []
    for field in fields:
        if min(data[field].shape) > 0:
            f_lines = plt.plot(data['t'], data[field], *args, **kwargs)
            lines.extend(f_lines)
            labels.extend(data['labels'][field])
    plt.legend(lines, labels, ncol=2, loc='best')
    plt.xlabel('t, sec')
    plt.grid()
286379
def plot_prior_dates(self, dwidth=30, ax=None):
        """"""
        if ax is None:
            ax = plt.gca()
        depth, probs = self.prior_dates()
        pat = []
        for i, d in enumerate(depth):
            p = probs[i]
            z = np.array([p[:, 0], dwidth * p[:, 1] / np.sum(p[:, 1])])  # Normalize
            z = z[:, z[0].argsort(kind='mergesort')]  # np.interp requires `xp` arg to be sorted
            zy = np.linspace(np.min(z[0]), np.max(z[0]), num=200)
            zp = np.interp(x=zy, xp=z[0], fp=z[1])
            pol = np.vstack([np.concatenate([d + zp, d - zp[::-1]]),
                             np.concatenate([zy, zy[::-1]])])
            pat.append(Polygon(pol.T))
        p = PatchCollection(pat)
        p.set_label('Prior dates')
        ax.add_collection(p)
        ax.autoscale_view()
        ax.set_ylabel('Age (cal yr BP)')
        ax.set_xlabel('Depth (cm)')
        ax.grid(True)
        return ax
415336
def spatial_heatmap(array, path, title=None, color="Greens", figformat="png"):
    """"""
    logging.info("Nanoplotter: Creating heatmap of reads per channel using {} reads."
                 .format(array.size))
    activity_map = Plot(
        path=path + "." + figformat,
        title="Number of reads generated per channel")
    layout = make_layout(maxval=np.amax(array))
    valueCounts = pd.value_counts(pd.Series(array))
    for entry in valueCounts.keys():
        layout.template[np.where(layout.structure == entry)] = valueCounts[entry]
    plt.figure()
    ax = sns.heatmap(
        data=pd.DataFrame(layout.template, index=layout.yticks, columns=layout.xticks),
        xticklabels="auto",
        yticklabels="auto",
        square=True,
        cbar_kws={"orientation": "horizontal"},
        cmap=color,
        linewidths=0.20)
    ax.set_title(title or activity_map.title)
    activity_map.fig = ax.get_figure()
    activity_map.save(format=figformat)
    plt.close("all")
    return [activity_map]
1203866
def log_y_cb(self, w, val):
        """"""
        self.tab_plot.logy = val
        self.plot_two_columns()
965912
def _make_trace(neuron, plane):
    ''''''
    for neurite in iter_neurites(neuron):
        segments = list(iter_segments(neurite))

        segs = [(s[0][COLS.XYZ], s[1][COLS.XYZ]) for s in segments]

        coords = dict(x=list(chain.from_iterable((p1[0], p2[0], None) for p1, p2 in segs)),
                      y=list(chain.from_iterable((p1[1], p2[1], None) for p1, p2 in segs)),
                      z=list(chain.from_iterable((p1[2], p2[2], None) for p1, p2 in segs)))

        color = TREE_COLOR.get(neurite.root_node.type, 'black')
        if plane.lower() == '3d':
            plot_fun = go.Scatter3d
        else:
            plot_fun = go.Scatter
            coords = dict(x=coords[plane[0]], y=coords[plane[1]])
        yield plot_fun(
            line=dict(color=color, width=2),
            mode='lines',
            **coords
        )
325981
def plot(args):
    
    from jcvi.graphics.base import plt, savefig
    from jcvi.graphics.chromosome import ChromosomeMap

    p = OptionParser(plot.__doc__)
    p.add_option("--firstn", type="int", help="Only plot the first N genes")
    p.add_option("--ymax", type="int", help="Y-axis max value")
    p.add_option("--log", action="store_true",
                help="Write plotting data [default: %default]")
    opts, args, iopts = p.set_image_options(args, figsize="6x4")

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

    taggedbed, chr = args
    bed = Bed(taggedbed)
    beds = list(bed.sub_bed(chr))
    old, new = [], []
    i = 0
    for b in beds:
        accn = b.extra[0]
        if "te" in accn:
            continue

        accn, tag = accn.split("|")
        if tag == "OVERLAP":
            continue

        c, r = atg_name(accn)
        if tag == "NEW":
            new.append((i, r))
        else:
            old.append((i, r))
        i += 1

    ngenes = i
    assert ngenes == len(new) + len(old)

    logging.debug("Imported {0} ranks on {1}.".format(ngenes, chr))
    fig = plt.figure(1, (iopts.w, iopts.h))
    root = fig.add_axes([0, 0, 1, 1])

    xstart, xend = .2, .8
    ystart, yend = .2, .8
    pad = .02

    ngenes = opts.firstn or ngenes
    ymax = opts.ymax or 500000

    title = "Assignment of Medtr identifiers"
    if opts.ymax:
        subtitle = "{0}, first {1} genes".format(chr, ngenes)
    else:
        subtitle = "{0}, {1} genes ({2} new)".format(chr, ngenes, len(new))

    chr_map = ChromosomeMap(fig, root, xstart, xend, ystart, yend, pad, 0,
                        ymax, 5, title, subtitle)

    ax = chr_map.axes

    if opts.log:
        from jcvi.utils.table import write_csv
        header = ["x", "y"]
        write_csv(header, new, filename=chr + ".new")
        write_csv(header, old, filename=chr + ".old")

    x, y = zip(*new)
    ax.plot(x, y, "b,")
    x, y = zip(*old)
    ax.plot(x, y, "r,")

    # Legends
    ymid = (ystart + yend) / 2
    y = ymid + pad
    root.plot([.2], [y], "r.", lw=2)
    root.text(.2 + pad, y, "Existing Medtr ids", va="center", size=10)
    y = ymid - pad
    root.plot([.2], [y], "b.", lw=2)
    root.text(.2 + pad, y, "Newly instantiated ids", va="center", size=10)

    ax.set_xlim(0, ngenes)
    ax.set_ylim(0, ymax)
    ax.set_axis_off()

    root.set_xlim(0, 1)
    root.set_ylim(0, 1)
    root.set_axis_off()

    image_name = chr + ".identifiers." + iopts.format
    savefig(image_name, dpi=iopts.dpi, iopts=iopts)
1178753
def prevPlot(self):
        """"""
        if self.stacker.currentIndex() > 0:
            self.stacker.setCurrentIndex(self.stacker.currentIndex()-1)
281820
def plot(self, key, part='re', scale='log', steps=50, legend=True, plotargs={}):
        
        try:
            import matplotlib.pyplot as plt
        except ImportError:
            raise ImportError("Please install matplotlib if you want to use the plot method")
        pdat = self.plotdata(key, part=part, scale=scale, steps=steps)
        plt.plot(*pdat, label=key, **plotargs)
        if scale == 'log':
            plt.xscale('log')
        if legend:
            plt.legend()
1280603
def _plot_data_to_ax(
    data_all,
    ax1,
    e_unit=None,
    sed=True,
    ylabel=None,
    ulim_opts={},
    errorbar_opts={},
):
    

    if e_unit is None:
        e_unit = data_all["energy"].unit

    f_unit, sedf = sed_conversion(
        data_all["energy"], data_all["flux"].unit, sed
    )

    if "group" not in data_all.keys():
        data_all["group"] = np.zeros(len(data_all))

    groups = np.unique(data_all["group"])

    for g in groups:
        data = data_all[np.where(data_all["group"] == g)]
        _, sedfg = sed_conversion(data["energy"], data["flux"].unit, sed)

        # wrap around color and marker cycles
        color = color_cycle[int(g) % len(color_cycle)]
        marker = marker_cycle[int(g) % len(marker_cycle)]

        ul = data["ul"]
        notul = ~ul

        # Hack to show y errors compatible with 0 in loglog plot
        yerr_lo = data["flux_error_lo"][notul]
        y = data["flux"][notul].to(yerr_lo.unit)
        bad_err = np.where((y - yerr_lo) <= 0.0)
        yerr_lo[bad_err] = y[bad_err] * (1.0 - 1e-7)
        yerr = u.Quantity((yerr_lo, data["flux_error_hi"][notul]))
        xerr = u.Quantity((data["energy_error_lo"], data["energy_error_hi"]))

        opts = dict(
            zorder=100,
            marker=marker,
            ls="",
            elinewidth=2,
            capsize=0,
            mec=color,
            mew=0.1,
            ms=5,
            color=color,
        )
        opts.update(**errorbar_opts)

        ax1.errorbar(
            data["energy"][notul].to(e_unit).value,
            (data["flux"][notul] * sedfg[notul]).to(f_unit).value,
            yerr=(yerr * sedfg[notul]).to(f_unit).value,
            xerr=xerr[:, notul].to(e_unit).value,
            **opts
        )

        if np.any(ul):
            if "elinewidth" in errorbar_opts:
                ulim_opts["elinewidth"] = errorbar_opts["elinewidth"]

            _plot_ulims(
                ax1,
                data["energy"][ul].to(e_unit).value,
                (data["flux"][ul] * sedfg[ul]).to(f_unit).value,
                (xerr[:, ul]).to(e_unit).value,
                color,
                **ulim_opts
            )

    ax1.set_xscale("log")
    ax1.set_yscale("log")
    xmin = 10 ** np.floor(
        np.log10(
            np.min(data["energy"] - data["energy_error_lo"]).to(e_unit).value
        )
    )
    xmax = 10 ** np.ceil(
        np.log10(
            np.max(data["energy"] + data["energy_error_hi"]).to(e_unit).value
        )
    )
    ax1.set_xlim(xmin, xmax)
    # avoid autoscaling to errorbars to 0
    notul = ~data_all["ul"]
    if np.any(data_all["flux_error_lo"][notul] >= data_all["flux"][notul]):
        elo = (data_all["flux"][notul] * sedf[notul]).to(f_unit).value - (
            data_all["flux_error_lo"][notul] * sedf[notul]
        ).to(f_unit).value
        gooderr = np.where(
            data_all["flux_error_lo"][notul] < data_all["flux"][notul]
        )
        ymin = 10 ** np.floor(np.log10(np.min(elo[gooderr])))
        ax1.set_ylim(bottom=ymin)

    if ylabel is None:
        if sed:
            ax1.set_ylabel(
                r"$E^2\mathrm{{d}}N/\mathrm{{d}}E$"
                " [{0}]".format(u.Unit(f_unit).to_string("latex_inline"))
            )
        else:
            ax1.set_ylabel(
                r"$\mathrm{{d}}N/\mathrm{{d}}E$"
                " [{0}]".format(u.Unit(f_unit).to_string("latex_inline"))
            )
    else:
        ax1.set_ylabel(ylabel)