Exemple #1
0
def from_file(f):
    if type(f) == type(""):
        f = file(f, 'rb')
    if f.mode != 'rb':
        raise "FileModeError: file mode must equal 'rb'"
    array_type = string.strip(f.readline())
    array_shape = eval(string.strip(f.readline()))
    byteorder = string.strip(f.readline())
    a = numarray.fromfile(f, array_type, array_shape)
    f.close()
    if byteorder != sys.byteorder:
        a.byteswap()
    return a
Exemple #2
0
def _open_fix(file):
    """Takes in a fits file name, open the file in binary mode and creates an HDU.

    Will attempt to fix some of the header keywords to match the standard FITS format.
    """
    import pyfits, re, string
    temp = pyfits.HDUList()
    hdu = pyfits.PrimaryHDU()

    hdu._file=open(file,'rb')

    _number_RE = re.compile(
                r'(?P<sign>[+-])?0*(?P<digt>(\.\d+|\d+(\.\d*)?)([deDE][+-]?\d+)?)')

    ### here's the real difference between pyFits and cfh12kFits.
    ### I'm more flexible on the format of the header file so that allows me
    ### read more files.
    card_RE=re.compile(r"""
    (?P<KEY>[-A-Z0-9_a-za ]{8})   ### keyword is the first 8 bytes... i'll allow small letters
    (
     (
      (?P<VALUE>=\s)             ### =\s indicats a value coming.
      (\s*
       (   
        (?P<STRING>\'[^\']*[\'/])   ### a string 
        |
        (?P<FLOAT>([+-]?(\.\d+|\d+\.\d*)([dDEe][+-]?\d+)?))  ### a floating point number
        |
        (?P<INT>[+-]?\d+)      ### an integer
        |
        (?P<BOOL>[TFtf])       ### perhaps value is boolian
        )
       \s*
       (( / )?(?P<COMMENT>.*))?    ### value related comment.
      )
     )
     |
     (?P<C2>.*)     ### strickly a comment field
    )
    """,re.VERBOSE)

    
    done=0
    while ( not done):

        ### read a line of 80 characters up to a new line from the file.
        block=hdu._file.readline(80)

        string_end=79
        if len(block)== 0:
            done=1
            continue
        if block[-1]=='\n':
            string_end=len(block)-2

        line = re.match(r'[ -~]{0,'+str(string_end)+'}',block)

        line = string.ljust(line.group(0),80)[0:79]

        if line[0:8] == 'END     ':
            done=1
            break

        card=card_RE.match(line)
        if not card or not card.group('KEY'):
            print card.groups()
            raise SyntaxError("Failed to get keyword from FITS Card %s" % line)
            
        key=card.group('KEY')
        value=None
        if card.group('INT'):
            try:
                value=int(card.group('INT'))
            except:
                value=card.group('INT')
        elif card.group('FLOAT'):
            try:
                value=float(card.group('FLOAT'))
            except:
                value=float(card.group('FLOAT'))
        elif card.group('BOOL'):
            value=pyfits.Boolean(card.group('BOOL'))
        elif card.group('STRING'):
            value=card.group('STRING')[1:-1]
            
        if card.group('COMMENT'):
            _comment=card.group('COMMENT')
        elif card.group('C2'):
            _comment=card.group('C2')
        else:
            _comment=None

        try:
            if key =='COMMENT ':
                hdu.header.add_comment(_comment)
            elif key =='HISTORY ':
                hdu.header.add_history(_comment)
            elif key =='        ':
                hdu.header.add_blank(_comment)
            elif key:
                if key =='DATE-OBS' and value:
                    value=string.replace(value,'/','-')
                hdu.header.update(key,value,comment=_comment)
        except:
            raise SyntaxError("Failed to convert line to FITS Card %s" % line)

    ### set some internal variables to decided on data flow.
    hdu._bzero=hdu.header.get('BZERO',0)
    hdu._bscale=hdu.header.get('BSCALE',1)
    hdu._bitpix=hdu.header.get('BITPIX',-16)

    if hdu.header.get('NAXIS',0)>0:
        naxis1=hdu.header.get('NAXIS1',1)
        naxis2=hdu.header.get('NAXIS2',1)
    ### now read the data... this is a HACK from pyfits.py
        import numarray as num
    
        code = pyfits._ImageBaseHDU.NumCode[hdu._bitpix]
        dims = tuple([naxis2,naxis1])
        raw_data = num.fromfile(hdu._file,type=code,shape=dims)
        raw_data._byteorder='big'

        if ( hdu._bzero != 0
             or hdu._bscale!=1 ):
            if  hdu._bitpix > 0 :
                hdu.data=num.array(raw_data,type=num.Float32)
            else:
                hdu.data=raw_data
            if hdu._bscale != 1:
                num.multiply(hdu.data,hdu._bscale,hdu.data)
            if hdu._bzero!=0:
                hdu.data=hdu.data + hdu._bzero

            del hdu.header['BSCALE']
            del hdu.header['BZERO']
            hdu.header['BITPIX']=pyfits._ImageBaseHDU.ImgCode[hdu.data.type()]
            
    temp.append(hdu)
    return temp
Exemple #3
0
def _open_fix(file):
    """Takes in a fits file name, open the file in binary mode and creates an HDU.

    Will attempt to fix some of the header keywords to match the standard FITS format.
    """
    import pyfits, re, string
    temp = pyfits.HDUList()
    hdu = pyfits.PrimaryHDU()

    hdu._file = open(file, 'rb')

    _number_RE = re.compile(
        r'(?P<sign>[+-])?0*(?P<digt>(\.\d+|\d+(\.\d*)?)([deDE][+-]?\d+)?)')

    ### here's the real difference between pyFits and cfh12kFits.
    ### I'm more flexible on the format of the header file so that allows me
    ### read more files.
    card_RE = re.compile(
        r"""
    (?P<KEY>[-A-Z0-9_a-za ]{8})   ### keyword is the first 8 bytes... i'll allow small letters
    (
     (
      (?P<VALUE>=\s)             ### =\s indicats a value coming.
      (\s*
       (   
        (?P<STRING>\'[^\']*[\'/])   ### a string 
        |
        (?P<FLOAT>([+-]?(\.\d+|\d+\.\d*)([dDEe][+-]?\d+)?))  ### a floating point number
        |
        (?P<INT>[+-]?\d+)      ### an integer
        |
        (?P<BOOL>[TFtf])       ### perhaps value is boolian
        )
       \s*
       (( / )?(?P<COMMENT>.*))?    ### value related comment.
      )
     )
     |
     (?P<C2>.*)     ### strickly a comment field
    )
    """, re.VERBOSE)

    done = 0
    while (not done):

        ### read a line of 80 characters up to a new line from the file.
        block = hdu._file.readline(80)

        string_end = 79
        if len(block) == 0:
            done = 1
            continue
        if block[-1] == '\n':
            string_end = len(block) - 2

        line = re.match(r'[ -~]{0,' + str(string_end) + '}', block)

        line = string.ljust(line.group(0), 80)[0:79]

        if line[0:8] == 'END     ':
            done = 1
            break

        card = card_RE.match(line)
        if not card or not card.group('KEY'):
            print card.groups()
            raise SyntaxError("Failed to get keyword from FITS Card %s" % line)

        key = card.group('KEY')
        value = None
        if card.group('INT'):
            try:
                value = int(card.group('INT'))
            except:
                value = card.group('INT')
        elif card.group('FLOAT'):
            try:
                value = float(card.group('FLOAT'))
            except:
                value = float(card.group('FLOAT'))
        elif card.group('BOOL'):
            value = pyfits.Boolean(card.group('BOOL'))
        elif card.group('STRING'):
            value = card.group('STRING')[1:-1]

        if card.group('COMMENT'):
            _comment = card.group('COMMENT')
        elif card.group('C2'):
            _comment = card.group('C2')
        else:
            _comment = None

        try:
            if key == 'COMMENT ':
                hdu.header.add_comment(_comment)
            elif key == 'HISTORY ':
                hdu.header.add_history(_comment)
            elif key == '        ':
                hdu.header.add_blank(_comment)
            elif key:
                if key == 'DATE-OBS' and value:
                    value = string.replace(value, '/', '-')
                hdu.header.update(key, value, comment=_comment)
        except:
            raise SyntaxError("Failed to convert line to FITS Card %s" % line)

    ### set some internal variables to decided on data flow.
    hdu._bzero = hdu.header.get('BZERO', 0)
    hdu._bscale = hdu.header.get('BSCALE', 1)
    hdu._bitpix = hdu.header.get('BITPIX', -16)

    if hdu.header.get('NAXIS', 0) > 0:
        naxis1 = hdu.header.get('NAXIS1', 1)
        naxis2 = hdu.header.get('NAXIS2', 1)
        ### now read the data... this is a HACK from pyfits.py
        import numarray as num

        code = pyfits._ImageBaseHDU.NumCode[hdu._bitpix]
        dims = tuple([naxis2, naxis1])
        raw_data = num.fromfile(hdu._file, type=code, shape=dims)
        raw_data._byteorder = 'big'

        if (hdu._bzero != 0 or hdu._bscale != 1):
            if hdu._bitpix > 0:
                hdu.data = num.array(raw_data, type=num.Float32)
            else:
                hdu.data = raw_data
            if hdu._bscale != 1:
                num.multiply(hdu.data, hdu._bscale, hdu.data)
            if hdu._bzero != 0:
                hdu.data = hdu.data + hdu._bzero

            del hdu.header['BSCALE']
            del hdu.header['BZERO']
            hdu.header['BITPIX'] = pyfits._ImageBaseHDU.ImgCode[
                hdu.data.type()]

    temp.append(hdu)
    return temp
# public domain

import sys
import re
import wave
import glob
import numarray

max_val = 0
for fn in glob.glob("*/*48k*"):
    src = numarray.fromfile(fn, numarray.Float64)
    if sys.byteorder == "big":
        src.byteswap()

    max_val = max(max_val, abs(src.max()))

for fn in glob.glob("*/*48kL*"):
    L = numarray.fromfile(fn, numarray.Float64)
    R = numarray.fromfile(fn.replace("L", "R"), numarray.Float64)
    if sys.byteorder == "big":
        L.byteswap()
        R.byteswap()

    dst = numarray.array(type=numarray.Int16, shape=[L.shape[0] * 2])
    dst[0::2] = L * 32767 / max_val
    dst[1::2] = R * 32767 / max_val

    wav = wave.open(fn.replace("L", "").replace(".DDB", ".wav"), "w")
    wav.setnchannels(2)
    wav.setsampwidth(2)
    wav.setframerate(48000)
Exemple #5
0
import sys
import re
import wave
import glob
import numarray


def write_wavefile(fn, data):
    wav = wave.open(fn, "w")
    wav.setnchannels(2)
    wav.setsampwidth(2)
    wav.setframerate(44100)
    wav.writeframes(data.tostring())
    wav.close()


for fn in glob.glob("elev*/*.dat"):
    src = numarray.fromfile(fn, numarray.Int16)
    if sys.byteorder == "little":
        src.byteswap()

    (pre, ang) = re.match("(elev-?\d+/H-?\d+e)(\d+)a.dat", fn).groups()
    ang = int(ang)
    write_wavefile("%s%03da.wav" % (pre, ang), src)

    if ang != 0 and ang != 180:
        tmp = numarray.array(type=numarray.Int16, shape=src.shape)
        tmp[0::2] = src[1::2]
        tmp[1::2] = src[0::2]
        write_wavefile("%s%03da.wav" % (pre, 360 - ang), tmp)