Ejemplo n.º 1
0
def random_stars():
    seed = 23498739
    nstars = 1e6

    img_size = 8400
    mrange = [9, 24]
    lum_function = PowerLaw1D(1.0, mrange[0], -0.5)

    np.random.seed(seed)
    x = np.random.rand(nstars) * img_size
    y = np.random.rand(nstars) * img_size
    m_ran = (np.random.rand(nstars) * np.diff(mrange)) + mrange[0]

    return x, y
Ejemplo n.º 2
0
    def evaluate(self, in_x, Rv):
        """
        D22 function

        Parameters
        ----------
        in_x: float
           expects either x in units of wavelengths or frequency
           or assumes wavelengths in wavenumbers [1/micron]

           internally wavenumbers are used

        Returns
        -------
        axav: np array (float)
            A(x)/A(V) extinction curve [mag]

        Raises
        ------
        ValueError
           Input x values outside of defined range
        """
        # convert to wavenumbers (1/micron) if x input in units
        # otherwise, assume x in appropriate wavenumber units
        x = _get_x_in_wavenumbers(in_x)

        # check that the wavenumbers are within the defined range
        _test_valid_x_range(x, self.x_range, self.__class__.__name__)

        # just in case someone calls evaluate explicitly
        Rv = np.atleast_1d(Rv)

        # ensure Rv is a single element, not numpy array
        Rv = Rv[0]

        # intercepts
        mod_a = PowerLaw1D(amplitude=0.377, alpha=1.78, x_0=1.0)
        a = mod_a(1.0 / x)

        # slopes
        # from spline interpolation
        b = interpolate.splev(1.0 / x, self.spline_rep, der=0)

        # return A(x)/A(V)
        return a + b * (1.0 / Rv - 1 / 3.1)
Ejemplo n.º 3
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Fit and plot Crab nebula spectrum."""
import matplotlib.pyplot as plt
from astropy.modeling.models import PowerLaw1D
from astropy.modeling.fitting import NonLinearLSQFitter
from gammapy.datasets import tev_spectrum

data = tev_spectrum('crab')
energy, flux, flux_err = data['energy'], data['flux'], data['flux_err']

model = PowerLaw1D(4e-11, 1, 2.6)
model.x_0.fixed = True
fitter = NonLinearLSQFitter()

model = fitter(model, energy, flux, weights=(1. / flux_err))
print(model)

plt.errorbar(energy,
             energy**2 * flux,
             energy**2 * flux_err,
             fmt='o',
             label='HESS measurement')
plt.errorbar(energy, energy**2 * model(energy), fmt='r-', label='Powerlaw fit')
plt.loglog()
plt.xlabel('Energy (TeV)')
plt.ylabel('E^2 * dN / dE (TeV cm^-2 s^-1)')
plt.legend()
plt.savefig('fit_crab_spectrum.png')
Ejemplo n.º 4
0
    def plot_spectrum(self, ax=None):
        """Plot spectrum.
        """
        import matplotlib.pyplot as plt
        from gammapy.extern.stats import gmean
        from astropy.modeling.models import PowerLaw1D, LogParabola1D, ExponentialCutoffPowerLaw1D

        ax = plt.gca() if ax is None else ax

        # Only work with indices where we have a valid detection and a lower bound
        flux_bounds = [self.cat_row["Unc_" + self.y_labels[i]] for i in range(0, np.size(self.y_labels))]

        valid_indices = []

        for i in range(0, len(flux_bounds)):
            if np.size(flux_bounds[i]) == 2 and not np.isnan(flux_bounds[i][0]):
                valid_indices.append(i)

        y_vals = np.array([self.cat_row[i] for i in (self.y_labels[j] for j in valid_indices)])
        y_lower = np.array([self.cat_row["Unc_" + i][0] for i in (self.y_labels[j] for j in valid_indices)])
        y_upper = np.array([self.cat_row["Unc_" + i][1] for i in (self.y_labels[j] for j in valid_indices)])

        y_lower = y_vals + y_lower
        y_upper = y_vals + y_upper

        x_vals = [self.x_cens[i].value for i in valid_indices]
        bin_edges1 = [-(self.x_bins_edges[i] - self.x_cens[i]).value for i in valid_indices]
        bin_edges2 = [(self.x_bins_edges[i + 1] - self.x_cens[i]).value for i in valid_indices]

        y_vals = [y_vals[i] / x_vals[i] for i in range(0, np.size(y_vals))]
        y_upper = [y_upper[i] / x_vals[i] for i in range(0, np.size(y_vals))]
        y_lower = [y_lower[i] / x_vals[i] for i in range(0, np.size(y_vals))]

        y_cens = np.array([gmean([y_lower[i], y_upper[i]]) for i in range(0, np.size(y_lower))])

        y_upper = np.array([y_upper[i] - y_vals[i] for i in range(0, np.size(y_lower))])
        y_lower = np.array([y_vals[i] - y_lower[i] for i in range(0, np.size(y_lower))])

        ax.loglog()

        fmt = dict(elinewidth=1, linewidth=0, color='black')
        ax.errorbar(x_vals, y_vals, yerr=(y_lower, y_upper), **fmt)

        # Place the x-axis uncertainties in the center of the y-axis uncertainties.
        ax.errorbar(x_vals, y_cens, xerr=(bin_edges1, bin_edges2), **fmt)

        x_model = np.logspace(np.log10(min(x_vals)), np.log10(max(x_vals)), 25)

        if self.spec_type == "PowerLaw":

            y_model = PowerLaw1D(amplitude=self.flux_density,
                                 x_0=self.pivot_en,
                                 alpha=self.spec_index)

        elif self.spec_type == "LogParabola":

            y_model = LogParabola1D(amplitude=self.flux_density,
                                    x_0=self.pivot_en,
                                    alpha=self.spec_index,
                                    beta=self.beta)

        elif self.spec_type == "PLExpCutoff":

            y_model = ExponentialCutoffPowerLaw1D(amplitude=self.flux_density,
                                                  x_0=self.pivot_en,
                                                  alpha=self.spec_index,
                                                  x_cutoff=self.cutoff)
        elif self.spec_type == "PLSuperExpCutoff":
            raise NotImplementedError
        else:
            raise NotImplementedError

        ax.set_xlabel('Energy (MeV)')
        ax.set_ylabel('Flux (ph/cm^2/s/MeV)')
        ax.plot(x_model, y_model(x_model))

        return ax