def test_readWrite(self): """ Tests for SacIO read and write """ sacfile = os.path.join(self.path, 'test.sac') with NamedTemporaryFile() as tf: tempfile = tf.name t = SacIO() t.ReadSacFile(sacfile) self.assertEqual(t.GetHvalue('npts'), 100) self.assertEqual(t.GetHvalue("kcmpnm"), "Q ") self.assertEqual(t.GetHvalue("kstnm"), "STA ") t.SetHvalue("kstnm", "spiff") self.assertEqual(t.GetHvalue('kstnm'), 'spiff ') t.WriteSacBinary(tempfile) self.assertEqual(os.stat(sacfile)[6], os.stat(tempfile)[6]) self.assertEqual(os.path.exists(tempfile), True) t.ReadSacHeader(tempfile) self.assertEqual((t.hf is not None), True) t.SetHvalue("kstnm", "spoff") self.assertEqual(t.GetHvalue('kstnm'), 'spoff ') t.WriteSacHeader(tempfile) t.SetHvalueInFile(tempfile, "kcmpnm", 'Z ') self.assertEqual(t.GetHvalueFromFile(tempfile, "kcmpnm"), 'Z ') self.assertEqual( SacIO(tempfile, headonly=True).GetHvalue('kcmpnm'), 'Z ') self.assertEqual(t.IsValidSacFile(tempfile), True) self.assertEqual(t.IsValidXYSacFile(tempfile), False) self.assertEqual(SacIO().GetHvalueFromFile(sacfile, 'npts'), 100) self.assertEqual(SacIO(sacfile).GetHvalue('npts'), 100)
def test_issue171(self): """ Test for issue #171. """ tr = read()[0] with NamedTemporaryFile() as tf: tempfile = tf.name tr.write(tempfile, format="SAC") trace = SacIO(tempfile) trace.SetHvalue('stel', 91.0) trace.WriteSacHeader(tempfile) trace = SacIO(tempfile)
def test_readBigEnd(self): """ Test reading big endian binary files """ tfilel = os.path.join(os.path.dirname(__file__), 'data', 'test.sac') tfileb = os.path.join(os.path.dirname(__file__), 'data', 'test.sac.swap') tl = SacIO(tfilel) tb = SacIO(tfileb) self.assertEqual(tl.GetHvalue('kevnm'), tb.GetHvalue('kevnm')) self.assertEqual(tl.GetHvalue('npts'), tb.GetHvalue('npts')) self.assertEqual(tl.GetHvalue('delta'), tb.GetHvalue('delta')) np.testing.assert_array_equal(tl.seis, tb.seis)
def test_readXYheader(self): tfile = os.path.join(os.path.dirname(__file__), 'data', 'test.sac') with NamedTemporaryFile() as tf: tempfile = tf.name t = SacIO(tfile) t.WriteSacXY(tempfile) d = SacIO(tempfile, alpha=True) e = SacIO() e.ReadSacXYHeader(tempfile) self.assertEqual(e.GetHvalue('npts'), d.GetHvalue('npts')) self.assertEqual(e.GetHvalue('depmen'), d.GetHvalue('depmen')) self.assertEqual(e.starttime, d.starttime) self.assertNotEqual(e.seis.size, d.seis.size) c = SacIO(tempfile, alpha=True, headonly=True) self.assertEqual(e.seis.size, c.seis.size)
def test_read_with_fsize(self): """ Testing fsize option on SacIO.ReadSacFile() """ # reading sac file with wrong file size should raise error longer_file = os.path.join(self.path, 'seism-longer.sac') shorter_file = os.path.join(self.path, 'seism-shorter.sac') t = SacIO() # default self.assertRaises(SacError, t.ReadSacFile, longer_file) self.assertRaises(SacError, t.ReadSacFile, shorter_file) # fsize=True self.assertRaises(SacError, t.ReadSacFile, longer_file, fsize=True) self.assertRaises(SacError, t.ReadSacFile, shorter_file, fsize=True) # using fsize=False should not work for shorter file # (this is not supported by SAC) ... self.assertRaises(SacIOError, t.ReadSacFile, shorter_file, fsize=False) # ...but it should work for longer file t.ReadSacFile(longer_file, fsize=False) # checking trace self.assertEqual(t.GetHvalue('nzyear'), 1981) self.assertEqual(t.GetHvalue('nzjday'), 88) self.assertEqual(t.GetHvalue('nzhour'), 10) self.assertEqual(t.GetHvalue('nzmin'), 38) self.assertEqual(t.GetHvalue('nzsec'), 14) self.assertEqual(t.GetHvalue('nzmsec'), 0) # we should never test equality for float values: self.assertTrue(abs(t.GetHvalue('delta') - 0.01) <= 1e-9) self.assertEqual(t.GetHvalue('scale'), -12345.0) self.assertEqual(t.GetHvalue('npts'), 998) self.assertEqual(t.GetHvalue('knetwk'), '-12345 ') self.assertEqual(t.GetHvalue('kstnm'), 'CDV ') self.assertEqual(t.GetHvalue('kcmpnm'), 'Q ')
def test_iztype11(self): # test that iztype 11 is read correctly sod_file = os.path.join(self.path, 'data', 'dis.G.SCZ.__.BHE_short') tr = read(sod_file)[0] sac = SacIO(sod_file) t1 = tr.stats.starttime - float(tr.stats.sac.b) t2 = sac.reftime self.assertAlmostEqual(t1.timestamp, t2.timestamp, 5) # see that iztype is written corretly tempfile = NamedTemporaryFile().name tr.write(tempfile, format="SAC") sac2 = SacIO(tempfile) os.remove(tempfile) self.assertEqual(sac2.iztype, 11) self.assertAlmostEqual(tr.stats.sac.b, sac2.b) self.assertAlmostEqual(t2.timestamp, sac2.reftime.timestamp, 5)
def test_swapbytes(self): tfilel = os.path.join(os.path.dirname(__file__), 'data', 'test.sac') tfileb = os.path.join(os.path.dirname(__file__), 'data', 'test.sac.swap') with NamedTemporaryFile() as tf: tempfile = tf.name tb = SacIO(tfileb) tb.swap_byte_order() tb.WriteSacBinary(tempfile) tr1 = SacIO(tempfile) tl = SacIO(tfilel) np.testing.assert_array_equal(tl.seis, tr1.seis) self.assertEqual(tl.GetHvalue('kevnm'), tr1.GetHvalue('kevnm')) self.assertEqual(tl.GetHvalue('npts'), tr1.GetHvalue('npts')) self.assertEqual(tl.GetHvalueFromFile(tfilel, 'kcmpnm'), tr1.GetHvalueFromFile(tempfile, 'kcmpnm'))
def export_sac(db, filename, pair, components, filterid,corr,ncorr=0,sac_format=None,maxlag=None,cc_sampling_rate=None): if sac_format is None: sac_format=get_config(db,"sac_format") if maxlag is None: maxlag = float(get_config(db,"maxlag")) if cc_sampling_rate is None: cc_sampling_rate = float(get_config(db,"cc_sampling_rate")) try: os.makedirs(os.path.split(filename)[0]) except: pass filename += ".SAC" mytrace = Trace(data=corr) mytrace.stats['station'] = pair mytrace.stats['sampling_rate'] = cc_sampling_rate st = Stream(traces = [mytrace,]) st.write(filename,format='SAC') tr = SacIO(filename) if sac_format == "doublets": tr.SetHvalue('A',120) else: tr.SetHvalue('B',-maxlag) tr.SetHvalue('DEPMIN',np.min(corr)) tr.SetHvalue('DEPMAX',np.max(corr)) tr.SetHvalue('DEPMEN',np.mean(corr)) tr.SetHvalue('SCALE',1) tr.SetHvalue('NPTS',len(corr)) tr.WriteSacBinary(filename) del st, tr return
def write2sac(d, header, output): ''' Function to write the data and header to sac files Inputs: d - data array header - dictionary of the header info output - filename of the output sac file ''' sacio = SacIO() sacio.fromarray(d) # set the date t = header['record_time'] sacio.SetHvalue('nzyear', t.year) sacio.SetHvalue('nzjday', t.julday) sacio.SetHvalue('delta', 1. / header['df']) sacio.SetHvalue('nzhour', t.hour) sacio.SetHvalue('nzmin', t.minute) sacio.SetHvalue('nzsec', t.second) sacio.SetHvalue('kstnm', header['stnm']) sacio.SetHvalue('stla', header['stla']) sacio.SetHvalue('stlo', header['stlo']) sacio.SetHvalue('stel', header['stel']) sacio.SetHvalue('kcmpnm', header['comp']) sacio.SetHvalue('evla', header['evla']) sacio.SetHvalue('evlo', header['evlo']) sacio.SetHvalue('o', header['o']) sacio.SetHvalue('mag', header['mag']) sacio.SetHvalue('o', header['o']) #TRUE if DIST AZ BAZ and GCARC are to be calculated from st event coordinates. sacio.SetHvalue('LCALDA', 1) #set the type of the dependent variable as acceleration nm/sec/sec #sacio.SetHvalue('idep',8) sacio.WriteSacBinary(output)
def test_getdist(self): tfile = os.path.join(os.path.dirname(__file__), 'data', 'test.sac') with NamedTemporaryFile() as tf: tempfile = tf.name t = SacIO(tfile) t.SetHvalue('evla', 48.15) t.SetHvalue('evlo', 11.58333) t.SetHvalue('stla', -41.2869) t.SetHvalue('stlo', 174.7746) t.SetHvalue('lcalda', 1) t.WriteSacBinary(tempfile) t2 = SacIO(tempfile) b = np.array([18486532.5788 / 1000., 65.654154562, 305.975459869], dtype=native_str('>f4')) self.assertEqual(t2.GetHvalue('dist'), b[0]) self.assertEqual(t2.GetHvalue('az'), b[1]) self.assertEqual(t2.GetHvalue('baz'), b[2])
def test_Date(self): """ Test for SacIO '_get_date_'-function to calculate timestamp """ fn = os.path.join(os.path.dirname(__file__), 'data', 'test.sac') t = SacIO(fn) self.assertEqual(t.reftime.timestamp, 269596800.0) diff = t.GetHvalue('npts') self.assertEqual(int(t.endtime - t.starttime), diff)
def test_readWriteXY(self): """ Tests for ascii sac io """ with NamedTemporaryFile() as tf: tempfile = tf.name tfile = os.path.join(os.path.dirname(__file__), 'data', 'test.sac') t = SacIO(tfile) t.WriteSacXY(tempfile) d = SacIO(tempfile, alpha=True) e = SacIO() e.ReadSacXY(tempfile) self.assertEqual(e.GetHvalue('npts'), d.GetHvalue('npts')) self.assertEqual(e.IsValidXYSacFile(tempfile), True) self.assertEqual(e.IsValidSacFile(tempfile), False) with NamedTemporaryFile() as tf: tempfile = tf.name d.WriteSacBinary(tempfile) size1 = os.stat(tempfile)[6] size2 = os.stat(tfile)[6] self.assertEqual(size1, size2) np.testing.assert_array_almost_equal(t.seis, d.seis, decimal=5)
def test_undefinedB(self): """ Test that an undefined B value (-12345.0) is not messing up the starttime """ # read in the test file an see that sac reference time and # starttime of seismogram are correct tr = read(self.file)[0] self.assertEqual(tr.stats.starttime.timestamp, 269596810.0) self.assertEqual(tr.stats.sac.b, 10.0) sac_ref_time = SacIO(self.file).reftime self.assertEqual(sac_ref_time.timestamp, 269596800.0) # change b to undefined and write (same case as if b == 0.0) # now sac reference time and reftime of seismogram must be the # same tr.stats.sac.b = -12345.0 tmpfile = NamedTemporaryFile().name tr.write(tmpfile, format="SAC") tr2 = read(tmpfile)[0] self.assertEqual(tr2.stats.starttime.timestamp, 269596810.0) self.assertEqual(tr2.stats.sac.b, -12345.0) sac_ref_time2 = SacIO(tmpfile).reftime self.assertEqual(sac_ref_time2.timestamp, 269596810.0) os.remove(tmpfile)
def test_read(self): """ Tests for SacIO read and write """ data = np.array([-8.7422776573475858e-08, -0.30901697278022766, -0.58778536319732666, -0.8090171217918396, -0.95105659961700439, -1.0, -0.95105630159378052, -0.80901658535003662, -0.5877845287322998, -0.30901604890823364, 1.1285198979749111e-06], dtype=native_str('<f4')) sacfile = os.path.join(self.path, 'test.sac') t = SacIO() t.ReadSacFile(sacfile) np.testing.assert_array_equal(t.seis[0:11], data) self.assertEqual(t.GetHvalue('npts'), 100) self.assertEqual(t.GetHvalue("kstnm"), "STA ")
def updateSacHeader(sac,dir,latStaz,lonStaz,evla,evlo): # load sac trace, update headers, write and close tr = SacIO(dir + os.sep + sac) tr.SetHvalue('evla',evla) tr.SetHvalue('evlo',evlo) tr.SetHvalue('stla',latStaz) tr.SetHvalue('stlo',lonStaz) (distD,Az,Baz,distkm)=dlaz(evla,evlo,latStaz,lonStaz) tr.SetHvalue('dist',distkm) tr.SetHvalue('gcarc',distD) tr.SetHvalue('baz',Baz) tr.SetHvalue('az',Az) tr.WriteSacHeader(dir + os.sep + sac) return 1
def updateSacHeaderEida(sacFiles, sourceFileFormat, outFileFormat, dir,evla,evlo): # this operation works only if the source seed file is a fseed if sourceFileFormat == "FSEED" and outFileFormat == "SAC": # open rdseed.station file # file = open(dir + "/rdseed.stations") # loop over sac files to find stations for sac in sacFiles: info = sac.split('.') staz = info[0] #loop over line of rdseed.stations file = open(dir + os.sep + "rdseed.stations") for line in file: a = line.split(' ') station = a[0] network = a[1] latStaz = eval(a[2]) lonStaz = eval(a[3]) # if stations are the same, upadte header and exit this loop if station == staz: # load sac trace, update headers, write and close tr = SacIO(dir + os.sep + sac) tr.SetHvalue('evla',evla) tr.SetHvalue('evlo',evlo) tr.SetHvalue('stla',latStaz) tr.SetHvalue('stlo',lonStaz) (distD,Az,Baz,distkm)=dlaz(evla,evlo,latStaz,lonStaz) tr.SetHvalue('dist',distkm) tr.SetHvalue('gcarc',distD) tr.SetHvalue('baz',Baz) tr.SetHvalue('az',Az) #distkm=dlaz(evla,evlo,latStaz,lonStaz) tr.WriteSacHeader(dir + os.sep + sac) break return sacFiles
def write2sac(d, header, evla, evlo, evdp, mag, output): sacio = SacIO() sacio.fromarray(d) # set the date to today sacio.SetHvalue('nzyear', header['nzyear']) sacio.SetHvalue('nzjday', header['nzjday']) sacio.SetHvalue('delta', 0.02) sacio.SetHvalue('nzhour', header['nzhour']) sacio.SetHvalue('nzmin', header['nzmin']) sacio.SetHvalue('nzsec', header['nzsec']) sacio.SetHvalue('nzmsec', header['nzmsec']) sacio.SetHvalue('kstnm', header['stnm']) sacio.SetHvalue('stla', header['stla']) sacio.SetHvalue('stlo', header['stlo']) sacio.SetHvalue('kcmpnm', header['comp']) sacio.SetHvalue('evla', evla) sacio.SetHvalue('evlo', evlo) sacio.SetHvalue('evdp', evdp) sacio.SetHvalue('mag', mag) #dist = sacio.GetHvalue('dist') #print dist dist = gps2DistAzimuth(stla, stlo, evla, evlo)[0] / 1000. sacio.SetHvalue('dist', dist) #sacio.SetHvalue('knetwk','phones') #sacio.SetHvalue('kstnm',phone) #sacio.SetHvalue('kcmpnm',comp) #sacio.SetHvalue('kevnm',loc) #sacio.SetHvalue('kuser0',test + ' test') #sacio.SetHvalue('kuser0',version) #sacio.SetHvalue('kuser1',brand) #set the type of the dependent variable as acceleration nm/sec/sec #sacio.SetHvalue('idep',8) sacio.WriteSacBinary(output)
def test_getattr(self): tfile = os.path.join(os.path.dirname(__file__), 'data', 'test.sac') tr = SacIO(tfile) self.assertEqual(tr.npts, tr.GetHvalue('npts')) self.assertEqual(tr.kstnm, tr.GetHvalue('kstnm'))
templateDateTime = UTCDateTime(template) # converts the event name to a datetime class templateJulDay = templateDateTime.julday # int templateYear = templateDateTime.year # int backgroundTime = 10 #Amount of time in longer event file before event origin time in seconds # phaseMarkerList = [] # staList = [] # compList = [] phaseDict[template] = {} ######################################################### for file in os.listdir('%s/event%s' %(templateDir,template)): os.chdir('%s/event%s' %(templateDir,template)) if file.endswith('.SAC'): file1 = file station = file1[3:7] component = file1[13] quality_amarker=str(SacIO().GetHvalueFromFile(file1,'ka')) #P phase aMarker = SacIO().GetHvalueFromFile(file1,'a')#P phase quality_t0marker=str(SacIO().GetHvalueFromFile(file1,'kt0')) #S phase t0Marker = SacIO().GetHvalueFromFile(file1,'t0')#S phase if float(aMarker)!=-12345.0: if (not phaseDict[template].has_key(station)): phaseDict[template][station]=[] phaseDict[template][station].append(aMarker) aMarkerDateTime = templateDateTime - backgroundTime + aMarker phaseDict[template][station].append(aMarkerDateTime) elif float(t0Marker)!=-12345.0 and component =='E': if (not phaseDict[template].has_key(station)): phaseDict[template][station]=[] phaseDict[template][station].append(t0Marker) t0MarkerDateTime = templateDateTime - backgroundTime + t0Marker phaseDict[template][station].append(t0MarkerDateTime)
def test_isSAC(self): """ Assertion is raised if file is not a SAC file """ t = SacIO() self.assertRaises(SacError, t.ReadSacFile, __file__)