Example #1
0
def obj2sac(gsac):
    """ Save headers in python objects to SAC files.
    """
    for sacdh in gsac.saclist:
        sacdh.savesac()
        # save more headers 
        nzyear, mon, day, nzhour, nzmin, nzsec, evla, evlo, evdp, mag = gsac.event
        kevnm = gsac.kevnm
        idep = gsac.idep
        iztype = gsac.iztype
        nzjday = date2jul(nzyear, mon, day)
        nzmsec = int(round((nzsec - int(nzsec))*1000))
        nzsec = int(nzsec)
        evdp *= 1000
        stla, stlo, stel = gsac.stadict[sacdh.netsta]
        stel *= 1000
        hdrs = ['nzyear', 'nzjday', 'nzhour', 'nzmin', 'nzsec', 'nzmsec', 'evla', 'evlo', 'evdp', 'mag', ]
        hdrs += ['stla', 'stlo', 'stel' ]
        hdrs += ['kevnm', 'idep', 'iztype']
        for sacdh in gsac.saclist:
                sacobj = SacIO.from_file(sacdh.filename)
                for hdr in hdrs:
                        setattr(sacobj, hdr, eval(hdr))
                sacobj.write(sacdh.filename)
                del sacobj
    if 'stkdh' in gsac.__dict__:
        gsac.stkdh.savesac()
Example #2
0
 def writeHdrs(self):
     """
     Write SAC headers (t_n, user_n, and kuser_n) in python obj to existing SAC file.
     """
     sacobj = SacIO.from_file(self.filename)
     self.sethdrs(sacobj)
     sacobj.write(self.filename)
     del sacobj
Example #3
0
 def writeHdrs(self):
     """
     Write SAC headers (t_n, user_n, and kuser_n) in python obj to existing SAC file.
     """
     sacobj = SacIO.from_file(self.filename)
     self.sethdrs(sacobj)
     sacobj.write(self.filename)
     del sacobj
Example #4
0
def loadData(ifiles, opts, para):
    """
    Load data either from SAC files or (gz/bz2 compressed) pickle file.
    Get sampling rate from command line option or default config file.
    Resample data if a positive sample rate is given.
    Output file type is the same as input file (filemode and zipmode do not change).
    If filemode == 'sac': zipmode = None
    If filemode == 'pkl': zipmode = None/bz2/gz 
    """
    if opts.srate is not None:
        srate = opts.srate
    else:
        srate = para.srate
    ifile0 = ifiles[0]
    filemode, zipmode = fileZipMode(ifile0)
    opts.filemode = filemode
    opts.zipmode = zipmode
    if filemode == 'sac':
        if srate <= 0:
            isac = SacIO.from_file(ifile0)
            delta = isac.delta
            del isac
        else:
            delta = 1.0/srate
        gsac = sac2obj(ifiles, delta)
        opts.delta = delta
        opts.pklfile = None
    elif len(ifiles) > 1:
        print('More than one pickle file given. Exit.')
        sys.exit()
    else:
        if zipmode is not None:
            pklfile = ifile0[:-len(zipmode)-1]
        else:
            pklfile = ifile0
        gsac = readPickle(pklfile, zipmode)
        opts.pklfile = pklfile
        if srate > 0:
            sacdh0 = gsac.saclist[0]
            if int(round(sacdh0.npts * sacdh0.delta * srate)) != sacdh0.npts:
                gsac.resampleData(1./srate)
        opts.delta = gsac.saclist[0].delta

    # warn user if sampling rates are inconsistent
    class BreakIt(Exception): pass
    length_of_saclist = len(gsac.saclist)
    try:
        for k in range(length_of_saclist):
            for j in range(length_of_saclist):
                if gsac.saclist[k].delta - gsac.saclist[j].delta > 0.01:
                    print('WARNING: sampling rates inconsistent. If sampling rates not all equal, errors in cross correlation may occur.')
                    raise BreakIt
    except BreakIt:
        pass

    print(('Read {0:d} seismograms with sampling interval: {1:f}s'.format(len(gsac.saclist), opts.delta)))
    return gsac
Example #5
0
 def __init__(self, ifile, delta=-1):
     """ Read SAC file to python objects in memory.
     """
     print('Reading SAC file: ' + ifile)
     isac = SacIO.from_file(ifile)
     nthdr = 10
     nkhdr = 3
     thdrs = [
         -12345.,
     ] * nthdr
     users = [
         -12345.,
     ] * nthdr
     kusers = [
         '-1234567',
     ] * nkhdr
     for i in range(nthdr):
         thdr = getattr(isac, 't' + str(i))
         user = getattr(isac, 'user' + str(i))
         if thdr is not None:
             thdrs[i] = thdr
         if user is not None:
             users[i] = user
     for i in range(nkhdr):
         kuser = getattr(isac, 'kuser' + str(i))  #.rstrip()
         if kuser is not None:
             kusers[i] = kuser
     self.thdrs = thdrs
     self.users = users
     self.kusers = kusers
     self.az = isac.az
     self.baz = isac.baz
     self.dist = isac.dist
     self.gcarc = isac.gcarc
     self.stla = isac.stla
     self.stlo = isac.stlo
     self.stel = isac.stel * 0.001
     self.staloc = [self.stla, self.stlo, self.stel]
     self.filename = ifile
     # resample data if given a different positive delta
     self.data, self.delta = resampleSeis(array(isac.data), isac.delta,
                                          delta)
     self.npts = len(self.data)
     self.b = isac.b
     self.e = isac.e
     self.o = isac.o
     self.kstnm = isac.kstnm.replace('\x00', '')
     self.knetwk = isac.knetwk.replace('\x00', '')
     self.netsta = '.'.join([self.knetwk, self.kstnm])
     self.cmpaz = isac.cmpaz
     self.cmpinc = isac.cmpinc
     self.kcmpnm = isac.kcmpnm.replace('\x00', '')
     del isac
Example #6
0
 def __init__(self, ifile, delta=-1):
     """ Read SAC file to python objects in memory.
     """
     print('Reading SAC file: '+ifile)
     isac = SacIO.from_file(ifile)
     nthdr = 10
     nkhdr = 3
     thdrs = [-12345.,] * nthdr
     users = [-12345.,] * nthdr
     kusers = ['-1234567',] * nkhdr
     for i in range(nthdr):
         thdr = getattr(isac, 't'+str(i))
         user = getattr(isac, 'user'+str(i))
         if thdr is not None:
             thdrs[i] = thdr
         if user is not None:
             users[i] = user
     for i in range(nkhdr):
         kuser = getattr(isac, 'kuser'+str(i))#.rstrip()
         if kuser is not None:
             kusers[i] = kuser
     self.thdrs = thdrs
     self.users = users
     self.kusers = kusers
     self.az = isac.az
     self.baz = isac.baz
     self.dist = isac.dist
     self.gcarc = isac.gcarc
     self.stla = isac.stla
     self.stlo = isac.stlo
     self.stel = isac.stel*0.001
     self.staloc = [self.stla, self.stlo, self.stel]
     self.filename = ifile
     # resample data if given a different positive delta
     self.data, self.delta = resampleSeis(array(isac.data), isac.delta, delta)
     self.npts = len(self.data)
     self.b = isac.b
     self.e = isac.e
     self.o = isac.o
     self.kstnm = isac.kstnm.replace('\x00','')
     self.knetwk = isac.knetwk.replace('\x00','')
     self.netsta = '.'.join([self.knetwk, self.kstnm])
     self.cmpaz = isac.cmpaz
     self.cmpinc = isac.cmpinc
     self.kcmpnm = isac.kcmpnm.replace('\x00','')
     del isac
Example #7
0
 def __init__(self, ifiles, delta=-1):
     self.stadict = {}
     self.saclist = []
     for ifile in ifiles:
         sacdh = SacDataHdrs(ifile, delta)
         self.stadict[sacdh.netsta] = sacdh.staloc
         self.saclist.append(sacdh)
         del sacdh.staloc
     # get event info
     isac = SacIO.from_file(ifiles[0])
     year, jday = isac.nzyear, isac.nzjday
     mon, day = jul2date(year, jday)
     mag = isac.mag or 0.
     self.event = [ year, mon, day, isac.nzhour, isac.nzmin, isac.nzsec+isac.nzmsec*0.001, isac.evla, isac.evlo, isac.evdp*0.001, mag ]
     self.idep = isac.idep
     self.iztype = isac.iztype
     self.kevnm = isac.kevnm or 'unknown'
     del isac
     if delta > 0:
         self.resampleData(delta)
Example #8
0
 def savesac(self):
     """
     Save all data and header variables to an existing or new sacfile.
     """
     if os.path.isfile(self.filename):
         sacobj = SacIO.from_file(self.filename)
     else:
         fspl = self.filename.split('/')
         if len(fspl) > 1:
             os.system('mkdir -p ' + '/'.join(fspl[:-1]))
         sacobj = SacIO()
         sacobj.stla = 0
         sacobj.stlo = 0
         sacobj.stel = 0
     hdrs = [
         'o', 'b', 'delta', 'data', 'gcarc', 'az', 'baz', 'dist', 'kstnm',
         'knetwk'
     ]
     hdrs += ['cmpaz', 'cmpinc', 'kcmpnm', 'stla', 'stlo', 'stel']
     for hdr in hdrs:
         setattr(sacobj, hdr, self.__dict__[hdr])
     self.sethdrs(sacobj)
     sacobj.write(self.filename)
     del sacobj
Example #9
0
def obj2sac(gsac):
    """ Save headers in python objects to SAC files.
    """
    for sacdh in gsac.saclist:
        sacdh.savesac()
        # save more headers
        nzyear, mon, day, nzhour, nzmin, nzsec, evla, evlo, evdp, mag = gsac.event
        kevnm = gsac.kevnm
        idep = gsac.idep
        iztype = gsac.iztype
        nzjday = date2jul(nzyear, mon, day)
        nzmsec = int(round((nzsec - int(nzsec)) * 1000))
        nzsec = int(nzsec)
        evdp *= 1000
        stla, stlo, stel = gsac.stadict[sacdh.netsta]
        stel *= 1000
        hdrs = [
            'nzyear',
            'nzjday',
            'nzhour',
            'nzmin',
            'nzsec',
            'nzmsec',
            'evla',
            'evlo',
            'evdp',
            'mag',
        ]
        hdrs += ['stla', 'stlo', 'stel']
        hdrs += ['kevnm', 'idep', 'iztype']
        for sacdh in gsac.saclist:
            sacobj = SacIO.from_file(sacdh.filename)
            for hdr in hdrs:
                setattr(sacobj, hdr, eval(hdr))
            sacobj.write(sacdh.filename)
            del sacobj
    if 'stkdh' in gsac.__dict__:
        gsac.stkdh.savesac()
Example #10
0
 def savesac(self):
     """
     Save all data and header variables to an existing or new sacfile.
     """
     if os.path.isfile(self.filename):
         sacobj = SacIO.from_file(self.filename)
     else:
         fspl = self.filename.split('/')
         if len(fspl) > 1:
             os.system('mkdir -p '+ '/'.join(fspl[:-1]))
         sacobj = SacIO()
         sacobj.stla = 0
         sacobj.stlo = 0
         sacobj.stel = 0
     hdrs = ['o', 'b', 'delta', 'data', 'gcarc', 'az', 'baz', 'dist', 'kstnm', 'knetwk']
     hdrs += ['cmpaz', 'cmpinc', 'kcmpnm', 'stla', 'stlo', 'stel']
     for hdr in hdrs:
         setattr(sacobj, hdr, self.__dict__[hdr])
     self.sethdrs(sacobj)
     sacobj.write(self.filename)
     del sacobj
Example #11
0
 def __init__(self, ifiles, delta=-1):
     self.stadict = {}
     self.saclist = []
     for ifile in ifiles:
         sacdh = SacDataHdrs(ifile, delta)
         self.stadict[sacdh.netsta] = sacdh.staloc
         self.saclist.append(sacdh)
         del sacdh.staloc
     # get event info
     isac = SacIO.from_file(ifiles[0])
     year, jday = isac.nzyear, isac.nzjday
     mon, day = jul2date(year, jday)
     mag = isac.mag or 0.
     self.event = [
         year, mon, day, isac.nzhour, isac.nzmin,
         isac.nzsec + isac.nzmsec * 0.001, isac.evla, isac.evlo,
         isac.evdp * 0.001, mag
     ]
     self.idep = isac.idep
     self.iztype = isac.iztype
     self.kevnm = isac.kevnm or 'unknown'
     del isac
     if delta > 0:
         self.resampleData(delta)
Example #12
0
"""
Example python script to read, resample and plot a seismogram.

Xiaoting Lou ([email protected])
03/07/2012
"""

from pysmo.core.sac import SacIO
from numpy import linspace, array
from scipy import signal
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms

# read sac file:
ifilename = 'TA.109C.__.BHZ'
sacobj = SacIO.from_file(ifilename)
b = sacobj.b
npts = sacobj.npts
delta = sacobj.delta
x = linspace(b, b + npts * delta, npts)
y = array(sacobj.data)
# resample:
deltanew = 2.0
nptsnew = int(round(npts * delta / deltanew))
x2 = linspace(b, b + npts * delta, nptsnew)
y2 = signal.resample(y, nptsnew)
# plot:
fig = plt.figure(figsize=(12, 4))
ax = fig.add_subplot(111)
trans = transforms.blended_transform_factory(ax.transAxes, ax.transAxes)
plt.plot(x, y, 'b-', label='Delta = {0:.3f} s'.format(delta))
Example #13
0
"""
Example python script to read, resample and plot a seismogram.

Xiaoting Lou ([email protected])
03/07/2012
"""

from pysmo.core.sac import SacIO
from numpy import linspace, array
from scipy import signal
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms

# read sac file:
ifilename = 'TA.109C.__.BHZ'
sacobj = SacIO.from_file(ifilename)
b = sacobj.b
npts = sacobj.npts
delta = sacobj.delta
x = linspace(b, b+npts*delta, npts)
y = array(sacobj.data)
# resample:
deltanew = 2.0
nptsnew = int(round(npts*delta/deltanew))
x2 = linspace(b, b+npts*delta, nptsnew)
y2 = signal.resample(y, nptsnew)
# plot:
fig = plt.figure(figsize=(12,4))
ax = fig.add_subplot(111)
trans = transforms.blended_transform_factory(ax.transAxes, ax.transAxes)
plt.plot(x,  y, 'b-',  label='Delta = {0:.3f} s'.format(delta))
Example #14
0
def loadData(ifiles, opts, para):
    """
    Load data either from SAC files or (gz/bz2 compressed) pickle file.
    Get sampling rate from command line option or default config file.
    Resample data if a positive sample rate is given.
    Output file type is the same as input file (filemode and zipmode do not change).
    If filemode == 'sac': zipmode = None
    If filemode == 'pkl': zipmode = None/bz2/gz 
    """
    if opts.srate is not None:
        srate = opts.srate
    else:
        srate = para.srate
    ifile0 = ifiles[0]
    filemode, zipmode = fileZipMode(ifile0)
    opts.filemode = filemode
    opts.zipmode = zipmode
    if filemode == 'sac':
        if srate <= 0:
            isac = SacIO.from_file(ifile0)
            delta = isac.delta
            del isac
        else:
            delta = 1.0 / srate
        gsac = sac2obj(ifiles, delta)
        opts.delta = delta
        opts.pklfile = None
    elif len(ifiles) > 1:
        print('More than one pickle file given. Exit.')
        sys.exit()
    else:
        if zipmode is not None:
            pklfile = ifile0[:-len(zipmode) - 1]
        else:
            pklfile = ifile0
        gsac = readPickle(pklfile, zipmode)
        opts.pklfile = pklfile
        if srate > 0:
            sacdh0 = gsac.saclist[0]
            if int(round(sacdh0.npts * sacdh0.delta * srate)) != sacdh0.npts:
                gsac.resampleData(1. / srate)
        opts.delta = gsac.saclist[0].delta

    # warn user if sampling rates are inconsistent
    class BreakIt(Exception):
        pass

    length_of_saclist = len(gsac.saclist)
    try:
        for k in range(length_of_saclist):
            for j in range(length_of_saclist):
                if gsac.saclist[k].delta - gsac.saclist[j].delta > 0.01:
                    print(
                        'WARNING: sampling rates inconsistent. If sampling rates not all equal, errors in cross correlation may occur.'
                    )
                    raise BreakIt
    except BreakIt:
        pass

    print(('Read {0:d} seismograms with sampling interval: {1:f}s'.format(
        len(gsac.saclist), opts.delta)))
    return gsac