def test_readWithWrongChecksum(self): """ """ # read original file gse2file = os.path.join(self.path, 'loc_RJOB20050831023349.z.wrong_chksum') # should fail fp = open(gse2file, 'rb') self.assertRaises(ChksumError, libgse2.read, fp, verify_chksum=True) # should not fail fp.seek(0) libgse2.read(fp, verify_chksum=False) fp.close()
def test_readAndWrite(self): """ Writes, reads and compares files created via libgse2. """ gse2file = os.path.join(self.path, 'loc_RNON20040609200559.z') with open(gse2file, 'rb') as f: header, data = libgse2.read(f) with NamedTemporaryFile() as f: libgse2.write(header, data, f) f.flush() newheader, newdata = libgse2.read(open(f.name, 'rb')) self.assertEqual(header, newheader) np.testing.assert_equal(data, newdata)
def test_read(self): """ Compares waveform data read by libgse2 with an ASCII dump. Checks the first 13 datasamples when reading loc_RJOB20050831023349.z. The values are assumed to be correct. The values were created using getevents. Only checks relative values. """ gse2file = os.path.join(self.path, 'loc_RJOB20050831023349.z') # list of known data samples datalist = [12, -10, 16, 33, 9, 26, 16, 7, 17, 6, 1, 3, -2] f = open(gse2file, 'rb') header, data = libgse2.read(f, verify_chksum=True) self.assertEqual('RJOB ', header['station']) self.assertEqual(' Z', header['channel']) self.assertEqual(200.0, header['samp_rate']) self.assertEqual('20050831023349.850', "%04d%02d%02d%02d%02d%06.3f" % ( header['d_year'], header['d_mon'], header['d_day'], header['t_hour'], header['t_min'], header['t_sec'])) self.assertAlmostEqual(9.49e-02, header['calib']) self.assertEqual(1.0, header['calper']) self.assertEqual(-1.0, header['vang']) self.assertEqual(-1.0, header['hang']) self.assertEqual(data[0:13].tolist(), datalist) f.close()
def test_readAndWrite(self): """ Writes, reads and compares files created via libgse2. """ gse2file = os.path.join(self.path, 'loc_RNON20040609200559.z') f = open(gse2file, 'rb') header, data = libgse2.read(f) f.close() tmp_file = NamedTemporaryFile().name f = open(tmp_file, 'wb') libgse2.write(header, data, f) f.close() newheader, newdata = libgse2.read(open(tmp_file, 'rb')) self.assertEqual(header, newheader) np.testing.assert_equal(data, newdata) os.remove(tmp_file)
def read(self,gsefile): """Read seismogram from GSE2.0 file Header attributes are assigned as attributes, for example see: g = GseParser('test.gse') print g """ try: os.path.exists(gsefile) # Old C wraped version: #(h,data) = ext_gse.read(gsefile) (h,data) = libgse2.read(gsefile) except IOError: assert 1, "No such file to write: " + gsefile # # define the h entries as attributes self.auxid = h['auxid'] self.calib = h['calib'] self.calper = h['calper'] self.channel = h['channel'] self.datatype = h['datatype'] self.hang = h['hang'] self.instype = h['instype'] self.npts = h['n_samps'] self.df = h['samp_rate'] self.station = h['station'] self.vang = h['vang'] intsec = int(h['t_sec']) date = "%04d%02d%02d%02d%02d%02d" % (h['d_year'],h['d_mon'],h['d_day'],h['t_hour'],h['t_min'],intsec) self.julsec = self.date_to_julsec('%Y%m%d%H%M%S',date) + h['t_sec']-intsec # if not type(data) == list: self.trace = list(data) else: self.trace = data
def test_stringIO(self): """ Checks that reading and writing works via StringIO """ gse2file = os.path.join(self.path, 'loc_RNON20040609200559.z') with open(gse2file, 'rb') as f: fin = StringIO(f.read()) header, data = libgse2.read(fin) # be sure something es actually read self.assertEqual(12000, header['npts']) self.assertEqual(1, data[-1]) fout = StringIO() libgse2.write(header, data, fout) fout.seek(0) newheader, newdata = libgse2.read(fout) self.assertEqual(header, newheader) np.testing.assert_equal(data, newdata)
def test_bytesIO(self): """ Checks that reading and writing works via BytesIO. """ gse2file = os.path.join(self.path, 'loc_RNON20040609200559.z') with open(gse2file, 'rb') as f: fin = io.BytesIO(f.read()) header, data = libgse2.read(fin) # be sure something es actually read self.assertEqual(12000, header['npts']) self.assertEqual(1, data[-1]) fout = io.BytesIO() libgse2.write(header, data, fout) fout.seek(0) newheader, newdata = libgse2.read(fout) self.assertEqual(header, newheader) np.testing.assert_equal(data, newdata)
def test_CHK2InCM6(self): """ Tests a file which contains the "CHK2" string in the CM6 encoded string (line 13 of twiceCHK2.gse2). """ f = open(os.path.join(self.path, 'twiceCHK2.gse2'), 'rb') header, data = libgse2.read(f, verify_chksum=True) self.assertEqual(header['n_samps'], 750) np.testing.assert_array_equal(data[-4:], np.array([-139, -153, -169, -156]))
def test_CHK2InCM6(self): """ Tests a file which contains the "CHK2" string in the CM6 encoded string (line 13 of twiceCHK2.gse2). """ with open(os.path.join(self.path, 'twiceCHK2.gse2'), 'rb') as f: header, data = libgse2.read(f, verify_chksum=True) self.assertEqual(header['npts'], 750) np.testing.assert_array_equal(data[-4:], np.array([-139, -153, -169, -156]))
def readGSE2(filename, headonly=False, verify_chksum=True, **kwargs): # @UnusedVariable """ Reads a GSE2 file and returns a Stream object. GSE2 files containing multiple WID2 entries/traces are supported. .. warning:: This function should NOT be called directly, it registers via the ObsPy :func:`~obspy.core.stream.read` function, call this instead. :type filename: string :param filename: GSE2 file to be read. :type headonly: boolean, optional :param headonly: If True read only head of GSE2 file. :type verify_chksum: boolean, optional :param verify_chksum: If True verify Checksum and raise Exception if it is not correct. :rtype: :class:`~obspy.core.stream.Stream` :returns: Stream object containing header and data. .. rubric:: Example >>> from obspy import read >>> st = read("/path/to/loc_RJOB20050831023349.z") """ traces = [] with open(filename, 'rb') as f: # reading multiple gse2 parts while True: try: if headonly: header = libgse2.readHeader(f) traces.append(Trace(header=header)) else: header, data = libgse2.read(f, verify_chksum=verify_chksum) traces.append(Trace(header=header, data=data)) except EOFError: break return Stream(traces=traces)
def read(self, filename, **kwargs): if not os.path.exists(filename): msg = "File not found '%s'" % (filename) raise IOError(msg) # read GSE2 file header, data = libgse2.read(filename) # reset header information self.stats = Stats() # assign all header entries to stats for _i in header.keys(): setattr(self.stats,_i,header[_i]) # now assign the common attributes of the Trace class # station name self.stats.station = header['station'] # sampling rate in Hz (float) self.stats.sampling_rate = header['samp_rate'] # number of samples/data points (int) self.stats.npts = header['n_samps'] # network ID self.stats.network = "" # location ID self.stats.location = "" # channel ID self.stats.channel = header['channel'] # data quality indicator self.stats.dataquality = "" # convert time to seconds since epoch seconds = int(header['t_sec']) microseconds = int(1e6*(header['t_sec'] - seconds)) self.stats.starttime = DateTime( header['d_year'],header['d_mon'],header['d_day'], header['t_hour'],header['t_min'], seconds,microseconds ) self.stats.endtime = DateTime.utcfromtimestamp( self.stats.starttime.timestamp() + header['n_samps']/float(header['samp_rate']) ) self.data=array(data)
def read(self, filename, **kwargs): if not os.path.exists(filename): msg = "File not found '%s'" % (filename) raise IOError(msg) # read GSE2 file header, data = libgse2.read(filename) # reset header information self.stats = Stats() # assign all header entries to stats for _i in header.keys(): setattr(self.stats, _i, header[_i]) # now assign the common attributes of the Trace class # station name self.stats.station = header['station'] # sampling rate in Hz (float) self.stats.sampling_rate = header['samp_rate'] # number of samples/data points (int) self.stats.npts = header['n_samps'] # network ID self.stats.network = "" # location ID self.stats.location = "" # channel ID self.stats.channel = header['channel'] # data quality indicator self.stats.dataquality = "" # convert time to seconds since epoch seconds = int(header['t_sec']) microseconds = int(1e6 * (header['t_sec'] - seconds)) self.stats.starttime = DateTime(header['d_year'], header['d_mon'], header['d_day'], header['t_hour'], header['t_min'], seconds, microseconds) self.stats.endtime = DateTime.utcfromtimestamp( self.stats.starttime.timestamp() + header['n_samps'] / float(header['samp_rate'])) self.data = array(data)
def readGSE2(filename, headonly=False, verify_chksum=True, **kwargs): # @UnusedVariable """ Reads a GSE2 file and returns a Stream object. GSE2 files containing multiple WID2 entries/traces are supported. .. warning:: This function should NOT be called directly, it registers via the ObsPy :func:`~obspy.core.stream.read` function, call this instead. :type filename: string :param filename: GSE2 file to be read. :type headonly: boolean, optional :param headonly: If True read only head of GSE2 file. :type verify_chksum: boolean, optional :param verify_chksum: If True verify Checksum and raise Exception if it is not correct. :rtype: :class:`~obspy.core.stream.Stream` :returns: Stream object containing header and data. .. rubric:: Example >>> from obspy.core import read >>> st = read("/path/to/loc_RJOB20050831023349.z") """ traces = [] # read GSE2 file f = open(filename, 'rb') for _k in xrange(10000): # avoid endless loop pos = f.tell() widi = f.readline()[0:4] if widi == '': # end of file break elif widi != 'WID2': continue else: # valid gse2 part f.seek(pos) if headonly: header = libgse2.readHead(f) else: header, data = libgse2.read(f, verify_chksum=verify_chksum) # assign all header entries to a new dictionary compatible with an # ObsPy Trace object. new_header = {} for i, j in convert_dict.iteritems(): value = header[i] if isinstance(value, str): value = value.strip() new_header[j] = value # assign gse specific header entries new_header['gse2'] = {} for i in gse2_extra: new_header['gse2'][i] = header[i] # Calculate start time. new_header['starttime'] = UTCDateTime( header['d_year'], header['d_mon'], header['d_day'], header['t_hour'], header['t_min'], 0) + header['t_sec'] if headonly: traces.append(Trace(header=new_header)) else: traces.append(Trace(header=new_header, data=data)) f.close() return Stream(traces=traces)
def readGSE2(filename, headonly=False, verify_chksum=True, **kwargs): # @UnusedVariable """ Reads a GSE2 file and returns a Stream object. GSE2 files containing multiple WID2 entries/traces are supported. .. warning:: This function should NOT be called directly, it registers via the ObsPy :func:`~obspy.core.stream.read` function, call this instead. :type filename: string :param filename: GSE2 file to be read. :type headonly: boolean, optional :param headonly: If True read only head of GSE2 file. :type verify_chksum: boolean, optional :param verify_chksum: If True verify Checksum and raise Exception if it is not correct. :rtype: :class:`~obspy.core.stream.Stream` :returns: Stream object containing header and data. .. rubric:: Example >>> from obspy import read >>> st = read("/path/to/loc_RJOB20050831023349.z") """ traces = [] # read GSE2 file with open(filename, "rb") as f: for _k in xrange(10000): # avoid endless loop pos = f.tell() widi = f.readline()[0:4] if widi == "": # end of file break elif widi != "WID2": continue else: # valid gse2 part f.seek(pos) if headonly: header = libgse2.readHead(f) else: header, data = libgse2.read(f, verify_chksum=verify_chksum) # assign all header entries to a new dictionary compatible with # an ObsPy Trace object. new_header = {} for i, j in convert_dict.iteritems(): value = header[i] if isinstance(value, str): value = value.strip() new_header[j] = value # assign gse specific header entries new_header["gse2"] = {} for i in gse2_extra: new_header["gse2"][i] = header[i] # Calculate start time. new_header["starttime"] = ( UTCDateTime( header["d_year"], header["d_mon"], header["d_day"], header["t_hour"], header["t_min"], 0 ) + header["t_sec"] ) if headonly: traces.append(Trace(header=new_header)) else: traces.append(Trace(header=new_header, data=data)) return Stream(traces=traces)