def Extraction(name, wavelength, flux):
    data = np.array([wavelength, flux]).transpose()
    li = Lines.Lines(data)
    wg_lines, flux_lines, sflux_lines = li.ExtractLines()
    li.Plot(write=True, name=str(name + '.pdf'))
    tb.DumpTuple(['wg_lines', 'flux_lines', 'sflux_lines'],
                 [wg_lines, flux_lines, sflux_lines], str(name + '.list'))
 def Atmo(self, wavelength, signal, mkcalib=True, name='', **kwargs):
     if self.sed.calspec:
         fig = pl.figure()
         signal = np.array(signal)
         wg, atmo = self.sed.EstimateAtmoT(wavelength, signal, mkcalib=True)
         tb.DumpTuple(['wg', 'atmo'], [wg, atmo],
                      os.path.join(self.directory,
                                   str('Tatmo' + name + '.list')))
         if self.plot is True:
             pl.plot(wg, atmo, '-k', label=str('Tatmo' + name))
             pl.xlabel('wavelength (nm)')
             pl.ylabel('Atmospheric transmission (norm@max)')
             ymin = np.nanmin(atmo)
             ymax = np.nanmax(atmo)
             xmin = np.nanmin(wg)
             xmax = np.nanmax(wg)
             xmax = min(xmax, 1100)
             pl.xlim(xmin, xmax)
             pl.ylim(ymin, ymax)
             pl.legend()
     return
示例#3
0
    def ExtractProfile(self,footprint, mask, direction):
        Y =[]
        if(direction=="y"):
            footprint = footprint.T
            mask      = mask.T
        rows, cols = len(footprint),  len(footprint[0])
        for i in range(0,rows): 
            keep = footprint[i , :]
            remo = mask[i , :]
            keep = keep[remo==0]
            if len(keep) is 0 :
                flux = Y[-1]
            else:
                flux = np.median(keep)
            Y.append(flux)

        rows = np.arange(0,rows)
        file = str("background"+self.spectrum.order+".list")
        tb.DumpTuple(('rows', 'level'),(rows, Y)
                     , os.path.join(self.spectrum.out_dir,file) )
        return Y
示例#4
0
            edges.append(item[2][0])
        for i in EW:
            print 'EW : ', i
            #ew_w, ew_f = equWidth(wght, signal, continuum, i) #abrupt version
            ew_w, ew_f = equWidth2(data[:,0],data[:,1], i, plot=plot)          #fitted edges
            print Object, jd, airmass, ew_w, ew_f, mean_seeing
            
            outlist.append([Object, jd, airmass,parallactic_angle, ew_w, ew_f, mean_seeing, pwv])
              
        if plot:
            pl.figure
            pl.plot(wght, continuum, 'g', lw=1, label='continuum')
            pl.plot(data[:,0],data[:,1], 'r^',label='raw flux')
            pl.plot(continuum_w, continuum_f, 'bo',label='spline input')
            pl.legend()

            pl.figure()
            pl.plot(edges, np.ones(len(EW)*2), 'r|')
            pl.plot(wght, (signal) / continuum, label='signal/continuum')
            pl.legend()
            pl.show()
          


    names =['object', 'jd', 'airmass', 'parallactic','ew_w','ew_f', 'mean_seeing', 'pwv']
    tb.DumpTuple(names,
                zip(*outlist),
                 outfile)
    print 'writing : ', outfile
     
import scipy.interpolate as interp


if __name__ == "__main__":

    outfile    = sys.argv[1]
    files = sys.argv[2:]
    values = []
    fig = pl.figure()
    for file in files:
        print file
        name = os.path.basename(file)
        value, keys = tb.readlist(file, ('wavelength', 'contamination'))
        values.append(value)
        pl.plot(value[0], value[1], label = name)
    
        pl.ylim(0.001, .02)
        pl.legend()

    pl.xlabel('wavelength (nm)')
    pl.ylabel('Contamination (fraction)')
    pl.title('Ronchi 200 - 2nd order light contamination')
    fig.savefig("contamination.pdf")
    pl.show()

    ### I guess I will fit a constant value 
    tb.DumpTuple(('wavelength', 'contamination'),(second[:,0], interp/second[:,1])
                     , outfile )
    
  
示例#6
0
            c = FK5(Angle(looking_ra, u.degree), Angle(looking_dec, u.degree))
            idx, d2d, d3d = match_coordinates_sky(c, catalog)
            print idx, ' distance ~ ', (
                d2d.degree)[0] * 3600 / 0.8,  #mode rebin 2*2
            print ' object is at number : ', sources_nb[idx]

            found = objects[objects.field('NUMBER') == sources_nb[idx]]
            print 'Found : ', found, ' => ', found.field(
                'X_IMAGE'), found.field('Y_IMAGE')

            pixcrd = np.array(
                [[found.field('X_IMAGE')[0],
                  found.field('Y_IMAGE')[0]]], np.float_)
            world = w.wcs_pix2world(pixcrd, 1)
            ra = world[0][0]
            dec = world[0][1]
            name = reference[0]
            data.append(
                list([
                    name, date, exptime, band, ra, dec, airmass, outhum,
                    outpress, wndspeed
                ]) + list(found[0]))
            if item == 0:
                columns = ('name', 'date', 'exptime', 'band', 'ra', 'dec',
                           'airmass', 'outhum', 'outpress',
                           'wndspeed') + found.dtype.names
                print 'output entries : ', columns

    print 'writing ', outcat
    tb.DumpTuple(columns, zip(*data), outcat)
if __name__ == "__main__":

    step = 1.
    wght = np.arange(450, 901, step)

    qe = np.loadtxt(sys.argv[1])
    cbp = np.loadtxt(sys.argv[2])

    QE = interp.griddata(qe[:, 0], qe[:, 1], wght)
    CBP = interp.griddata(cbp[:, 0], cbp[:, 1], wght)

    out = QE / CBP

    filename = 'Oct2017QE.list'
    outdir = os.path.dirname(sys.argv[1])
    tb.DumpTuple(('wght', 'qe'), (wght, out), os.path.join(outdir, filename))

    pl.figure()
    pl.plot(qe[:, 0], qe[:, 1], 'r^', label='file1')
    pl.legend()

    pl.figure()
    pl.plot(cbp[:, 0], cbp[:, 1], 'bo', label='file2')
    pl.legend()

    pl.figure()
    pl.plot(wght, out, 'r^', label='cbp Norm')
    #pl.plot(wght, CBP, b'o')
    pl.legend()
    pl.show()
示例#8
0
        else:
            wneg.append(i)
            neg.append(abs(j))
    pl.plot(wpos, pos, color='red', marker='+', label="pos.")
    pl.plot(wneg, neg, color='blue', marker='+', label="neg.")
    #pl.errorbar(Wreg,Freg0, sFreg0, color='red',  marker='+', linestyle='None', label= "Extrapolation to z=0 ")
    pl.title('0 airmass')
    pl.xlabel('wavelength (nm)')
    pl.ylabel('-2.5*log10(flux) (mag)')
    pl.legend(loc='upper left')
    fig3.savefig("regressionOairmassP0.pdf")

    fig4 = pl.figure()
    pl.errorbar(Wreg,
                Freg1,
                sFreg1,
                color='red',
                marker='+',
                linestyle='None',
                label="regression ")
    pl.xlabel('wavelength (nm)')

    pl.legend(loc='upper right')
    fig4.savefig("regressionOairmassP1.pdf")
    pl.show()

    outlist = [Wreg, Freg0, sFreg0, Freg1, sFreg1]
    names = ['wght', 'intercept', 'sintercept', 'slope', 'sslope']
    tb.DumpTuple(names, outlist, outfile)
    print 'writing : ', outfile
#!/usr/bin/env python
'''
dump spectrum from stis fitsimage

Author: Augustin Guyonnet
[email protected]
'''

import os, sys
import astropy.io.fits as pf
import toolbox as tb

if __name__ == "__main__":

    Image = sys.argv[1]
    fits = pf.open(Image)
    target = fits[0].header.get('TARGETID')
    tbdata = fits[1].data  # the table is in extension 1
    cols = tbdata.columns  # names of the columns
    tbdata = tbdata[tbdata.field(0) < 11000]  # Select lambda<1100nm
    wavelength = tbdata.field(0) / 10  # Convert in nm
    flux = tbdata.field(1)
    staterror = tbdata.field(2)
    syserror = tbdata.field(3)

    tb.DumpTuple(('wavelength', 'flux', 'staterror', 'syserror'),\
                 [wavelength, flux, staterror, syserror], str(target)+'.list')
  

        
if __name__ == "__main__":
  
    if len(sys.argv) <= 1:
        usage()

    files = sys.argv[1:]
    data = []
    names = zeroth(files[0]).dtype.names
    for file in files:
        dirname  = os.path.dirname(file)
        img      = dirname.split("_")[-1]
        fits     = os.path.join(dirname,'segmentation.fits')
        filters  = pf.open(fits)[0].header.get('FILTERS')
        comments = str(pf.open(fits)[0].header.get('COMMENT'))
        wght     = comments.split("WAVE")[1].split(" ")[1]
        print fits, 'wght = ', wght
        obj = zeroth(file)
        if (len(obj)!=1):
            continue
        obj = list(obj[0].tolist())
        obj = [int(img)] + [float(wght)] + obj
        data.append(obj)


    names = ['img']+['wght']+list(names)
    tb.DumpTuple(names, zip(*data), 'cbp.list')
#!/usr/bin/env python
'''
dump a atmospheric trnasmission profile

Author: Augustin Guyonnet
[email protected]
'''

import os, sys
import toolbox as tb
import scipy.ndimage.filters as filt

if __name__ == "__main__":
    wavelength, flux = tb.AtmoTransmission()
    flux = filt.gaussian_filter1d(flux, sigma=2.46)
    tb.DumpTuple(('wavelength', 'flux'), [wavelength, flux], 'atmo.list')
        print "A*x*np.exp(-(x)**2/(2.*sigma**2)) / sigma**2"
        print "A, sigma = ", coeff
        fit = rayleigh(x, *coeff)
        distrib = "Rayleigh"
        pl.text(10, 0.1, 'A, sigma =  %s' % (coeff), color='red', fontsize=8)

    if method == 'G':
        gg_init = models.Gaussian1D(amplitude=1, mean=260,
                                    stddev=10.) + models.Gaussian1D(
                                        amplitude=1, mean=290, stddev=10.)
        fitter = fitting.SLSQPLSQFitter()
        gg_fit = fitter(gg_init, x, n)
        print gg_fit
        fit = gg_fit(x)
        distrib = "Two gaussian"
        pl.text(220,
                0.02,
                '%s \n %s' % (gg_fit.param_names, gg_fit.parameters),
                color='red',
                fontsize=8)

    pl.plot(x, fit, 'b-', label=distrib + ' distribution')
    pl.xlabel(name)
    pl.legend()
    pl.show()

    outname = name + '_distrib'
    names = ['bin', 'value']
    tb.DumpTuple(names, [x, nTO3_distrib.list * bin_width], outname + '.list')
    print 'writing : ', outname + '.list'
                                   wght_recal)
        outfile = str('spectrum' + name + '.list')
        tb.DumpFile(keys, ('pixel', 'wght', 'wght_recal', 'flux', 'sed_flux',
                           'sed_flux_noqe'),
                    (pixel, w, wght_recal, best_flux, sed_flux, sed_flux_noqe),
                    os.path.join(input_rep, outfile))
        '''Measurement of the EW based on the position of the lines'''
        '''From the template +/- the resolution at this position '''
        sigmas = []
        segments = []
        for i in ew_position:
            sigmas.append(mod.Resolution(i))
        ew_flux, segments = EW(wght_recal, best_flux, ew_position, sigmas)
        outfile = str('ew_extraction' + name + '.pdf')
        Plot(wght_recal,
             best_flux,
             segments,
             name=os.path.join(input_rep, outfile))
        outfile = str('ew_extraction' + name + '.list')
        tb.DumpTuple(['wg_lines', 'flux_lines', 'sflux_lines'],
                     [ew_position, ew_flux,
                      np.zeros(len(ew_position))],
                     os.path.join(input_rep, outfile))
        '''Replot after having rescaled the wght solution'''
        mod.ForwardModeling(wght_recal, best_flux, name='_2')
        mod.Atmo(wght_recal, best_flux, mkcalib=True, name='_2')

        if plot:
            pl.show()
        pl.clf()
示例#14
0
        Y.append(flux)
    return X, Y


if __name__ == "__main__":
    amps = ('11', '12', '21', '22')
    direction = sys.argv[1]  # 'x' is default, 'y' transpose the array
    Image = sys.argv[2:]
    for img in Image:
        figOp = pl.figure(1)
        inst = instru.telinst(img)
        data = inst.Image(img)
        (filepath, filename) = os.path.split(img)
        name = filename.split('.')[0] + str(direction)

        colors = iter(cm.rainbow(np.linspace(0, 1, len(amps))))
        for amp in amps:
            overscan = inst.OverscanRegion(data, amp)
            X, Y = extract_profile(overscan, direction)

            # Draw raw profile and dump tuple:
            graph(X, Y, Color=next(colors), Linestyle='-', Name=str(amp))
            tb.DumpTuple(['X', 'Y'], [X, Y], name + str(amp) + '.list')

        pl.xlabel('position (pixel)')
        pl.ylabel('counts (ADU)')
        pl.title('Overscans' + name)
        pl.legend(loc='upper left')
        name += '.pdf'
        figOp.savefig(name)