myIO.py 7.87 KB
Newer Older
Maude Martin's avatar
Maude Martin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
"""
 I/O wrapper which handles both FITS and DMC format
"""

# Copyright (C) 2009 APC CNRS Universite Paris Diderot
# <lejeune@apc.univ-paris7.fr>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see http://www.gnu.org/licenses/gpl.html        

try:
    import piolib as pio
except ImportError:
    print "Can't import piolib"
import healpy as hp
import fitsfunc2 as sp
import os
import numpy as np

def __piolib(file):
    return not(os.path.realpath(file)[-1-3:]=='fits')

def save_pie_param (file, dic):
    """ Save a python dictionnary into a pie parameter file

    Parameters
    ----------
    file: string, pie file name
    dic: dictionnary
    """
    f = open(file, "w")
    for name, value in dic.items():
        if isinstance(value, list):
            f.write("number_of_"+name+" ="+str(len(value))+"\n")
            for el in range(len(value)):
                f.write(name+str(el+1)+' = '+str(value[el])+'\n')
        else:
            f.write(name+' = '+str(value)+'\n')
    f.close()   
    
            
        
def checkgroup (groupname, PIOTYPE, *args):
    """ Check that groupname of type PIOTYPE exists, if not create it with arguments args.
    """
    try:
        exec("test_grp = pio.Open"+PIOTYPE+"Grp(groupname,\"r\")")
        exec("pio.Close"+PIOTYPE+"Grp(test_grp)")
    except Exception, e:
        print "Grp " + groupname + " not found, creating it..."
        if len(args)>0:
            arglist = ","+",".join(args)
        else:
            arglist = ""
        try:
            exec("pio.Create"+PIOTYPE+"Grp(groupname"+arglist+")")
        except Exception, e2:
            print "cannot create group "+groupname+" !!!"
                
def read_map(file):
    """ Read Healpix map from file

    Parameters
    ----------
    file: string, FITS file name or DMC object name

    Returns
    -------
    m, array-like.
    """
    if __piolib(file):
        m = pio.ReadMAPObject(file, "PIODOUBLE", "")
    else:
        m = hp.read_map(file)
    return m

def write_map (file, map):
    """ Write map to file.

    Parameters
    ----------
    file: string, FITS file name or DMC object name
    map: array-like, Healpix map
    
    """
    if __piolib(file):
        order  = "RING"
        coord  = "GALACTIC"
        nside  = hp.npix2nside(len(map))
        try:
            grpname = pio.GetGrpName(file)
            checkgroup (grpname, "MAP", "\""+coord+"\"", "\""+order+"\"", str(nside)) 
            grp     = pio.OpenMAPGrp(grpname, "w")
            val     = pio.CreateMAPObject(file,'PIODOUBLE')
            pio.WriteMAPObject (map, file, 'PIODOUBLE','',grp)
            pio.CloseMAPGrp(grp)
        except pio.pioError,val: 
            return str(val)
    else:
Maude Le Jeune's avatar
Maude Le Jeune committed
110
        hp.write_map(file, map,dtype=np.float64 )
Maude Martin's avatar
Maude Martin committed
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131

def read_alm (file):
    """ Read Healpix alm from file

    Parameters
    ----------
    file: string, FITS file name or DMC object name
    
    Returns
    -------
    alm, array-like.
    """
    if __piolib(file):
        vec  = pio.ReadVECTObject(file, "PIODOUBLE", "")
        lmax = np.round((np.sqrt(1+8*len(vec)/2)-3)/2);
        alm  = np.zeros(( (lmax+1)*(lmax+2)/2, 1), dtype="complex")
        j = 0
        for i in range(0,len(vec),2):
            alm[j] = complex(vec[i], vec[i+1])
            j = j+1
    else:
Maude Le Jeune's avatar
+nilc  
Maude Le Jeune committed
132
        alm = hp.read_alm(file)
Maude Martin's avatar
Maude Martin committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
    return np.squeeze(alm)
    

def write_alm(file, alm):
    """ Write alm to file.
    
    Parameters
    ----------
    file: string, FITS file name or DMC object name
    alm: array-like, Healpix alm
    
    """

    if __piolib(file):
        salm = len(alm)  
        tabalm  = np.zeros(( salm*2, 1))
        j = 0
        for i in range(0,salm*2,2):
            tabalm[i]   = alm[j].real
            tabalm[i+1] = alm[j].imag
            j = j+1   
        try:
            grpname = pio.GetGrpName(file)
            checkgroup(grpname, "VECT")
            grp     = pio.OpenVECTGrp(grpname, "w")
            val     = pio.CreateVECTObject(file,'PIODOUBLE')
            pio.WriteVECTObject (tabalm, file, 'PIODOUBLE','begin=0 &\n end='+str(salm*2-1),grp)
            pio.CloseVECTGrp(grp)
        except pio.pioError,val:
            return str(val)
    else:
Maude Le Jeune's avatar
Maude Le Jeune committed
164
        sp.write_alm(file, alm)     
Maude Martin's avatar
Maude Martin committed
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228

def read_cl (file):
    """ Read cl from file
    
    Parameters
    ----------
    file: string, FITS file name or DMC object name
    
    Returns
    -------
    cl, array-like.
    """
    if __piolib(file):
        cl  = pio.ReadVECTObject(file, "PIODOUBLE", "")
    else:
        cl = sp.read_cl(file)
    return np.squeeze(cl)

def write_cl(file, cl):
    """ Write cl to file.
    
    Parameters
    ----------
    file: string, FITS file name or DMC object name
    cl: array-like
    
    """
    if __piolib(file):
        try:
            grpname = pio.GetGrpName(file)
            checkgroup (grpname, "VECT")
            grp     = pio.OpenVECTGrp(grpname, "w")
            val     = pio.CreateVECTObject(file,'PIODOUBLE')
            lmax    = len(cl)-1
            pio.WriteVECTObject (cl, file, 'PIODOUBLE','begin=0 &\n end='+str(lmax),grp)
            pio.CloseVECTGrp(grp)
        except pio.pioError,val:
            return str(val)
    else:
        sp.write_cl(file, cl) 
            
def read_cat (file):
    """ Read cat from file
    
    Parameters
    ----------
    file: string, FITS file name or DMC object name
    
    Returns
    -------
    cat, array-like.
    """
    if __piolib(file):
        cat  = pio.ReadTAB2DObject(file, "PIODOUBLE", "")
        grpname = pio.GetGrpName(file)
        grp  = pio.OpenTAB2DGrp(grpname, "r")   
        ncols= pio.GetTAB2DColumnGrp(grp)
        nrows   = len(cat)/ncols
        cat = cat.reshape(nrows, ncols)
    else:
        cat = np.loadtxt(file)
    return cat   

def write_covmat(file, cov, nbmodes=None):
Maude Martin's avatar
Maude Martin committed
229
    """ Write cov mat to file.
Maude Martin's avatar
Maude Martin committed
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    
    Parameters
    ----------
    file: string, FITS file name or DMC object name
    stats: array-like
    nbmodes: array-like
    """
    if __piolib(file):
        try:
            grpname = pio.GetGrpName(file)
            checkgroup (grpname, "TAB2D")
            grp     = pio.OpenTAB2DGrp(grpname, "w")
            val     = pio.CreateTAB2DObject(file,'PIODOUBLE')
            nr = shape(R)[0]
            nc = shape(R)[1]+1
            val = pio.WriteTAB2DObject(w,file, 'PIO'+precision,"tab=0:0,0:"+str(nr-1) , grp)
            val = pio.WriteTAB2DObject(R,file, 'PIO'+precision,"tab=1:"+str(nc-1)+",0:"+str(nr-1) , grp)
            val     = pio.CloseTAB2DGrp(grp)
            pio.CloseTAB2DGrp(grp)
        except pio.pioError,val:
            return str(val)
Maude Le Jeune's avatar
Maude Le Jeune committed
251 252
    else:
        sp.write_covmat(file, cov, nbmodes=nbmodes)    
Maude Martin's avatar
Maude Martin committed
253 254 255
            
            
            
Maude Martin's avatar
Maude Martin committed
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
def write_table(file, tab):
    """ Write table to file.
    
    Parameters
    ----------
    file: string, FITS file name or DMC object name
    tab: array-like
    """
    if __piolib(file):
        try:
            grpname = pio.GetGrpName(file)
            checkgroup (grpname, "TAB2D")
            grp     = pio.OpenTAB2DGrp(grpname, "w")
            val     = pio.CreateTAB2DObject(file,'PIODOUBLE')
            nr = shape(tab)[0]
            nc = shape(tab)[1]
            val = pio.WriteTAB2DObject(tab,file, 'PIO'+precision,"tab=0:%d,0:%d"%((nc-1),(nr-1)) , grp)
            pio.CloseTAB2DGrp(grp)
        except pio.pioError,val:
            return str(val)
        else:
            sp.write_table(file, tab)
            
            
            
Maude Le Jeune's avatar
Maude Le Jeune committed
281