コード例 #1
0
ファイル: plot_simple.py プロジェクト: eigenbrot/snakes
def plot_maps(inputfile, outputfile, eps=False, exclude=[], sky=False, labelfibers=True, MLWA=True):

    if MLWA:
        data = np.loadtxt(inputfile, usecols=(12,), unpack=True)
        label = "Mean Light Weighted Age [Gyr]"
        minval = np.nanmin(data)
        maxval = np.nanmax(data)
    else:
        data = np.loadtxt(inputfile, usecols=(11,), unpack=True)
        label = "Mean Mass Weighted Age [Gyr]"
        minval = np.nanmin(data)  # 7
        maxval = np.nanmax(data)  # 10

    map_ax = GPP.plot_img(
        data,
        fitsfile="/d/monk/eigenbrot/WIYN/14B-0456/NGC_891.fits",
        imrot=67.0,
        pa=295.787,
        center=[35.6034125, 42.32349444],
        clabel=label,
        method="cubic",
        cmap="gnuplot2",
        exclude=exclude,
        sky=sky,
        minval=minval,
        maxval=maxval,
    )

    fiber_ax = GPP.plot(
        data,
        fitsfile="/d/monk/eigenbrot/WIYN/14B-0456/NGC_891.fits",
        imrot=67.0,
        pa=295.787,
        center=[35.6034125, 42.32349444],
        clabel=label,
        cmap="gnuplot2",
        labelfibers=labelfibers,
        exclude=exclude,
        sky=sky,
        minval=minval,
        maxval=maxval,
    )

    if eps:
        fiber_name = outputfile + "_fibers.eps"
        map_name = outputfile + "_map.eps"

        fiber_ax.figure.savefig(fiber_name, format="eps")
        map_ax.figure.savefig(map_name, format="eps")
    else:
        pp = PDF(outputfile)
        pp.savefig(fiber_ax.figure)
        pp.savefig(map_ax.figure)
        pp.close()

    # plt.close(fiber_ax.figure)
    # plt.close(map_ax.figure)

    return fiber_ax
コード例 #2
0
ファイル: plot_simple.py プロジェクト: eigenbrot/snakes
def plot_heights(inputfile, outputfile, title=""):

    MMWA, MLWA, SNR = np.loadtxt(inputfile, usecols=(11, 12, 14), unpack=True)

    pp = PDF(outputfile)

    ax = GPP.plot_rows(MMWA, weights=SNR, ylabel="Age [Gyr]", label="MMWA", kpc_scale=0.0485)
    GPP.plot_rows(MLWA, weights=SNR, label="MLWA", ax=ax, kpc_scale=0.0485)
    ax.legend(loc=0, scatterpoints=1, numpoints=1, frameon=False)
    ax.set_xlim(-0.5, 3)
    ax.set_title(title)
    pp.savefig(ax.figure)
    pp.close()
    plt.close(ax.figure)

    return
コード例 #3
0
ファイル: plot_allZ2.py プロジェクト: eigenbrot/snakes
def all_heights(output, inputprefix='NGC_891', err=True, binned=True):

    datname = output.split('.pdf')[0]+'.dat'
    f = open(datname,'w')
    f.write('#{:5}{:>13}{:>13}{:>13}{:>13}{:>13}{:>13}{:>13}{:>13}{:>13}{:>13}\n#\n'.\
            format('','height [kpc]','age [Gyr]',
                   'age eom','age stderr',
                   'AV','AV eom','AV stderr',
                   'Z/Z_sol','Z eom', 'Z stderr'))

    pp = PDF(output)
    symblist = ["o","^","v","s","*","x"]
    colorlist = ['b','c','g','y','m','r']
    kpc_scale = 0.0485
    plist = [6,3,4,2,1,5]
    zcorrlist = [-0.01, -0.113, -0.225, -0.07, -0.142, -0.004]
    rlist = [-10.0, -6.4, -2.3, 0.8, 4.4, 8.1]

    ageax = None
    AVax = None
    Zax = None

    for i in range(6):
        
        inputfile = glob('{}*P{}*allz2*.dat'.format(inputprefix,plist[i]))[0]
        print inputfile
        if binned:
            fitsname = glob('{}*P{}*.ms*fits'.format(inputprefix,plist[i]))[0]
            print fitsname
            binhead = pyfits.open(fitsname)[0].header
        else:
            binhead = False
            
        MLWA, MLWZ, TAUV, SNR = np.loadtxt(inputfile, usecols=(62,64,66,67),
                                           unpack=True)

        MLWZ = np.log10(MLWZ)
        ageax, tmpz, tmpage, tmperr, tmpstd = GPP.plot_rows(MLWA, 
                                                            binheader=binhead,
                                                            weights=SNR,
                                                            ax=ageax,
                                                            label='{}'.\
                                                            format(rlist[i]),
                                                            fullout=True,
                                                            kpc_scale=kpc_scale,
                                                            zcorr=zcorrlist[i],
                                                            err=err, 
                                                            marker=symblist[i], 
                                                            linestyle='',
                                                            color=colorlist[i])

        AVax, _, tmpAV, tmpAVerr, tmpAVstd = GPP.plot_rows(TAUV*1.086,
                                                           binheader = binhead,
                                                           weights=SNR,
                                                           ax=AVax,
                                                           label='{}'.\
                                                           format(rlist[i]),
                                                           fullout=True,
                                                           kpc_scale=kpc_scale,
                                                           zcorr=zcorrlist[i],
                                                           err=err,
                                                           marker=symblist[i],
                                                           linestyle='',
                                                           color=colorlist[i])

        Zax, _, tmpZ, tmpZerr, tmpZstd = GPP.plot_rows(MLWZ, 
                                                       binheader = binhead,
                                                       weights=SNR,
                                                       ax=Zax,
                                                       label='{}'.\
                                                       format(rlist[i]),
                                                       fullout=True,
                                                       kpc_scale=kpc_scale,
                                                       zcorr=zcorrlist[i],
                                                       err=err,
                                                       marker=symblist[i],
                                                       linestyle='',
                                                       color=colorlist[i])
        
        
        f.write('\n# P{} '.format(plist[i])+92*'#'+'\n# r ~ {} kpc\n'.\
                format(rlist[i]))
        for i in range(tmpz.size):
            f.write('{:6}{:13.3f}{:13.3f}{:13.3f}{:13.3f}{:13.3f}{:13.3f}{:13.3f}{:13.3f}{:13.3f}{:13.3f}\n'.\
                    format('',tmpz[i],tmpage[i],tmperr[i],tmpstd[i],
                           tmpAV[i],tmpAVerr[i],tmpAVstd[i],
                           tmpZ[i],tmpZerr[i],tmpZstd[i]))
        
        try:
            z = np.vstack((z,tmpz))
            age = np.vstack((age,tmpage))
            err = np.vstack((err,tmperr))
            std = np.vstack((std,tmpstd))
            AV = np.vstack((AV,tmpAV))
            AVstd = np.vstack((AVstd,tmpAVstd))
            AVerr = np.vstack((AVerr,tmpAVerr))
            Z = np.vstack((Z,tmpZ))
            Zerr = np.vstack((Zerr,tmpZerr))
            Zstd = np.vstack((Zstd,tmpZstd))
        except UnboundLocalError:
            z = tmpz
            age = tmpage
            err = tmperr
            std = tmpstd
            AV = tmpAV
            AVstd = tmpAVstd
            AVerr = tmpAVerr
            Z = tmpZ
            Zerr = tmpZerr
            Zstd = tmpZstd

    bigz = np.nanmean(z,axis=0)
    bigage = np.nanmean(age,axis=0)
    bigerr = np.sqrt(
        np.nansum(err*(age - bigage)**2,axis=0)/
        ((err.shape[0] - 1.)/(err.shape[0]) * np.nansum(err,axis=0)))
    bigAV = np.nanmean(AV,axis=0)
    bigAVerr = np.sqrt(
        np.nansum(AVerr*(AV - bigAV)**2,axis=0)/
        ((AVerr.shape[0] - 1.)/(AVerr.shape[0]) * np.nansum(AVerr,axis=0)))
    bigZ = np.nanmean(Z,axis=0)
    bigZerr = np.sqrt(
        np.nansum(Zerr*(Z - bigZ)**2,axis=0)/
        ((Zerr.shape[0] - 1.)/(Zerr.shape[0]) * np.nansum(Zerr,axis=0)))

    with open('{}_means.dat'.format(datname.split('.dat')[0]),'w') as fm:
        fm.write(str('#{:>9}'+'{:>10}'*6+'\n').format('height',
                                                      'MLWA',
                                                      'MLWA err',
                                                      'Av',
                                                      'Av err',
                                                      'Z',
                                                      'Z err'))

        for i in range(bigz.size):
              fm.write('{:10.4f}{:10.4f}{:10.4f}{:10.4f}{:10.4f}{:10.4f}{:10.4f}\n'.\
                       format(bigz[i],bigage[i],bigerr[i],bigAV[i],bigAVerr[i],bigZ[i],bigZerr[i]))

    ageax.plot(bigz, bigage)
    ageax.fill_between(bigz,bigage-bigerr,bigage+bigerr,alpha=0.1)
    ageax.legend(loc=1,title='radius [kpc]',scatterpoints=1,numpoints=1,frameon=False)
    ageax.set_xlim(-0.6,2.6)
    ageax.set_ylim(0,13)
    ageax.set_ylabel('Light-weighted age [Gyr]')
    ageax.set_title('Generated on {}'.format(time.asctime()))

    AVax.plot(bigz,bigAV)
    AVax.fill_between(bigz,bigAV-bigAVerr,bigAV+bigAVerr,alpha=0.1)
    AVax.legend(loc=1,title='radius [kpc]',scatterpoints=1,numpoints=1,frameon=False)
    AVax.set_xlim(-0.6,2.6)
    AVax.set_ylim(0,6)
    AVax.set_ylabel(r'$A_V$')

    Zax.plot(bigz,bigZ)
    Zax.fill_between(bigz, bigZ-bigZerr, bigZ+bigZerr,alpha=0.1)
    Zax.legend(loc=1,title='radius [kpc]',scatterpoints=1,
               numpoints=1,frameon=False)
    Zax.set_xlim(-0.6,2.6)
#    Zax.set_ylim(-1.5,3.0)
    Zax.set_ylabel(r'Log( MLWZ [$Z_{\odot}$] )')

    pp.savefig(ageax.figure)
    pp.savefig(AVax.figure)
    pp.savefig(Zax.figure)
    plt.close(ageax.figure)
    plt.close(AVax.figure)
    plt.close(Zax.figure)

    pp.close()
    f.close()

    return
コード例 #4
0
ファイル: GradPak_bin.py プロジェクト: eigenbrot/GradPak
def create_locations(binfile, galcenter=[35.637962,42.347629], 
                     ifucenter=[35.637962,42.347629], reffiber=105,
                     galpa=293.3, ifupa=295.787, kpc_scale=0.0485):
    """Given a binned data file, creat a list of bin locations, relative to a galactic center.

    The function is designed to give physical meaning to the location of each
    bin created by :func:`bin`. For each bin found in the FITS header it
    computes physical coordinates in both arcsec and kpc. This method was
    written with a 2D projection of cylindrical coordinates in mind (r,z), but
    the user is free to fully define the location and meaning of the
    coordinate system through keyword options.

    The output is a text file containig the location of each bin in the
    desired coordinate system.

    The current defaults are for NGC 891 and WIYN proposal 14B-0456. You
    should probably change them.

    Parameters
    ----------
    
    binfile : str
        The name of a FITS file produced by :func:`bin`
    
    galcenter : list, optional
        A list containing the [RA,DEC] coordinates of the center of the
        coordinate system. The units are decimal degrees.

    ifucenter : list, optional 
        A list containing the center of the fiber specified in
        **reffiber**. Units are decimal degrees. This is usually the
        coordinates of your GradPak pointing.

    reffiber : int, optional
        The *fiber* number whoes coordinates are given in **ifucenter**. This
        is generally the fiber you used to align GradPak during observations.

    galpa : float, optional
        The position angle of the desired coordinate system. This angle
        defines rotation of the horizontal axis relative to the sky.
    
    ifupa : float, optional 
        The position angle of GradPak. This is defined as an absolute PA,
        relative to North, *not* to the defined coordinate system. This is
        generally the PA you entered during GradPak observations.
    
    kpc_scale : float, optional
        kpc/arcsec of the object in question

    Returns
    -------

    None :
        The result is file with the suffix "locations.dat" that contains
        information about the location in the user defined coordinates of each
        aperture (bin). Coordinates are given in arcsec and kpc. Note that the
        reported "size" is the size of the fibers that went into each bin, not
        the size of the bin itself. This is admittedly confusing.

    """

    hdu = pyfits.open(binfile)[0]
    numaps = hdu.data.shape[0]
    binhead = hdu.header
    
    patches = GPP.get_binned_patches(binhead)
    refpatches = GPP.GradPak_patches()
    
    patches, refpatches = GPP.transform_patches(patches,refpatches=refpatches,
                                                pa=ifupa, center=ifucenter, 
                                                reffiber=reffiber)

    decrad = galcenter[1]*2*np.pi/360.
    parad = galpa*2*np.pi/360.
    
    f = open('{}_locations.dat'.format(binfile.split('.ms.fits')[0]),'w')
    f.write("""# Generated on {}
# Inpute file: {}
#
""".format(time.asctime(),binfile))
    f.write('# {:4}{:>10}{:>10}{:>10}{:>10}{:>10}\n#\n'.format('Apnum',
                                                              'size (")',
                                                              'r (")',
                                                              'z (")',
                                                              'r (kpc)',
                                                              'z (kpc)'))

    for i, p in enumerate(patches[:,1]):
    
        fibers = binhead['BIN{:03}F'.format(i+1)]
        radius = refpatches[int(fibers.split(' ')[0]) - 1][1].get_radius()

        ra_diff = 3600*(galcenter[0] - p.center[0])*np.cos(decrad)
        dec_diff = 3600*(galcenter[1] - p.center[1])

        r_diff = ra_diff*np.cos(parad) - dec_diff*np.sin(parad)
        z_diff = -1*(ra_diff*np.sin(parad) + dec_diff*np.cos(parad))

        print i+1, p.center, ra_diff, dec_diff, r_diff, z_diff

        f.write(str('{:7n}'+5*'{:10.3f}'+'\n').format(i,
                                                             radius,
                                                             r_diff,
                                                             z_diff,
                                                             r_diff*kpc_scale,
                                                             z_diff*kpc_scale))
    f.close()
    return
コード例 #5
0
ファイル: plot_simple.py プロジェクト: eigenbrot/snakes
def all_heights(output, inputprefix="NGC_891", err=True, binned=False, reg=True):

    datname = output.split(".pdf")[0] + ".dat"
    f = open(datname, "w")
    f.write(
        "#{:5}{:>13}{:>13}{:>13}{:>13}{:>13}{:>13}{:>13}{:>13}{:>13}{:>13}\n#\n".format(
            "",
            "height [kpc]",
            "age [Gyr]",
            "age eom",
            "age stderr",
            "AV",
            "AV eom",
            "AV stderr",
            "Z/Z_sol",
            "Z eom",
            "Z stderr",
        )
    )

    pp = PDF(output)
    symblist = ["o", "^", "v", "s", "*", "x"]
    colorlist = ["b", "c", "g", "y", "m", "r"]
    kpc_scale = 0.0485
    plist = [6, 3, 4, 2, 1, 5]
    rlist = [-10.0, -6.4, -2.3, 0.8, 4.4, 8.1]
    #    rlist = [4.4,0.8,-6.4,-2.3,8.1,-10.0]

    ax = None
    AVax = None
    metalax = None
    if reg:
        psi0ax = None
        tausfax = None
        invtausfax = None
        tformax = None
        massax = None
    for i in range(6):

        inputfile = glob("{}*P{}*fit.dat".format(inputprefix, plist[i]))[0]
        print inputfile
        if binned:
            fitsname = glob("{}*P{}*ms*fits".format(inputprefix, plist[i]))[0]
            print fitsname
            binhead = pyfits.open(fitsname)[0].header
        else:
            binhead = False
        if reg:
            MMWA, MLWA, TAUV, SNR, Z, PSI0, TAUSF, TFORM = np.loadtxt(
                inputfile, usecols=(11, 12, 13, 14, 17, 18, 19, 20), unpack=True
            )

            mdata = np.loadtxt(inputfile)
            MASS = np.sum(mdata[:, 1:11], axis=1)
        else:
            MMWA, MLWA, TAUV, SNR, Z = np.loadtxt(inputfile, usecols=(11, 12, 13, 14, 19), unpack=True)

        Z = np.log10(Z)
        ax, tmpz, tmpage, tmperr, tmpstd = GPP.plot_rows(
            MLWA,
            binheader=binhead,
            weights=SNR,
            ax=ax,
            label="{}".format(rlist[i]),
            fullout=True,
            kpc_scale=kpc_scale,
            err=err,
            marker=symblist[i],
            linestyle="",
            color=colorlist[i],
        )
        AVax, _, tmpAV, tmpAVerr, tmpAVstd = GPP.plot_rows(
            TAUV * 1.086,
            binheader=binhead,
            weights=SNR,
            ax=AVax,
            label="{}".format(rlist[i]),
            fullout=True,
            kpc_scale=kpc_scale,
            err=err,
            marker=symblist[i],
            linestyle="",
            color=colorlist[i],
        )

        metalax, _, tmpmetal, tmpmetalerr, tmpmetalstd = GPP.plot_rows(
            Z,
            binheader=binhead,
            weights=SNR,
            ax=metalax,
            label="{}".format(rlist[i]),
            fullout=True,
            kpc_scale=kpc_scale,
            err=err,
            marker=symblist[i],
            linestyle="",
            color=colorlist[i],
        )

        if reg:
            psi0ax, _, tmppsi0, tmppsi0err, tmppsi0std = GPP.plot_rows(
                np.log10(PSI0),
                binheader=binhead,
                weights=SNR,
                ax=psi0ax,
                label="{}".format(rlist[i]),
                fullout=True,
                kpc_scale=kpc_scale,
                err=err,
                marker=symblist[i],
                linestyle="",
                color=colorlist[i],
            )

            tausfax, _, tmptausf, tmptausferr, tmptausfstd = GPP.plot_rows(
                TAUSF,
                binheader=binhead,
                weights=SNR,
                ax=tausfax,
                label="{}".format(rlist[i]),
                fullout=True,
                kpc_scale=kpc_scale,
                err=err,
                marker=symblist[i],
                linestyle="",
                color=colorlist[i],
            )

            invtausfax, _, tmpinvtausf, tmpinvtausferr, tmpinvtausfstd = GPP.plot_rows(
                1.0 / TAUSF,
                binheader=binhead,
                weights=SNR,
                ax=invtausfax,
                label="{}".format(rlist[i]),
                fullout=True,
                kpc_scale=kpc_scale,
                err=err,
                marker=symblist[i],
                linestyle="",
                color=colorlist[i],
            )

            tformax, _, tmptform, tmptformerr, tmptformstd = GPP.plot_rows(
                TFORM,
                binheader=binhead,
                weights=SNR,
                ax=tformax,
                label="{}".format(rlist[i]),
                fullout=True,
                kpc_scale=kpc_scale,
                err=err,
                marker=symblist[i],
                linestyle="",
                color=colorlist[i],
            )

            massax, _, tmpmass, tmpmasserr, tmpmassstd = GPP.plot_rows(
                np.log10(MASS),
                binheader=binhead,
                weights=SNR,
                ax=massax,
                label="{}".format(rlist[i]),
                fullout=True,
                kpc_scale=kpc_scale,
                err=err,
                marker=symblist[i],
                linestyle="",
                color=colorlist[i],
            )

        f.write("\n# P{} ".format(i + 1) + 92 * "#" + "\n# r ~ {} kpc\n".format(rlist[i]))
        for i in range(tmpz.size):
            f.write(
                "{:6}{:13.3f}{:13.3f}{:13.3f}{:13.3f}{:13.3f}{:13.3f}{:13.3f}{:13.3f}{:13.3f}{:13.3f}\n".format(
                    "",
                    tmpz[i],
                    tmpage[i],
                    tmperr[i],
                    tmpstd[i],
                    tmpAV[i],
                    tmpAVerr[i],
                    tmpAVstd[i],
                    tmpmetal[i],
                    tmpmetalerr[i],
                    tmpmetalstd[i],
                )
            )

        try:
            z = np.vstack((z, tmpz))
            age = np.vstack((age, tmpage))
            err = np.vstack((err, tmperr))
            std = np.vstack((std, tmpstd))
            AV = np.vstack((AV, tmpAV))
            AVstd = np.vstack((AVstd, tmpAVstd))
            AVerr = np.vstack((AVerr, tmpAVerr))
            metal = np.vstack((metal, tmpmetal))
            metalerr = np.vstack((metalerr, tmpmetalerr))
            metalstd = np.vstack((metalstd, tmpmetalstd))
            if reg:
                psi0 = np.vstack((psi0, tmppsi0))
                psi0err = np.vstack((psi0err, tmppsi0err))
                psi0std = np.vstack((psi0std, tmppsi0std))
                tausf = np.vstack((tausf, tmptausf))
                tausferr = np.vstack((tausferr, tmptausferr))
                tausfstd = np.vstack((tausfstd, tmptausfstd))
                invtausf = np.vstack((invtausf, tmpinvtausf))
                invtausferr = np.vstack((invtausferr, tmpinvtausferr))
                invtausfstd = np.vstack((invtausfstd, tmpinvtausfstd))
                tform = np.vstack((tform, tmptform))
                tformerr = np.vstack((tformerr, tmptformerr))
                tformstd = np.vstack((tformstd, tmptformstd))
                mass = np.vstack((mass, tmpmass))
                masserr = np.vstack((masserr, tmpmasserr))
                massstd = np.vstack((massstd, tmpmassstd))
        except UnboundLocalError:
            z = tmpz
            age = tmpage
            err = tmperr
            std = tmpstd
            AV = tmpAV
            AVstd = tmpAVstd
            AVerr = tmpAVerr
            metal = tmpmetal
            metalerr = tmpmetalerr
            metalstd = tmpmetalstd
            if reg:
                psi0 = tmppsi0
                psi0err = tmppsi0err
                psi0std = tmppsi0std
                tausf = tmptausf
                tausferr = tmptausferr
                tausfstd = tmptausfstd
                invtausf = tmpinvtausf
                invtausferr = tmpinvtausferr
                invtausfstd = tmpinvtausfstd
                tform = tmptform
                tformerr = tmptformerr
                tformstd = tmptformstd
                mass = tmpmass
                masserr = tmpmasserr
                massstd = tmpmassstd

    bigz = np.nanmean(z, axis=0)
    bigage = np.nanmean(age, axis=0)
    bigerr = np.sqrt(
        np.nansum(err * (age - bigage) ** 2, axis=0) / ((err.shape[0] - 1.0) / (err.shape[0]) * np.nansum(err, axis=0))
    )
    bigAV = np.nanmean(AV, axis=0)
    bigAVerr = np.sqrt(
        np.nansum(AVerr * (AV - bigAV) ** 2, axis=0)
        / ((AVerr.shape[0] - 1.0) / (AVerr.shape[0]) * np.nansum(AVerr, axis=0))
    )
    bigmetal = np.nanmean(metal, axis=0)
    bigmetalerr = np.sqrt(
        np.nansum(metalerr * (metal - bigmetal) ** 2, axis=0)
        / ((metalerr.shape[0] - 1.0) / (metalerr.shape[0]) * np.nansum(metalerr, axis=0))
    )

    if reg:
        bigpsi0 = np.nanmean(psi0, axis=0)
        bigpsi0err = np.sqrt(
            np.abs(
                np.nansum(psi0err * (psi0 - bigpsi0) ** 2, axis=0)
                / ((psi0err.shape[0] - 1.0) / (psi0err.shape[0]) * np.nansum(psi0err, axis=0))
            )
        )
        bigtausf = np.nanmean(tausf, axis=0)
        bigtausferr = np.sqrt(
            np.nansum(tausferr * (tausf - bigtausf) ** 2, axis=0)
            / ((tausferr.shape[0] - 1.0) / (tausferr.shape[0]) * np.nansum(tausferr, axis=0))
        )
        biginvtausf = np.nanmean(invtausf, axis=0)
        biginvtausferr = np.sqrt(
            np.nansum(invtausferr * (invtausf - biginvtausf) ** 2, axis=0)
            / ((invtausferr.shape[0] - 1.0) / (invtausferr.shape[0]) * np.nansum(invtausferr, axis=0))
        )
        bigtform = np.nanmean(tform, axis=0)
        bigtformerr = np.sqrt(
            np.nansum(tformerr * (tform - bigtform) ** 2, axis=0)
            / ((tformerr.shape[0] - 1.0) / (tformerr.shape[0]) * np.nansum(tformerr, axis=0))
        )
        bigmass = np.nanmean(mass, axis=0)
        bigmasserr = np.sqrt(
            np.nansum(masserr * (mass - bigmass) ** 2, axis=0)
            / ((masserr.shape[0] - 1.0) / (masserr.shape[0]) * np.nansum(masserr, axis=0))
        )

    with open("{}_means.dat".format(datname.split(".dat")[0]), "w") as fm:
        fm.write(str("#{:>9}" + "{:>10}" * 6 + "\n").format("height", "MLWA", "MLWA err", "Av", "Av err", "Z", "Z err"))

        for i in range(bigz.size):
            fm.write(
                "{:10.4f}{:10.4f}{:10.4f}{:10.4f}{:10.4f}{:10.4f}{:10.4f}\n".format(
                    bigz[i], bigage[i], bigerr[i], bigAV[i], bigAVerr[i], bigmetal[i], bigmetalerr[i]
                )
            )

    ax.plot(bigz, bigage)
    ax.fill_between(bigz, bigage - bigerr, bigage + bigerr, alpha=0.1)
    ax.legend(loc=1, title="radius [kpc]", scatterpoints=1, numpoints=1, frameon=False)
    ax.set_xlim(-0.1, 2.6)
    ax.set_ylim(-2, 10)
    ax.set_ylabel("Light-weighted age [Gyr]")
    ax.set_title("Generated on {}".format(time.asctime()))

    AVax.plot(bigz, bigAV)
    AVax.fill_between(bigz, bigAV - bigAVerr, bigAV + bigAVerr, alpha=0.1)
    AVax.legend(loc=1, title="radius [kpc]", scatterpoints=1, numpoints=1, frameon=False)
    AVax.set_xlim(-0.1, 2.6)
    AVax.set_ylim(0, 6)
    AVax.set_ylabel(r"$A_V$")
    # plotz = np.linspace(0,2.5,20)
    # for t in range(len(rlist)):
    #     modelAv = mA.A_vec(np.abs(rlist[t]),plotz,zd=1.0,tau0=0.85,hd=7.68)
    #     AVax.plot(plotz,modelAv,color=colorlist[t])

    metalax.plot(bigz, bigmetal)
    metalax.fill_between(bigz, bigmetal - bigmetalerr, bigmetal + bigmetalerr, alpha=0.1)
    metalax.legend(loc=1, title="radius [kpc]", scatterpoints=1, numpoints=1, frameon=False)
    metalax.set_xlim(-0.1, 2.6)
    #    metalax.set_ylim(-1.5,3.0)
    metalax.set_ylabel(r"Log( $Z/Z_{\odot}$ )")

    if reg:
        psi0ax.plot(bigz, bigpsi0)
        psi0ax.fill_between(bigz, bigpsi0 - bigpsi0err, bigpsi0 + bigpsi0err, alpha=0.1)
        psi0ax.legend(loc=1, title="radius [kpc]", scatterpoints=1, numpoints=1, frameon=False)
        psi0ax.set_xlim(-0.1, 2.6)
        psi0ax.set_ylabel(r"Log($\psi_0$)")

        tausfax.plot(bigz, bigtausf)
        tausfax.fill_between(bigz, bigtausf - bigtausferr, bigtausf + bigtausferr, alpha=0.1)
        tausfax.legend(loc=1, title="radius [kpc]", scatterpoints=1, numpoints=1, frameon=False)
        tausfax.set_ylim(-1, 5)
        tausfax.set_xlim(-0.1, 2.6)
        tausfax.set_ylabel(r"$\tau_{\mathrm{sf}}$")

        invtausfax.plot(bigz, biginvtausf)
        invtausfax.fill_between(bigz, biginvtausf - biginvtausferr, biginvtausf + biginvtausferr, alpha=0.1)
        invtausfax.legend(loc=1, title="radius [kpc]", scatterpoints=1, numpoints=1, frameon=False)
        invtausfax.set_ylim(-1, 5)
        invtausfax.set_xlim(-0.1, 2.6)
        invtausfax.set_ylabel(r"$1/\tau_{\mathrm{sf}}$")

        tformax.plot(bigz, bigtform)
        tformax.fill_between(bigz, bigtform - bigtformerr, bigtform + bigtformerr, alpha=0.1)
        tformax.legend(loc=1, title="radius [kpc]", scatterpoints=1, numpoints=1, frameon=False)
        tformax.set_xlim(-0.1, 2.6)
        tformax.set_ylabel(r"$t_{\mathrm{form}}$")

        massax.plot(bigz, bigmass)
        massax.fill_between(bigz, bigmass - bigmasserr, bigmass + bigmasserr, alpha=0.1)
        massax.legend(loc=1, title="radius [kpc]", scatterpoints=1, numpoints=1, frameon=False)
        massax.set_xlim(-0.1, 2.6)
        massax.set_ylabel(r"Log($M_{\mathrm{total}}$)")

    pp.savefig(ax.figure)
    pp.savefig(AVax.figure)
    pp.savefig(metalax.figure)
    plt.close(ax.figure)
    plt.close(AVax.figure)
    plt.close(metalax.figure)

    if reg:
        pp.savefig(psi0ax.figure)
        pp.savefig(tausfax.figure)
        pp.savefig(tformax.figure)
        pp.savefig(invtausfax.figure)
        pp.savefig(massax.figure)
        plt.close(psi0ax.figure)
        plt.close(tausfax.figure)
        plt.close(invtausfax.figure)
        plt.close(tformax.figure)
        plt.close(massax.figure)

    pp.close()
    f.close()

    return
コード例 #6
0
ファイル: plot_simple.py プロジェクト: eigenbrot/snakes
def all_maps(
    output,
    col=12,
    inputprefix="NGC_891",
    inputsuffix="fit.dat",
    labelfibers=False,
    label="Mean Light Weighted Age [Gyr]",
    log=False,
    plotbins=False,
    minval=None,
    maxval=None,
    exclude=None,
    binned=False,
    cmap="gnuplot2",
):

    pp = PDF(output)
    centers = [
        [35.603413, 42.323494],
        [35.615154, 42.3426],
        [35.636325, 42.37935],
        [35.625617, 42.35935],
        [35.591642, 42.304247],
        [35.648196, 42.401217],
    ]

    ax = None
    if exclude is None:
        exclude = [[], [], [], [], [], []]
    figlist = []
    for i in range(6):
        print i
        try:
            inputfile = glob("{}*P{}*{}".format(inputprefix, i + 1, inputsuffix))[0]
        except IndexError:
            print "Could not find P{} data, skipping".format(i + 1)
            continue

        print inputfile

        if binned:
            fitsname = glob("{}*P{}*ms*fits".format(inputprefix, i + 1))[0]
            print fitsname
            binhead = pyfits.open(fitsname)[0].header
        else:
            binhead = None

        data = np.loadtxt(inputfile, usecols=(col,), unpack=True)
        if col == 12:
            label = "Mean Light Weighted Age [Gyr]"
            minval = 0
            maxval = 13  # np.nanmax(data)
        elif col == 11:
            label = "Mean Mass Weighted Age [Gyr]"
            minval = 0  # np.nanmin(data)#7
            maxval = 10  # np.nanmax(data)#10
        elif col == 13:
            label = "$A_V$"
            data *= 1.086
            minval = 0
            maxval = 6
        elif col == 19:
            data = np.log10(data)
            label = r"Log( Metallicity [$Z_{\odot}$] )"
            # cmap = mplcolors.ListedColormap(['black','blue','green','yellow','red','white'])
            # norm = mplcolors.BoundaryNorm([0,0.005,0.02,0.2,0.4,1,2.5], cmap.N)
            minval = -4
            maxval = 1
        elif col == 65:
            data *= 1.086

        if log:
            data = np.log10(data)
            if i == 0:
                label = "Log( {} )".format(label)
        print "excluding", exclude[i]
        ax = GPP.plot(
            data,
            ax=ax,
            binheader=binhead,
            plotbins=plotbins,
            figsize=(8, 4),
            fitsfile="/d/monk/eigenbrot/WIYN/14B-0456/NGC_891.fits",
            wcsax=False,
            imrot=67,  # 64.213,
            pa=295.787,
            center=centers[i],
            clabel=label,
            cmap=cmap,
            labelfibers=labelfibers,
            exclude=exclude[i],
            sky=False,
            minval=minval,
            maxval=maxval,
            alpha=1,
        )

        # Do it again, for the single-pointing figure
        sax = GPP.plot(
            data,
            ax=None,
            binheader=binhead,
            plotbins=plotbins,
            figsize=(8, 4),
            fitsfile="/d/monk/eigenbrot/WIYN/14B-0456/NGC_891.fits",
            wcsax=False,
            imrot=67,  # 64.213,
            pa=295.787,
            center=centers[i],
            clabel=label,
            cmap=cmap,
            labelfibers=labelfibers,
            exclude=exclude[i],
            sky=False,
            minval=minval,
            maxval=maxval,
            alpha=1,
        )
        sax.text(
            0.5, 0.8, "P{}".format(i + 1), color="r", fontsize=20, transform=sax.transAxes, ha="center", va="center"
        )
        figlist.append(sax.figure)

    ax.set_xlim(160, 755)
    ax.set_ylim(350, 600)
    header = pyfits.open("/d/monk/eigenbrot/WIYN/14B-0456/NGC_891.fits")[0].header
    hw = pywcs.WCS(header)
    centpx = hw.wcs_sky2pix([[35.63689, 42.34633]], 0)[0]
    xticks = np.arange(-300, 301, 100) / (header["CDELT1"] * 3600.0) + centpx[0]
    yticks = np.arange(-100, 201, 100) / (header["CDELT2"] * 3600.0) + centpx[1]
    ax.set_xticks(xticks)
    ax.set_yticks(yticks)
    xlabs = ["{:3.0f}".format((centpx[0] - i) * header["CDELT1"] * 3600.0) for i in ax.get_xticks()]
    ylabs = ["{:3.0f}".format((i - centpx[1]) * header["CDELT2"] * 3600.0) for i in ax.get_yticks()]
    ax.set_xticklabels(xlabs)
    ax.set_yticklabels(ylabs)
    ax.set_xlabel("arcsec")
    ax.set_ylabel("arcsec")
    pp.savefig(ax.figure)
    for f in figlist:
        pp.savefig(f)
    pp.close()
    plt.close("all")
    return ax
コード例 #7
0
def bin(datafile, errfile, SNR, outputfile, waverange=None, exclude=[], 
        logfile=None, logfits=None):
    """Bin GradPak fibers along a row until the desired SNR is achieved.

    The way fibers are grouped together is somewhat simplistic, but the
    underlying mathematics is correct. 

    The first bin starts at the smallest non-sky, non-excluded fiber (usually
    fiber #3) and just keeps adding the next fiber until the desire SNR is
    reached. Fibers are not binned across rows, which ensures that each bin is
    made up only of fibers of one size, but also limits the amount of binning
    that can be done. The major limitation of this method is that the ends of
    rows can often be left with a single, low SNR fiber. For example, if a bin
    is constructed containing fibers 14-16 and fiber 17 (at the end of the
    row) is below the threshold it will not be added to the previous bin and
    instead will make up a single bin with low a low SNR. This should be easy
    to fix but in practice it doesn't cause that much of an issue so I just
    haven't done it.

    The spectrum for each bin is an average of all the contributing fibers,
    weighted by each individual's SNR^2. The corresponding error bin is a sum
    in quadrature, weighted in the same way.

    The history of each bin is recorded in the output FITS header using two keywords:

     **BINXXXF** The fibers that went into bin XXX

     **BINXXXP** The position (in arcsec) of the center of bin XXX. This is
       the *unweighted* average of the centers of the contributing fibers.

    Parameters
    ----------

    datafile : str
        The name of a multispec FITS file that you want to bin

    errfile : str
        The name of a multispec FITS file containing error vectors corresponding to the datafile

    SNR : float
        The minimum SNR in each bin

    outputfile : str 
        The base name of the binned spectral and error arrays. The results
        will be called OUTPUTFILE.ms.fits and OUTPUTFILE.me.fits.

    waverange : list (default: None)
        A 2 element list containing the minimum and maximum wavelengths
        to consider *for the SNR calculations*. Regardless of this parameter
        the final output will span the same wavelength range as the input
        files.
    
    exclude : list (default: [])
        A list containing fibers to exlcude from binning. Sky fibers are
        automatically excluded and fiber numbers start at 1.

    logfile : str
        Name of a log file that will contain, for each aperture, a
        list of the individual fibers and the total S/N.

    logfits : str
        Name of a FITS file that will contain a separate HDU for each
        aperture. Each HDU will contain an array with two dimensions
        that records the fiber numbers and associated weights for that
        aperture.
        
    Returns
    -------
    
    finalf : numpy.ndarray
        Array with shape NBINS x NWAVE containing the binned data

    finatle : numpy.ndarray
        Array with same shape as finalf containing the errors on the binned data

    fibdict : dict
        Dictionary of questionable usefulness that contains information about
        which fibers went into each bin. The keys are ROW_BIN and the entries
        are a list of the fibers that went into that bin (e.g., '1_2' for the
        second bin in the first row).

    """
    hdu = pyfits.open(datafile)[0]
    data = hdu.data
    err = pyfits.open(errfile)[0].data

    if waverange is not None:
        wave = (np.arange(data.shape[1]) + hdu.header['CRPIX1'] - 1)\
               *hdu.header['CDELT1'] + hdu.header['CRVAL1']
        waveidx = np.where((wave >= waverange[0]) & (wave <= waverange[1]))[0]
    else:
        waveidx = None

    data *= 1e17
    err *= 1e17

    y_values = np.array([c.center[1] for c in GPP.GradPak_patches()[:,1]])
    x_values = np.array([c.center[0] for c in GPP.GradPak_patches()[:,1]])
    fibnums = np.arange(109) + 1
    row_pos = np.unique(y_values)

    finalf = np.zeros(data.shape[1])
    finale = np.zeros(data.shape[1])

    fibdict = {}
    binnum = 1

    if logfile is not None:
        lf = open(logfile,'w')
        
    if logfits is not None:
        log_HDUs = [] #This will hold [fiber_list, weight_list] for each aperture
        
    for i in range(row_pos.size):

        if row_pos[i] > 80:
            continue

        idx = np.where(y_values == row_pos[i])[0]
        b = 0
        n = 0

        while fibnums[idx[n]] in exclude:
            print 'Skipping fiber {}'.format(fibnums[idx[n]])
            n += 1

        while n < len(idx):
            try:
                while fibnums[idx[n]] in exclude:
                    print 'Skipping fiber {}'.format(fibnums[idx[n]])
                    n += 1
            except IndexError: #The rest of the fibers in the row are excluded
                break

            fstack = data[idx[n]][None,:]
            estack = err[idx[n]][None,:]
            tmp = compute_SN(data[idx[n]], err[idx[n]], waveidx)
            snstack = np.array([[tmp]])
            fibers = [fibnums[idx[n]]]
            xpos = [x_values[idx[n]]]
            ypos = [y_values[idx[n]]]

            while tmp < SNR:
                n += 1
                print 'fibers: {}, SNR: {}'.format(fibers, tmp)
                if n > len(idx) - 1:
                    print "WARNING, SN threshold not met in row {}, bin {}".\
                        format(i,b)
                    break

                if fibnums[idx[n]] in exclude:
                    print 'Skipping fiber {}'.format(fibnums[idx[n]])
                    continue
                    
                fstack = np.vstack((fstack, data[idx[n]]))
                estack = np.vstack((estack, err[idx[n]]))
                snstack = np.vstack((snstack, compute_SN(data[idx[n]], 
                                                         err[idx[n]], 
                                                         waveidx)))
                tmpf, tmpe = create_bin(fstack, estack, snstack)
                tmp = compute_SN(tmpf, tmpe, waveidx)
                fibers.append(fibnums[idx[n]])
                xpos.append(x_values[idx[n]])
                ypos.append(y_values[idx[n]])

            binf, bine = create_bin(fstack, estack, snstack)
            binsn = compute_SN(binf, bine, waveidx)
            print 'binned aperture {}: {}, SNR: {}'.format(binnum,fibers, binsn)
            if logfile is not None:
                lf.write('binned aperture {}: {}, SNR: {}\n'.format(binnum,fibers, binsn))
            if logfits is not None:
                log_HDUs.append(pyfits.ImageHDU(np.vstack([fibers, snstack.T[0]])))

            bin_x_pos = np.mean(xpos)
            bin_y_pos = np.mean(ypos)
            fibstr = [str(i) for i in fibers]
            hdu.header.update('BIN{:03}F'.format(binnum),' '.join(fibstr))
            hdu.header.update('BIN{:03}P'.format(binnum),' '.\
                              join([str(bin_x_pos),str(bin_y_pos)]))

            finalf = np.vstack((finalf,binf))
            finale = np.vstack((finale,bine))
            fibdict['{}_{}'.format(i,b)] = fibers
            b += 1
            n += 1
            binnum += 1

    finalf = finalf[1:]/1e17
    finale = finale[1:]/1e17
    pyfits.PrimaryHDU(finalf, hdu.header).\
        writeto('{}.ms.fits'.format(outputfile),clobber=True)
    pyfits.PrimaryHDU(finale, hdu.header).\
        writeto('{}.me.fits'.format(outputfile),clobber=True)

    if logfits is not None:
        lP = pyfits.PrimaryHDU()
        lP.header.update('HDUDIM','APERTURE')
        lP.header.update('AXIS1','FIBERS')
        lP.header.update('AXIS2','0: FIBER NUMBER 1: WEIGHT')
        pyfits.HDUList([lP] + log_HDUs).writeto(logfits, clobber=True)
        
    return finalf, finale, fibdict
コード例 #8
0
def create_locations(binfile, galcenter=[35.637962,42.347629], 
                     ifucenter=[35.637962,42.347629], reffiber=105,
                     galpa=293.3, ifupa=295.787, kpc_scale=0.0485):
    """Given a binned data file, creat a list of bin locations, relative to a galactic center.

    The function is designed to give physical meaning to the location of each
    bin created by :func:`bin`. For each bin found in the FITS header it
    computes physical coordinates in both arcsec and kpc. This method was
    written with a 2D projection of cylindrical coordinates in mind (r,z), but
    the user is free to fully define the location and meaning of the
    coordinate system through keyword options.

    The output is a text file containig the location of each bin in the
    desired coordinate system.

    The current defaults are for NGC 891 and WIYN proposal 14B-0456. You
    should probably change them.

    Parameters
    ----------
    
    binfile : str
        The name of a FITS file produced by :func:`bin`
    
    galcenter : list, optional
        A list containing the [RA,DEC] coordinates of the center of the
        coordinate system. The units are decimal degrees.

    ifucenter : list, optional 
        A list containing the center of the fiber specified in
        **reffiber**. Units are decimal degrees. This is usually the
        coordinates of your GradPak pointing.

    reffiber : int, optional
        The *fiber* number whoes coordinates are given in **ifucenter**. This
        is generally the fiber you used to align GradPak during observations.

    galpa : float, optional
        The position angle of the desired coordinate system. This angle
        defines rotation of the horizontal axis relative to the sky.
    
    ifupa : float, optional 
        The position angle of GradPak. This is defined as an absolute PA,
        relative to North, *not* to the defined coordinate system. This is
        generally the PA you entered during GradPak observations.
    
    kpc_scale : float, optional
        kpc/arcsec of the object in question

    Returns
    -------

    None :
        The result is file with the suffix "locations.dat" that contains
        information about the location in the user defined coordinates of each
        aperture (bin). Coordinates are given in arcsec and kpc. Note that the
        reported "size" is the size of the fibers that went into each bin, not
        the size of the bin itself. This is admittedly confusing.

    """

    hdu = pyfits.open(binfile)[0]
    numaps = hdu.data.shape[0]
    binhead = hdu.header
    
    patches = GPP.get_binned_patches(binhead)
    refpatches = GPP.GradPak_patches()
    
    patches, refpatches = GPP.transform_patches(patches,refpatches=refpatches,
                                                pa=ifupa, center=ifucenter, 
                                                reffiber=reffiber)

    decrad = galcenter[1]*2*np.pi/360.
    parad = galpa*2*np.pi/360.
    
    f = open('{}_locations.dat'.format(binfile.split('.ms.fits')[0]),'w')
    f.write("""# Generated on {}
# Inpute file: {}
#
""".format(time.asctime(),binfile))
    f.write('# {:4}{:>10}{:>10}{:>10}{:>10}{:>10}\n#\n'.format('Apnum',
                                                              'size (")',
                                                              'r (")',
                                                              'z (")',
                                                              'r (kpc)',
                                                              'z (kpc)'))

    for i, p in enumerate(patches[:,1]):
    
        fibers = binhead['BIN{:03}F'.format(i+1)]
        radius = refpatches[int(fibers.split(' ')[0]) - 1][1].get_radius()

        ra_diff = 3600*(galcenter[0] - p.center[0])*np.cos(decrad)
        dec_diff = 3600*(galcenter[1] - p.center[1])

        r_diff = ra_diff*np.cos(parad) - dec_diff*np.sin(parad)
        z_diff = -1*(ra_diff*np.sin(parad) + dec_diff*np.cos(parad))

        print i+1, p.center, ra_diff, dec_diff, r_diff, z_diff

        f.write(str('{:7n}'+5*'{:10.3f}'+'\n').format(i,
                                                             radius,
                                                             r_diff,
                                                             z_diff,
                                                             r_diff*kpc_scale,
                                                             z_diff*kpc_scale))
    f.close()
    return