Exemplo n.º 1
0
def library_difference(params,
                       prop,
                       suffix='_sm',
                       ptlabels=False,
                       rescale=True,
                       plt_kw={'color': 'blue'}):
    """Plot the residuals (library-derived) for each star in the library.

    Args:
        params (pd.DataFrame): Parameter table with library and derived values
        prop (str): Parameter to plot on the x-axis.
        suffix (str): Suffix on columns in parameter table with derived values
    """
    if prop == 'radius':
        resid = (params[prop + suffix] - params[prop]) / params[prop]
        plt.semilogx(params[prop], resid, 'o', **plt_kw)
        plt.xlim(0.1, 20)
    elif prop == 'mass':
        resid = (params[prop + suffix] - params[prop]) / params[prop]
        plt.plot(params[prop], resid, 'o', **plt_kw)
    else:
        resid = params[prop + suffix] - params[prop]
        plt.plot(params[prop], resid, 'o', **plt_kw)

    if ptlabels is not False and ptlabels in params.columns:
        params['resid'] = resid
        params.apply(lambda row: plots.annotate_point(row[prop], row['resid'],
                                                      row[ptlabels]),
                     axis=1)

    mean = np.mean(resid)
    rms = np.sqrt(np.mean(resid**2))

    ax = plt.gca()
    bbox = dict(facecolor='white', edgecolor='none', alpha=0.8)
    plt.text(0.05,
             0.1,
             "Mean Diff: {0:.3g}\nRMS Diff: {1:.3g}".format(mean, rms),
             transform=ax.transAxes,
             bbox=bbox)
    plt.axhline(y=0, color='k', linestyle='dashed')

    plots.label_axes(param_x=prop, rescale=rescale)
Exemplo n.º 2
0
    def plot(self,
             paramx,
             paramy,
             grouped=False,
             marker='.',
             ptlabels=False,
             plt_kw={}):
        """Create a plot of the library in parameter space

        Args:
            paramx (str): Parameter to plot on the x-axis
            paramy (str): Parameter to plot on the y-axis
            grouped (bool, optional): Whether to group the stars by source
            ptlabels (str, optional): Library column to annotate points with
            plt_kw (dict, optional): Additional keyword arguments to pass to
                pyplot.plot
        """
        source_labels = {
            'Gaidos': 'K-dwarfs',
            'Von Braun': 'Interferometric',
            'Brewer': 'Brewer (2016)',
            'Mann': 'Mann (2015)',
            'Bruntt': 'Bruntt (2012)'
        }
        if grouped:
            g = self.library_params.groupby('source')

            for source in g.groups:
                cut = self.library_params.ix[g.groups[source]]
                plt.plot(cut[paramx],
                         cut[paramy],
                         marker,
                         label=source_labels[source])
        else:
            plt.plot(self.library_params[paramx], self.library_params[paramy],
                     marker, **plt_kw)

        if ptlabels is not False:
            self.library_params.apply(lambda x: plots.annotate_point(
                x[paramx], x[paramy], x[ptlabels]),
                                      axis=1)

        plots.label_axes(paramx, paramy)
Exemplo n.º 3
0
def library_comparison(params,
                       param_x,
                       param_y,
                       suffix='_sm',
                       ptlabels=False,
                       legend=True,
                       rescale=True):
    """Create a library comparison plot showing the library values of the
    parameters as points, with lines point to derived parameters.

    Args:
        params (pd.DataFrame): Parameter table with library and derived values
        param_x (str): Parameter to plot on the x-axis.
        param_y (str): Parameter to plot on the y-axis.
        suffix (str): Suffix on columns in parameter table with derived values
        ptlabels (str, optional): Column to annotate points with.
            Defaults to False, denoting no labels.
    """
    if param_x not in Library.STAR_PROPS:
        raise ValueError("{0} is not a valid parameter.".format(param_x))
    if param_y not in Library.STAR_PROPS:
        raise ValueError("{0} is not a valid parameter.".format(param_y))

    plt.plot(params[param_x], params[param_y], 'ko', label='Library value')

    x = params[[param_x + suffix, param_x]]
    y = params[[param_y + suffix, param_y]]
    plt.plot(x.T, y.T, 'r')
    plt.plot(x.iloc[0], y.iloc[0], 'r', label='SpecMatch-Emp value')
    plots.label_axes(param_x, param_y, rescale)
    if legend:
        plt.legend(loc='best')

    if ptlabels is not False and ptlabels in params.columns:
        params.apply(lambda row: plots.annotate_point(row[param_x], row[
            param_y], row[ptlabels]),
                     axis=1)
Exemplo n.º 4
0
    def plot_chi_squared_surface(self, region=0, num_best=None):
        """Plot the chi-squared surface from the pairwise matching procedure.

        Creates a three-column plot of the best chi-squared obtained with
        each library spectrum as a function of the library parameters.

        Args:
            region (int or tuple): The wavelength region to plot.
                If an int is given, refers to the index of the region in
                `self.regions`.
                If a tuple is given, should be present in `self.regions`.
            num_best (optional [int]): Number of best spectra to highlight.
                (default: `self.num_best`)
        """
        if self.match_results.empty:
            return

        if isinstance(region, int):
            region = self.regions[region]
        elif isinstance(region, tuple) and region not in self.regions:
            raise ValueError("Region {0} was not a region.".format(region))

        if len(self.regions) == 1:
            cs_col = 'chi_squared'
        else:
            cs_col = 'chi_squared_{0:.0f}'.format(region[0])
        self.match_results.sort_values(by=cs_col, inplace=True)

        if num_best is None:
            num_best = self.num_best

        ax1 = plt.subplot(131)
        plt.semilogy()
        plt.plot(self.match_results['Teff'], self.match_results[cs_col], '.',
                 color='blue')
        plt.plot(self.match_results['Teff'].head(num_best),
                 self.match_results[cs_col].head(num_best), 'r.')
        plt.ylabel(r'$\chi^2$')
        plt.xlabel(r'$T_{eff}$ (K)')
        plots.label_axes(param_x='Teff')

        plt.subplot(132, sharey=ax1)
        plt.semilogy()
        plt.plot(self.match_results['radius'], self.match_results[cs_col], '.',
                 color='blue')
        plt.plot(self.match_results['radius'].head(num_best),
                 self.match_results[cs_col].head(num_best), 'r.')
        plots.label_axes(param_x='radius')

        plt.subplot(133, sharey=ax1)
        plt.semilogy()
        plt.plot(self.match_results['feh'], self.match_results[cs_col], '.',
                 color='blue')
        plt.plot(self.match_results['feh'].head(num_best),
                 self.match_results[cs_col].head(num_best), 'r.')
        plots.label_axes(param_x='feh')
Exemplo n.º 5
0
    def plot_references(self, region=0, num_best=None, verbose=True):
        """Plots the location of the best references used in the linear
        combination step.

        Args:
            region (int or tuple): The region used in matching.
                If an int is given, refers to the index of the region in
                `self.regions`.
                If a tuple is given, should be present in `self.regions`.
            num_best (optional [int]): Number of best spectra to highlight.
                (default: `self.num_best`)
            verbose (optional [bool]): Whether to annotate the points with
                the lincomb coefficients
        """
        if self.match_results is None:
            return

        # get region
        if isinstance(region, int):
            region_num = region
            region = self.regions[region_num]
        elif isinstance(region, tuple):
            if region in self.regions:
                region_num = self.regions.index(region)
            else:
                # Raise exception of region was not found.
                raise ValueError("Region {0} was not a region.".format(region))

        if len(self.regions) == 1:
            cs_col = 'chi_squared'
        else:
            cs_col = 'chi_squared_{0:.0f}'.format(region[0])
        self.match_results.sort_values(by=cs_col, inplace=True)

        if num_best is None:
            num_best = self.num_best

        def _plot_ref_params(paramx, paramy, zoom=False):
            plt.plot(self.match_results[paramx], self.match_results[paramy],
                     'b.', alpha=0.6, label='_nolegend_')
            plt.plot(self.match_results.head(num_best)[paramx],
                     self.match_results.head(num_best)[paramy], '^',
                     color='forestgreen', label='Best Matches')
            if zoom:
                plots.set_tight_lims(self.match_results.head(num_best)[paramx],
                                     self.match_results.head(num_best)[paramy])

                if verbose and self.coeffs is not None:
                    for i in range(self.num_best):
                        p = self.match_results.iloc[i]
                        plots.annotate_point(p[paramx], p[paramy],
                                             '{0:.3f}'.format(
                                             self.coeffs[region_num][i]))

        gs = gridspec.GridSpec(2, 2)
        plt.subplot(gs[0])
        _plot_ref_params('Teff', 'radius')
        if len(self.results) > 0:
            plt.plot(self.lincomb_results[region_num]['Teff'],
                     self.lincomb_results[region_num]['radius'], 's',
                     color='purple', label='Derived Parameters')
        plots.label_axes('Teff', 'radius')

        plt.subplot(gs[1])
        _plot_ref_params('Teff', 'radius', zoom=True)
        if len(self.results) > 0:
            plt.plot(self.lincomb_results[region_num]['Teff'],
                     self.lincomb_results[region_num]['radius'], 's',
                     color='purple', label='Derived Parameters')
        plots.label_axes('Teff', 'radius', rescale=False)

        plt.subplot(gs[2])
        _plot_ref_params('feh', 'radius')
        if len(self.results) > 0:
            plt.plot(self.lincomb_results[region_num]['feh'],
                     self.lincomb_results[region_num]['radius'], 's',
                     color='purple', label='Derived Parameters')
        plots.label_axes('feh', 'radius')

        plt.subplot(gs[3])
        _plot_ref_params('feh', 'radius', zoom=True)
        if len(self.results) > 0:
            plt.plot(self.lincomb_results[region_num]['feh'],
                     self.lincomb_results[region_num]['radius'], 's',
                     color='purple', label='Derived Parameters')
        plots.label_axes('feh', 'radius', rescale=False)
Exemplo n.º 6
0
    def plot_chi_squared_surface(self, region=0, num_best=None):
        """Plot the chi-squared surface from the pairwise matching procedure.

        Creates a three-column plot of the best chi-squared obtained with
        each library spectrum as a function of the library parameters.

        Args:
            region (int or tuple): The wavelength region to plot.
                If an int is given, refers to the index of the region in
                `self.regions`.
                If a tuple is given, should be present in `self.regions`.
            num_best (optional [int]): Number of best spectra to highlight.
                (default: `self.num_best`)
        """
        if self.match_results.empty:
            return

        if isinstance(region, int):
            region = self.regions[region]
        elif isinstance(region, tuple) and region not in self.regions:
            raise ValueError("Region {0} was not a region.".format(region))

        if len(self.regions) == 1:
            cs_col = 'chi_squared'
        else:
            cs_col = 'chi_squared_{0:.0f}'.format(region[0])
        self.match_results.sort_values(by=cs_col, inplace=True)

        if num_best is None:
            num_best = self.num_best

        ax1 = plt.subplot(131)
        plt.semilogy()
        plt.plot(self.match_results['Teff'],
                 self.match_results[cs_col],
                 '.',
                 color='blue')
        plt.plot(self.match_results['Teff'].head(num_best),
                 self.match_results[cs_col].head(num_best), 'r.')
        plt.ylabel(r'$\chi^2$')
        plt.xlabel(r'$T_{eff}$ (K)')
        plots.label_axes(param_x='Teff')

        plt.subplot(132, sharey=ax1)
        plt.semilogy()
        plt.plot(self.match_results['radius'],
                 self.match_results[cs_col],
                 '.',
                 color='blue')
        plt.plot(self.match_results['radius'].head(num_best),
                 self.match_results[cs_col].head(num_best), 'r.')
        plots.label_axes(param_x='radius')

        plt.subplot(133, sharey=ax1)
        plt.semilogy()
        plt.plot(self.match_results['feh'],
                 self.match_results[cs_col],
                 '.',
                 color='blue')
        plt.plot(self.match_results['feh'].head(num_best),
                 self.match_results[cs_col].head(num_best), 'r.')
        plots.label_axes(param_x='feh')
Exemplo n.º 7
0
    def plot_references(self, region=0, num_best=None, verbose=True):
        """Plots the location of the best references used in the linear
        combination step.

        Args:
            region (int or tuple): The region used in matching.
                If an int is given, refers to the index of the region in
                `self.regions`.
                If a tuple is given, should be present in `self.regions`.
            num_best (optional [int]): Number of best spectra to highlight.
                (default: `self.num_best`)
            verbose (optional [bool]): Whether to annotate the points with
                the lincomb coefficients
        """
        if self.match_results is None:
            return

        # get region
        if isinstance(region, int):
            region_num = region
            region = self.regions[region_num]
        elif isinstance(region, tuple):
            if region in self.regions:
                region_num = self.regions.index(region)
            else:
                # Raise exception of region was not found.
                raise ValueError("Region {0} was not a region.".format(region))

        if len(self.regions) == 1:
            cs_col = 'chi_squared'
        else:
            cs_col = 'chi_squared_{0:.0f}'.format(region[0])
        self.match_results.sort_values(by=cs_col, inplace=True)

        if num_best is None:
            num_best = self.num_best

        def _plot_ref_params(paramx, paramy, zoom=False):
            plt.plot(self.match_results[paramx],
                     self.match_results[paramy],
                     'b.',
                     alpha=0.6,
                     label='_nolegend_')
            plt.plot(self.match_results.head(num_best)[paramx],
                     self.match_results.head(num_best)[paramy],
                     '^',
                     color='forestgreen',
                     label='Best Matches')
            if zoom:
                plots.set_tight_lims(
                    self.match_results.head(num_best)[paramx],
                    self.match_results.head(num_best)[paramy])

                if verbose and self.coeffs is not None:
                    for i in range(self.num_best):
                        p = self.match_results.iloc[i]
                        plots.annotate_point(
                            p[paramx], p[paramy],
                            '{0:.3f}'.format(self.coeffs[region_num][i]))

        gs = gridspec.GridSpec(2, 2)
        plt.subplot(gs[0])
        _plot_ref_params('Teff', 'radius')
        if len(self.results) > 0:
            plt.plot(self.lincomb_results[region_num]['Teff'],
                     self.lincomb_results[region_num]['radius'],
                     's',
                     color='purple',
                     label='Derived Parameters')
        plots.label_axes('Teff', 'radius')

        plt.subplot(gs[1])
        _plot_ref_params('Teff', 'radius', zoom=True)
        if len(self.results) > 0:
            plt.plot(self.lincomb_results[region_num]['Teff'],
                     self.lincomb_results[region_num]['radius'],
                     's',
                     color='purple',
                     label='Derived Parameters')
        plots.label_axes('Teff', 'radius', rescale=False)

        plt.subplot(gs[2])
        _plot_ref_params('feh', 'radius')
        if len(self.results) > 0:
            plt.plot(self.lincomb_results[region_num]['feh'],
                     self.lincomb_results[region_num]['radius'],
                     's',
                     color='purple',
                     label='Derived Parameters')
        plots.label_axes('feh', 'radius')

        plt.subplot(gs[3])
        _plot_ref_params('feh', 'radius', zoom=True)
        if len(self.results) > 0:
            plt.plot(self.lincomb_results[region_num]['feh'],
                     self.lincomb_results[region_num]['radius'],
                     's',
                     color='purple',
                     label='Derived Parameters')
        plots.label_axes('feh', 'radius', rescale=False)
Exemplo n.º 8
0
# code-stop-imports
rc('savefig',dpi=160)




# code-start-loadlibrary: load in the library around the Mgb triplet
lib = specmatchemp.library.read_hdf(wavlim=[5140,5200])
# code-stop-loadlibrary



# code-start-library: Here's how the library spans the HR diagram.
fig = figure()
plot(lib.library_params.Teff, lib.library_params.radius,'k.',)
smplot.label_axes('Teff','radius')
# code-stop-library
fig.savefig('quickstart-library.png')




# code-start-library-labeled
fig = figure()
g = lib.library_params.groupby('source')
colors = ['Red','Orange','LimeGreen','Cyan','RoyalBlue','Magenta','ForestGreen']
i = 0
for source, idx in g.groups.items():
    cut = lib.library_params.ix[idx]
    color = colors[i]
    plot(