本文整理汇总了Python中obspy.core.Stream.write方法的典型用法代码示例。如果您正苦于以下问题:Python Stream.write方法的具体用法?Python Stream.write怎么用?Python Stream.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类obspy.core.Stream
的用法示例。
在下文中一共展示了Stream.write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_Header
# 需要导入模块: from obspy.core import Stream [as 别名]
# 或者: from obspy.core.Stream import write [as 别名]
def test_Header(self):
"""
Tests whether the header is correctly written and read.
"""
tempfile = NamedTemporaryFile().name
np.random.seed(815) # make test reproducable
data = np.random.randint(-1000, 1000, 50).astype('int32')
stats = {'network': 'BW', 'station': 'TEST', 'location': 'A',
'channel': 'EHE', 'npts': len(data), 'sampling_rate': 200.0,
'mseed': {'record_length': 512, 'encoding': 'STEIM2',
'filesize': 512, 'dataquality': 'D',
'number_of_records': 1, 'byteorder': '>'}}
stats['starttime'] = UTCDateTime(2000, 1, 1)
st = Stream([Trace(data=data, header=stats)])
# Write it.
st.write(tempfile, format="MSEED")
# Read it again and delete the temporary file.
stream = read(tempfile)
os.remove(tempfile)
stream.verify()
# Loop over the attributes to be able to assert them because a
# dictionary is not a stats dictionary.
# This also assures that there are no additional keys.
for key in stats.keys():
self.assertEqual(stats[key], stream[0].stats[key])
示例2: export_sac
# 需要导入模块: from obspy.core import Stream [as 别名]
# 或者: from obspy.core.Stream import write [as 别名]
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
示例3: merge_single
# 需要导入模块: from obspy.core import Stream [as 别名]
# 或者: from obspy.core.Stream import write [as 别名]
def merge_single(nch,dstart,dend):
'''Merges traces of one channel to larger traces. Used for cross-correlation'''
# here you load all the functions you need to use
from obspy.seg2.seg2 import readSEG2
from obspy.core import Stream
dataDir2 = "/import/neptun-radler/STEINACH_feb/"
dataDir = "/import/three-data/hadzii/STEINACH/STEINACH_longtime/"
outdir = "/home/jsalvermoser/Desktop/Processing/out_merged"
tr = []
for k in range(dstart, dend, 1):
fname = '%d' %(k)
fileName = fname + ".dat"
st = readSEG2(dataDir + fileName)
#st.detrend('linear')
tr.append(st[nch-1])
new_stream = Stream(traces=tr)
new_stream.merge(method=1, fill_value='interpolate')
start = new_stream[0].stats.starttime
end = new_stream[0].stats.endtime
timeframe = str(nch)+ "_" + str(start.year) +'.'+ str(start.julday) +'.'+ str(start.hour) +'.'+ str(start.minute) +'.'+ str(start.second) \
+'-'+ str(end.year) +'.'+ str(end.julday) +'.'+ str(end.hour) +'.'+ str(end.minute) +'.'+ str(end.second)
new_stream.write(outdir + timeframe + ".mseed", format="MSEED")
return new_stream[0]
示例4: test_writeAndReadDifferentEncodings
# 需要导入模块: from obspy.core import Stream [as 别名]
# 或者: from obspy.core.Stream import write [as 别名]
def test_writeAndReadDifferentEncodings(self):
"""
Writes and read a file with different encoding via the obspy.core
methods.
"""
npts = 1000
np.random.seed(815) # make test reproducable
data = np.random.randn(npts).astype('float64') * 1e3 + .5
st = Stream([Trace(data=data)])
# Loop over some record lengths.
for encoding, value in ENCODINGS.iteritems():
seed_dtype = value[2]
tempfile = NamedTemporaryFile().name
# Write it once with the encoding key and once with the value.
st[0].data = data.astype(seed_dtype)
st.verify()
st.write(tempfile, format="MSEED", encoding=encoding)
st2 = read(tempfile)
del st2[0].stats.mseed
np.testing.assert_array_equal(st[0].data, st2[0].data)
del st2
ms = _MSStruct(tempfile)
ms.read(-1, 1, 1, 0)
self.assertEqual(ms.msr.contents.encoding, encoding)
del ms # for valgrind
os.remove(tempfile)
示例5: export_sac
# 需要导入模块: from obspy.core import Stream [as 别名]
# 或者: from obspy.core.Stream import write [as 别名]
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
if maxlag:
mytrace.stats.starttime = -maxlag
mytrace.stats.sac = AttribDict()
mytrace.stats.sac.depmin = np.min(corr)
mytrace.stats.sac.depmax = np.max(corr)
mytrace.stats.sac.depmen = np.mean(corr)
mytrace.stats.sac.scale = 1
mytrace.stats.sac.npts = len(corr)
st = Stream(traces=[mytrace, ])
st.write(filename, format='SAC')
del st
return
示例6: test_writeStreamViaObsPy
# 需要导入模块: from obspy.core import Stream [as 别名]
# 或者: from obspy.core.Stream import write [as 别名]
def test_writeStreamViaObsPy(self):
"""
Write streams, i.e. multiple files via L{obspy.Trace}
"""
testdata = np.array([111, 111, 111, 111, 111, 109, 106, 103, 103,
110, 121, 132, 139])
testfile = NamedTemporaryFile().name
self.file = os.path.join(self.path, '3cssan.reg.8.1.RNON.wav')
tr = read(self.file, format='WAV')[0]
np.testing.assert_array_equal(tr.data[:13], testdata)
# write
st2 = Stream([Trace(), Trace()])
st2[0].data = tr.data.copy() # copy the data
st2[1].data = tr.data.copy() // 2 # be sure data are different
st2.write(testfile, format='WAV', framerate=7000)
# read without giving the WAV format option
base, ext = os.path.splitext(testfile)
testfile0 = "%s%03d%s" % (base, 0, ext)
testfile1 = "%s%03d%s" % (base, 1, ext)
tr30 = read(testfile0)[0]
tr31 = read(testfile1)[0]
self.assertEqual(tr30.stats, tr.stats)
self.assertEqual(tr31.stats, tr.stats)
np.testing.assert_array_equal(tr30.data[:13], testdata)
np.testing.assert_array_equal(tr31.data[:13], testdata // 2)
os.remove(testfile)
os.remove(testfile0)
os.remove(testfile1)
示例7: test_convert2Sac
# 需要导入模块: from obspy.core import Stream [as 别名]
# 或者: from obspy.core.Stream import write [as 别名]
def test_convert2Sac(self):
"""
Test that an obspy trace is correctly written to SAC.
All the header variables which are tagged as required by
http://www.iris.edu/manuals/sac/SAC_Manuals/FileFormatPt2.html
are controlled in this test
also see http://www.iris.edu/software/sac/manual/file_format.html
"""
# setUp is called before every test, not only once at the
# beginning, that is we allocate the data just here
# generate artificial mseed data
np.random.seed(815)
head = {'network': 'NL', 'station': 'HGN', 'location': '00',
'channel': 'BHZ', 'calib': 1.0, 'sampling_rate': 40.0,
'starttime': UTCDateTime(2003, 5, 29, 2, 13, 22, 43400)}
data = np.random.randint(0, 5000, 11947).astype("int32")
st = Stream([Trace(header=head, data=data)])
# write them as SAC
tmpfile = NamedTemporaryFile().name
st.write(tmpfile, format="SAC")
st2 = read(tmpfile, format="SAC")
# file must exist, we just created it
os.remove(tmpfile)
# check all the required entries (see url in docstring)
self.assertEqual(st2[0].stats.starttime, st[0].stats.starttime)
self.assertEqual(st2[0].stats.npts, st[0].stats.npts)
self.assertEqual(st2[0].stats.sac.nvhdr, 6)
self.assertAlmostEqual(st2[0].stats.sac.b, 0.000400)
# compare with correct digit size (nachkommastellen)
self.assertAlmostEqual((0.0004 + (st[0].stats.npts - 1) * \
st[0].stats.delta) / st2[0].stats.sac.e, 1.0)
self.assertEqual(st2[0].stats.sac.iftype, 1)
self.assertEqual(st2[0].stats.sac.leven, 1)
self.assertAlmostEqual(st2[0].stats.sampling_rate / \
st[0].stats.sampling_rate, 1.0)
示例8: test_readAndWriteViaObsPy
# 需要导入模块: from obspy.core import Stream [as 别名]
# 或者: from obspy.core.Stream import write [as 别名]
def test_readAndWriteViaObsPy(self):
"""
Read and Write files via L{obspy.Stream}
"""
# read trace
tr = read(self.file)[0]
# write comparison trace
st2 = Stream()
st2.traces.append(Trace())
tr2 = st2[0]
tr2.data = copy.deepcopy(tr.data)
tr2.stats = copy.deepcopy(tr.stats)
tempfile = NamedTemporaryFile().name
st2.write(tempfile, format="SAC")
# read comparison trace
tr3 = read(tempfile)[0]
os.remove(tempfile)
# check if equal
self.assertEqual(tr3.stats["station"], tr.stats["station"])
self.assertEqual(tr3.stats.npts, tr.stats.npts)
self.assertEqual(tr.stats["sampling_rate"], tr.stats["sampling_rate"])
self.assertEqual(tr.stats.get("channel"), tr.stats.get("channel"))
self.assertEqual(tr.stats.get("starttime"), tr.stats.get("starttime"))
self.assertEqual(tr.stats.sac.get("nvhdr"), tr.stats.sac.get("nvhdr"))
np.testing.assert_equal(tr.data, tr3.data)
示例9: ascii2sac
# 需要导入模块: from obspy.core import Stream [as 别名]
# 或者: from obspy.core.Stream import write [as 别名]
def ascii2sac(sismograma):
Wav, Head = [], []
r=open(sismograma, 'rU')
counter = 0
for linea in r:
counter+=1
if counter <= 5:
# print linea
Head.append(linea.strip())
else:
Wav.append(linea)
#print Head
date = Head[2][0:10]
hour = Head[2][11:19]
Fs = float(Head[3][0:8])
counts = float(Head[4][0:4])
station = Head[1]
#si la estacion es triaxial:
channel = Head[1][3]
esta = station[0:3]
print date, hour, str(Fs), str(counts), station
data = np.array(Wav, dtype=np.float32)
# print data
if channel == 'Z':
stats = {'network': 'OP', 'station': esta , 'location': '',
'channel': 'BHZ', 'npts': len(data), 'sampling_rate': Fs,
'mseed': {'dataquality': 'D'}}
elif channel == 'N':
stats = {'network': 'OP', 'station': esta , 'location': '',
'channel': 'BHN', 'npts': len(data), 'sampling_rate': Fs,
'mseed': {'dataquality': 'D'}}
elif channel == 'E':
stats = {'network': 'OP', 'station': esta , 'location': '',
'channel': 'BHE', 'npts': len(data), 'sampling_rate': Fs,
'mseed': {'dataquality': 'D'}}
else:
stats = {'network': 'OP', 'station': station , 'location': '',
'channel': 'SHZ', 'npts': len(data), 'sampling_rate': Fs,
'mseed': {'dataquality': 'D'}}
Date = date+hour
Date = datetime.datetime.strptime(Date, '%Y/%m/%d%H:%M:%S')
starttime = UTCDateTime(Date)
stats['starttime'] = starttime
print stats
st = Stream([Trace(data=data, header=stats)])
st.write(r.name[0:-4]+'.sac', format='SAC', encoding=4)
# st1 = read(r.name[0:-4]+'.mseed')
# print st1
# st1.plot(color='r')
return('traza convertida')
#ascii2sac(sismo)
示例10: test_writeIntegersViaObsPy
# 需要导入模块: from obspy.core import Stream [as 别名]
# 或者: from obspy.core.Stream import write [as 别名]
def test_writeIntegersViaObsPy(self):
"""
Write file test via L{obspy.Trace}.
"""
tempfile = NamedTemporaryFile().name
npts = 1000
# data cloud of integers - float won't work!
np.random.seed(815) # make test reproducable
data = np.random.randint(-1000, 1000, npts).astype('int32')
stats = {'network': 'BW', 'station': 'TEST', 'location': '',
'channel': 'EHE', 'npts': npts, 'sampling_rate': 200.0}
start = UTCDateTime(2000, 1, 1)
stats['starttime'] = start
tr = Trace(data=data, header=stats)
st = Stream([tr])
st.verify()
# write
st.write(tempfile, format="GSE2")
# read again
stream = read(tempfile)
os.remove(tempfile)
stream.verify()
np.testing.assert_equal(data, stream[0].data)
# test default attributes
self.assertEqual('CM6', stream[0].stats.gse2.datatype)
self.assertEqual(-1, stream[0].stats.gse2.vang)
self.assertEqual(1.0, stream[0].stats.gse2.calper)
self.assertEqual(1.0, stream[0].stats.calib)
示例11: test_writeAndReadDifferentRecordLengths
# 需要导入模块: from obspy.core import Stream [as 别名]
# 或者: from obspy.core.Stream import write [as 别名]
def test_writeAndReadDifferentRecordLengths(self):
"""
Tests Mini-SEED writing and record lengths.
"""
# libmseed instance.
npts = 6000
np.random.seed(815) # make test reproducable
data = np.random.randint(-1000, 1000, npts).astype('int32')
st = Stream([Trace(data=data)])
record_lengths = [256, 512, 1024, 2048, 4096, 8192]
# Loop over some record lengths.
for rec_len in record_lengths:
# Write it.
tempfile = NamedTemporaryFile().name
st.write(tempfile, format="MSEED", reclen=rec_len)
# Get additional header info
info = util.getRecordInformation(tempfile)
# Test reading the two files.
temp_st = read(tempfile)
np.testing.assert_array_equal(data, temp_st[0].data)
del temp_st
os.remove(tempfile)
# Check record length.
self.assertEqual(info['record_length'], rec_len)
# Check if filesize is a multiple of the record length.
self.assertEqual(info['filesize'] % rec_len, 0)
示例12: axisem2mseed_all
# 需要导入模块: from obspy.core import Stream [as 别名]
# 或者: from obspy.core.Stream import write [as 别名]
def axisem2mseed_all(path):
"""
change .dat files into MSEED format
"""
global test_param
t = UTCDateTime(0)
traces = []
for file in glob.iglob(os.path.join(path, '*.dat')):
stationID = file.split('/')[-1].split('_')[0]
chan = file.split('/')[-1].split('_')[-1].split('.')[0]
dat = np.loadtxt(file)
npts = len(dat[:,0])
stats = {'network': 'SG',
'station': stationID,
'location': '',
'channel': chan,
'npts': npts,
'sampling_rate': (npts - 1.)/(dat[-1,0] - dat[0,0]),
'starttime': t + dat[0,0],
'mseed' : {'dataquality': 'D'}}
traces.append(Trace(data=dat[:,1], header=stats))
st = Stream(traces)
st.sort()
fname = os.path.join(path, 'seismograms.mseed')
print fname
st.write(fname, format='MSEED')
示例13: test_searchFlagInBlockette
# 需要导入模块: from obspy.core import Stream [as 别名]
# 或者: from obspy.core.Stream import write [as 别名]
def test_searchFlagInBlockette(self):
"""
Test case for obspy.io.mseed.util._search_flag_in_blockette
"""
# Write dummy file
npts = 2000
np.random.seed(42) # make test reproducible
data = np.random.randint(-1000, 1000, npts).astype(np.int32)
# This header ensures presence of blockettes 1000 and 1001
stat_header = {'network': 'NE', 'station': 'STATI', 'location': 'LO',
'channel': 'CHA', 'npts': len(data), 'sampling_rate': 1,
'mseed': {'dataquality': 'D',
'blkt1001': {'timing_quality': 63}}}
stat_header['starttime'] = UTCDateTime(datetime(2012, 8, 1,
12, 0, 0, 42))
trace1 = Trace(data=data, header=stat_header)
st = Stream([trace1])
with NamedTemporaryFile() as tf:
st.write(tf, format="mseed", encoding=11, reclen=512)
tf.seek(0, os.SEEK_SET)
file_name = tf.name
with open(file_name, "rb") as file_desc:
file_desc.seek(0, os.SEEK_SET)
# Test from file start
read_bytes = util._search_flag_in_blockette(
file_desc, 48, 1001, 4, 1)
self.assertFalse(read_bytes is None)
self.assertEqual(unpack(native_str(">B"), read_bytes)[0], 63)
# Test from middle of a record header
file_desc.seek(14, os.SEEK_CUR)
file_pos = file_desc.tell()
read_bytes = util._search_flag_in_blockette(
file_desc, 34, 1000, 6, 1)
self.assertFalse(read_bytes is None)
self.assertEqual(unpack(native_str(">B"), read_bytes)[0], 9)
# Check that file_desc position has not changed
self.assertEqual(file_desc.tell(), file_pos)
# Test from middle of a record data
file_desc.seek(60, os.SEEK_CUR)
read_bytes = util._search_flag_in_blockette(
file_desc, -26, 1001, 5, 1)
self.assertFalse(read_bytes is None)
self.assertEqual(unpack(native_str(">B"), read_bytes)[0], 42)
# Test another record. There is at least 3 records in a
# mseed with 2000 data points and 512 bytes record length
file_desc.seek(1040, os.SEEK_SET)
read_bytes = util._search_flag_in_blockette(file_desc,
32, 1001, 4, 1)
self.assertEqual(unpack(native_str(">B"), read_bytes)[0], 63)
# Test missing blockette
read_bytes = util._search_flag_in_blockette(file_desc,
32, 201, 4, 4)
self.assertIs(read_bytes, None)
示例14: test_SavingSmallASCII
# 需要导入模块: from obspy.core import Stream [as 别名]
# 或者: from obspy.core.Stream import write [as 别名]
def test_SavingSmallASCII(self):
"""
Tests writing small ASCII strings.
"""
tempfile = NamedTemporaryFile().name
st = Stream()
st.append(Trace(data=np.fromstring("A" * 8, "|S1")))
st.write(tempfile, format="MSEED")
os.remove(tempfile)
示例15: _writeData
# 需要导入模块: from obspy.core import Stream [as 别名]
# 或者: from obspy.core.Stream import write [as 别名]
def _writeData(self, traceData, stats, timeObj):
streamObj = Stream([Trace(data=traceData, header=stats)])
filename = self._prepareFilename(timeObj)
offset = int(np.mean(streamObj.traces[0].data))
streamObj.traces[0].data = np.array([x - offset for x in streamObj.traces[0].data])
self.logger.debug("["+ strftime('%X') + "] Saving %d samples (corrected by %d) to %s..." % (len(traceData), offset, filename))
streamObj.write(filename, format='MSEED')