Example #1
0
    def __init__(self, spec, velscale, pklfile=None):
        """ Load the pkl file from previous ppxf fit and define some atributes.
        """
        if pklfile == None:
            pklfile = spec.replace(".fits", ".pkl")
        with open(pklfile) as f:
            pp = pickle.load(f)
        self.__dict__ = pp.__dict__.copy()
        self.spec = spec
        if not os.path.exists(os.path.join(os.getcwd(), spec)):
            self.spec = os.path.join(data_dir, spec)
        self.velscale = velscale
        self.w = wavelength_array(os.path.join(data_dir, spec))
        self.flux = pf.getdata(self.spec)
        self.flux_log, self.logw, velscale = util.log_rebin(
            [self.w[0], self.w[-1]], self.flux, velscale=velscale)
        self.w_log = np.exp(self.logw)
        self.header = pf.getheader(os.path.join(data_dir, spec))
        self.lam = self.header['CRVAL1'] + np.array(
            [0., self.header['CDELT1'] * (self.header['NAXIS1'] - 1)])
        ######################################################################
        # # Read templates
        star_templates, self.logLam2, self.delta, miles = stellar_templates(
            velscale)
        ######################################################################
        # Convolve our spectra to match MILES resolution
        FWHM_tem = 2.51
        FWHM_spec = 2.1
        FWHM_dif = np.sqrt(FWHM_tem**2 - FWHM_spec**2)
        sigma = FWHM_dif / 2.355 / self.delta  # Sigma difference in pixels
        ######################################################################
        spec_lin = ndimage.gaussian_filter1d(self.flux, sigma)
        # Rebin to logarithm scale
        galaxy, self.logLam1, velscale = util.log_rebin(self.lam,
                                                        spec_lin,
                                                        velscale=velscale)
        self.dv = (self.logLam2[0] - self.logLam1[0]) * c
        # if self.sky != None:
        #     sky = self.weights[-1] * self.sky.T[0]
        #     self.bestfit -= sky
        #     self.galaxy -= sky
        #     skyspec = os.path.join(sky_data_dir, spec.replace("fin1", "sky1"))
        #     sky_lin = pf.getdata(skyspec)

        return
def check_ppxf(spec, velscale):
    """ Checking if velocity os star is zero"""
    templates, logLam2, delta, miles= stellar_templates(velscale)
    FWHM_dif = np.sqrt(FWHM_tem**2 - FWHM_spec**2)
    sigma = FWHM_dif/2.355/delta # Sigma difference in pixels
    star = pf.getdata(spec)
    star1 = ndimage.gaussian_filter1d(star, sigma)
    w = wavelength_array(spec)
    lamRange= np.array([w[0], w[-1]])
    galaxy, logLam1, velscale = util.log_rebin(lamRange, star1, \
                                               velscale=velscale)
    sn = snr(star1)
    noise = np.ones_like(galaxy) / sn
    dv = (logLam2[0]-logLam1[0])*c
    pp = ppxf(templates, galaxy, noise, velscale, [0,50],
        plot=True, moments=2, degree=5, mdegree=-1, vsyst=dv)
    plt.show()
    return
Example #3
0
    def __init__(self, spec, velscale, pklfile=None):
        """ Load the pkl file from previous ppxf fit and define some atributes.
        """
        if pklfile == None:
            pklfile = spec.replace(".fits", ".pkl")
        with open(pklfile) as f:
            pp = pickle.load(f)
        self.__dict__ = pp.__dict__.copy()
        self.spec = spec
        if not os.path.exists(os.path.join(os.getcwd(), spec)):
            self.spec = os.path.join(data_dir, spec)
        self.velscale = velscale
        self.w = wavelength_array(os.path.join(data_dir, spec))
        self.flux = pf.getdata(self.spec)
        self.flux_log, self.logw, velscale = util.log_rebin(
                        [self.w[0], self.w[-1]], self.flux, velscale=velscale)
        self.w_log = np.exp(self.logw)
        self.header = pf.getheader(os.path.join(data_dir, spec))
        self.lam = self.header['CRVAL1'] + np.array([0.,
                              self.header['CDELT1']*(self.header['NAXIS1']-1)])
        ######################################################################
        # # Read templates
        star_templates, self.logLam2, self.delta, miles= stellar_templates(velscale)
        ######################################################################
        # Convolve our spectra to match MILES resolution
        FWHM_tem = 2.51
        FWHM_spec = 2.1
        FWHM_dif = np.sqrt(FWHM_tem**2 - FWHM_spec**2)
        sigma = FWHM_dif/2.355/self.delta # Sigma difference in pixels
        ######################################################################
        spec_lin = ndimage.gaussian_filter1d(self.flux,sigma)
        # Rebin to logarithm scale
        galaxy, self.logLam1, velscale = util.log_rebin(self.lam, spec_lin,
                                                   velscale=velscale)
        self.dv = (self.logLam2[0]-self.logLam1[0])*c
        # if self.sky != None:
        #     sky = self.weights[-1] * self.sky.T[0]
        #     self.bestfit -= sky
        #     self.galaxy -= sky
        #     skyspec = os.path.join(sky_data_dir, spec.replace("fin1", "sky1"))
        #     sky_lin = pf.getdata(skyspec)


        return
Example #4
0
def run_ppxf(spectra, velscale, ncomp=2, has_emission=True, mdegree=-1,
             degree=20, pkls=None, plot=False, data_sky=None):
    """ Run pPXF in a list of spectra"""
    if isinstance(spectra, str):
        spectra = [spectra]
    if isinstance(pkls, str):
        pkls = [pkls]
    if pkls == None:
        pkls = [x.replace(".fits", ".pkl") for x in spectra]
    ##########################################################################
    # Load templates for both stars and gas
    star_templates, logLam2, delta, miles= stellar_templates(velscale)
    gas_templates,logLam_gas, delta_gas, gas_files=emission_templates(velscale)
    ##########################################################################
    # Join templates in case emission lines are used.
    if has_emission:
        templates = np.column_stack((star_templates, gas_templates))
    else:
        templates = star_templates
    ##########################################################################
    if ncomp == 1:
        components = 0
        moments = [4]
        templates_names = miles
    elif ncomp == 2:
        components = np.hstack((np.zeros(len(star_templates[0])),
                                np.ones(len(gas_templates[0]))))
        moments = [4,2]
        templates_names = np.hstack((miles, gas_files))

    else:
        raise Exception("ncomp has to be 1 or 2.")
    for i, spec in enumerate(spectra):
        print "pPXF run of spectrum {0} ({1} of {2})".format(spec, i+1,
              len(spectra))
        pkl = pkls[i]
        ######################################################################
        # Read one galaxy spectrum and define the wavelength range
        specfile = os.path.join(data_dir, spec)
        hdu = pf.open(specfile)
        spec_lin = hdu[0].data
        h1 = pf.getheader(specfile)
        lamRange1 = h1['CRVAL1'] + np.array([0.,h1['CDELT1']*(h1['NAXIS1']-1)])
        ######################################################################
        # Degrade observed spectra to match template resolution
        FWHM_dif = np.sqrt(FWHM_tem**2 - FWHM_spec**2)
        sigma = FWHM_dif/2.355/delta # Sigma difference in pixels
        spec_lin = ndimage.gaussian_filter1d(spec_lin,sigma)
        ######################################################################
        # Rebin to log scale
        galaxy, logLam1, velscale = util.log_rebin(lamRange1, spec_lin, 
                                                   velscale=velscale)
        ######################################################################
        # First guess for the noise
        noise = np.ones_like(galaxy) * np.std(galaxy - medfilt(galaxy, 5))
        ######################################################################
        # Calculate difference of velocity between spectrum and templates
        # due to different initial wavelength
        dv = (logLam2[0]-logLam1[0])*c
        ######################################################################
        # Set first guess from setup files
        start, goodPixels = read_setup_file(spec, logLam1, mask_emline=False)
        ######################################################################
        # Expand start variable to include multiple components
        if ncomp > 1:
            start = [start, [start[0], 30]]
        ######################################################################
        # Read sky in needed
        if data_sky == None:
            sky = None
        else:
            sky_lin = pf.getdata(data_sky[i])
            sky_lin = ndimage.gaussian_filter1d(sky_lin,sigma)
            sky, logLam1, velscale = util.log_rebin(lamRange1, sky_lin,
                                                    velscale=velscale)
            sky = sky.reshape(-1,1)
        ######################################################################
        # First pPXF interaction
        if os.path.exists(spec.replace(".fits", ".pkl")):
            pp0 = pPXF(spec, velscale, pklfile=spec.replace(".fits", ".pkl"))
            noise0 = pp0.noise
        else:
            pp0 = ppxf(templates, galaxy, noise, velscale, start,
                       goodpixels=goodPixels, plot=False, moments=moments,
                       degree=12, mdegree=-1, vsyst=dv, component=components,
                       sky=sky)
            rms0 = galaxy[goodPixels] - pp0.bestfit[goodPixels]
            noise0 = 1.4826 * np.median(np.abs(rms0 - np.median(rms0)))
            noise0 = np.zeros_like(galaxy) + noise0
        # Second pPXF interaction, realistic noise estimation
        pp = ppxf(templates, galaxy, noise0, velscale, start,
                  goodpixels=goodPixels, plot=plot, moments=moments,
                  degree=degree, mdegree=mdegree, vsyst=dv,
                  component=components, sky=sky)
        # pp.template_files = templates_names
        # pp.has_emission = has_emission
        ######################################################################
        # Save to output file to keep session
        with open(pkl, "w") as f:
            pickle.dump(pp, f)
        ######################################################################
    return
Example #5
0
def run_ppxf(spectra,
             velscale,
             ncomp=2,
             has_emission=True,
             mdegree=-1,
             degree=20,
             pkls=None,
             plot=False,
             data_sky=None):
    """ Run pPXF in a list of spectra"""
    if isinstance(spectra, str):
        spectra = [spectra]
    if isinstance(pkls, str):
        pkls = [pkls]
    if pkls == None:
        pkls = [x.replace(".fits", ".pkl") for x in spectra]
    ##########################################################################
    # Load templates for both stars and gas
    star_templates, logLam2, delta, miles = stellar_templates(velscale)
    gas_templates, logLam_gas, delta_gas, gas_files = emission_templates(
        velscale)
    ##########################################################################
    # Join templates in case emission lines are used.
    if has_emission:
        templates = np.column_stack((star_templates, gas_templates))
    else:
        templates = star_templates
    ##########################################################################
    if ncomp == 1:
        components = 0
        moments = [4]
        templates_names = miles
    elif ncomp == 2:
        components = np.hstack(
            (np.zeros(len(star_templates[0])), np.ones(len(gas_templates[0]))))
        moments = [4, 2]
        templates_names = np.hstack((miles, gas_files))

    else:
        raise Exception("ncomp has to be 1 or 2.")
    for i, spec in enumerate(spectra):
        print "pPXF run of spectrum {0} ({1} of {2})".format(
            spec, i + 1, len(spectra))
        pkl = pkls[i]
        ######################################################################
        # Read one galaxy spectrum and define the wavelength range
        specfile = os.path.join(data_dir, spec)
        hdu = pf.open(specfile)
        spec_lin = hdu[0].data
        h1 = pf.getheader(specfile)
        lamRange1 = h1['CRVAL1'] + np.array(
            [0., h1['CDELT1'] * (h1['NAXIS1'] - 1)])
        ######################################################################
        # Degrade observed spectra to match template resolution
        FWHM_dif = np.sqrt(FWHM_tem**2 - FWHM_spec**2)
        sigma = FWHM_dif / 2.355 / delta  # Sigma difference in pixels
        spec_lin = ndimage.gaussian_filter1d(spec_lin, sigma)
        ######################################################################
        # Rebin to log scale
        galaxy, logLam1, velscale = util.log_rebin(lamRange1,
                                                   spec_lin,
                                                   velscale=velscale)
        ######################################################################
        # First guess for the noise
        noise = np.ones_like(galaxy) * np.std(galaxy - medfilt(galaxy, 5))
        ######################################################################
        # Calculate difference of velocity between spectrum and templates
        # due to different initial wavelength
        dv = (logLam2[0] - logLam1[0]) * c
        ######################################################################
        # Set first guess from setup files
        start, goodPixels = read_setup_file(spec, logLam1, mask_emline=False)
        ######################################################################
        # Expand start variable to include multiple components
        if ncomp > 1:
            start = [start, [start[0], 30]]
        ######################################################################
        # Read sky in needed
        if data_sky == None:
            sky = None
        else:
            sky_lin = pf.getdata(data_sky[i])
            sky_lin = ndimage.gaussian_filter1d(sky_lin, sigma)
            sky, logLam1, velscale = util.log_rebin(lamRange1,
                                                    sky_lin,
                                                    velscale=velscale)
            sky = sky.reshape(-1, 1)
        ######################################################################
        # First pPXF interaction
        if os.path.exists(spec.replace(".fits", ".pkl")):
            pp0 = pPXF(spec, velscale, pklfile=spec.replace(".fits", ".pkl"))
            noise0 = pp0.noise
        else:
            pp0 = ppxf(templates,
                       galaxy,
                       noise,
                       velscale,
                       start,
                       goodpixels=goodPixels,
                       plot=False,
                       moments=moments,
                       degree=12,
                       mdegree=-1,
                       vsyst=dv,
                       component=components,
                       sky=sky)
            rms0 = galaxy[goodPixels] - pp0.bestfit[goodPixels]
            noise0 = 1.4826 * np.median(np.abs(rms0 - np.median(rms0)))
            noise0 = np.zeros_like(galaxy) + noise0
        # Second pPXF interaction, realistic noise estimation
        pp = ppxf(templates,
                  galaxy,
                  noise0,
                  velscale,
                  start,
                  goodpixels=goodPixels,
                  plot=plot,
                  moments=moments,
                  degree=degree,
                  mdegree=mdegree,
                  vsyst=dv,
                  component=components,
                  sky=sky)
        # pp.template_files = templates_names
        # pp.has_emission = has_emission
        ######################################################################
        # Save to output file to keep session
        with open(pkl, "w") as f:
            pickle.dump(pp, f)
        ######################################################################
    return