Example #1
0
    def view_observed_gsm(self, logged=False, show=False, **kwargs):
        """ View the GSM (Mollweide), with below-horizon area masked. """
        sky = self.observed_sky
        if logged:
            sky = np.log2(sky)

        # Get RA and DEC of zenith
        ra_rad, dec_rad = self.radec_of(0, np.pi / 2)
        ra_deg  = ra_rad / np.pi * 180
        dec_deg = dec_rad / np.pi * 180

        # Apply rotation
        derotate = hp.Rotator(rot=[ra_deg, dec_deg])
        g0, g1 = derotate(self._theta, self._phi)
        pix0 = hp.ang2pix(self._n_side, g0, g1)
        sky = sky[pix0]

        coordrotate = hp.Rotator(coord=['C', 'G'], inv=True)
        g0, g1 = coordrotate(self._theta, self._phi)
        pix0 = hp.ang2pix(self._n_side, g0, g1)
        sky = sky[pix0]

        hp.mollview(sky, coord='G', **kwargs)

        if show:
            plt.show()

        return sky
Example #2
0
    def view(self, idx=0, logged=False):
        """ View generated map using healpy's mollweide projection.

        Parameters
        ----------
        idx: int
            index of map to view. Only required if you generated maps at
            multiple frequencies.
        logged: bool
            Take the log of the data before plotting. Defaults to False.

        """

        if self.generated_map_data is None:
            raise RuntimeError("No GSM map has been generated yet. Run generate() first.")

        if self.generated_map_data.ndim == 2:
            gmap = self.generated_map_data[idx]
            freq = self.generated_map_freqs[idx]
        else:
            gmap = self.generated_map_data
            freq = self.generated_map_freqs

        if logged:
            gmap = np.log2(gmap)

        hp.mollview(gmap, coord='G',
                    title='Global Sky Model %s %s' % (str(freq), self.unit))
        plt.show()
 def _interp_beam(self,beam_file,pol,chan):
     line0=open(beam_file).readlines()[0]
     if 'dBi' in line0:
         db=True
     else:
         db=False
     print('db='+str(db))
     data=n.loadtxt(beam_file,skiprows=2);
     theta,phi=hp.pix2ang(self.nSide,range(self.nPix))
     theta=n.round(n.degrees(theta)).astype(int)
     phi=n.round(n.degrees(phi)).astype(int)
     if db:
         self.data[pol,chan,:]=10**((data[:,2].squeeze().reshape(360,181))[phi,theta]/10.)
     else:
         self.data[pol,chan,:]=(data[:,2].squeeze().reshape(360,181))[phi,theta]
     self.data[pol,chan,:]/=self.data[pol,chan,:].flatten().max();
     #print('rotatexy='+str(self.rotatexy))
     if self.rotatexz:
         self.data[pol,chan,:]=rotateBeam(self.data[pol,chan,:].flatten(),rot=[0,-90,0])
     if self.rotatexy:
         self.data[pol,chan,:]=rotateBeam(self.data[pol,chan,:].flatten(),rot=[-90,0,90])
     if(self.invert):
         self.data[pol,chan,:]=rotateBeam(self.data[pol,chan,:].flatten(),rot=[0,180,0])
     if DEBUG:
         hp.mollview(self.data[pol,chan,:])
         plt.show()
     self.data[pol,chan,theta>90.]=0.
def plot_sky_projection_healpy_count(Sliced_Halo_data,nside):
    HEALPix_mode = read_data_bool(tag_name = 'HEALPix_Cartesian',file_name = 'parameters/Output_Parameters.xml')
    HEALPix_grat = read_data_bool(tag_name = 'HEALPix_Graticule',file_name = 'parameters/Output_Parameters.xml')
    fdir  = './Output/plots/HEALPix/'
    Sl_n  = len(Sliced_Halo_data)
    Z_max = max(Sliced_Halo_data[Sl_n-1].Z_red[:])
    rc('text',usetex=True)
    for k in range(Sl_n):
        pix     = zeros(12*nside**2)
        n       = len(Sliced_Halo_data[k].RA[:])
        for i in range(n):
           j    = hp.ang2pix(nside,DtoR*(90.0-Sliced_Halo_data[k].DEC[i]),DtoR*Sliced_Halo_data[k].RA[i])
           pix[j] += 1
        clf()
        if (HEALPix_mode):
           hp.cartview(pix)           
        else:
           hp.mollview(pix)
        if (HEALPix_grat):
           hp.graticule()
        fname = 'sky_projection_HEALPix_Count_%i_%i.pdf'%(nside,(k+1))
        title(r'sky projection for redshift between %0.2f and %0.2f'%(Sliced_Halo_data[k].z_min,Sliced_Halo_data[k].z_max),fontsize = 20)
        print 'Saving plot', fname
        savefig(fdir+fname,bbox_inches='tight')
    rc('text',usetex=False)
    close()  
    return 0
Example #5
0
def plot_map(n, limit, radius='small'):
    """
    Plot the sky area there there are fewer than N stars brighter than limit
    in a radius of either 'small' (0.7 deg) or 'large' (0.9 deg).  For speed, limit
    should be one of the mag limits already evaluated
    limits = [10.13, 10.02, 9.92, 10.38, 10.29, 10.2, 10.0, 10.1, 10.3]
    Makes a mollweide visualization using healpy.
    """
    if limit not in limits:
        raise ValueError("not calculated for limit {}".format(limit))
    if radius == 'small':
        if not os.path.exists('small_{}.npy'.format(limit)):
            make_maps()
        if radius == 'small':
            field = np.load('small_{}.npy'.format(limit))
        else:
            field = np.load('big_{}.npy'.format(limit))
        if len(field) != healpy.nside2npix(NSIDE):
            make_maps()
            if radius == 'small':
                field = np.load('small_{}.npy'.format(limit))
            else:
                field = np.load('big_{}.npy'.format(limit))
        map = (field > n).astype('int')
        healpy.mollview(map, xsize=2000)
Example #6
0
def make_random(nside,data,Nf,outfile=None,viewmap=True,fmt='ascii',rsd=True):
    import healpy as hp
    import numpy as np
    import astropy.table as tab
    import matplotlib.pyplot as plt
    data_tab = tab.Table.read(data)
    ran=np.hstack((data_tab,)*Nf)
    Nr=len(ran)
    ran['ra']=np.random.uniform(0,360,Nr)
    ran['dec']=np.degrees(np.arcsin(np.random.uniform(-1,1,Nr)))
    map_gal = make_hp_map(nside,data)
    pix_nums = hp.ang2pix(nside,np.pi/2-ran['dec']*np.pi/180,ran['ra']*np.pi/180)
    mask = map_gal[pix_nums]>0
    if(rsd):
        new_random = tab.Table([ran['ra'][mask],ran['dec'][mask],ran['z'][mask]+ran['dz'][mask],np.ones(len(ran['ra'][mask]))],names=('ra','dec','z','w'))
    else:
        new_random = tab.Table([ran['ra'][mask],ran['dec'][mask],ran['z'][mask],np.ones(len(ran['ra'][mask]))],names=('ra','dec','z','w'))
    if(outfile!=None):
        new_random.write(outfile,format=fmt)
    if(viewmap):
        pix_nums = hp.ang2pix(nside,np.pi/2-new_random['dec']*np.pi/180,new_random['ra']*np.pi/180)
        bin_count = np.bincount(pix_nums)
        map_ran = np.append(bin_count,np.zeros(12*nside**2-len(bin_count)))
        plt.figure()
        hp.mollview(map_ran)
    return ran
Example #7
0
def hp_mollweide(map, unit="", title=""):
    """
	a wrapper for the healpy mollview functionality
	"""
    fig = plt.figure()
    hp.mollview(map, fig=fig.number, flip="geo", unit=unit, title=title)
    return fig, fig.gca()
Example #8
0
def main(argv):
    
    _path = '/home/tiago/Develop/SMAPs/'

    file15 = 'smpas_obstime_15.fits'
    file2 = 'smpas_obstime_2.fits'
    extMapFile = 'extintion_at3800.fits'
    
    map15 = H.read_map(os.path.join(_path,file15))
    map2 = H.read_map(os.path.join(_path,file2))    
    extMap = H.read_map(os.path.join(_path,extMapFile))

    fig = py.figure(1,figsize=(8,3))

    H.mollview(map2*10**(-extMap),fig=1,coord=['G','E'],title='secz < 2.0',sub=(1,2,1),max=1296,cbar=False,notext=True)#,unit='hours z < 1.3')

    H.graticule()

    H.mollview(map15*10**(-extMap),fig=1,coord=['G','E'],title='secz < 1.5',sub=(1,2,2),max=1296,cbar=False,notext=True)#,unit='hours z < 1.3')

    H.graticule()

    #H.write_map(os.path.join(_path,'dcorr_'+file15),map15*10**(-extMap))
    #H.write_map(os.path.join(_path,'dcorr_'+file2),map2*10**(-extMap))
    #H.write_map(os.path.join(_path,'dcorr_'+file3),map3*10**(-extMap))

    py.savefig(os.path.join(_path,'Figures/fig2.png'))

    py.show()
Example #9
0
def plot_tsfile(file,skiprows=32,column=22):

    
    data = np.loadtxt(file,skiprows=skiprows,unpack=True)

    print len(data[0])
    nside=int(round(mt.sqrt(len(data[9])/12)))
    tsarray=np.zeros(nside*nside*12)
    index=np.array(data[0]).astype(int)

    '''
    data2=np.transpose(0*data)
    data2[index]=np.transpose(data)
    data2=np.transpose(data2)
    print(data2[0])
    print(data2[10])
    return
    '''

    tsarray[index]=data[column]
    tsarray_s = hp.sphtfunc.smoothing(tsarray,sigma = 1.023/nside)

    hp.mollview(tsarray,coord=['C','G'], title='TS Map', unit='prob',xsize = 2048)
    hp.graticule()
    plt.savefig("%s_c%d.png" % (file,column))
    plt.show()

    hp.mollview(tsarray_s,coord=['C','G'], title='TS Map Smoothed', unit='prob',xsize = 2048)
    hp.graticule()
    plt.savefig("%s_c%d__s.png" % (file,column))
    plt.show()
Example #10
0
def surv_sum_diff(surveydict,ss=1,nside=128,freq=70,mask_ps=True,fwhm=10.0):
    """
    function to genreate smoothed difference between chosen survey and sum of the other 5 surveys from andreas interactive destriper/binner. uses common masks smooth to 10 degrees
    fwhm is in degrees, if zero or negative don't smooth at all, default 10 degrees
    """
    sumlist=surveydict.keys()
    sumlist.remove(ss)
    nsum=len(sumlist)
    m=hp.ma(np.array(surveydict[sumlist[0]]))/nsum
    totalmask=m.mask
    if mask_ps==True:
        psmask = np.logical_not(np.floor(hp.ud_grade(hp.read_map(glob('/project/projectdirs/planck/data/mission/DPC_maps/dx8/lfi/DX8_MASKs/' + 'mask_ps_%dGHz_*.fits' % freq)[0]), nside,order_out='NEST')))
        totalmask=m.mask | psmask
    for ss in sumlist[1:]:
        m1=hp.ma(np.array(surveydict[ss]))
        m=m+m1/nsum
        totalmask=m1.mask | totalmask
    m.mask=totalmask
    m.mask |= np.isnan(m)
    
    m1=hp.ma(np.array(surveydict[ss]))
    totalmask=totalmask | m1.mask
    d=(m1-m)/2.
    d=hp.ud_grade(d,nside,order_in='NEST',order_out='RING')
    if fwhm>0:
        dsm=hp.ma(hp.smoothing(d.filled(),fwhm*np.pi/180.))
        dsm.mask=m.mask
    if fwhm<=0:
        dsm=d
    hp.mollview(dsm,min=-1e-5,max=1e-5,title='SS'+np.str(ss)+ '  - sum of others')
    return dsm
Example #11
0
def test_observed_mollview():
    """ Generate animated maps of observing coverage over 24 hours """

    (latitude, longitude, elevation) = ('37.2', '-118.2', 1222)
    ov = GSMObserver()
    ov.lon = longitude
    ov.lat = latitude
    ov.elev = elevation

    obs = []
    for ii in range(0, 24, 1):
        ov.date = datetime(2000, 1, 1, ii, 0)
        ov.generate(50)
        sky = ov.view_observed_gsm(logged=True, show=False, min=9, max=20)
        plt.savefig('generated_sky/galactic-%02d.png' % ii)
        plt.close()

        hp.mollview(sky, coord=['G', 'E'], min=9, max=20)
        plt.savefig('generated_sky/ecliptic-%02d.png' % ii)
        plt.close()

        hp.mollview(sky, coord=['G', 'C'], min=9, max=20)
        plt.savefig('generated_sky/equatorial-%02d.png' % ii)
        plt.close()

        ov.view(logged=True, show=False, min=9, max=20)
        plt.savefig('generated_sky/ortho-%02d.png' % ii)
        plt.close()

        print ii

    os.system('convert -delay 20 generated_sky/ortho-*.png ortho.gif')
    os.system('convert -delay 20 generated_sky/galactic-*.png galactic.gif')
    os.system('convert -delay 20 generated_sky/ecliptic-*.png ecliptic.gif')
    os.system('convert -delay 20 generated_sky/equatorial-*.png equatorial.gif')
Example #12
0
    def _generatePlot(self, table):
        coords, proj = self.__getCoordinatesAndProjection()

        fignum = 1
        self.Plot.figure(num = fignum, tight_layout = True)

        pixels = self.__getPixelsData(table)
        #pixels = self.__getMaskedPixels(pixels)

        cmap = self.Plot.get_cmap(self.Configuration.getValueOf(ChartHealpixOptions.COLOURMAP, "jet"))
        cmap.set_under('w')

        healpy.mollview(pixels, fig = fignum, coord = [coords, proj], unit = 'mas', title = "",
                        min = self.__Min, max = self.__Max, flip = 'astro', cbar = False,
                        cmap = cmap, norm = self.__getNormalization(), nest = self.__nestedPixels())
        healpy.graticule(dpar = 30, dmer = 30, coord = proj, local = None, linestyle = ':',
                         color = 'white')

        healpy.projtext(0,  90,  "90", lonlat = True, coord = proj,
                        verticalalignment = 'bottom', horizontalalignment = 'center',
                        fontsize = 12)
        healpy.projtext(0, 270, "-90", lonlat = True, coord = proj,
                        verticalalignment = 'top', horizontalalignment = 'center',
                        linespacing = 2.0, fontsize = 12)
        healpy.projtext( 179, 0,  "180 ", lonlat = True, coord = proj,
                        verticalalignment = 'center', horizontalalignment = 'right',
                        fontsize = 12)
        healpy.projtext(-179, 0, " -180", lonlat = True, coord = proj,
                        verticalalignment = 'center', horizontalalignment = 'left',
                        fontsize = 12)
Example #13
0
def main():
    star = StarIsolated(90.0, 0.5, 0.5, 10., nside=64)
    Flux0 = star.flux(0.0)
    # for tt in np.arange(0,360,80):
    # star.makeSpot(0,-45,10.,0.8)
    # star.makeSpot(45,+00,10.,0.8)
    # star.makeSpot(90.,0,10.,0.8)
    # for theta in range(0,360,45):
    #	star.makeSpot(theta,0,10.,0.8)
    # star.makeSpot(00,-90,10.,0.8)
    # star.makeSpot(0,+45,10.,0.8)
    # star.makeSpot(270,-10.,10.,0.8)
    # star.makeSpot(180,-45.,10.,0.8)
    #	star.makeSpot(tt,65.,10.,0.5)

    phases = np.linspace(-0.5, 0.5, 100)
    flux = np.zeros(len(phases))
    for i in range(len(phases)):
        flux[i] = star.flux(phases[i]) / Flux0

    H.mollview(star.I, sub=211, rot=(-90, -90))

    py.subplot(212)
    py.plot(phases, flux, 'o')
    py.show()
Example #14
0
def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description="Build and test models based on dim reductions and provided spectra",
    )
    parser.add_argument(
        "--metadata_path", type=str, default=".", metavar="PATH", help="Metadata path to work from, if not " "." ""
    )
    parser.add_argument(
        "--lunar_metadata",
        type=str,
        default=None,
        metavar="LUNAR_METADATA",
        required=True,
        help="File containing lunar ephemeris metadata.",
    )
    parser.add_argument("--start_dt", type=ani.valid_date, help="DateTime to plot sky for")
    parser.add_argument("--end_dt", type=ani.valid_date, help="DateTime to plot sky for")
    parser.add_argument("--ra", type=str)
    parser.add_argument("--dec", type=str)
    args = parser.parse_args()

    m = np.zeros(hp.nside2npix(NSIDE))
    lunar_row, solar_row, ss_count, ss_area = ani.get_metadata_for_dt(
        args.datetime, args.lunar_metadata, args.solar_metadata, args.sunspot_metadata
    )

    fig = plt.figure(1, figsize=(10, 7.5))
    hp.mollview(m, coord=["C"], title="Mollview image RING", fig=1)
    plt.show()
Example #15
0
 def show_CMB_T_map(self,Tmap=None, max=100, title = "CMB graviational potential fluctuations as seen from inside the LSS", from_perspective_of = "observer", cmap=None):
     if Tmap is None:
         self.NSIDE = 256
         self.Tmap = hp.alm2map(self.alm,self.NSIDE)
     else:
         self.Tmap = Tmap
         
     if from_perspective_of == "observer":
         
         dpi = 300
         figsize_inch = 60, 40
         fig = plt.figure(figsize=figsize_inch, dpi=dpi)
         # Sky map:
         hp.mollview(self.Tmap, rot=(-90,0,0),  min=-max, max=max,  title=title + ", $\ell_{max}=$%d " % self.truncated_lmax, cmap=cmap, unit="$\mu$K")
         
         plt.savefig(title+".png", dpi=dpi, bbox_inches="tight")
     
     else:
         # Interactive "external" view ([like this](http://zonca.github.io/2013/03/interactive-3d-plot-of-sky-map.html))            pass
         #   beatbox.zoncaview(self.Tmap)
         # This did not work, sadly. Maybe we can find a 3D
         # spherical surface plot routine using matplotlib? For
         # now, just use the healpix vis.
         R = (0.0,0.0,0.0) # (lon,lat,psi) to specify center of map and rotation to apply
         hp.orthview(self.Tmap,rot=R,flip='geo',half_sky=True,title="CMB graviational potential fluctuations as seen from outside the LSS, $\ell_{max}$=%d" % self.truncated_lmax)
         print "Ahem - we can't visualize maps on the surface of the sphere yet, sorry."
     return
Example #16
0
def main():
    star = StarBinary(90.0, 0.5, nside=64, limb_law=-1, limb_coeff=[0.8])
    Flux0 = star.flux(0.0)
    phases = np.linspace(-0.5, 0.5, 100)

    flux1 = np.zeros(len(phases))
    for i in range(len(phases)):
        flux1[i] = star.flux(phases[i]) / Flux0

    # for tt in np.arange(0,360,80):
    # star.makeSpot(0,-45,10.,0.8)
    # star.makeSpot(45,+00,10.,0.8)
    # star.makeSpot(00, -90, 20., 0.)
    # for theta in range(0,360,45):
    #	star.makeSpot(theta,65,10.,0.8)

    # star.makeSpot(00,-90,20.,0.)
    # star.makeSpot(0,+45,10.,0.8)
    # star.makeSpot(270,-10.,10.,0.8)
    # star.makeSpot(180,-45.,10.,0.8)
    #	star.makeSpot(tt,65.,10.,0.5)

    flux2 = np.zeros(len(phases))
    for i in range(len(phases)):
        flux2[i] = star.flux(phases[i]) / Flux0

    H.mollview(star.I, sub=211, rot=(-90, 90))

    #ff = np.loadtxt('/tmp/cl.dat', unpack=True)

    py.subplot(212)
    py.plot(phases, flux1, '-')
    # py.plot(phases,flux2,'-')
    #py.plot(ff[0], ff[1], '.')
    py.show()
Example #17
0
def _main():

    """
    This is the main routine.
    """

    data = np.loadtxt("all_ts_data_0.1GeVplus.gz",skiprows=32,unpack=True)

    print len(data[0])
    nside=int(round(mt.sqrt(len(data[9])/12)))
    tsarray=data[0]*0
    RA=data[8]
    decl=data[9]
#    index=DeclRaToIndex(decl,RA,nside)
    index=hp.nest2ring(nside,np.array(data[0]).astype(int))
    tsarray[index]=data[22]
    tsarray = hp.sphtfunc.smoothing(tsarray,sigma = 0.008)

 #   tsmap=0*tsarray


    hp.mollview(np.arcsinh(tsarray)/mt.log(10.0),coord='C', title='TS Map', unit='prob',xsize = 2048)
#    hp.graticule()
    plt.savefig("ts.png")
    plt.show()
 def __init__(self,cat,nside,theta_apo) :
     """ Initializes Mask object from catalog and resolution parameters
     
     Parameters
     ----------
     cat : fc.Catalog
         Catalog containing window information
     nside : int
         HEALPix resolution index
     theta_apo : float
         Apodization scale in degrees
     """
     
     if cat.window.typestr=='decbcut':
         npix=hp.nside2npix(nside)
         ind_aux=np.arange(0,npix)
         theta,phi=hp.pix2ang(nside,ind_aux)
         self.weights=cat.window(phi*180/np.pi,90-theta*180/np.pi)
     elif cat.window.typestr=='base':
         self.weights=np.ones(12*nside**2)
     else:
         self.weights=cat.window.map.copy()
     if debug:
         hp.mollview(self.weights)
         plt.show() 
     #Figure out which pixels are empty
     self.ip_nomask=np.where(self.weights>0)[0] 
     #Generate sky mask and apply apodization
     self.binary=np.zeros_like(self.weights)
     self.binary[self.ip_nomask]=1.
     if theta_apo>0 :
         self.mask_apo=nmt.mask_apodization(self.binary,theta_apo,apotype='C1')
     else :
         self.mask_apo=self.binary.copy()
     #Final weights are a combination of mask + depth fluctuations
     self.total=self.mask_apo*self.weights
     #Can't generate maps with pixels larger than the mask
     if (cat.window.typestr!='decbcut') & (cat.window.typestr!='base'):
         if nside<cat.window.nside:
             #If mask pixelization is higher, upgrade output maps
             self.nside=cat.window.nside
         else :
             #If mask pixelization is lower, upgrade mask
             self.nside=nside
             self.total  =hp.ud_grade(self.total  ,nside_out=nside)
             self.binary =hp.ud_grade(self.binary ,nside_out=nside)
             self.weights=hp.ud_grade(self.weights,nside_out=nside)
             self.ip_nomask=np.where(self.weights>0)[0] 
     else:
         self.nside=nside
         self.total  =hp.ud_grade(self.total  ,nside_out=nside)
         self.binary =hp.ud_grade(self.binary ,nside_out=nside)
         self.weights=hp.ud_grade(self.weights,nside_out=nside)
         self.ip_nomask=np.where(self.weights>0)[0]
     #Pixel area
     self.pixOmega=4*np.pi/hp.nside2npix(self.nside)
     if debug:
         hp.mollview(self.weights)
         plt.show()
Example #19
0
def plot_galaxies_and_density(t, p, M):
    """Plots galaxies and pixels from polar form."""
    plt.figure(1, dpi=100)
    hp.mollview(M, fig=1, nest=True, title='Density')
    plt.figure(2, dpi=100)
    hp.mollview(M*0-1, fig=2, nest=True, cbar=False, cmap=cm.binary,
        min=-1, max=1, title='Galaxies')
    hp.projscatter(t, p, marker='.', facecolor='white', s=0.1, alpha=0.9)
Example #20
0
 def rebuild(self, N, A_, S_, freq_num=100):
     self.s = 0
     for i in range(N):
         self.s = self.s + S_[:, i] * A_[freq_num, i]
     hp.mollview(self.s, title='rebuild_freq_%d' % freq_num)
     plt.savefig('N_%d_rebuid_freq_%d.eps' % (N, freq_num))
     plt.cla()
     return self.s
Example #21
0
 def rebuild(self, N, A_, S_, freq_num=0):
     self.s = 0
     for i in np.arange(N):
         self.s = self.s + S_[:, i] * A_[freq_num, i]
     hp.mollview(self.s,min=self.s.mean()-self.s.std(),max=self.s.mean()+self.s.std(), title='rebuild_freq_%d' % freq_num)
     plt.savefig('N_%d_rebuid_freq_%d.eps' % (N, freq_num))
     plt.cla()
     return self.s
Example #22
0
 def GetComponent(self, N):
     plt.clf()
     for i in range(N):
         mean=S_[:,i].mean()
         std=S_[:,i].std()
         hp.mollview(S_[:, i],min=mean-std,max=mean+std,title='component $%d$' % (i + 1))
         plt.savefig('N_%d_result%i.eps' % (N, i))
         plt.cla()
Example #23
0
def main():

    """
    This is the main routine.
    """

    h_nside=512       # The same value a bayesstar.fits
    smoothing=0.01    # Smooth the resulting map to 0.01 radians with a Gaussian
    hubbleconstant=72
    speedoflight=3E5
    

    filenameCat = 'XSC_Completed.tbl.gz'

    RA,DEC,JMAG,HMAG,KMAG = np.loadtxt(filenameCat,skiprows= 50,
                                       usecols = (0,1,3,4,5),
                                       dtype=[('f0',float),
                                              ('f1',float),
                                              ('f2',float),
                                              ('f3',float),
                                              ('f4',float)], unpack = True)
    
    MK_Star = -24.0
    DIST = np.power(10,(KMAG-MK_Star)/5)*1E-05

    REDSHIFT = (DIST*hubbleconstant)/speedoflight
    
    print("Interval of K MAG = ",min(KMAG)," - ",max(KMAG))
    print("Interval of distances [Mpc] = ",min(DIST)," - ",max(DIST))
    print("Interval of redshift = ",min(REDSHIFT)," - ",max(REDSHIFT))
    
    # Select Galaxies by redshift under the assumption of MK=MK_Star

    for rmin in np.arange(4)*0.01:
        rmax=rmin+0.01
        if rmin == 0:
            kmin=0
        else:
            kmin=5*np.log10(rmin/hubbleconstant*speedoflight*1E5)+MK_Star
            
        kmax=5*np.log10(rmax/hubbleconstant*speedoflight*1E5)+MK_Star
        galpixels_Range= np.zeros(hp.nside2npix(h_nside))
        include_me = np.logical_and((REDSHIFT > rmin),
                                    np.logical_and((REDSHIFT<rmax),
                                                   (KMAG != 0.0)))
        ra_Range         = RA[include_me]
        dec_Range        = DEC[include_me]
        pix_num_Range    = (DeclRaToIndex(dec_Range,ra_Range,h_nside))
        galpixels_Range[pix_num_Range]+=1
    
        print("Number of objects with %g < z < %g : %d" % (rmin,rmax,len(ra_Range)))
        map = hp.sphtfunc.smoothing(galpixels_Range,sigma = smoothing)
        hp.write_map("%g-%g_raw.fits" % (rmin,rmax),galpixels_Range)
        hp.write_map("%g-%g.fits" % (rmin,rmax),map)
        hp.mollview(map,coord='C',rot = [0,0.3], title='Relative Surface Density of Galaxies: %0.1f < K < %0.1f (%g < z < %g)' % (kmin,kmax,rmin,rmax), unit='prob',xsize = 2048)
        hp.graticule()
        plt.savefig("%g-%g.png" % (rmin,rmax))
        plt.show()
 def plot(self, filter, ra=None, dec=None):
     """
     Plot zoomed zeropoint shiftmap for chosen filter centered on (ra, dec) given in degrees,
     or simply Mollweide all-sky map by default.
     """
     if ra is not None and dec is not None:
         healpy.gnomview(self.zeropoint_shiftmap.data.field(filter), rot=(ra, dec, 0))
     else:
         healpy.mollview(self.zeropoint_shiftmap.data.field(filter))
Example #25
0
    def visualize(self, plotname=None, compare=False):
        hp.mollview(self.hmap[:,0])
        f = plt.gcf()
        ax = plt.gca()

        if (plotname is not None) & (not compare):
            plt.savefig(plotname)

        return f, ax
Example #26
0
def plot_maps(maps,titles=None):
    """
    Plots a list of healpix maps in mollweide projection
    """
    s = int(np.ceil(np.sqrt(float(len(maps)))))
    for i,m in enumerate(maps):
        if titles is not None: hp.mollview(m,title=titles[i],sub=(s,s,i+1))
        else: hp.mollview(m,sub=(s,s,i+1))
    plt.show()
Example #27
0
 def ReadMap(self,filename=''):
     self.f=h5py.File(filename)
     self.map=self.f['map'].value
     self.f.close()
     for self.i in range(len(self.map)):
         self.fig=plt.figure(filename)
         hp.mollview(self.map[self.i][0])
         plt.savefig(filename+'_freq_%d.png'%self.i)
         plt.cla()
     return self.map
Example #28
0
def get_component():
    plt.clf()
    for i in range(N):
        #        hp.mollview(S_[:, i], title='$%d$' %
        #                    (i + 1), sub=((N / 3 + bool(N % 3)) * 100 + 30 + i + 1))
        #    plt.savefig('component.eps')
        #    plt.cla()
        hp.mollview(S_[:, i], title='component $%d$' % (i + 1))
        plt.savefig('N_%d_result%i.eps' % (N, i))
        plt.cla()
Example #29
0
def get_simpic(N):
    for i in range(N):
        hp.mollview(map1[i, pol])
        plt.title('$signal-21cm-%i$' % i)
        plt.savefig('N_%d_signal_21cm_%i.eps' % (N, i))
        plt.cla()
    for j in range(N):
        hp.mollview(map3[j, pol])
        plt.title('$signal-galaxy-%i$' % j)
        plt.savefig('N_%d_signal_galaxy_%i.eps' % (N, j))
        plt.cla()
Example #30
0
def setup_scan():
    b.make_dirs_for_run(run_tag)
    b_disk.make_dirs_for_run(run_tag_disk_only)
    b_poiss.make_dirs_for_run(run_tag_poiss)
    b_just_NFW.make_dirs_for_run(run_tag_just_NFW)
    b_plus_IPS.make_dirs_for_run(run_tag_plus_iso)
    b_iso.make_dirs_for_run(run_tag_iso)

    hp.mollview(b.mask_total )
    plt.savefig(b.plots_dir_for_run + 'mask_ROI.pdf')
    plt.close()
Example #31
0
    def plot_map(self, min_m=-100, max_m=-100, colbar='yes'):
        """
        Plots the map after evaluating, the cells are colored with the mean value inside each
        one of them

        :param float min_m: Lower limit for coloring the cells, -100 uses min value
        :param float max_m: Upper limit for coloring the cells, -100 uses max value
        :param str colbar: Include a colorbar ('yes','no')
        """

        import matplotlib.pyplot as plt
        import matplotlib as mpl
        import matplotlib.cm as cm
        from matplotlib import collections, transforms
        from matplotlib.colors import colorConverter

        if self.top == 'sphere': import healpy as H

        if self.top == 'grid':
            M = numpy.zeros(self.npix) - 20.
            for i in range(self.npix):
                if i in self.yvals:
                    M[i] = numpy.mean(self.yvals[i])
            M2 = numpy.reshape(M, (self.Ntop, self.Ntop))
            plt.figure(figsize=(8, 8), dpi=100)
            if min_m == -100: min_m = M2[numpy.where(M2 > -10)].min()
            if max_m == -100: max_m = M2.max()
            SM2 = plt.imshow(M2,
                             origin='center',
                             interpolation='nearest',
                             cmap=cm.jet,
                             vmin=min_m,
                             vmax=max_m)
            SM2.cmap.set_under("grey")
            if colbar == 'yes': plt.colorbar()
            plt.axis('off')
        if self.top == 'hex':
            nx = self.Ntop
            ny = self.Ntop
            xL = numpy.arange(0, nx, 1.)
            dy = 0.8660254
            yL = numpy.arange(0, ny, dy)
            ny = len(yL)
            nx = len(xL)
            npix = nx * ny
            bX = numpy.zeros(nx * ny)
            bY = numpy.zeros(nx * ny)
            kk = 0
            for jj in range(ny):
                for ii in range(nx):
                    if jj % 2 == 0: off = 0.
                    if jj % 2 == 1: off = 0.5
                    bX[kk] = xL[ii] + off
                    bY[kk] = yL[jj]
                    kk += 1
            xyo = list(zip(bX, bY))
            sizes_2 = numpy.zeros(nx * ny) + (
                (8. * 0.78 /
                 (self.Ntop + 0.5)) / 2. * 72.)**2 * 4. * numpy.pi / 3.
            M = numpy.zeros(npix) - 20.
            fcolors = [
                plt.cm.Spectral_r(x) for x in numpy.random.rand(nx * ny)
            ]
            for i in range(npix):
                if i in self.yvals:
                    M[i] = numpy.mean(self.yvals[i])
            if max_m == -100: max_m = M.max()
            if min_m == -100: min_m = M[numpy.where(M > -10)].min()
            M = M - min_m
            M = M / (max_m - min_m)
            for i in range(npix):
                if M[i] <= 0:
                    fcolors[i] = plt.cm.Greys(.5)
                else:
                    fcolors[i] = plt.cm.jet(M[i])
            figy = ((8. * 0.78 / (self.Ntop + 0.5) / 2.) *
                    (3. * ny + 1) / numpy.sqrt(3)) / 0.78
            fig3 = plt.figure(figsize=(8, figy), dpi=100)
            #fig3.subplots_adjust(left=0,right=1.,top=1.,bottom=0.)
            a = fig3.add_subplot(1, 1, 1)
            col = collections.RegularPolyCollection(6,
                                                    sizes=sizes_2,
                                                    offsets=xyo,
                                                    transOffset=a.transData)
            col.set_color(fcolors)
            a.add_collection(col, autolim=True)
            a.set_xlim(-0.5, nx)
            a.set_ylim(-1, nx + 0.5)
            plt.axis('off')
            if colbar == 'yes':
                figbar = plt.figure(figsize=(8, 1.), dpi=100)
                ax1 = figbar.add_axes([0.05, 0.8, 0.9, 0.15])
                cmap = cm.jet
                norm = mpl.colors.Normalize(vmin=min_m, vmax=max_m)
                cb1 = mpl.colorbar.ColorbarBase(ax1,
                                                cmap=cmap,
                                                norm=norm,
                                                orientation='horizontal')
                cb1.set_label('')
        if self.top == 'sphere':
            M = numpy.zeros(self.npix) + H.UNSEEN
            for i in range(self.npix):
                if i in self.yvals:
                    M[i] = numpy.mean(self.yvals[i])
            plt.figure(10, figsize=(8, 8), dpi=100)
            if min_m == -100: min_m = M[numpy.where(M > -10)].min()
            if max_m == -100: max_m = M.max()
            if colbar == 'yes':
                H.mollview(M,
                           fig=10,
                           title="",
                           min=min_m,
                           max=max_m,
                           cbar=True)
            if colbar == 'no':
                H.mollview(M,
                           fig=10,
                           title="",
                           min=min_m,
                           max=max_m,
                           cbar=False)
        plt.show()
Example #32
0
    #hide pixels in the northern hemisphere and plot
    print "Plotting..."

    #hide pixels that are more than 65 deg from pole or are too close to pole
    for i in range(NPIX):
        if thetas[i] < 2:
            dp[i] = hp.UNSEEN

        #mask weirdness at pole
        if args.mask and (np.pi - thetas[i]) * 180 / np.pi < args.mask:
            dp[i] = hp.UNSEEN

    #show in IC standard rotated half sky mollview
    if args.moll:
        hp.mollview(dp, min=args.min, max=args.max, cbar=False, rot=180)
        plt.ylim(-1, .005)

    #show an individual pixel's histogram compared to average if specified
    #error bars not currently working
    elif args.pixel:

        #get data, fix errors
        data = matrix[args.pixel]

        for i in range(len(data)):
            if data[i] <= 0:
                data[i] = .0001

        #normalize, get error bars (not working yet)
        sum = float(np.sum(data))
Example #33
0
    if (i == ydays-1): 
        h.write_map(dir_out+'/fits/nhits_'+str(i+1)+'_tmp.fits',nhits)
        h.write_map(dir_out+'/fits/cos_r1_'+str(i+1)+'_tmp.fits',cos_r1)
        h.write_map(dir_out+'/fits/sin_r1_'+str(i+1)+'_tmp.fits',sin_r1)
        h.write_map(dir_out+'/fits/cos_r2_'+str(i+1)+'_tmp.fits',cos_r2)
        h.write_map(dir_out+'/fits/sin_r2_'+str(i+1)+'_tmp.fits',sin_r2)
        h.write_map(dir_out+'/fits/cos_r4_'+str(i+1)+'_tmp.fits',cos_r4)
        h.write_map(dir_out+'/fits/sin_r4_'+str(i+1)+'_tmp.fits',sin_r4)
        
r1 = np.sqrt((cos_r1/np.float_(nhits))**2. + (sin_r1/np.float_(nhits))**2.)
r2 = np.sqrt((cos_r2/np.float_(nhits))**2. + (sin_r2/np.float_(nhits))**2.)
r4 = np.sqrt((cos_r4/np.float_(nhits))**2. + (sin_r4/np.float_(nhits))**2.)

filename_out = dir_out+'/ps/'+filename+'_nhits'
h.write_map(filename_out+'.fits', nhits)
h.mollview(nhits, title='Nobs, '+filename_out, rot=[0.,0.])
h.graticule(dpar=10,dmer=10,coord='E')
py.savefig(filename_out+'.ps')


filename_out = dir_out+'/ps/'+filename+'_cos_r1'
h.write_map(filename_out+'.fits', cos_r1)
h.mollview(cos_r1, title='cos_r1, '+filename_out, rot=[0.,0.])
h.graticule(dpar=10,dmer=10,coord='E')
py.savefig(filename_out+'.ps')

filename_out = dir_out+'/ps/'+filename+'_sin_r1'
h.write_map(filename_out+'.fits', sin_r1)
h.mollview(sin_r1, title='sin_r1, '+filename_out, rot=[0.,0.])
h.graticule(dpar=10,dmer=10,coord='E')
py.savefig(filename_out+'.ps')
Example #34
0
                                   64)  #reduce nside to make it faster
    prob64 = prob64 / np.sum(prob64)
    pixels = np.arange(prob64.size)
    #sample_points = np.array(hp.pix2ang(nside,pixels)).T
    levels = [0.50, 0.90]
    theta_contour, phi_contour = compute_contours(levels, prob64)

    # Access DESI contours.
    #desi_mask = hp.read_map('desi_mask_nside{:04d}.fits'.format(nside_all))
    #sum_map[desi_mask == 0] = hp.UNSEEN

    # Plot GW skymap in Mollweide projection
    hp.mollview(binned_maps[:, k],
                cbar=True,
                unit=r'probability',
                min=0,
                max=3e-4,
                rot=180,
                cmap=cmap)
    hp.graticule(ls=':', alpha=0.5, dpar=30, dmer=45)  # Set grid lines

    # Draw containment contour around GW skymap
    nregion = len(theta_contour) // len(levels)
    for i, (tc, pc) in enumerate(zip(theta_contour, phi_contour)):
        hp.projplot(tc, pc, linewidth=1, c='k')
    ax = plt.gca()

    # Label latitude lines.
    ax.text(2.00, 0.10, r'$0^\circ$', horizontalalignment='left')
    ax.text(1.80, 0.45, r'$30^\circ$', horizontalalignment='left')
    ax.text(1.30, 0.80, r'$60^\circ$', horizontalalignment='left')
Example #35
0
def mkCross(**kwargs):
    """                                      
    """
    get_var_from_file(kwargs['config'])

    logger.info('Calculating PSF with gtpsf...')
    dict_gtpsf = data.DICT_GTPSF
    logger.info('Calculating Wbeam Function...')
    out_wb_label = data.OUT_W_LABEL
    out_wb_txt = os.path.join(GRATOOLS_OUT, 'Wbeam_%s.txt'%out_wb_label)
    if not os.path.exists(out_wb_txt):
        from GRATools.utils.ScienceTools_ import gtpsf
        gtpsf(dict_gtpsf)
        from GRATools.utils.gWindowFunc import get_psf
        psf_file = data.PSF_FILE
        psf = get_psf(psf_file)
        _l = np.arange(0, 1000)
        from GRATools.utils.gWindowFunc import build_wbeam
        wb = build_wbeam(psf, _l, out_wb_txt)
    else:
        from GRATools.utils.gWindowFunc import get_wbeam
        wb = get_wbeam(out_wb_txt)
    save_current_figure('Wbeam_%s.png'%out_wb_label, clear=True)

    logger.info('Starting Cl analysis...')
    in_label1 = data.IN_LABEL1
    in_label2 = data.IN_LABEL2
    out_label = data.OUT_LABEL
    binning_label = data.BINNING_LABEL
    mask_file = data.MASK_FILE
    mask = hp.read_map(mask_file)
    cl_param_file1 = os.path.join(GRATOOLS_OUT, '%s_%s_parameters.txt' \
                                     %(in_label1, binning_label))
    cl_param_file2 = os.path.join(GRATOOLS_OUT, '%s_%s_parameters.txt' \
                                      %(in_label2, binning_label))
    from GRATools.utils.gFTools import get_cl_param
    _emin, _emax, _emean, _f, _ferr, _cn, _fsky = get_cl_param(cl_param_file1)
    _emin2, _emax2, _emean2, _f2, _ferr2, _cn2, _fsky2 = get_cl_param(cl_param_file2)
    cross_txt = open(os.path.join(GRATOOLS_OUT, '%s_%s_cross.txt' \
                                   %(out_label, binning_label)), 'w')
    for i, (emin, emax) in enumerate(zip(_emin, _emax)):
        logger.info('Considering bin %.2f - %.2f ...'%(emin, emax))
        gamma = data.WEIGHT_SPEC_INDEX
        Im = (1/(1-gamma))*(emax**(1-gamma)-emin**(1-gamma))/(emax-emin)
        eweightedmean = np.power(1/Im, 1/gamma)
        cross_txt.write('ENERGY\t %.2f %.2f %.2f\n'%(emin, emax, eweightedmean))
        l_max= 1000
        _l = np.arange(l_max)
        wb_en = wb.hslice(eweightedmean)(_l)
        flux_map_name1 = in_label1+'_flux_%i-%i.fits'%(emin, emax)
        flux_map_name2 = in_label2+'_flux_%i-%i.fits'%(emin, emax)
        flux_map1 = hp.read_map(os.path.join(GRATOOLS_OUT_FLUX, flux_map_name1))
        flux_map2 = hp.read_map(os.path.join(GRATOOLS_OUT_FLUX, flux_map_name2))
        flux_map_masked1 = hp.ma(flux_map1)
        flux_map_masked1.mask = np.logical_not(mask)
        flux_map_masked2 = hp.ma(flux_map2)
        flux_map_masked2.mask = np.logical_not(mask)
        fsky1 = 1.-(len(np.where(flux_map_masked1.filled() == hp.UNSEEN)[0])/\
                       float(len(flux_map1)))
        fsky2 = 1.-(len(np.where(flux_map_masked2.filled() == hp.UNSEEN)[0])/\
                       float(len(flux_map2)))
        if kwargs['show'] == True:
            hp.mollview(flux_map_masked1.filled(), title='f$_{sky}$ = %.3f'%fsky,
                        min=1e-7, max=1e-4, norm='log')
            plt.show()
        print 'fsky = ', fsky1, fsky2
        fsky = np.sqrt(fsky1*fsky2)
        nside1 = hp.npix2nside(len(flux_map1))
        nside2 = hp.npix2nside(len(flux_map1))
        wpix1 = hp.sphtfunc.pixwin(nside1)[:l_max]
        wpix2 = hp.sphtfunc.pixwin(nside2)[:l_max]
        _cl_cross = hp.sphtfunc.anafast(flux_map_masked1.filled(),
                                        flux_map_masked2.filled(), lmax=l_max-1, \
                                             iter=5)
        wl2 = wb_en*wb_en*wpix1*wpix2
        _cl_cross = (_cl_cross/fsky)/(wl2)
        cross_txt.write('Cl\t%s\n'%str(list(_cl_cross)).replace('[',''). \
                         replace(']','').replace(', ', ' '))
        _cl_cross_err = np.sqrt(2./((2*_l+1)*fsky))*(_cl_cross)
        cross_txt.write('Cl_ERR\t%s\n\n'%str(list(_cl_cross_err)).replace('[',''). \
                         replace(']','').replace(', ', ' '))
    cross_txt.close()
    logger.info('Created %s'%(os.path.join(GRATOOLS_OUT, '%s_%s_cross.txt' \
                                               %(out_label, binning_label))))
Example #36
0
    def make_figures(self,lon,lat,width,Tmax,Pmax,option_part=False):
#        os.popen('mkdir -p '+self.out_dir+'/png/'+self.dir_coadd)
#        os.popen('mv '+self.out_dir+'/*.npy '+self.out_dir+'/npy/')

        if option_part:
            map = h.read_map(self.fnameH+'.fits')
            h.mollview(map, title='H',max=max(map),min=0)
            h.graticule(dpar=10,dmer=10,coord='C')
            py.savefig(self.out_dir+'/png/'+self.dir_coadd+'/mapH.png')
            
            h.cartview(map,coord='C',rot=[lon,lat],lonra=[-width/2.,width/2.],latra=[-width/2.,width/2.],\
                           title='H', max=max(map),min=0)
            h.graticule(dpar=10,dmer=10,coord='C')
            py.savefig(self.out_dir+'/png/'+self.dir_coadd+'/mapH_cart.png')


            map = h.read_map(self.fnameM+'_CNexcluded.fits')
            h.mollview(map, title='M CNexcluded',max=max(map),min=0)
            h.graticule(dpar=10,dmer=10,coord='C')
            py.savefig(self.out_dir+'/png/'+self.dir_coadd+'/mapM_CNexcluded.png')
            
            h.cartview(map,coord='C',rot=[lon,lat],lonra=[-width/2.,width/2.],latra=[-width/2.,width/2.],\
                           title='M CNexcluded', max=max(map),min=0)
            h.graticule(dpar=10,dmer=10,coord='C')
            py.savefig(self.out_dir+'/png/'+self.dir_coadd+'/mapM_cart_CNexcluded.png')

            ind = np.where(map == 1)
            ind_non = np.where(map != 1)
            

            map = h.read_map(self.fnameT+'.fits')
            h.mollview(map, title='T', max=Tmax, min=-Tmax)
            h.graticule(dpar=10,dmer=10,coord='C')
            py.savefig(self.out_dir+'/png/'+self.dir_coadd+'/mapT.png')
            
            h.cartview(map,coord='C',rot=[lon,lat],lonra=[-width/2.,width/2.],latra=[-width/2.,width/2.],\
                           title='T', max=Tmax, min=-Tmax)
            h.graticule(dpar=10,dmer=10,coord='C')
            py.savefig(self.out_dir+'/png/'+self.dir_coadd+'/mapT_cart.png')


            map = h.read_map(self.fnameQ+'.fits')
            h.mollview(map, title='Q',max=Pmax, min=-Pmax)
            h.graticule(dpar=10,dmer=10,coord='C')
            py.savefig(self.out_dir+'/png/'+self.dir_coadd+'/mapQ.png')

            h.cartview(map,coord='C',rot=[lon,lat],lonra=[-width/2.,width/2.],latra=[-width/2.,width/2.],\
                           title='Q', max=Pmax, min=-Pmax)
            h.graticule(dpar=10,dmer=10,coord='C')
            py.savefig(self.out_dir+'/png/'+self.dir_coadd+'/mapQ_cart.png')


            map = h.read_map(self.fnameU+'.fits')
            h.mollview(map, title='U',max=Pmax,min=-Pmax)
            h.graticule(dpar=10,dmer=10,coord='C')
            py.savefig(self.out_dir+'/png/'+self.dir_coadd+'/mapU.png')

            h.cartview(map,coord='C',rot=[lon,lat],lonra=[-width/2.,width/2.],latra=[-width/2.,width/2.],\
                           title='U', max=Pmax,min=-Pmax)
            h.graticule(dpar=10,dmer=10,coord='C')
            py.savefig(self.out_dir+'/png/'+self.dir_coadd+'/mapU_cart.png')
Example #37
0
import healpy as hp
import matplotlib.pyplot as P

a = hp.fitsfunc.read_map('outputs/kmap.fits')
hp.mollview(a, title='Kmap Mollweide View')
P.savefig('plots/kmap.png')
P.close()

b = hp.fitsfunc.read_map('outputs/amap.fits')
hp.mollview(b, title='Amap Mollweide View')
P.savefig('plots/amap.png')
P.close()

c = hp.fitsfunc.read_map('outputs/pmap.fits')
hp.mollview(c, title='Pmap Mollweide View')
P.savefig('plots/pmap.png')
P.close()
Example #38
0
        f.create_dataset('rec_cm', data=res)

    # # plot pc
    # plt.figure()
    # fig = plt.figure(1, figsize=(13, 5))
    # healpy.mollview(pc[cind], fig=1, title='')
    # healpy.graticule(verbose=False)
    # fig.savefig(out_dir + 'pc_%d.png' % i)
    # plt.close()

    # plot pc_sum
    plt.figure()
    fig = plt.figure(1, figsize=(13, 5))
    healpy.mollview(pc_sum[cind],
                    fig=1,
                    title='',
                    min=0,
                    max=50,
                    unit='brightness temperature [K]')
    healpy.graticule(verbose=False)
    fig.savefig(out_dir + 'pc_sum_%d.png' % i)
    plt.close()

    # plot the difference covariance of pc_sum
    plt.figure()
    plt.imshow(R_f - np.dot(pc_sum, pc_sum.T) / pc_sum.shape[-1])
    plt.colorbar()
    plt.savefig(out_dir + 'Rf_diff_%d.png' % i)
    plt.close()

    # plot res
    plt.figure()
Example #39
0
nside = 2
npix = hp.nside2npix(nside)

#Uncomment below to make poissonian data
data = np.random.poisson(1, npix)

#Split the data up into energy bins
data_bin1 = data * first_spectral_coeff  #This is the number of photons in the first energy bin according to the power law
#Note: Fractional number of photons, maybe non physical?
data_bin2 = data * second_spectral_coeff  #This is the number of photons in the second energy bin according to the power law
exposure = np.ones(npix)

max_counts = np.amax(data)

hp.mollview(data_bin1,
            title='Fake Data, photons in energy bin 1',
            min=0,
            max=max_counts)
hp.mollview(data_bin2,
            title='Fake Data, photons in energy bin 2',
            min=0,
            max=max_counts)
hp.mollview(data,
            title='Fake Data, total number of photons',
            min=0,
            max=max_counts)
hp.mollview(data_bin1 + data_bin2,
            'Fake Data, photons in energy bin 1 + photons in energy bin 2',
            min=0,
            max=max_counts)

energy_data = [data_bin1, data_bin2]
Example #40
0
pix = hp.ang2pix(NSIDE, theta, phi)
hit_pix, bins = np.histogram(pix,bins=NPIX)

print("Reading Planck data...")
file_path = "/Users/yusuke/program/py_program/CMB/skymap/data/LFI_SkyMap_030-BPassCorrected_0256_R2.01_full.fits"
I_planck = hp.read_map(file_path, field = (0,1,2), dtype=np.float32)#PlanckのRING型データ
I_obs = [I_planck[0][pix], I_planck[1][pix], I_planck[2][pix]]#Planckのデータを観測されるpix順に並び換えた時系列観測データI_obs

npix_array=np.arange(0,NPIX)
npix_split=np.array_split(npix_array, 10)
#s_par = np.array(Parallel(n_jobs=-1, verbose=5)( [delayed(stokes)(i,I_obs) for i in npix_split[number][0:10] ])).T
#s_par = np.array([stokes(i,I_obs) for i in range(507976, 550000) ]).T
s_par = np.array([stokes(i,I_obs) for i in npix_split[number][0:10] ]).T

Runtime = time.time() - start
print("\nFinish!")
print ("Runtime: {0}".format(Runtime) + "[sec]")

print ("Now, data saving...")
path = "/Users/yusuke/program/py_program/CMB/skymap/stokes/reconstruct/Jobs"
np.savez_compressed(path+"/output/sp_{}.npz".format(number), I=s_par[0], Q=s_par[1], V=s_par[2], U=s_par[3])
print ("Complete...")
s_par[0]
I_planck[0]
print ("Show plot!")
hp.mollview(hit_pix, title="Hit count map in Ecliptic coordinates", unit="Hit number")
#hp.mollview(I_planck[0], title="I_STOKES observed by Planck", unit="mK", cmap="jet")
#hp.mollview(map, title="LiteBIRD observation {:.4}-days".format(times/(day+1)), unit="mK",norm="hist",cmap="jet")
#plt.show()
print ("Shut down.")
Example #41
0
    def test_sim(self):
        rank = 0
        if self.comm is not None:
            rank = self.comm.rank
        # make a simple pointing matrix
        pointing = OpPointingHpix(nside=self.nside, nest=False, mode="I")
        pointing.exec(self.data)

        # generate timestreams
        op = OpSimDipole(mode="solar", coord="G")
        op.exec(self.data)

        # make a binned map

        # construct distributed maps to store the covariance,
        # noise weighted map, and hits

        invnpp = DistPixels(
            self.data,
            nnz=1,
            dtype=np.float64,
            nest=False,
        )
        invnpp.data.fill(0.0)

        zmap = DistPixels(
            self.data,
            nnz=1,
            dtype=np.float64,
            nest=False,
        )
        zmap.data.fill(0.0)

        hits = DistPixels(
            self.data,
            nnz=1,
            dtype=np.int64,
            nest=False,
        )
        hits.data.fill(0)

        # accumulate the inverse covariance and noise weighted map.
        # Use detector weights based on the analytic NET.

        tod = self.data.obs[0]["tod"]

        detweights = {}
        for d in tod.local_dets:
            detweights[d] = 1.0

        build_invnpp = OpAccumDiag(detweights=detweights,
                                   invnpp=invnpp,
                                   hits=hits,
                                   zmap=zmap,
                                   name="dipole")
        build_invnpp.exec(self.data)

        invnpp.allreduce()
        hits.allreduce()
        zmap.allreduce()

        hits.write_healpix_fits(os.path.join(self.outdir, "hits.fits"))
        invnpp.write_healpix_fits(os.path.join(self.outdir, "invnpp.fits"))
        zmap.write_healpix_fits(os.path.join(self.outdir, "zmap.fits"))

        # invert it
        covariance_invert(invnpp, 1.0e-3)

        invnpp.write_healpix_fits(os.path.join(self.outdir, "npp.fits"))

        # compute the binned map, N_pp x Z

        covariance_apply(invnpp, zmap)
        zmap.write_healpix_fits(os.path.join(self.outdir, "binned.fits"))

        if rank == 0:
            import matplotlib.pyplot as plt

            mapfile = os.path.join(self.outdir, "hits.fits")
            data = hp.read_map(mapfile, nest=False)
            nt.assert_almost_equal(
                data, self.data.comm.ngroups * self.ndet * np.ones_like(data))

            outfile = "{}.png".format(mapfile)
            hp.mollview(data, xsize=1600, nest=False)
            plt.savefig(outfile)
            plt.close()

            mapfile = os.path.join(self.outdir, "binned.fits")
            data = hp.read_map(mapfile, nest=False)

            # verify that the extrema are in the correct location
            # and have the correct value.

            minmap = np.min(data)
            maxmap = np.max(data)
            nt.assert_almost_equal(maxmap, self.dip_check, decimal=5)
            nt.assert_almost_equal(minmap, -self.dip_check, decimal=5)

            minloc = np.argmin(data)
            maxloc = np.argmax(data)
            nt.assert_equal(minloc, self.dip_min_pix)
            nt.assert_equal(maxloc, self.dip_max_pix)

            outfile = "{}.png".format(mapfile)
            hp.mollview(data, xsize=1600, nest=False)
            plt.savefig(outfile)
            plt.close()
        return
Example #42
0
judge = np.sign(dif[0] * n_vec[1] - dif[1] * n_vec[0])  #角度psiの正負は外積で判断
cos_psi = inner / (L_dif * L_n)
cos_psi
psi = np.rad2deg(np.arccos(cos_psi)) * judge
psi
#psi[2461]
ang = 180
a = np.where((psi > ang - 1)
             & (psi < ang + 1))[0]  #-1<ang<1の範囲に軌道ベクトルがきたときの時間[s]
a
pix = hp.ang2pix(NSIDE, orbit[0], orbit[1])
#pix_ = np.concatenate([pix, a,a,a,a,a,a])
#pix_
hit_pix, bins = np.histogram(pix, bins=NPIX)

I_lu = np.zeros(NPIX)
for i in range(times):
    for j in range(len(a)):
        if i == a[j]:
            I_lu[pix[i]] += 10  #a[s]の時は+10
    I_lu[pix[i]] += 1
#I_lu[pix[2461]]

hp.mollview(I_lu,
            title="Hit count map in Ecliptic coordinates",
            unit="Hit number",
            cmap="jet")
hp.graticule()
plt.show()
        line_strength[pix] = np.nanmedian(field_mean_halpha[idx_line])

    i_p = 0
    for i_s in np.where(idx_in_field)[0]:
        plt.plot(wvl_ccd3, normalized_data_ccd3[i_s,:] + i_p*0.0, color='blue', linewidth=0.5, alpha=0.04)
        i_p += 1
        if i_p >= 50:
            break
    plt.xlim(halpha_lim)
    plt.ylim((-0.05, 0.05))
    plt.savefig('halpha_l{:05.1f}_b{:05.1f}_pix{:.0f}_individual.png'.format(l_center, b_center, pix), dpi=350)
    plt.close()



hp.mollview(line_strength, min=-0.01, max=0.01)
plt.savefig('line_strength_map.png', dpi=350)
plt.close()

    # plot 2
    # idx_plot = np.logical_and(field_mean_hbeta <= 0.02,
    #                           field_mean_hbeta >= -0.02)
    # plt.plot(wvl_ccd1, field_mean_hbeta, color='black')
    # plt.plot(wvl_ccd1, all_mean_hbeta - field_mean_hbeta, color='blue')
    # plt.plot(wvl_ccd1, all_mean_hbeta / field_mean_hbeta, color='blue')
    # plt.errorbar(wvl_ccd1, field_mean_hbeta, yerr=field_std_hbeta, markersize=0)
    # plt.xlim(hbeta_lim)
    # plt.ylim((-0.05, 0.05))
    # plt.savefig('hbeta_ra{:03.1f}_dec{:03.1f}.png'.format(ra_center, dec_center), dpi=350)
    # plt.close()
        dec.append((target.dec))
        n += 1
    phi = ra
    theta = [np.pi / 2 - i for i in dec]
    heal_index = hp.ang2pix(NSIDE, theta, phi)

    return heal_index


#%%

# taurus A
TauA_ra = 8
TauA_dec = -47.5
TauA_heal_index = findTarget(NSIDE, TauA_ra, TauA_dec, my_location)
m[TauA_heal_index] = 1

#RCW38
RCW38_ra = 5.51
RCW38_dec = 22.0
RCW38_heal_index = findTarget(NSIDE, RCW38_ra, RCW38_dec, my_location)
m[RCW38_heal_index] = 2

#Cen A
CenA_ra = 13.5
CenA_dec = -43
CenA_heal_index = findTarget(NSIDE, CenA_ra, CenA_dec, my_location)
m[CenA_heal_index] = 4

hp.mollview(m, coord=['G', 'E'])
Example #45
0
        npix = len( map )
        ns = np.sqrt( npix/12 )
        if verbose:
            print ' - determining map size...: %s' %nside    

        maps = np.zeros( npix, nfreq, dtype=np.float )
        print 'reading maps...'

        psmask = np.ones( npix )
        for ifreq in range(nfreq):
            print ' - map ', ifreq+1, ' of', nfreq, ' :'+mapfiles[ifreq]
            temp = hp.read_map( mapfiles[ifreq] )
            psmask[ int (np.logical_not( (temp == -1.6375e30) or (np.isfinite(temp)) ) ) ] = 0.
            maps[*,ifreq] = temp
            if check:
                hp.mollview(temp, min=-300, max=300., fig=ifreq+1)
            

    else:
        npix = n_elements( maps[*,0] )
        ns = np.sqrt( npix/12 )
        psmask = np.ones( npix )
        for ifreq in range(nfreq):
            print ' - map ', ifreq+1, ' of', nfreq, ' :'+mapfiles[ifreq]
            temp = ( mapfiles[ifreq] )
            psmask[ int (np.logical_not( (temp == -1.6375e30) or (np.isfinite(temp)) ) ) ] = 0.
            if check:
                hp.mollview(temp, min=-300, max=300., fig=ifreq+1)

    mask = np.ones( npix )
Example #46
0
if False:
    lindir_p_96 = '/home/jbm120/nonlinear_forecast/cosmograph/build/nl_runs/r96_P0.13_M1_resc1.0e-3/dust_lensing.1/'
    rho_data_lin_96 = loadData(lindir_p_96, 1.0)
    rho_interp_lin_96 = rho_interp(rho_data_lin_96)
    rhos_lin_96 = rho(rho_interp_lin_96, 0.5)
    cls_lin_96 = hp.anafast(rhos_lin_96)

    nldir_p_96 = '/home/jbm120/nonlinear_forecast/cosmograph/build/nl_runs/r96_P0.13_M1_resc1.0/dust_lensing/'
    rho_data_nl_96 = loadData(nldir_p_96, 1.0)
    rho_interp_nl_96 = rho_interp(rho_data_nl_96)
    rhos_nl_96 = rho(rho_interp_nl_96, 0.5)
    cls_nl_96 = hp.anafast(rhos_nl_96)

    hpmin = np.min(rhos_lin_96)
    hpmax = np.max(rhos_lin_96)
    hp.mollview(rhos_lin_96, min=hpmin, max=hpmax)
    plt.savefig('rhos_lin_96.png')
    plt.close()
    hp.mollview(rhos_nl_96, min=hpmin, max=hpmax)
    plt.savefig('rhos_nl_96.png')
    plt.close()

    # print( ( (rhos_nl_96-np.mean(rhos_nl_96)) - (rhos_lin_96-np.mean(rhos_lin_96)) ) / np.std(rhos_lin_96) )
    delta_lin_96 = (rhos_lin_96 - np.mean(rhos_lin_96)) / np.mean(rhos_lin_96)
    delta_nl_96 = (rhos_nl_96 - np.mean(rhos_nl_96)) / np.mean(rhos_nl_96)

    lindir_p_128 = '/home/jbm120/nonlinear_forecast/cosmograph/build/nl_runs/r128_P0.00000013_M1/dust_lensing.1/'
    rho_data_lin_128 = loadData(lindir_p_128, 1000.0)
    rho_interp_lin_128 = rho_interp(rho_data_lin_128)
    rhos_lin_128 = rho(rho_interp_lin_128, 0.5)
    cls_lin_128 = hp.anafast(rhos_lin_128)
Example #47
0
        sm.computeSpec()
        mags = sm.computeMags(canonDict[band])

        good = np.where(mags > 0)
        if np.size(good[0]) > 10:
            modelhp = healplots.healbin(az[good],
                                        alt[good],
                                        mags[good],
                                        nside=nside)
            zp = np.median(mags[good] - skydata['sky'][good])
            #zps.append(zp)
            fig = plt.figure(num=1)
            hp.mollview(skyhp + zp,
                        rot=(0, 90),
                        sub=(2, 1, 1),
                        fig=1,
                        title='Cannon ' + band + ' mjd=%0.2f' % sm.mjd,
                        min=cmin,
                        max=cmax)
            hp.mollview(modelhp,
                        rot=(0, 90),
                        sub=(2, 1, 2),
                        fig=1,
                        title='Model. Sun Alt = %0.1f, moon alt = %0.1f' %
                        (np.degrees(sm.sunAlt), np.degrees(sm.moonAlt)),
                        min=cmin,
                        max=cmax)

            fig.savefig(
                os.path.join(outDir, 'skymovie_%04d' % counter + '.png'))
            plt.close(1)
# create the input map (or pick it up if maptyp = checkfile) and broadcast it to ID neq 0

if myid == 0:

    map_in = run.map_in

    #save a plot of the input map (can remove this/make it optional)

    cbar = True
    if maptyp == '1pole':
        cbar = False
        print 'the monopole is ', map_in[0]

    plt.figure()
    hp.mollview(map_in, cbar=cbar)
    plt.savefig('%s/map_in_%s.pdf' % (out_path, maptyp))
    plt.close('all')

else:
    map_in = None

map_in = comm.bcast(map_in, root=0)

##########################  RUN  TIMES  #########################################

# RUN TIMES : define start and stop time to search in GPS seconds;
# if checkpoint = True make sure to start from end of checkpoint

counter = 0  #counter = number of mins analysed
start = 1126224017  #start = start time of O1 ...
Example #49
0
    def test_phase(self):
        # Choose scan parameters so that we return to the origin.
        nobs = 366
        precangle = 35.0
        spinangle = 55.0
        spinperiod = 240
        precperiod = 8640

        # Precession axis slew
        degday = 360.0 / 366.0

        samplerate = 1.0 / 60.0

        daysamps = 24 * 60
        goodsamps = 24 * 60
        # goodsamps = 22 * 60
        badsamps = daysamps - goodsamps

        # hit map
        nside = 32
        pix = hpx.Pixels(nside)
        pdata = np.zeros(12 * nside * nside, dtype=np.int32)

        # Only simulate 22 out of 24 hours per observation, in order to test
        # that the starting phase is propagated.  Put the "gap" at the start
        # of each day, so that we can look at the final data point of the
        # final observation.

        zaxis = np.array([0.0, 0.0, 1.0])

        vlast = None

        for ob in range(nobs):
            firstsamp = ob * daysamps + badsamps

            # On the last observation, simulate one extra sample so we get
            # back to the starting point.
            nsim = goodsamps
            if ob == nobs - 1:
                nsim += 1

            qprec = np.empty(4 * nsim, dtype=np.float64).reshape((-1, 4))
            slew_precession_axis(
                qprec, firstsamp=firstsamp, samplerate=samplerate, degday=degday
            )

            boresight = np.empty(4 * nsim, dtype=np.float64).reshape((-1, 4))
            satellite_scanning(
                boresight,
                firstsamp=firstsamp,
                samplerate=samplerate,
                qprec=qprec,
                spinperiod=spinperiod,
                spinangle=spinangle,
                precperiod=precperiod,
                precangle=precangle,
            )

            v = qa.rotate(boresight, zaxis)
            p = pix.vec2ring(v)
            pdata[p] += 1
            vlast = v[-1]

        if self.data.comm.world_rank == 0:
            import matplotlib.pyplot as plt

            hitsfile = os.path.join(self.outdir, "tod_satellite_hits.fits")
            if os.path.isfile(hitsfile):
                os.remove(hitsfile)
            hp.write_map(hitsfile, pdata, nest=False, dtype=np.int32)
            outfile = "{}.png".format(hitsfile)
            hp.mollview(pdata, xsize=1600, nest=False)
            plt.savefig(outfile)
            plt.close()

        np.testing.assert_almost_equal(vlast[0], 0.0)
        np.testing.assert_almost_equal(vlast[1], -1.0)
        np.testing.assert_almost_equal(vlast[2], 0.0)
        return
Example #50
0
def plot_density(input_dir_list,
                 mag,
                 i_bound,
                 i_fig,
                 rows=3,
                 cols=2,
                 title_list=None):

    n_pix = hp.nside2npix(NSIDE)

    margins = (0.01, 0.01, 0.04, 0.01)

    dtype = np.dtype([('ct', int)])
    tag_list = []

    legend = None

    tag = '%s_%d' % (mag, i_bound)

    ct_arr = {}

    for input_dir in input_dir_list:
        list_of_files = os.listdir(input_dir)
        ct_arr[input_dir] = np.zeros(n_pix)
        for file_name in list_of_files:

            if not tag in file_name:
                continue

            full_name = os.path.join(input_dir, file_name)

            with open(full_name, 'r') as input_file:
                if legend is None:
                    legend = input_file.readlines()[0]
                    print legend
                else:
                    assert legend == input_file.readlines()[0]

            data = np.genfromtxt(full_name, dtype=dtype)
            assert len(data['ct']) == n_pix
            ct_arr[input_dir] += data['ct']

    c_min = None
    c_max = None
    for input_dir in input_dir_list:
        lmin = ct_arr[input_dir].min()
        lmax = ct_arr[input_dir].max()
        if c_min is None or lmin < c_min:
            c_min = lmin
        if c_max is None or lmax > c_max:
            c_max = lmax

    for input_dir, title in zip(input_dir_list, title_list):
        if title_list is None:
            fig_title = legend.strip().replace('# ', '')
        else:
            fig_title = legend.strip().replace('# ', '') + ' ' + title

        hp.mollview(ct_arr[input_dir],
                    title=fig_title,
                    cbar=False,
                    margins=margins,
                    sub=(rows, cols, i_fig))
        hp.graticule(dpar=10, dmer=20, verbose=False)

        i_fig += 1

        ax = plt.gca()
        im = ax.get_images()[0]

        cticks = np.arange(c_min, c_max, 0.2 * (c_max - c_min))
        clabels = ['%.2e' % cc for cc in cticks]

        cb = plt.colorbar(im)
        cb.set_ticks(cticks)
        cb.set_ticklabels(clabels)
        cb.set_clim(vmin=c_min, vmax=c_max)
        cb.ax.tick_params(labelsize=10)
        cb.draw_all()

    return i_fig
Example #51
0
def healpix(filename, plotDir, data_out):

    bayestar = True
    if bayestar:
        healpix_data = hp.read_map(filename, field=(0, 1, 2, 3))

        distmu_data = healpix_data[1]
        diststd_data = healpix_data[2]
        prob_data = healpix_data[0]
        norm_data = healpix_data[3]

        plotName = os.path.join(plotDir, 'mollview.png')
        vmin = np.min(prob_data)
        vmax = np.max(prob_data)
        hp.mollview(prob_data, min=vmin, max=vmax, title="", unit='Likelihood')
        hp.graticule()
        plt.show()
        plt.savefig(plotName, dpi=200)
        plotName = os.path.join(plotDir, 'mollview.eps')
        plt.savefig(plotName, dpi=200)
        plotName = os.path.join(plotDir, 'mollview.pdf')
        plt.savefig(plotName, dpi=200)
        plt.close('all')

        distmu_data[distmu_data < 0] = np.inf
        distmu_data_cut = distmu_data[~np.isinf(distmu_data)]

        plotName = os.path.join(plotDir, 'mollview_dist.png')
        vmin = np.min(distmu_data_cut)
        vmax = np.max(distmu_data_cut)

        hp.mollview(distmu_data,
                    min=vmin,
                    max=vmax,
                    title="",
                    unit='Distance [Mpc]')
        hp.graticule()
        plt.show()
        plt.savefig(plotName, dpi=200)
        plotName = os.path.join(plotDir, 'mollview_dist.eps')
        plt.savefig(plotName, dpi=200)
        plotName = os.path.join(plotDir, 'mollview_dist.pdf')
        plt.savefig(plotName, dpi=200)
        plt.close('all')

        diststd_data[diststd_data < 0] = np.inf
        diststd_data_cut = diststd_data[~np.isinf(diststd_data)]

        plotName = os.path.join(plotDir, 'mollview_dist_std.png')
        vmin = np.min(diststd_data_cut)
        vmax = np.max(diststd_data_cut)

        hp.mollview(diststd_data,
                    min=vmin,
                    max=vmax,
                    title="",
                    unit='Distance [Mpc]')
        hp.graticule()
        plt.show()
        plt.savefig(plotName, dpi=200)
        plotName = os.path.join(plotDir, 'mollview_dist_std.eps')
        plt.savefig(plotName, dpi=200)
        plotName = os.path.join(plotDir, 'mollview_dist_std.pdf')
        plt.savefig(plotName, dpi=200)
        plt.close('all')

        distmu_data = hp.ud_grade(distmu_data, nside)
        diststd_data = hp.ud_grade(diststd_data, nside)
        norm_data = hp.ud_grade(norm_data, nside)
    else:
        prob_data = hp.read_map(filename, field=0)
        prob_data = prob_data / np.sum(prob_data)
    prob_data = hp.ud_grade(prob_data, nside)
    prob_data = prob_data / np.sum(prob_data)

    indexes = np.where(prob_data < np.max(prob_data) * 0.01)[0]
    prob_data_nan = prob_data.copy()
    prob_data_nan[indexes] = np.nan
    vmin = np.nanmin(prob_data_nan)
    vmax = np.nanmax(prob_data_nan)

    plotName = os.path.join(plotDir, 'mollview_small.png')
    hp.mollview(prob_data_nan, min=vmin, max=vmax, title="", unit='Likelihood')
    hp.graticule()
    plt.show()
    plt.savefig(plotName, dpi=200)
    plotName = os.path.join(plotDir, 'mollview_small.eps')
    plt.savefig(plotName, dpi=200)
    plotName = os.path.join(plotDir, 'mollview_small.pdf')
    plt.savefig(plotName, dpi=200)
    plt.close('all')

    npix = hp.nside2npix(nside)
    theta, phi = hp.pix2ang(nside, np.arange(npix))
    ra = np.rad2deg(phi)
    dec = np.rad2deg(0.5 * np.pi - theta)
    absm = np.random.rand(len(
        data_out["ra"]), ) * (maxabsm - minabsm) + minabsm
    data_out["absm"] = absm
    fade = np.random.rand(len(
        data_out["ra"]), ) * (maxfade - minfade) + minfade
    data_out["fade"] = fade

    # Run MC
    print "Ra: %.5f %.5f" % (np.min(data_out["ra"]), np.max(data_out["ra"]))
    print "Declination: %.5f %.5f" % (np.min(
        data_out["dec"]), np.max(data_out["dec"]))
    print "Distance: %.5f %.5f" % (np.min(
        data_out["dist"]), np.max(data_out["dist"]))
    print "Absolute Magnitude: %.5f %.5f" % (np.min(
        data_out["absm"]), np.max(data_out["absm"]))

    if telescope == "combined":
        # number of dimensions our problem has
        parameters = [
            "n_PS1", "cl_PS1", "r_PS1", "n_ATLAS", "cl_ATLAS", "r_ATLAS"
        ]
    else:
        # number of dimensions our problem has
        parameters = ["n", "cl", "r"]
    n_params = len(parameters)

    global prob_data, distmu_data

    if telescope == "combined":
        pymultinest.run(myloglike_multi,
                        myprior_multi,
                        n_params,
                        importance_nested_sampling=False,
                        resume=True,
                        verbose=True,
                        sampling_efficiency='parameter',
                        n_live_points=1000,
                        outputfiles_basename='%s/2-' % plotDir,
                        evidence_tolerance=0.001,
                        multimodal=False)
    else:
        pymultinest.run(myloglike,
                        myprior,
                        n_params,
                        importance_nested_sampling=False,
                        resume=True,
                        verbose=True,
                        sampling_efficiency='parameter',
                        n_live_points=1000,
                        outputfiles_basename='%s/2-' % plotDir,
                        evidence_tolerance=0.001,
                        multimodal=False)

    # lets analyse the results
    a = pymultinest.Analyzer(n_params=n_params,
                             outputfiles_basename='%s/2-' % plotDir)
    s = a.get_stats()

    import json
    # store name of parameters, always useful
    with open('%sparams.json' % a.outputfiles_basename, 'w') as f:
        json.dump(parameters, f, indent=2)
    # store derived stats
    with open('%sstats.json' % a.outputfiles_basename, mode='w') as f:
        json.dump(s, f, indent=2)
    print()
    print("-" * 30, 'ANALYSIS', "-" * 30)
    print("Global Evidence:\n\t%.15e +- %.15e" %
          (s['nested sampling global log-evidence'],
           s['nested sampling global log-evidence error']))

    #multifile= os.path.join(plotDir,'2-.txt')
    multifile = get_post_file(plotDir)
    data = np.loadtxt(multifile)

    #loglikelihood = -(1/2.0)*data[:,1]
    #idx = np.argmax(loglikelihood)

    if telescope == "combined":

        n_PS1 = data[:, 0]
        cl_PS1 = data[:, 1]
        r_PS1 = data[:, 2]
        n_ATLAS = data[:, 3]
        cl_ATLAS = data[:, 4]
        r_ATLAS = data[:, 5]
        loglikelihood = data[:, 6]
        idx = np.argmax(loglikelihood)

        n_PS1_best = data[idx, 0]
        cl_PS1_best = data[idx, 1]
        r_PS1_best = data[idx, 2]
        n_ATLAS_best = data[idx, 3]
        cl_ATLAS_best = data[idx, 4]
        r_ATLAS_best = data[idx, 5]

        image_optimal_array = numimages_combine(prob_data, distmu_data,
                                                data_out, n_PS1_best,
                                                cl_PS1_best, r_PS1_best,
                                                n_ATLAS_best, cl_ATLAS_best,
                                                r_ATLAS_best)
        image_optimal_array_sorted = np.sort(image_optimal_array)

        image_nominal_array = numimages_combine(prob_data, distmu_data,
                                                data_out, 0.0, 0.99, 0.0, 0.0,
                                                0.99, 0.0)
        image_nominal_array_sorted = np.sort(image_nominal_array)

        image_known_array = numknown(prob_data, data_out, PS1_Telescope_T,
                                     PS1_Telescope_m)
        image_known_array_sorted = np.sort(image_known_array)

        filename = os.path.join(plotDir, 'samples.dat')
        fid = open(filename, 'w+')
        for i, j, k, l, m, o in zip(n_PS1, cl_PS1, r_PS1, n_ATLAS, cl_ATLAS,
                                    r_ATLAS):
            fid.write('%.5f %.5f %.5f %.5f %.5f %.5f\n' % (i, j, k, l, m, o))
        fid.close()

        filename = os.path.join(plotDir, 'best.dat')
        fid = open(filename, 'w')
        fid.write('%.5f %.5f %.5f %.5f %.5f %.5f\n' %
                  (n_PS1_best, cl_PS1_best, r_PS1_best, n_ATLAS_best,
                   cl_ATLAS_best, r_ATLAS_best))
        fid.close()

        plt.figure(figsize=(12, 10))
        bins1, hist1 = hist_results(n_PS1)
        bins2, hist2 = hist_results(n_ATLAS)
        #plt.plot(bins1, np.cumsum(hist1),'k',label='PS1')
        #plt.plot(bins2, np.cumsum(hist2),'k--',label='ATLAS')
        plt.plot(bins1, hist1, 'k', label='PS1')
        plt.plot(bins2, hist2, 'k--', label='ATLAS')
        plt.legend(loc='best')
        #plt.xlim([10,1e6])
        #plt.ylim([0,1.0])
        plt.xlabel('Likelihood Powerlaw Index')
        plt.ylabel('Probability Density Function')
        plt.show()
        plotName = os.path.join(plotDir, 'n.pdf')
        plt.savefig(plotName, dpi=200)
        plt.close('all')

        plt.figure(figsize=(12, 10))
        bins1, hist1 = hist_results(cl_PS1)
        bins2, hist2 = hist_results(cl_ATLAS)
        #plt.plot(bins1, np.cumsum(hist1),'k',label='PS1')
        #plt.plot(bins2, np.cumsum(hist2),'k--',label='ATLAS')
        plt.plot(bins1, hist1, 'k', label='PS1')
        plt.plot(bins2, hist2, 'k--', label='ATLAS')
        plt.legend(loc='best')
        #plt.xlim([10,1e6])
        #plt.ylim([0,1.0])
        plt.xlabel('Likelihood Confidence Level')
        plt.ylabel('Probability Density Function')
        plt.show()
        plotName = os.path.join(plotDir, 'cl.pdf')
        plt.savefig(plotName, dpi=200)
        plt.close('all')

        plt.figure(figsize=(12, 10))
        bins1, hist1 = hist_results(r_PS1)
        bins2, hist2 = hist_results(r_ATLAS)
        #plt.plot(bins1, np.cumsum(hist1),'k',label='PS1')
        #plt.plot(bins2, np.cumsum(hist2),'k--',label='ATLAS')
        plt.plot(bins1, hist1, 'k', label='PS1')
        plt.plot(bins2, hist2, 'k--', label='ATLAS')
        plt.legend(loc='best')
        #plt.xlim([10,1e6])
        #plt.ylim([0,1.0])
        plt.xlabel('Distance Powerlaw Index')
        plt.ylabel('Probability Density Function')
        plt.show()
        plotName = os.path.join(plotDir, 'r.pdf')
        plt.savefig(plotName, dpi=200)
        plt.close('all')

    else:
        n = data[:, 0]
        cl = data[:, 1]
        r = data[:, 2]
        loglikelihood = data[:, 3]
        idx = np.argmax(loglikelihood)

        n_best = data[idx, 0]
        cl_best = data[idx, 1]
        r_best = data[idx, 2]

        image_optimal_array = numimages(prob_data, distmu_data, data_out,
                                        Telescope_T, Telescope_m, n_best,
                                        cl_best, r_best)
        image_optimal_array_sorted = np.sort(image_optimal_array)

        image_nominal_array = numimages(prob_data, distmu_data, data_out,
                                        Telescope_T, Telescope_m, 0.0, 0.99,
                                        0.0)
        image_nominal_array_sorted = np.sort(image_nominal_array)

        image_known_array = numknown(prob_data, data_out, Telescope_T,
                                     Telescope_m)
        image_known_array_sorted = np.sort(image_known_array)

        filename = os.path.join(plotDir, 'samples.dat')
        fid = open(filename, 'w+')
        for i, j, k in zip(n, cl, r):
            fid.write('%.5f %.5f %.5f\n' % (i, j, k))
        fid.close()

        filename = os.path.join(plotDir, 'best.dat')
        fid = open(filename, 'w')
        fid.write('%.5f %.5f %.5f\n' % (n_best, cl_best, r_best))
        fid.close()

        plt.figure(figsize=(12, 10))
        bins1, hist1 = hist_results(n)
        plt.plot(bins1, hist1)
        plt.xlabel('Powerlaw Index')
        plt.ylabel('Probability Density Function')
        plt.show()
        plotName = os.path.join(plotDir, 'n.pdf')
        plt.savefig(plotName, dpi=200)
        plt.close('all')

        plt.figure(figsize=(12, 10))
        bins1, hist1 = hist_results(cl)
        plt.plot(bins1, hist1)
        plt.xlabel('Powerlaw Index')
        plt.ylabel('Probability Density Function')
        plt.show()
        plotName = os.path.join(plotDir, 'cl.pdf')
        plt.savefig(plotName, dpi=200)
        plt.close('all')

        plt.figure(figsize=(12, 10))
        bins1, hist1 = hist_results(r)
        plt.plot(bins1, hist1)
        plt.xlabel('Powerlaw Index')
        plt.ylabel('Probability Density Function')
        plt.show()
        plotName = os.path.join(plotDir, 'r.pdf')
        plt.savefig(plotName, dpi=200)
        plt.close('all')

        ns = np.linspace(0.01, 2.0, 50)
        cls = np.linspace(0.5, 1.0, 50)

        images_detected = np.zeros((len(ns), len(cls)))
        images_T = np.zeros((len(ns), len(cls)))

        for ii, n in enumerate(ns):
            for jj, cl in enumerate(cls):
                image_array = numimages(prob_data, distmu_data, data_out,
                                        Telescope_T, Telescope_m, n, cl, 0.0)
                image_array_sorted = np.sort(image_array)

                tmax = tmax = data_out["fade"] * 3600
                image_detected = float(len(
                    np.where(image_array < tmax)[0])) / float(len(image_array))

                index = np.floor(len(image_array) * 0.5)
                image_T = image_array_sorted[index]

                images_detected[ii, jj] = image_detected
                images_T[ii, jj] = image_T / 3600.0

        NS, CLS = np.meshgrid(ns, cls)

        vmin = np.min(images_detected)
        vmax = np.max(images_detected)
        plotName = os.path.join(plotDir, 'images_detected.png')
        plt.figure()
        plt.pcolor(NS,
                   CLS,
                   images_detected.T,
                   vmin=vmin,
                   vmax=vmax,
                   cmap=plt.get_cmap('rainbow'))
        cbar = plt.colorbar()
        cbar.ax.set_ylabel('Percentage of detections')
        plt.xlabel('Power Law Index')
        plt.ylabel('Confidence Level')
        plt.xlim([0.01, 2.0])
        plt.ylim([0.5, 1.0])
        plt.show()
        plt.savefig(plotName, dpi=200)
        plotName = os.path.join(plotDir, 'images_detected.eps')
        plt.savefig(plotName, dpi=200)
        plotName = os.path.join(plotDir, 'images_detected.pdf')
        plt.savefig(plotName, dpi=200)
        plt.close('all')

        vmin = 0.0
        vmax = 10.0
        plotName = os.path.join(plotDir, 'images_T.png')
        plt.figure()
        plt.pcolor(NS,
                   CLS,
                   images_T.T,
                   vmin=vmin,
                   vmax=vmax,
                   cmap=plt.get_cmap('rainbow'))
        cbar = plt.colorbar()
        cbar.ax.set_ylabel('Median detection time [hours]')
        plt.xlabel('Power Law Index')
        plt.ylabel('Confidence Level')
        plt.xlim([0.01, 2.0])
        plt.ylim([0.5, 1.0])
        plt.show()
        plt.savefig(plotName, dpi=200)
        plotName = os.path.join(plotDir, 'images_T.eps')
        plt.savefig(plotName, dpi=200)
        plotName = os.path.join(plotDir, 'images_T.pdf')
        plt.savefig(plotName, dpi=200)
        plt.close('all')

    nums = np.arange(0, len(image_nominal_array_sorted))
    nums[:] = 1.0
    nums = nums / np.sum(nums)
    nums_cumsum = np.cumsum(nums)

    plotName = os.path.join(plotDir, 'optimization.png')
    plt.figure()
    plt.semilogx(image_nominal_array_sorted,
                 100 * nums_cumsum,
                 'k--',
                 label='Naive')
    plt.semilogx(image_optimal_array_sorted,
                 100 * nums_cumsum,
                 'r.-',
                 label='Optimal')
    plt.semilogx(image_known_array_sorted,
                 100 * nums_cumsum,
                 'c',
                 label='Known')
    plt.legend(loc=2)
    plt.xlim([10, 1e6])
    plt.ylim([0, 100.0])
    plt.xlabel('Time [s]')
    plt.ylabel('Percentage of imaged counterparts')
    plt.show()
    plt.savefig(plotName, dpi=200)
    plotName = os.path.join(plotDir, 'optimization.eps')
    plt.savefig(plotName, dpi=200)
    plotName = os.path.join(plotDir, 'optimization.pdf')
    plt.savefig(plotName, dpi=200)
    plt.close('all')

    filename = os.path.join(plotDir, 'images.dat')
    fid = open(filename, 'w+')
    for i, j, k, l in zip(nums_cumsum, image_nominal_array_sorted,
                          image_optimal_array_sorted,
                          image_known_array_sorted):
        fid.write('%.5e %.5e %.5e %.5e\n' % (i, j, k, l))
    fid.close()
Example #52
0
import numpy as np
import pylab as py
import healpy as h
import sys
'''

'''

filename1 = '/home/cmb/tmatsumu/develop/LiteBIRD/projects/LB_SYSPL_v4.1_release/Simulator/data_proj/SimedMaps/RunLog/20160818_140GHz_TQU_1/coadd_map/coadd_map1/mapAA_CNexcluded'
filename2 = '/home/cmb/tmatsumu/develop/LiteBIRD/projects/LB_SYSPL_v4.1_release/Simulator/data_proj/SimedMaps/RunLog/20160818_140GHz_TQU_2/coadd_map/coadd_map1/mapAA_CNexcluded'
mapin1 = h.read_map(filename1 + '.fits')
mapin2 = h.read_map(filename2 + '.fits')
h.mollview(mapin1 / mapin2, max=2000, min=1)
py.savefig('AAratio.png')

#h.mollview(mapin1/mapin2,norm='log')
#py.savefig('AAratio_log.png')
Example #53
0
import healpy
import matplotlib.pypot as plt
import scipy
betw = lambda x, x1, x2: (x > x1) & (x < x2)

exec idlsave.restore('gaia_scan_512_gal.psav')

#locs=np.r_[np.arange(48)/24.,np.arange(2,365),np.arange(365,5*365,5)]
locs = np.r_[1, 10, 100, 500]


def doit(x):
    return scipy.histogram(x, locs)[0]


superres = [doit(_) for _ in obstimes]
arr = np.array(superrres)
arr = np.array(superres)

for i in range(nx):
    plt.clf()
    healpy.mollview((arr[:, :i]).sum(axis=1),
                    fig=1,
                    nest=True,
                    hold=True,
                    title='%.03f days' % locs[i],
                    min=0,
                    max=max(((arr[:, :i]).sum(axis=1)).max(), 1),
                    xsize=2000)
    plt.savefig('xx_%04d.png' % i, dpi=600)
Example #54
0
			tfiles = [ gmodel.galaxy.cmb.filename, gmodel.galaxy.dust.filename, gmodel.galaxy.freefree.filename, 
				gmodel.galaxy.sync.filename, h.filename, dir+'map_monopole_ns0128.fits', dir+'map_xdipole_ns0128.fits',
				dir+'map_ydipole_ns0128.fits', dir+'map_zdipole_ns0128.fits' ]

			map = getattr( data, 'f'+freq )
			r = map_regression( map.imap.map, tfiles, rms=map.irms.map, maskfile=setup.mask.filename, return_res=True, return_chi2=True )
			chisq_nod.append( str("%.3f" % r[3]) )
			c2 += r[3]

			if plot_gnom:
				ccc = r[0][5] + gmodel.galaxy.dipole_x.map*r[0][6] + \
					gmodel.galaxy.dipole_y.map*r[0][7] + \
					gmodel.galaxy.dipole_z.map*r[0][8]
				ccc = asinh10( ccc )
				# ccc[bpix] = hp.UNSEEN
				hp.mollview( ccc, title=freq, fig=1)
				hp.graticule( dpar=20, dmer=20 )

				ccc = asinh10( map.imap.map )
				hp.mollview( ccc, title=freq, fig=3)
				hp.graticule( dpar=20, dmer=20 )

			# freq_min[ freq ] = r
			mnpnt_nod['f'+freq+'_cmb'] = r[0][0]
			mnpnt_nod['f'+freq+'_dust'] = r[0][1]
			mnpnt_nod['f'+freq+'_freefree'] = r[0][2]
			mnpnt_nod['f'+freq+'_sync'] = r[0][3]
			mnpnt_nod['f'+freq+'_haze'] = r[0][4]
			mnpnt_nod['f'+freq+'_monopole'] = r[0][5]
			mnpnt_nod['f'+freq+'_dipole_x'] = r[0][6]
			mnpnt_nod['f'+freq+'_dipole_y'] = r[0][7]
Example #55
0
    idx = (zred != -1.)
    zred = zred[idx]
    idy = (zred <= 0.33)
    zred = zred[idy]
    mu_r = -1.0 + 2.*np.random.random(size = Nsize)
    phi_r = 2.0*np.pi*np.random.random(size = Nsize)
    theta_r = np.arccos(mu_r)

    pix = healpy.pixelfunc.ang2pix(2048, theta_r, phi_r)
    mask = (seln_func[pix] == 1) #Select only points within the seln_func
    theta_r = theta_r[mask]
    phi_r = phi_r[mask]
    zred_r = zred[np.random.permutation(phi_r.size) % zred.size] #Produce 'random' redshifts

    fig = plt.figure(1)
    healpy.mollview(seln_func,norm = 'hist', cmap = 'PRGn')
    fig.savefig(sel_fig)

    fig = plt.figure(2)
    healpy.mollview(seln_func, norm = 'hist', cmap = 'PRGn')
    healpy.projscatter(planck_theta, planck_phi, s = 1, lw = 0)
    fig.savefig(bcg_fig)

    fig = plt.figure(3)
    healpy.mollview(seln_func, norm = 'hist', cmap = 'PRGn')
    healpy.projscatter(theta_r, phi_r, s = 1, lw = 0)
    fig.savefig(dist_fig)

    # Now convert using astropy coordinates
    c = SkyCoord(l = phi_r, b = np.pi/2 - theta_r, frame = 'galactic', unit = 'radian')
    output = np.transpose([c.icrs.ra.deg,c.icrs.dec.deg,zred_r])
  invlap = 1.0 / ls / (ls + 1.0)
  invlap[0] = 0.0 # zero monopole (?)
  dPlm = hp.almxfl(dPlm, invlap)
  
  # contribution to map from each radial bin
  print("Computing dT_in_bin.")
  # total map is this integrated in all bins * geometric factors...
  chi_bin = (bin_lower_chi+bin_upper_chi)/2.0
  z_bin = zofchi(chi_bin)
  a_bin = 1.0 / (1.0 + z_bin)
  H_bin = Hofz(z_bin)/c
  dT_ML_lms += 3.0 * d_chi * (a_bin*H_bin)**2 * chi_bin * dPlm

# Store & Plot result.
dT_ML = hp.alm2map(dT_ML_lms, NSIDE)
hp.mollview(dT_ML)
plt.title('Moving Lens sky')
plt.savefig('Tmap_ML.png')
plt.close()
hp.fitsfunc.write_map('ML.fits', dT_ML, overwrite=True)

# Plot power spectra
CMBTuk = 2750000.
CMB_alms = hp.fitsfunc.read_alm('lensed_alm.fits').astype(np.complex)/CMBTuk
MLPS = hp.anafast(dT_ML)
CMBPS = hp.alm2cl(CMB_alms)

def Ls(PS) :
  return np.arange(len(PS))

def norm(PS) :
# result in an error if LaTeX is not installed on your system.  In that case,
# you can set usetex to False.
from astroML.plotting import setup_text_plots
setup_text_plots(fontsize=8, usetex=True)

#------------------------------------------------------------
# First plot an example pixellization

# Prepare the healpix pixels
NSIDE = 4
m = np.arange(hp.nside2npix(NSIDE))
print("number of pixels:", len(m))

# Plot the pixelization
fig = plt.figure(1, figsize=(5, 3.75))
hp.mollview(m, nest=True, title="HEALPix Pixels (Mollweide)", fig=1)

# remove colorbar: we don't need it for this plot
fig.delaxes(fig.axes[1])

#------------------------------------------------------------
# Next plot the wmap pixellization
wmap_unmasked = fetch_wmap_temperatures(masked=False)

# plot the unmasked map
fig = plt.figure(2, figsize=(5, 3.75))
hp.mollview(wmap_unmasked,
            min=-1,
            max=1,
            title='Raw WMAP data',
            unit=r'$\Delta$T (mK)',
Example #58
0
    print('number of galaxies randoms: ', len(ra_rand_g))
    print('number of matter randoms: ', len(ra_rand_m))

    if make_plots:

        def eq2ang(ra, dec):
            phi = ra * np.pi / 180.
            theta = (np.pi / 2.) - dec * (np.pi / 180.)
            return theta, phi

        theta_m, phi_m = eq2ang(ra_rand_m, dec_rand_m)
        ind_m_f = hp.ang2pix(128, theta_m, phi_m)
        mask_m = np.zeros(hp.nside2npix(128))
        mask_m[ind_m_f] = 1
        plt.figure()
        hp.mollview(mask_m)
        plt.savefig(save_dir + 'rand_m_sky.png')

    # pdb.set_trace()

    galaxy_param_dict = {'RA': ra_g, 'DEC': dec_g, 'R': r_g, 'JK': jk_g}
    galaxy_random_param_dict = {
        'RA': ra_rand_g,
        'DEC': dec_rand_g,
        'R': r_rand_g,
        'JK': jk_rand_g
    }
    matter_param_dict = {'RA': ra_m, 'DEC': dec_m, 'R': r_m, 'JK': jk_m}
    matter_random_param_dict = {
        'RA': ra_rand_m,
        'DEC': dec_rand_m,
Example #59
0
# In[3]:

get_ipython().magic(u'matplotlib inline')

import healpy
import matplotlib.pyplot as plt

#stack all maps
crMap = np.zeros(49152)
for pid in M.getParticleIds():
    energies = M.getEnergies(int(pid))
    for i, energy in enumerate(energies):
        crMap += M.getMap(int(pid), energy * crpropa.eV)

#plot maps using healpy
healpy.mollview(map=crMap, title='Unlensed')
plt.savefig('unlensed_map.png')

# ## Apply Galactic Lenses
#
# To apply a lens to a map, a lens object needs to be created and then applied to the map. The normalization of the lens ensures that the lens does not distort the spectra.

# In[5]:

get_ipython().magic(u'matplotlib inline')

# The lens can be downloaded here: https://crpropa.desy.de/ --> Additional downloads
lens = crpropa.MagneticLens('pathto/lens.cfg')
lens.normalizeLens()
M.applyLens(lens)
Example #60
0
galm = ct.rearange_alm(
    lmax,
    alm_data)  #preoblikovanje tabele podatkov v obliko, ki jo vrne map2alm
#g v imenu definiran za galaktične koordinate
#print(galm)

gmapa = hp.alm2map(galm, nside=64)  #kreacija mape iz galm koeficientov

#gmapa=gmapa*10**-2                        #renormalizacija (še ne pravilna)

b = cm.seismic  #
b.set_under("w")  #
hp.mollview(gmapa,
            cmap=b,
            title='Planck Kappa mapa (galaktični sistem)',
            cbar=True,
            xsize=1400)  #izris mape
#ct.mollaxes()
hp.graticule(coord=('E'))  #
plt.show()

#alm_check=hp.map2alm(gmapa,lmax=lmax)       #preveritev, če vrne map2alm vsaj podobne koeficiente kot v originalnih podatkih (vrne renormalizirane, ker vrnejo isto obliko mape z renormaliziranimi vrednostmi)

b, l, aomega = ct.eq2gal(0, 90)

hp.rotate_alm(galm, psi=l, theta=b, phi=aomega, lmax=lmax)

emapa = hp.alm2map(galm, nside=64)  #kreacija mape iz ealm koeficientov

#emapa=emapa*10**-2                        #renormalizacija (še ne pravilna)