Plot cumulative rate histograms. List of pkl files in order, as for make_psrrates.
341301
def plot_psrrates(pkllist, outname=''):
    

    if not outname:
        outname = 'tmp.png'

    labels = {0: 'Flux at 0\'', 1: 'Flux at 7\'', 2: 'Flux at 15\'', 3: 'Flux at 25\''}
    labelsr = {1: 'Flux Ratio 7\' to 0\'', 2: 'Flux Ratio 15\' to 0\'', 3: 'Flux Ratio 25\' to 0\''}
    colors = {0: 'b.', 1: 'r.', 2: 'g.', 3: 'y.'}

    rates = make_psrrates(pkllist)
    plt.clf()
    fig = plt.figure(1, figsize=(10,8), facecolor='white')
    ax = fig.add_subplot(211, axis_bgcolor='white')
    for kk in rates.keys():
        flux, rate = rates[kk]
        plt.plot(flux, rate, colors[kk], label=labels[kk])

    plt.setp( ax.get_xticklabels(), visible=False)
    plt.ylabel('Flux (Jy)', fontsize='20')
    plt.legend(numpoints=1)
    plt.loglog()

    ax2 = fig.add_subplot(212, sharex=ax, axis_bgcolor='white')
    flux0, rate0 = rates[0]
    for kk in rates.keys():
        flux, rate = rates[kk]
        if kk == 1:
            r10 = [rate[i]/rate0[np.where(flux0 == flux[i])[0][0]] for i in range(len(rate))]
            plt.plot(flux, r10, colors[kk], label=labelsr[kk])
        elif kk == 2:
            r20 = [rate[i]/rate0[np.where(flux0 == flux[i])[0][0]] for i in range(len(rate))]
            plt.plot(flux, r20, colors[kk], label=labelsr[kk])
        elif kk == 3:
            r30 = [rate[i]/rate0[np.where(flux0 == flux[i])[0][0]] for i in range(len(rate))]
            plt.plot(flux, r30, colors[kk], label=labelsr[kk])

    plt.xlabel('Rate (1/s)', fontsize='20')
    plt.ylabel('Flux ratio', fontsize='20')
    plt.legend(numpoints=1)
    plt.subplots_adjust(hspace=0)

    # find typical ratio. avoid pulsar period saturation and low-count regimes (high and low ends)
    if len(rates) == 4:
        logger.info('flux ratio, lowest common (1/0, 2/0, 3/0):', (r10[len(r30)-1], r20[len(r30)-1], r30[-1]))
        logger.info('flux ratio, high end (1/0, 2/0, 3/0):', (r10[-1], r20[-1], r30[-1]))
    elif len(rates) == 3:
        logger.info('flux ratio, lowest common (1/0, 2/0):', (r10[len(r20)-1], r20[-1]))
        logger.info('flux ratio, high end (1/0, 2/0):', (r10[-1], r20[-1]))

    plt.savefig(outname)
947875
def plot_results(fout_img, goea_results, **kws):
    """"""
    if "{NS}" not in fout_img:
        plt_goea_results(fout_img, goea_results, **kws)
    else:
        # Plot separately by NS: BP, MF, CC
        ns2goea_results = cx.defaultdict(list)
        for rec in goea_results:
            ns2goea_results[rec.NS].append(rec)
        for ns_name, ns_res in ns2goea_results.items():
            fout = fout_img.format(NS=ns_name)
            plt_goea_results(fout, ns_res, **kws)
806046
def prokka_barplot(self):
        

        # Specify the order of the different categories
        keys = OrderedDict()
        keys['CDS'] =           { 'name': 'CDS' }
        keys['rRNA'] =          { 'name': 'rRNA' }
        keys['tRNA'] =          { 'name': 'tRNA' }
        keys['tmRNA'] =         { 'name': 'tmRNA' }
        keys['misc_RNA'] =      { 'name': 'misc RNA' }
        keys['sig_peptide'] =   { 'name': 'Signal peptides' }
        keys['repeat_region'] = { 'name': 'CRISPR array'}

        plot_config = {
            'id': 'prokka_plot',
            'title': 'Prokka: Feature Types',
            'ylab': '# Counts',
            'cpswitch_counts_label': 'Features'
        }

        return bargraph.plot(self.prokka, keys, plot_config)
17929
def _histogram_data(iterator):
    
    histogram_started = False
    header_passed = False
    for l in iterator:
        if '## HISTOGRAM' in l:
            histogram_started = True
        elif histogram_started:
            if header_passed:
                values = l.rstrip().split("\t")
                problem_type, name = values[0].split(':')
                yield problem_type, name, int(values[1])
            elif l.startswith('Error Type'):
                header_passed = True
1072691
def plot_recurrence_model(
        input_model, catalogue, completeness, dmag=0.1, filename=None,
        figure_size=(8, 6), filetype='png', dpi=300, ax=None):
    
    annual_rates, cumulative_rates = _get_recurrence_model(input_model)

    # Get observed annual recurrence
    if not catalogue.end_year:
        catalogue.update_end_year()
    cent_mag, t_per, n_obs = get_completeness_counts(catalogue,
                                                     completeness,
                                                     dmag)
    obs_rates = n_obs / t_per
    cum_obs_rates = np.array([np.sum(obs_rates[i:])
                              for i in range(len(obs_rates))])

    if ax is None:
        fig, ax = plt.subplots(figsize=figure_size)
    else:
        fig = ax.get_figure()

    ax.semilogy(cent_mag, obs_rates, 'bo')
    ax.semilogy(annual_rates[:, 0], annual_rates[:, 1], 'b-')
    ax.semilogy(cent_mag, cum_obs_rates, 'rs')
    ax.semilogy(annual_rates[:, 0], cumulative_rates, 'r-')
    ax.grid(which='both')
    ax.set_xlabel('Magnitude')
    ax.set_ylabel('Annual Rate')
    ax.legend(['Observed Incremental Rate',
               'Model Incremental Rate',
               'Observed Cumulative Rate',
               'Model Cumulative Rate'])
    ax.tick_params(labelsize=12)
    _save_image(fig, filename, filetype, dpi)
327454
def runExperiment5A(dirName):
  
  # Results are put into a pkl file which can be used to generate the plots.
  # dirName is the absolute path where the pkl file will be placed.
  resultsFilename = os.path.join(dirName, "sensorimotor_sequence_example.pkl")
  results = runExperiment(
    {
      "numSequences": 0,
      "seqLength": 10,
      "numFeatures": 100,
      "trialNum": 4,
      "numObjects": 50,
      "numLocations": 100,
    }
  )

  # Pickle results for plotting and possible later debugging
  with open(resultsFilename, "wb") as f:
    cPickle.dump(results, f)
556934
def plot_temp_diagrams(config, results, temp_dir):
    """"""
    display_name = {
        'time': 'Compilation time (s)',
        'memory': 'Compiler memory usage (MB)',
    }

    files = config['files']
    img_files = []

    if any('slt' in result for result in results) and 'bmp' in files.values()[0]:
        config['modes']['slt'] = 'Using BOOST_METAPARSE_STRING with string literal templates'
        for f in files.values():
            f['slt'] = f['bmp'].replace('bmp', 'slt')

    for measured in ['time', 'memory']:
        mpts = sorted(int(k) for k in files.keys())
        img_files.append(os.path.join(temp_dir, '_{0}.png'.format(measured)))
        plot(
            {
                m: [(x, results[files[str(x)][m]][measured]) for x in mpts]
                for m in config['modes'].keys()
            },
            config['modes'],
            display_name[measured],
            (config['x_axis_label'], display_name[measured]),
            img_files[-1]
        )
    return img_files
629829
def plotres(psr,deleted=False,group=None,**kwargs):
    """"""

    res, t, errs = psr.residuals(), psr.toas(), psr.toaerrs
    
    if (not deleted) and N.any(psr.deleted != 0):
        res, t, errs = res[psr.deleted == 0], t[psr.deleted == 0], errs[psr.deleted == 0]
        print("Plotting {0}/{1} nondeleted points.".format(len(res),psr.nobs))

    meanres = math.sqrt(N.mean(res**2)) / 1e-6
    
    if group is None:
        i = N.argsort(t)
        P.errorbar(t[i],res[i]/1e-6,yerr=errs[i],fmt='x',**kwargs)
    else:
        if (not deleted) and N.any(psr.deleted):
            flagmask = psr.flagvals(group)[~psr.deleted]
        else:
            flagmask = psr.flagvals(group)

        unique = list(set(flagmask))
            
        for flagval in unique:
            f = (flagmask == flagval)
            flagres, flagt, flagerrs = res[f], t[f], errs[f]
            i = N.argsort(flagt)
            P.errorbar(flagt[i],flagres[i]/1e-6,yerr=flagerrs[i],fmt='x',**kwargs)
        
        P.legend(unique,numpoints=1,bbox_to_anchor=(1.1,1.1))

    P.xlabel('MJD'); P.ylabel('res [us]')
    P.title("{0} - rms res = {1:.2f} us".format(psr.name,meanres))
129242
def plot_basic_hist(samples, file_type, **plot_args):
    

    sumy = sum([int(samples[sample]['data'][x][0])
                for sample in samples
                for x in samples[sample]['data']])

    cutoff = sumy * 0.999
    all_x = set()
    for item in sorted(chain(*[samples[sample]['data'].items()
                                for sample in samples])):
        all_x.add(item[0])
        cutoff -= item[1][0]
        if cutoff < 0:
            xmax = item[0]
            break
    else:
        xmax = max(all_x)

    data = {
        sample: {
            x: samples[sample]['data'][x][0] if x in samples[sample]['data'] else 0
            for x in all_x
        }
        for sample in samples
    }

    plot_params = {
            'id': 'bbmap-' + file_type + '_plot',
            'title': 'BBTools: ' + plot_args['plot_title'],
            'xmax': xmax
    }
    plot_params.update(plot_args['plot_params'])
    plot = linegraph.plot(
        data,
        plot_params
    )

    return plot
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'))
875056
def plotMultipleInferenceRun(stats,
                       fields,
                       basename,
                       plotDir="plots"):
  
  if not os.path.exists(plotDir):
    os.makedirs(plotDir)

  plt.figure()

  colorList = ['r', 'b', 'g', 'm', 'c', 'k', 'y']

  # plot request stats
  for i, field in enumerate(fields):
    fieldKey = field[0] + " C0"
    trace = []
    for s in stats:
      trace += s[fieldKey]
    plt.plot(trace, label=field[1], color=colorList[i])

  # format
  plt.legend(loc="upper right")
  plt.xlabel("Input number")
  plt.xticks(range(0, len(stats)*stats[0]["numSteps"]+1,5))
  plt.ylabel("Number of cells")
  plt.ylim(-5, 55)
  plt.title("Inferring combined sensorimotor and temporal sequence stream")

  # save
  relPath = "{}_exp_combined.pdf".format(basename)
  path = os.path.join(plotDir, relPath)
  plt.savefig(path)
  plt.close()
1180914
def plot_cable_length(stats, plotpath):
    

    # cable and line kilometer distribution
    f, axarr = plt.subplots(2, 2, sharex=True)
    stats.hist(column=['Length of MV overhead lines'], bins=5, alpha=0.5, ax=axarr[0, 0])
    stats.hist(column=['Length of MV underground cables'], bins=5, alpha=0.5, ax=axarr[0, 1])
    stats.hist(column=['Length of LV overhead lines'], bins=5, alpha=0.5, ax=axarr[1, 0])
    stats.hist(column=['Length of LV underground cables'], bins=5, alpha=0.5, ax=axarr[1, 1])

    plt.savefig(os.path.join(plotpath,
                             'Histogram_cable_line_length.pdf'))
345958
def plot(self):
        """"""
        plt.plot(self.bin_edges, self.hist, self.bin_edges, self.best_pdf)
985029
def _plot_groups_hdrgos(self, hdrgos_usr, pltargs):
        """"""
        import datetime
        import timeit
        pngs = []
        tic = timeit.default_timer()
        # Loop through GO groups. Each group of GOs is formed under a single "header GO"
        hdrgo2usrgos, go2obj = self._get_plt_data(hdrgos_usr)
        for hdrgo, usrgos in hdrgo2usrgos.items():
            pngs.extend(self._plot_go_group(
                hdrgo, usrgos,
                pltargs=pltargs,
                go2parentids=get_go2parents_go2obj(go2obj)))
        sys.stdout.write("\nElapsed HMS: {HMS} to write ".format(
            HMS=str(datetime.timedelta(seconds=(timeit.default_timer()-tic)))))
        sys.stdout.write("{P:5,} GO DAG plots for {H:>5,} GO grouping headers\n".format(
            H=len(hdrgo2usrgos), P=len(pngs)))
        return sorted(set(pngs))
849607
def pbar_strings(files, desc='', **kwargs):
    
    return tqdm(
        sorted(files, key=lambda s: s.lower()),
        desc=('<' + str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + '> ' +
              desc),
        dynamic_ncols=True,
        **kwargs)
342573
def _do_classifyplot(df, out_file, title=None, size=None, samples=None, callers=None):
    
    metric_labels = {"fdr": "False discovery rate",
                     "fnr": "False negative rate"}
    metrics = [("fnr", "tpr"), ("fdr", "spc")]
    is_mpl2 = LooseVersion(mpl.__version__) >= LooseVersion('2.0')
    colors = ["light grey", "greyish"] * 10
    data_dict = df.set_index(["sample", "caller", "vtype"]).T.to_dict()
    plt.ioff()
    plt.style.use('seaborn-white')
    vtypes = sorted(df["vtype"].unique(), reverse=True)
    if not callers:
        callers = sorted(df["caller"].unique())
    if not samples:
        samples = sorted(df["sample"].unique())
    if len(samples) >= len(callers):
        cats, groups = (samples, callers)
        data_dict = df.set_index(["sample", "caller", "vtype"]).T.to_dict()
    else:
        cats, groups = (callers, samples)
        data_dict = df.set_index(["caller", "sample", "vtype"]).T.to_dict()
    fig, axs = plt.subplots(len(vtypes) * len(groups), len(metrics))
    fig.text(.5, .95, title if title else "", horizontalalignment='center', size=14)
    for vi, vtype in enumerate(vtypes):
        for gi, group in enumerate(groups):
            for mi, (metric, label) in enumerate(metrics):
                row_plots = axs if len(vtypes) * len(groups) == 1 else axs[vi * len(groups) + gi]
                cur_plot = row_plots if len(metrics) == 1 else row_plots[mi]
                vals, labels = [], []
                for cat in cats:
                    cur_data = data_dict.get((cat, group, vtype))
                    if cur_data:
                        vals.append(cur_data[metric])
                        labels.append(cur_data[label])
                cur_plot.barh(np.arange(len(vals)), vals, color=sns.xkcd_palette([colors[vi]]))
                all_vals = []
                for k, d in data_dict.items():
                    if k[-1] == vtype:
                        for m in metrics:
                            all_vals.append(d[m[0]])
                metric_max = max(all_vals)
                cur_plot.set_xlim(0, metric_max)
                pad = 0.1 * metric_max
                ai_adjust = 0.0 if is_mpl2 else 0.35
                for ai, (val, label) in enumerate(zip(vals, labels)):
                    cur_plot.annotate(label, (pad + (0 if max(vals) > metric_max / 2.0 else max(vals)),
                                              ai + ai_adjust),
                                      va='center', size=7)
                cur_plot.locator_params(nbins=len(cats) + (2 if len(cats) > 2 else 1), axis="y", tight=True)
                if mi == 0:
                    cur_plot.tick_params(axis='y', which='major', labelsize=8)
                    plot_cats = ([""] + cats) if is_mpl2 else cats
                    plot_va = "center" if is_mpl2 else "bottom"
                    cur_plot.set_yticklabels(plot_cats, size=8, va=plot_va)
                    cur_plot.set_title("%s: %s" % (vtype, group), fontsize=12, loc="left")
                else:
                    cur_plot.get_yaxis().set_ticks([])
                if gi == len(groups) - 1:
                    cur_plot.tick_params(axis='x', which='major', labelsize=8)
                    cur_plot.get_xaxis().set_major_formatter(
                        mpl_ticker.FuncFormatter(lambda v, p: "%s%%" % (int(v) if round(v) == v else v)))
                    if vi == len(vtypes) - 1:
                        cur_plot.get_xaxis().set_label_text(metric_labels[metric], size=12)
                else:
                    cur_plot.get_xaxis().set_ticks([])
                    cur_plot.spines['bottom'].set_visible(False)
                cur_plot.spines['left'].set_visible(False)
                cur_plot.spines['top'].set_visible(False)
                cur_plot.spines['right'].set_visible(False)
    x, y = (6, len(vtypes) * len(groups) + 1 * 0.5 * len(cats)) if size is None else size
    fig.set_size_inches(x, y)
    fig.tight_layout(rect=(0, 0, 1, 0.95))
    plt.subplots_adjust(hspace=0.6)
    fig.savefig(out_file)
21155
def classifyplot_from_valfile(val_file, outtype="png", title=None, size=None,
                              samples=None, callers=None):
    
    mpl.use('Agg', force=True)
    df = pd.read_csv(val_file)
    grouped = df.groupby(["sample", "caller", "vtype"])
    df = grouped.apply(_calculate_fnr_fdr)
    df = df.reset_index()
    if len(df) == 0:
        return []
    else:
        out_file = "%s.%s" % (os.path.splitext(val_file)[0], outtype)
        _do_classifyplot(df, out_file, title, size, samples, callers)
        return [out_file]