Example #1
0
	def savesac(self):
		""" Save all data and header variables to an existing or new sacfile. """
		if os.path.isfile(self.filename):
			sacobj = sacfile(self.filename, 'rw')
		else:
			sacobj = sacfile(self.filename, 'new')
			sacobj.stla =  0
			sacobj.stlo =  0
			sacobj.stel =  0
		for hdr in ['b', 'npts', 'data', 'delta', 'gcarc', 'az', 'baz', 'dist', 'kstnm', 'knetwk']:
			sacobj.__setattr__(hdr, self.__dict__[hdr])
		self.savehdrs(sacobj)
		sacobj.close()
Example #2
0
	def __init__(self, ifiles, delta=-1):
		stadict = {}
		saclist = []
		for ifile in ifiles:
			sacdh = SacDataHdrs(ifile, delta)
			stadict[sacdh.netsta] = sacdh.staloc
			saclist.append(sacdh)
			del sacdh.staloc
		self.stadict = stadict
		self.saclist = saclist
		self.ifiles = ifiles
		# get event info
		isac = sacfile(ifiles[0], 'ro')
		year, jday = isac.nzyear, isac.nzjday
		mon, day = jul2date(year, jday)
		try:
			mag = isac.mag
		except:
			mag = 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
                try:
                    self.kevnm = isac.kevnm
                except:
                    self.kevnm = 'unknown'
		isac.close()
		if delta > 0:
			self.resampleData(delta)
Example #3
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 = sacfile(sacdh.filename, 'rw')
                for hdr in hdrs:
                        sacobj.__setattr__(hdr, eval(hdr))
	        sacobj.close()
	if 'stkdh' in gsac.__dict__:
		gsac.stkdh.savesac()
Example #4
0
 def savesac(self):
     """ Save all data and header variables to an existing or new sacfile. """
     if os.path.isfile(self.filename):
         sacobj = sacfile(self.filename, 'rw')
     else:
         sacobj = sacfile(self.filename, 'new')
         sacobj.stla = 0
         sacobj.stlo = 0
         sacobj.stel = 0
     for hdr in [
             'b', 'npts', 'data', 'delta', 'gcarc', 'az', 'baz', 'dist',
             'kstnm', 'knetwk'
     ]:
         sacobj.__setattr__(hdr, self.__dict__[hdr])
     self.savehdrs(sacobj)
     sacobj.close()
Example #5
0
 def __init__(self, ifiles, delta=-1):
     stadict = {}
     saclist = []
     for ifile in ifiles:
         sacdh = SacDataHdrs(ifile, delta)
         stadict[sacdh.netsta] = sacdh.staloc
         saclist.append(sacdh)
         del sacdh.staloc
     self.stadict = stadict
     self.saclist = saclist
     self.ifiles = ifiles
     # get event info
     isac = sacfile(ifiles[0], 'ro')
     year, jday = isac.nzyear, isac.nzjday
     mon, day = jul2date(year, jday)
     try:
         mag = isac.mag
     except:
         mag = 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
     ]
     try:
         self.kevnm = isac.kevnm
     except:
         self.kevnm = 'unknown event'
     isac.close()
     if delta > 0:
         self.resampleData(delta)
Example #6
0
    def writeHdrs(self):
        """ Write SAC headers (t_n, user_n, and kuser_n) in python obj to existing SAC file.
		"""
        #		sacobj = sacfile(self.filename+'.sac', 'rw')
        sacobj = sacfile(self.filename, 'rw')
        self.savehdrs(sacobj)
        sacobj.close()
Example #7
0
	def writeHdrs(self):
		""" Write SAC headers (t_n, user_n, and kuser_n) in python obj to existing SAC file.
		"""
#		sacobj = sacfile(self.filename+'.sac', 'rw')
		sacobj = sacfile(self.filename, 'rw')
		self.savehdrs(sacobj)
		sacobj.close()
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 = sacfile(self.filename, 'rw')
		else:
                        fspl = self.filename.split('/')
                        if len(fspl) > 1: os.system('mkdir -p '+ '/'.join(fspl[:-1]))
			sacobj = sacfile(self.filename, 'new')
			sacobj.stla =  0
			sacobj.stlo =  0
			sacobj.stel =  0
                hdrs = ['o', 'b', 'npts', 'data', 'delta', 'gcarc', 'az', 'baz', 'dist', 'kstnm', 'knetwk']
                hdrs += ['cmpaz', 'cmpinc', 'kcmpnm']
		for hdr in hdrs:
			sacobj.__setattr__(hdr, self.__dict__[hdr])
		self.savehdrs(sacobj)
		sacobj.close()
Example #9
0
    def __init__(self, ifile, delta=-1):
        """ Read SAC file to python objects in memory.
		"""
        isac = sacfile(ifile, 'rw')
        nthdr = 10
        nkhdr = 3
        thdrs = [
            -12345.,
        ] * nthdr
        users = [
            -12345.,
        ] * nthdr
        kusers = [
            '-12345  ',
        ] * nkhdr
        for i in range(nthdr):
            try:
                thdrs[i] = isac.__getattr__('t' + str(i))
            except:
                pass
            try:
                users[i] = isac.__getattr__('user' + str(i))
            except:
                pass
        for i in range(nkhdr):
            try:
                kusers[i] = isac.__getattr__('kuser' + str(i))  #.rstrip()
            except:
                pass
        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
        stla, stlo, stel = isac.stla, isac.stlo, isac.stel * 0.001
        self.stla = stla
        self.stlo = stlo
        self.stel = stel
        self.staloc = [stla, stlo, 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
        self.knetwk = isac.knetwk
        net = isac.knetwk.rstrip()
        sta = isac.kstnm.rstrip()
        self.netsta = net + '.' + sta
        self.cmpaz = isac.cmpaz
        self.cmpinc = isac.cmpinc
        self.kcmpnm = isac.kcmpnm
        isac.close()
Example #10
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 = sacfile(ifile0, 'ro')
			delta = isac.delta
			isac.close()
		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 #11
0
 def savesac(self):
     """ Save all data and header variables to an existing or new sacfile. """
     if os.path.isfile(self.filename):
         sacobj = sacfile(self.filename, 'rw')
     else:
         fspl = self.filename.split('/')
         if len(fspl) > 1: os.system('mkdir -p ' + '/'.join(fspl[:-1]))
         sacobj = sacfile(self.filename, 'new')
         sacobj.stla = 0
         sacobj.stlo = 0
         sacobj.stel = 0
     hdrs = [
         'o', 'b', 'npts', 'data', 'delta', 'gcarc', 'az', 'baz', 'dist',
         'kstnm', 'knetwk'
     ]
     hdrs += ['cmpaz', 'cmpinc', 'kcmpnm']
     for hdr in hdrs:
         sacobj.__setattr__(hdr, self.__dict__[hdr])
     self.savehdrs(sacobj)
     sacobj.close()
Example #12
0
	def __init__(self, ifile, delta=-1):
		""" Read SAC file to python objects in memory.
		"""
		isac = sacfile(ifile, 'rw')
		nthdr = 10
		nkhdr = 3
		thdrs  = [-12345.,] * nthdr
		users  = [-12345.,] * nthdr
		kusers = ['-12345  ',] * nkhdr
		for i in range(nthdr):
			try:
				thdrs[i] = isac.__getattr__('t'+str(i))
			except:
				pass
			try:
				users[i] = isac.__getattr__('user'+str(i))
			except:
				pass
		for i in range(nkhdr):
			try:
				kusers[i] = isac.__getattr__('kuser'+str(i))#.rstrip()
			except:
				pass
		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
		stla, stlo, stel = isac.stla, isac.stlo, isac.stel*0.001
		self.stla = stla
		self.stlo = stlo
		self.stel = stel
		self.staloc = [stla, stlo, 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
		self.knetwk = isac.knetwk
		net = isac.knetwk.rstrip()
		sta = isac.kstnm.rstrip()
		self.netsta = net + '.' + sta
                self.cmpaz = isac.cmpaz
                self.cmpinc = isac.cmpinc
                self.kcmpnm = isac.kcmpnm
		isac.close()
Example #13
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 = sacfile(ifile0, 'ro')
            delta = isac.delta
            isac.close()
        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
    print('Read {0:d} seismograms with sampling interval: {1:f}s'.format(
        len(gsac.saclist), opts.delta))
    return gsac
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 = sacfile(ifile0, 'ro')
			delta = isac.delta
			isac.close()
		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
	print ('Read {0:d} seismograms with sampling interval: {1:f}s'.format(len(gsac.saclist), opts.delta))
	return gsac 
Example #15
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 = sacfile(sacdh.filename, 'rw')
        for hdr in hdrs:
            sacobj.__setattr__(hdr, eval(hdr))
        sacobj.close()
    if 'stkdh' in gsac.__dict__:
        gsac.stkdh.savesac()
Example #16
0
"""
Example python script to read, resample and plot a seismogram.

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

from pysmo.sac.sacio import sacfile
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.sac'
sacobj = sacfile(ifilename, 'rw')
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 #17
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 = sacfile(ifile0, 'ro')
            delta = isac.delta
            isac.close()
        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