Plots one or more spectra in the same plot.

    Args:
      ss: list of Spectrum objects
      title=None: window title
      setup: PlotSpectrumSetup object
176220
def plot_spectra_overlapped(ss, title=None, setup=_default_setup):
    

    plt.figure()
    draw_spectra_overlapped(ss, title, setup)
    plt.show()
30044
def _ss_tot(self):
        """"""
        return np.sum(
            np.square(self.ywins - np.expand_dims(self._ybar, axis=-1)), axis=1
        )
1025013
def setXlimits(self, lims):
        
        # update all "linked", plots
        self.specPlot.setXlim(lims)
        for plot in self.responsePlots.values():
            plot.setXlim(lims)
        # ridiculous...
        sizes = self.splittersw.sizes()
        if len(sizes) > 1:
            if self.badbadbad:
                sizes[0] +=1
                sizes[1] -=1
            else:
                sizes[0] -=1
                sizes[1] +=1
            self.badbadbad = not self.badbadbad
            self.splittersw.setSizes(sizes)

        self._ignore_range_signal = False
1228359
def calc_max_min(ss):
    "
    xmin, xmax, ymin, ymax = 1e38, -1e38, 1e38, -1e38
    for s in ss:
        assert isinstance(s, ft.Spectrum)
        if len(s.x) > 0:
            xmin, xmax = min(min(s.x), xmin), max(max(s.x), xmax)
            ymin, ymax = min(min(s.y), ymin), max(max(s.y), ymax)
    xspan = xmax-xmin
    yspan = ymax - ymin
    return xmin, xmax, ymin, ymax, xspan, yspan
1147298
def show_multi(func:Callable[[int,int],Image], r:int=1, c:int=1, figsize:Tuple=(9,9)):
    ""
    plot_multi(lambda i,j,ax: func(i,j).show(ax), r, c, figsize=figsize)
231556
def plot_contpix(self, x, y, contpix_x, contpix_y, figname):
        
        fig, axarr = plt.subplots(2, sharex=True)
        plt.xlabel(r"Wavelength $\lambda (\AA)$")
        plt.xlim(min(x), max(x))
        ax = axarr[0]
        ax.step(x, y, where='mid', c='k', linewidth=0.3,
                label=r'$\theta_0$' + "= the leading fit coefficient")
        ax.scatter(contpix_x, contpix_y, s=1, color='r',
                label="continuum pixels")
        ax.legend(loc='lower right', 
                prop={'family':'serif', 'size':'small'})
        ax.set_title("Baseline Spectrum with Continuum Pixels")
        ax.set_ylabel(r'$\theta_0$')
        ax = axarr[1]
        ax.step(x, y, where='mid', c='k', linewidth=0.3,
             label=r'$\theta_0$' + "= the leading fit coefficient")
        ax.scatter(contpix_x, contpix_y, s=1, color='r',
                label="continuum pixels")
        ax.set_title("Baseline Spectrum with Continuum Pixels, Zoomed")
        ax.legend(loc='upper right', prop={'family':'serif', 
            'size':'small'})
        ax.set_ylabel(r'$\theta_0$')
        ax.set_ylim(0.95, 1.05)
        print("Diagnostic plot: fitted 0th order spec w/ cont pix")
        print("Saved as %s.png" % (figname))
        plt.savefig(figname)
        plt.close()
429471
def plotstat(data, circleinds=None, crossinds=None, edgeinds=None, url_path=None, fileroot=None, 
             tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=450, plot_height=400):
    

    fields = ['imkur', 'specstd', 'sizes', 'colors', 'snrs', 'key']

    if not circleinds: circleinds = range(len(data['snrs']))

    # set ranges
    datalen = len(data['dm'])
    inds = circleinds + crossinds + edgeinds
    specstd = [data['specstd'][i] for i in inds]
    specstd_min = min(specstd)
    specstd_max = max(specstd)
    imkur = [data['imkur'][i] for i in inds]
    imkur_min = min(imkur)
    imkur_max = max(imkur)

    source = ColumnDataSource(data = dict({(key, tuple([value[i] for i in circleinds if i not in edgeinds])) 
                                           for (key, value) in data.iteritems() if key in fields}))
    stat = Figure(plot_width=plot_width, plot_height=plot_height, toolbar_location="left", x_axis_label='Spectral std',
                  y_axis_label='Image kurtosis', x_range=(specstd_min, specstd_max), 
                  y_range=(imkur_min, imkur_max), tools=tools, output_backend='webgl')
    stat.circle('specstd', 'imkur', size='sizes', line_color=None, fill_color='colors', fill_alpha=0.2, source=source)

    if crossinds:
        sourceneg = ColumnDataSource(data = dict({(key, tuple([value[i] for i in crossinds]))
                                                  for (key, value) in data.iteritems() if key in fields}))
        stat.cross('specstd', 'imkur', size='sizes', line_color='colors', line_alpha=0.3, source=sourceneg)

    if edgeinds:
        sourceedge = ColumnDataSource(data = dict({(key, tuple([value[i] for i in edgeinds]))
                                                   for (key, value) in data.iteritems() if key in fields}))
        stat.circle('specstd', 'imkur', size='sizes', line_color='colors', fill_color='colors', source=sourceedge, line_alpha=0.5, fill_alpha=0.2)

    hover = stat.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])

    if url_path and fileroot:
        url = '{}/cands_{}_@key.png'.format(url_path, fileroot)
        taptool = stat.select(type=TapTool)
        taptool.callback = OpenURL(url=url)

    return stat
645516
def setSr(self, fs):
        """"""
        self.tracePlot.setSr(fs)
        self.stimPlot.setSr(fs)
144525
def add_spectrum(self, compare_to_existing=True, **kwargs):
        """"""
        spec_key = self._KEYS.SPECTRA
        # Make sure that a source is given, and is valid (nor erroneous)
        source = self._check_cat_dict_source(Spectrum, spec_key, **kwargs)
        if source is None:
            return None

        # Try to create a new instance of `Spectrum`
        new_spectrum = self._init_cat_dict(Spectrum, spec_key, **kwargs)
        if new_spectrum is None:
            return None

        is_dupe = False
        for item in self.get(spec_key, []):
            # Only the `filename` should be compared for duplicates. If a
            # duplicate is found, that means the previous `exclude` array
            # should be saved to the new object, and the old deleted
            if new_spectrum.is_duplicate_of(item):
                if SPECTRUM.EXCLUDE in new_spectrum:
                    item[SPECTRUM.EXCLUDE] = new_spectrum[SPECTRUM.EXCLUDE]
                elif SPECTRUM.EXCLUDE in item:
                    item.update(new_spectrum)
                is_dupe = True
                break

        if not is_dupe:
            self.setdefault(spec_key, []).append(new_spectrum)
        return
844917
def seaborn_set(context='poster', style='white', palette='colorblind',
                font_scale=1.3, font='serif', rc=mpl_rc):
    
    sns.set(context="poster", style="white", palette="colorblind",
            font_scale=1.3, font="serif", rc=mpl_rc)
1253048
def intensities(self):
        
        buf = ffi.new("double[]", self.size)
        ims.spectrum_intensities(self.ptr, buf)
        return list(buf)
402391
def add_stats_plot(self):
        """"""

        keys = OrderedDict()
        keys['species_a'] = {'color': '#437bb1', 'name': 'Species a'}
        keys['species_b'] = {'color': '#b1084c', 'name': 'Species b'}
        keys['ambiguous'] = {'color': '#333333', 'name': 'Ambiguous'}

        plot_config = {
            'id': "disambiguated_alignments",
            'title': "Disambiguate: Alignment Counts",
            'cpswitch_counts_label': "# Reads",
            'ylab': "# Reads"
        }

        self.add_section(
            plot=bargraph.plot(self.data, keys, plot_config)
        )
172114
def plots_from_files(imspaths, figsize=(10,5), rows=1, titles=None, maintitle=None):
    
    f = plt.figure(figsize=figsize)
    if maintitle is not None: plt.suptitle(maintitle, fontsize=16)
    for i in range(len(imspaths)):
        sp = f.add_subplot(rows, ceildiv(len(imspaths), rows), i+1)
        sp.axis('Off')
        if titles is not None: sp.set_title(titles[i], fontsize=16)
        img = plt.imread(imspaths[i])
        plt.imshow(img)
263579
def _add_plots_to_output(out, data):
    
    out["plot"] = {}
    diagram_plot = _add_diagram_plot(out, data)
    if diagram_plot:
        out["plot"]["diagram"] = diagram_plot
    scatter = _add_scatter_plot(out, data)
    if scatter:
        out["plot"]["scatter"] = scatter
    scatter_global = _add_global_scatter_plot(out, data)
    if scatter_global:
        out["plot"]["scatter_global"] = scatter_global
    return out
309516
def add_subplot(self, *args, **kwargs):
        
        kwargs.setdefault("projection", "wright")
        return super().add_subplot(*args, **kwargs)
606906
def ss_tot(self):
        """"""
        return np.sum(np.square(self.y - self.ybar), axis=0)
852919
def overlay_spectra(model, dataset):
    
    best_flux, best_ivar = draw_spectra(model, dataset)
    coeffs_all, covs, scatters, all_chisqs, pivots, label_vector = model.model

    # Overplot original spectra with best-fit spectra
    print("Overplotting spectra for ten random stars")
    res = dataset.test_flux-best_flux
    lambdas = dataset.wl
    npix = len(lambdas)
    nstars = best_flux.shape[0]
    pickstars = []
    for i in range(10):
        pickstars.append(random.randrange(0, nstars-1))
    for i in pickstars:
        print("Star %s" % i)
        ID = dataset.test_ID[i]
        spec_orig = dataset.test_flux[i,:]
        bad = dataset.test_flux[i,:] == 0
        lambdas = np.ma.array(lambdas, mask=bad, dtype=float)
        npix = len(lambdas.compressed())
        spec_orig = np.ma.array(dataset.test_flux[i,:], mask=bad)
        spec_fit = np.ma.array(best_flux[i,:], mask=bad)
        ivars_orig = np.ma.array(dataset.test_ivar[i,:], mask=bad)
        ivars_fit = np.ma.array(best_ivar[i,:], mask=bad)
        red_chisq = np.sum(all_chisqs[:,i], axis=0) / (npix - coeffs_all.shape[1])
        red_chisq = np.round(red_chisq, 2)
        fig,axarr = plt.subplots(2)
        ax1 = axarr[0]
        im = ax1.scatter(lambdas, spec_orig, label="Orig Spec",
                         c=1 / np.sqrt(ivars_orig), s=10)
        ax1.scatter(lambdas, spec_fit, label="Cannon Spec", c='r', s=10)
        ax1.errorbar(lambdas, spec_fit, 
                     yerr=1/np.sqrt(ivars_fit), fmt='ro', ms=1, alpha=0.7)
        ax1.set_xlabel(r"Wavelength $\lambda (\AA)$")
        ax1.set_ylabel("Normalized flux")
        ax1.set_title("Spectrum Fit: %s" % ID)
        ax1.set_title("Spectrum Fit")
        ax1.set_xlim(min(lambdas.compressed())-10, max(lambdas.compressed())+10)
        ax1.legend(loc='lower center', fancybox=True, shadow=True)
        ax2 = axarr[1]
        ax2.scatter(spec_orig, spec_fit, c=1/np.sqrt(ivars_orig), alpha=0.7)
        ax2.errorbar(spec_orig, spec_fit, yerr=1 / np.sqrt(ivars_fit),
                     ecolor='k', fmt="none", ms=1, alpha=0.7)
        #fig.subplots_adjust(right=0.8)
        #cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
        fig.colorbar()
        #fig.colorbar(
        #        im, cax=cbar_ax,
        #        label="Uncertainties on the Fluxes from the Original Spectrum")
        xlims = ax2.get_xlim()
        ylims = ax2.get_ylim()
        lims = [np.min([xlims, ylims]), np.max([xlims, ylims])]
        ax2.plot(lims, lims, 'k-', alpha=0.75)
        textstr = "Red Chi Sq: %s" % red_chisq
        props = dict(boxstyle='round', facecolor='palevioletred', alpha=0.5)
        ax2.text(0.05, 0.95, textstr, transform=ax2.transAxes, fontsize=14,
                 verticalalignment='top', bbox=props)
        ax2.set_xlim(xlims)
        ax2.set_ylim(ylims)
        ax2.set_xlabel("Orig Fluxes")
        ax2.set_ylabel("Fitted Fluxes")
        plt.tight_layout()
        filename = "best_fit_spec_Star%s.png" % i
        print("Saved as %s" % filename)
        fig.savefig(filename)
        plt.close(fig)