示例#1
0
    def test_time_shifting_special_case(self):
        """
        Sometimes actually changing the time value is necessary. This works but
        is considered experimental and thus emits a warning. Therefore Python
        >= 2.6 only.
        """
        output_filename = NamedTemporaryFile().name
        # This file was created only for testing purposes.
        filename = os.path.join(self.path, 'data',
            "one_record_already_applied_time_correction.mseed")
        with warnings.catch_warnings(record=True):
            warnings.simplefilter('error', UserWarning)
            self.assertRaises(UserWarning, util.shiftTimeOfFile,
                              input_file=filename, output_file=output_filename,
                              timeshift=123400)
            # Now ignore the warnings and test the default values.
            warnings.simplefilter('ignore', UserWarning)
            util.shiftTimeOfFile(input_file=filename,
                                 output_file=output_filename, timeshift=123400)
        st_before = readMSEED(filename)
        st_after = readMSEED(output_filename)
        st_before[0].stats.starttime += 12.34
        self.assertEqual(st_before, st_after)

        # Test negative shifts.
        with warnings.catch_warnings(record=True):
            warnings.simplefilter('ignore', UserWarning)
            util.shiftTimeOfFile(input_file=filename,
                                 output_file=output_filename, timeshift=-22222)
        st_before = readMSEED(filename)
        st_after = readMSEED(output_filename)
        st_before[0].stats.starttime -= 2.2222
        self.assertEqual(st_before, st_after)

        os.remove(output_filename)
    def test_readAndWriteTraces(self):
        """
        Writes, reads and compares files created via obspy.mseed.

        This uses all possible encodings, record lengths and the byte order
        options. A re-encoded SEED file should still have the same values
        regardless of write options.
        Note: Test currently only tests the first trace
        """
        mseed_file = os.path.join(self.path, 'data', 'test.mseed')
        stream = readMSEED(mseed_file)
        # Define test ranges
        record_length_values = [2**i for i in range(8, 21)]
        encoding_values = {
            "ASCII": "|S1",
            "INT16": "int16",
            "INT32": "int32",
            "FLOAT32": "float32",
            "FLOAT64": "float64",
            "STEIM1": "int32",
            "STEIM2": "int32"
        }
        byteorder_values = ['>', '<']
        # Loop over every combination.
        for reclen in record_length_values:
            for byteorder in byteorder_values:
                for encoding in encoding_values.keys():
                    this_stream = copy.deepcopy(stream)
                    this_stream[0].data = \
                        np.require(this_stream[0].data,
                                   dtype=encoding_values[encoding])
                    temp_file = NamedTemporaryFile().name

                    writeMSEED(this_stream,
                               temp_file,
                               encoding=encoding,
                               byteorder=byteorder,
                               reclen=reclen)
                    new_stream = readMSEED(temp_file)
                    # Assert the new stream still has the chosen attributes.
                    # This should mean that writing as well as reading them
                    # works.
                    self.assertEqual(new_stream[0].stats.mseed.byteorder,
                                     byteorder)
                    self.assertEqual(new_stream[0].stats.mseed.record_length,
                                     reclen)
                    self.assertEqual(new_stream[0].stats.mseed.encoding,
                                     encoding)

                    np.testing.assert_array_equal(this_stream[0].data,
                                                  new_stream[0].data)
                    os.remove(temp_file)
示例#3
0
    def test_readGappyFile(self):
        """
        Compares waveform data read by obspy.mseed with an ASCII dump.

        Checks the first 9 datasamples of each entry in trace_list of
        gaps.mseed. The values are assumed to be correct. The first values
        were created using Pitsa.

        XXX: This tests is a straight port from an old libmseed test. Redundant
        to some other tests.
        """
        mseed_file = os.path.join(self.path, 'data', unicode('gaps.mseed'))
        # list of known data samples
        starttime = [
            1199145599915000L, 1199145604035000L, 1199145610215000L,
            1199145618455000L
        ]
        datalist = [[-363, -382, -388, -420, -417, -397, -418, -390, -388],
                    [-427, -416, -393, -430, -426, -407, -401, -422, -439],
                    [-396, -399, -387, -384, -393, -380, -365, -394, -426],
                    [-389, -428, -409, -389, -388, -405, -390, -368, -368]]
        i = 0
        stream = readMSEED(mseed_file)
        for trace in stream:
            self.assertEqual('BGLD', trace.stats.station)
            self.assertEqual('EHE', trace.stats.channel)
            self.assertEqual(200, trace.stats.sampling_rate)
            self.assertEqual(
                starttime[i],
                util._convertDatetimeToMSTime(trace.stats.starttime))
            self.assertEqual(datalist[i], trace.data[0:9].tolist())
            i += 1
        del stream
        # Also test unicode filenames.
        mseed_filenames = [
            unicode('BW.BGLD.__.EHE.D.2008.001.first_record'),
            unicode('qualityflags.mseed'),
            unicode('test.mseed'),
            unicode('timingquality.mseed')
        ]
        samprate = [200.0, 200.0, 40.0, 200.0]
        station = ['BGLD', 'BGLD', 'HGN', 'BGLD']
        npts = [412, 412, 11947, 41604, 1]
        for i, _f in enumerate(mseed_filenames):
            filename = os.path.join(self.path, 'data', _f)
            stream = readMSEED(filename)
            self.assertEqual(samprate[i], stream[0].stats.sampling_rate)
            self.assertEqual(station[i], stream[0].stats.station)
            self.assertEqual(npts[i], stream[0].stats.npts)
            self.assertEqual(npts[i], len(stream[0].data))
        del stream
    def test_readGappyFile(self):
        """
        Compares waveform data read by obspy.mseed with an ASCII dump.

        Checks the first 9 datasamples of each entry in trace_list of
        gaps.mseed. The values are assumed to be correct. The first values
        were created using Pitsa.

        XXX: This tests is a straight port from an old libmseed test. Redundant
        to some other tests.
        """
        mseed_file = os.path.join(self.path, 'data', str('gaps.mseed'))
        # list of known data samples
        starttime = [1199145599915000, 1199145604035000, 1199145610215000,
                     1199145618455000]
        datalist = [[-363, -382, -388, -420, -417, -397, -418, -390, -388],
                    [-427, -416, -393, -430, -426, -407, -401, -422, -439],
                    [-396, -399, -387, -384, -393, -380, -365, -394, -426],
                    [-389, -428, -409, -389, -388, -405, -390, -368, -368]]
        i = 0
        stream = readMSEED(mseed_file)
        for trace in stream:
            self.assertEqual('BGLD', trace.stats.station)
            self.assertEqual('EHE', trace.stats.channel)
            self.assertEqual(200, trace.stats.sampling_rate)
            self.assertEqual(
                starttime[i],
                util._convertDatetimeToMSTime(trace.stats.starttime))
            self.assertEqual(datalist[i], trace.data[0:9].tolist())
            i += 1
        del stream
        # Also test unicode filenames.
        mseed_filenames = [str('BW.BGLD.__.EHE.D.2008.001.first_record'),
                           str('qualityflags.mseed'),
                           str('test.mseed'),
                           str('timingquality.mseed')]
        samprate = [200.0, 200.0, 40.0, 200.0]
        station = ['BGLD', 'BGLD', 'HGN', 'BGLD']
        npts = [412, 412, 11947, 41604, 1]
        for i, _f in enumerate(mseed_filenames):
            filename = os.path.join(self.path, 'data', _f)
            stream = readMSEED(filename)
            self.assertEqual(samprate[i], stream[0].stats.sampling_rate)
            self.assertEqual(station[i], stream[0].stats.station)
            self.assertEqual(npts[i], stream[0].stats.npts)
            self.assertEqual(npts[i], len(stream[0].data))
        del stream
示例#5
0
    def test_time_shifting(self):
        """
        Tests the shiftTimeOfFile() function.
        """
        output_filename = NamedTemporaryFile().name
        # Test a normal file first.
        filename = os.path.join(self.path, 'data',
                                "BW.BGLD.__.EHE.D.2008.001.first_10_records")
        # Shift by one second.
        util.shiftTimeOfFile(filename, output_filename, 10000)
        st_before = readMSEED(filename)
        st_after = readMSEED(output_filename)
        st_before[0].stats.starttime += 1
        self.assertEqual(st_before, st_after)
        # Shift by 22 seconds in the other direction.
        util.shiftTimeOfFile(filename, output_filename, -220000)
        st_before = readMSEED(filename)
        st_after = readMSEED(output_filename)
        st_before[0].stats.starttime -= 22
        self.assertEqual(st_before, st_after)
        # Shift by 11.33 seconds.
        util.shiftTimeOfFile(filename, output_filename, 113300)
        st_before = readMSEED(filename)
        st_after = readMSEED(output_filename)
        st_before[0].stats.starttime += 11.33
        self.assertEqual(st_before, st_after)

        # Test a special case with the time correction applied flag set but no
        # actual time correction in the field.
        filename = os.path.join(
            self.path, 'data',
            "one_record_time_corr_applied_but_time_corr_is_zero.mseed")
        # Positive shift.
        util.shiftTimeOfFile(filename, output_filename, 22000)
        st_before = readMSEED(filename)
        st_after = readMSEED(output_filename)
        st_before[0].stats.starttime += 2.2
        self.assertEqual(st_before, st_after)
        # Negative shift.
        util.shiftTimeOfFile(filename, output_filename, -333000)
        st_before = readMSEED(filename)
        st_after = readMSEED(output_filename)
        st_before[0].stats.starttime -= 33.3
        self.assertEqual(st_before, st_after)

        # Remove the file after everything it done.
        os.remove(output_filename)
示例#6
0
    def test_time_shifting(self):
        """
        Tests the shiftTimeOfFile() function.
        """
        output_filename = NamedTemporaryFile().name
        # Test a normal file first.
        filename = os.path.join(self.path, 'data',
                                "BW.BGLD.__.EHE.D.2008.001.first_10_records")
        # Shift by one second.
        util.shiftTimeOfFile(filename, output_filename, 10000)
        st_before = readMSEED(filename)
        st_after = readMSEED(output_filename)
        st_before[0].stats.starttime += 1
        self.assertEqual(st_before, st_after)
        # Shift by 22 seconds in the other direction.
        util.shiftTimeOfFile(filename, output_filename, -220000)
        st_before = readMSEED(filename)
        st_after = readMSEED(output_filename)
        st_before[0].stats.starttime -= 22
        self.assertEqual(st_before, st_after)
        # Shift by 11.33 seconds.
        util.shiftTimeOfFile(filename, output_filename, 113300)
        st_before = readMSEED(filename)
        st_after = readMSEED(output_filename)
        st_before[0].stats.starttime += 11.33
        self.assertEqual(st_before, st_after)

        # Test a special case with the time correction applied flag set but no
        # actual time correction in the field.
        filename = os.path.join(self.path, 'data',
                    "one_record_time_corr_applied_but_time_corr_is_zero.mseed")
        # Positive shift.
        util.shiftTimeOfFile(filename, output_filename, 22000)
        st_before = readMSEED(filename)
        st_after = readMSEED(output_filename)
        st_before[0].stats.starttime += 2.2
        self.assertEqual(st_before, st_after)
        # Negative shift.
        util.shiftTimeOfFile(filename, output_filename, -333000)
        st_before = readMSEED(filename)
        st_after = readMSEED(output_filename)
        st_before[0].stats.starttime -= 33.3
        self.assertEqual(st_before, st_after)

        # Remove the file after everything it done.
        os.remove(output_filename)
    def test_readAndWriteTraces(self):
        """
        Writes, reads and compares files created via obspy.mseed.

        This uses all possible encodings, record lengths and the byte order
        options. A re-encoded SEED file should still have the same values
        regardless of write options.
        Note: Test currently only tests the first trace
        """
        mseed_file = os.path.join(self.path, 'data', 'test.mseed')
        stream = readMSEED(mseed_file)
        # Define test ranges
        record_length_values = [2 ** i for i in range(8, 21)]
        encoding_values = {"ASCII": "|S1", "INT16": "int16", "INT32": "int32",
                           "FLOAT32": "float32", "FLOAT64": "float64",
                           "STEIM1": "int32", "STEIM2": "int32"}
        byteorder_values = ['>', '<']
        # Loop over every combination.
        for reclen in record_length_values:
            for byteorder in byteorder_values:
                for encoding in encoding_values.keys():
                    this_stream = copy.deepcopy(stream)
                    this_stream[0].data = \
                        np.require(this_stream[0].data,
                                   dtype=encoding_values[encoding])
                    temp_file = NamedTemporaryFile().name

                    writeMSEED(this_stream, temp_file, encoding=encoding,
                               byteorder=byteorder, reclen=reclen)
                    new_stream = readMSEED(temp_file)
                    # Assert the new stream still has the chosen attributes.
                    # This should mean that writing as well as reading them
                    # works.
                    self.assertEqual(new_stream[0].stats.mseed.byteorder,
                                     byteorder)
                    self.assertEqual(new_stream[0].stats.mseed.record_length,
                                     reclen)
                    self.assertEqual(new_stream[0].stats.mseed.encoding,
                                     encoding)

                    np.testing.assert_array_equal(this_stream[0].data,
                                                  new_stream[0].data)
                    os.remove(temp_file)
 def test_readFullSEED(self):
     """
     Reads a full SEED volume.
     """
     files = os.path.join(self.path, 'data', 'fullseed.mseed')
     st = readMSEED(files)
     self.assertEqual(len(st), 3)
     self.assertEqual(len(st[0]), 602)
     self.assertEqual(len(st[1]), 623)
     self.assertEqual(len(st[2]), 610)
 def test_readAndWriteFileWithGaps(self):
     """
     Tests reading and writing files with more than one trace.
     """
     filename = os.path.join(self.path, 'data', 'gaps.mseed')
     # Read file and test if all traces are being read.
     stream = readMSEED(filename)
     self.assertEqual(len(stream), 4)
     # Write File to temporary file.
     with NamedTemporaryFile() as tf:
         outfile = tf.name
         writeMSEED(copy.deepcopy(stream), outfile)
         # Read the same file again and compare it to the original file.
         new_stream = readMSEED(outfile)
     self.assertEqual(len(stream), len(new_stream))
     # Compare new_trace_list with trace_list
     for tr1, tr2 in zip(stream, new_stream):
         self.assertEqual(tr1.stats, tr2.stats)
         np.testing.assert_array_equal(tr1.data, tr2.data)
 def test_readPartialFrameWithEmptyTimeRange(self):
     """
     Uses obspy.mseed.mseed.readMSEED to read a partial file with a
     timewindow outside of the actual data. Should return an empty Stream
     object.
     """
     starttime = UTCDateTime('2003-05-29T02:13:22.043400Z')
     testfile = os.path.join(self.path, 'data', 'test.mseed')
     stream = readMSEED(testfile, starttime=starttime - 1E6,
                        endtime=starttime - 1E6 + 1)
     self.assertEqual(len(stream), 0)
示例#11
0
def parse_file_to_dict(data_dict, samp_int_dict, file, counter, format=None, verbose=False):
    """ Читаются файлы в своих форматах, отуда вытаскивается информация о времени """
    # если формат не указан - это miniseed
    if format == None:
        try:
            stream = readMSEED(file, headonly=True)
        except:
            print("Can not read %s" % (file))
            return counter
    else:
        # у нас формат БАЙКАЛ
        bf = BaikalFile(file, headonly=True)
        # правильный ли файл
        if not bf.valid:
            print("Skipping file %s" % file)
            return counter
        Header = bf.MainHeader
        # заголовок
        hour, minute, seconds = datetime.timedelta(seconds=Header["to"]).__str__().split(":")
        header = {
            'network': 'BFG',
            'station': Header['station'][:3],
            'location': '',
            'channel': "0",
            'npts': 30000,# файлы обычно по 5 минут
            #'mseed': {'dataquality': 'D'},
            'starttime': UTCDateTime(
                Header["year"], #2009,
                Header["month"], #8,
                Header["day"], #24,
                int(hour), #0,
                int(minute), #20,
                float(seconds), #3,
            ),
            'sampling_rate': 1/Header['dt'],
        }
        # добавить канал (один для всех)
        trace = Trace(header=header)#, data=)
        # работаем в терминах obspy
        stream = Stream(traces=[trace])
    s = "%s %s" % (counter, file)
    if verbose:
        sys.stdout.write("%s\n" % s)
        for line in str(stream).split("\n"):
            sys.stdout.write("    " + line + "\n")
    else:
        sys.stdout.write("\r" + s)
        sys.stdout.flush()
    for tr in stream:
        _id = tr.getId()
        data_dict.setdefault(_id, [])
        data_dict[_id].append([date2num(tr.stats.starttime), date2num(tr.stats.endtime)])
        samp_int_dict.setdefault(_id, 1.0 / (24 * 3600 * tr.stats.sampling_rate))
    return (counter + 1)
 def test_readPartialWithOnlyEndtimeSet(self):
     """
     Uses obspy.mseed.mseed.readMSEED to read only the data ending before a
     certain time.
     """
     starttime = UTCDateTime('2007-12-31T23:59:59.915000Z')
     endtime = UTCDateTime('2008-01-01T00:00:20.510000Z')
     testfile = os.path.join(self.path, 'data',
                             'BW.BGLD.__.EHE.D.2008.001.first_10_records')
     stream = readMSEED(testfile, endtime=endtime - 6)
     self.assertEqual(starttime, stream[0].stats.starttime)
     self.assertTrue(endtime > stream[0].stats.endtime)
示例#13
0
 def test_unpackSteim2(self):
     """
     Test decompression of Steim2 strings. Remove 128 Bytes of header
     by hand, see SEEDManual_V2.4.pdf page 100.
     """
     steim2_file = os.path.join(self.path, 'data', 'steim2.mseed')
     # 128 Bytes header.
     data_string = open(steim2_file, 'rb').read()[128:]
     data = util._unpackSteim2(data_string, 5980, swapflag=self.swap,
                                verbose=0)
     data_record = readMSEED(steim2_file)[0].data
     np.testing.assert_array_equal(data, data_record)
示例#14
0
    def test_time_shifting_special_case(self):
        """
        Sometimes actually changing the time value is necessary. This works but
        is considered experimental and thus emits a warning. Therefore Python
        >= 2.6 only.
        """
        output_filename = NamedTemporaryFile().name
        # This file was created only for testing purposes.
        filename = os.path.join(
            self.path, 'data',
            "one_record_already_applied_time_correction.mseed")
        with warnings.catch_warnings(record=True):
            warnings.simplefilter('error', UserWarning)
            self.assertRaises(UserWarning,
                              util.shiftTimeOfFile,
                              input_file=filename,
                              output_file=output_filename,
                              timeshift=123400)
            # Now ignore the warnings and test the default values.
            warnings.simplefilter('ignore', UserWarning)
            util.shiftTimeOfFile(input_file=filename,
                                 output_file=output_filename,
                                 timeshift=123400)
        st_before = readMSEED(filename)
        st_after = readMSEED(output_filename)
        st_before[0].stats.starttime += 12.34
        self.assertEqual(st_before, st_after)

        # Test negative shifts.
        with warnings.catch_warnings(record=True):
            warnings.simplefilter('ignore', UserWarning)
            util.shiftTimeOfFile(input_file=filename,
                                 output_file=output_filename,
                                 timeshift=-22222)
        st_before = readMSEED(filename)
        st_after = readMSEED(output_filename)
        st_before[0].stats.starttime -= 2.2222
        self.assertEqual(st_before, st_after)

        os.remove(output_filename)
 def test_readPartialTimewindowFromFile(self):
     """
     Uses obspy.mseed.mseed.readMSEED to read only read a certain time
     window of a file.
     """
     starttime = UTCDateTime('2007-12-31T23:59:59.915000Z')
     endtime = UTCDateTime('2008-01-01T00:00:20.510000Z')
     testfile = os.path.join(self.path, 'data',
                             'BW.BGLD.__.EHE.D.2008.001.first_10_records')
     stream = readMSEED(testfile, starttime=starttime + 6,
                        endtime=endtime - 6)
     self.assertTrue(starttime < stream[0].stats.starttime)
     self.assertTrue(endtime > stream[0].stats.endtime)
示例#16
0
 def test_brokenLastRecord(self):
     """
     Test if Libmseed is able to read files with broken last record. Use
     both methods, readMSTracesViaRecords and readMSTraces
     """
     file = os.path.join(self.path, "data", "brokenlastrecord.mseed")
     # independent reading of the data
     data_string = open(file, 'rb').read()[128:]  # 128 Bytes header
     data = util._unpackSteim2(data_string, 5980, swapflag=self.swap,
                               verbose=0)
     # test readMSTraces
     data_record = readMSEED(file)[0].data
     np.testing.assert_array_equal(data, data_record)
示例#17
0
 def test_unpackSteim1(self):
     """
     Test decompression of Steim1 strings. Remove 64 Bytes of header
     by hand, see SEEDManual_V2.4.pdf page 100.
     """
     steim1_file = os.path.join(self.path, 'data',
                                'BW.BGLD.__.EHE.D.2008.001.first_record')
     # 64 Bytes header.
     data_string = open(steim1_file, 'rb').read()[64:]
     data = util._unpackSteim1(data_string, 412, swapflag=self.swap,
                                verbose=0)
     data_record = readMSEED(steim1_file)[0].data
     np.testing.assert_array_equal(data, data_record)
示例#18
0
 def test_unpackSteim2(self):
     """
     Test decompression of Steim2 strings. Remove 128 Bytes of header
     by hand, see SEEDManual_V2.4.pdf page 100.
     """
     steim2_file = os.path.join(self.path, 'data', 'steim2.mseed')
     # 128 Bytes header.
     data_string = open(steim2_file, 'rb').read()[128:]
     data = util._unpackSteim2(data_string,
                               5980,
                               swapflag=self.swap,
                               verbose=0)
     data_record = readMSEED(steim2_file)[0].data
     np.testing.assert_array_equal(data, data_record)
示例#19
0
 def test_brokenLastRecord(self):
     """
     Test if Libmseed is able to read files with broken last record. Use
     both methods, readMSTracesViaRecords and readMSTraces
     """
     file = os.path.join(self.path, "data", "brokenlastrecord.mseed")
     # independent reading of the data
     data_string = open(file, 'rb').read()[128:]  # 128 Bytes header
     data = util._unpackSteim2(data_string,
                               5980,
                               swapflag=self.swap,
                               verbose=0)
     # test readMSTraces
     data_record = readMSEED(file)[0].data
     np.testing.assert_array_equal(data, data_record)
示例#20
0
 def test_unpackSteim1(self):
     """
     Test decompression of Steim1 strings. Remove 64 Bytes of header
     by hand, see SEEDManual_V2.4.pdf page 100.
     """
     steim1_file = os.path.join(self.path, 'data',
                                'BW.BGLD.__.EHE.D.2008.001.first_record')
     # 64 Bytes header.
     data_string = open(steim1_file, 'rb').read()[64:]
     data = util._unpackSteim1(data_string,
                               412,
                               swapflag=self.swap,
                               verbose=0)
     data_record = readMSEED(steim1_file)[0].data
     np.testing.assert_array_equal(data, data_record)
示例#21
0
    def test_getStartAndEndTime(self):
        """
        Tests getting the start- and endtime of a file.

        The values are compared with the results of reading the full files.
        """
        mseed_filenames = ['BW.BGLD.__.EHE.D.2008.001.first_10_records',
                           'test.mseed', 'timingquality.mseed']
        for _i in mseed_filenames:
            filename = os.path.join(self.path, 'data', _i)
            # Get the start- and end time.
            (start, end) = util.getStartAndEndTime(filename)
            # Parse the whole file.
            stream = readMSEED(filename)
            self.assertEqual(start, stream[0].stats.starttime)
            self.assertEqual(end, stream[0].stats.endtime)
 def test_readFileViaMSEED(self):
     """
     Read file test via L{obspy.mseed.mseed.readMSEED}.
     """
     testfile = os.path.join(self.path, 'data', 'test.mseed')
     data = [2787, 2776, 2774, 2780, 2783]
     # Read the file directly to a Stream object.
     stream = readMSEED(testfile)
     stream.verify()
     self.assertEqual(stream[0].stats.network, 'NL')
     self.assertEqual(stream[0].stats['station'], 'HGN')
     self.assertEqual(stream[0].stats.get('location'), '00')
     self.assertEqual(stream[0].stats.npts, 11947)
     self.assertEqual(stream[0].stats['sampling_rate'], 40.0)
     self.assertEqual(stream[0].stats.get('channel'), 'BHZ')
     for _i in xrange(5):
         self.assertEqual(stream[0].data[_i], data[_i])
示例#23
0
    def test_writeWithDateTimeBefore1970(self):
        """
        Write an stream via libmseed with a datetime before 1970.

        This test depends on the platform specific localtime()/gmtime()
        function.
        """
        # create trace
        tr = Trace(data=np.empty(1000))
        tr.stats.starttime = UTCDateTime("1969-01-01T00:00:00")
        # write file
        tempfile = NamedTemporaryFile().name
        writeMSEED(Stream([tr]), tempfile, format="MSEED")
        # read again
        stream = readMSEED(tempfile)
        os.remove(tempfile)
        stream.verify()
示例#24
0
 def test_oneSampleOverlap(self):
     """
     Both methods readMSTraces and readMSTracesViaRecords should recognize a
     single sample overlap.
     """
     # create a stream with one sample overlapping
     trace1 = Trace(data=np.zeros(1000))
     trace2 = Trace(data=np.zeros(10))
     trace2.stats.starttime = UTCDateTime(999)
     st = Stream([trace1, trace2])
     # write into MSEED
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         writeMSEED(st, tempfile, format="MSEED")
         # read it again
         new_stream = readMSEED(tempfile)
         self.assertEqual(len(new_stream), 2)
    def test_writeWithDateTimeBefore1970(self):
        """
        Write an stream via libmseed with a datetime before 1970.

        This test depends on the platform specific localtime()/gmtime()
        function.
        """
        # create trace
        tr = Trace(data=np.empty(1000))
        tr.stats.starttime = UTCDateTime("1969-01-01T00:00:00")
        # write file
        with NamedTemporaryFile() as tf:
            tempfile = tf.name
            writeMSEED(Stream([tr]), tempfile, format="MSEED")
            # read again
            stream = readMSEED(tempfile)
            stream.verify()
 def test_writeIntegers(self):
     """
     Write integer array via L{obspy.mseed.mseed.writeMSEED}.
     """
     npts = 1000
     # data array of integers - float won't work!
     np.random.seed(815)  # make test reproducable
     data = np.random.randint(-1000, 1000, npts).astype('int32')
     st = Stream([Trace(data=data)])
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         # write
         writeMSEED(st, tempfile, format="MSEED")
         # read again
         stream = readMSEED(tempfile)
     stream.verify()
     np.testing.assert_array_equal(stream[0].data, data)
 def test_oneSampleOverlap(self):
     """
     Both methods readMSTraces and readMSTracesViaRecords should recognize a
     single sample overlap.
     """
     # create a stream with one sample overlapping
     trace1 = Trace(data=np.zeros(1000))
     trace2 = Trace(data=np.zeros(10))
     trace2.stats.starttime = UTCDateTime(999)
     st = Stream([trace1, trace2])
     # write into MSEED
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         writeMSEED(st, tempfile, format="MSEED")
         # read it again
         new_stream = readMSEED(tempfile)
         self.assertEqual(len(new_stream), 2)
示例#28
0
    def test_getStartAndEndTime(self):
        """
        Tests getting the start- and endtime of a file.

        The values are compared with the results of reading the full files.
        """
        mseed_filenames = [
            'BW.BGLD.__.EHE.D.2008.001.first_10_records', 'test.mseed',
            'timingquality.mseed'
        ]
        for _i in mseed_filenames:
            filename = os.path.join(self.path, 'data', _i)
            # Get the start- and end time.
            (start, end) = util.getStartAndEndTime(filename)
            # Parse the whole file.
            stream = readMSEED(filename)
            self.assertEqual(start, stream[0].stats.starttime)
            self.assertEqual(end, stream[0].stats.endtime)
示例#29
0
 def test_bugWriteReadFloat32SEEDWin32(self):
     """
     Test case for issue #64.
     """
     # create stream object
     data = np.array([395.07809448, 395.0782, 1060.28112793, -1157.37487793,
                      -1236.56237793, 355.07028198, -1181.42175293],
                     dtype=np.float32)
     st = Stream([Trace(data=data)])
     tempfile = NamedTemporaryFile().name
     writeMSEED(st, tempfile, format="MSEED")
     # read temp file directly without libmseed
     bin_data = open(tempfile, "rb").read()
     bin_data = np.array(unpack(">7f", bin_data[56:84]))
     np.testing.assert_array_equal(data, bin_data)
     # read via ObsPy
     st2 = readMSEED(tempfile)
     os.remove(tempfile)
     # test results
     np.testing.assert_array_equal(data, st2[0].data)
示例#30
0
 def test_bugWriteReadFloat32SEEDWin32(self):
     """
     Test case for issue #64.
     """
     # create stream object
     data = np.array([395.07809448, 395.0782, 1060.28112793, -1157.37487793,
                      -1236.56237793, 355.07028198, -1181.42175293],
                     dtype=np.float32)
     st = Stream([Trace(data=data)])
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         writeMSEED(st, tempfile, format="MSEED")
         # read temp file directly without libmseed
         with open(tempfile, 'rb') as fp:
             fp.seek(56)
             bin_data = np.fromfile(fp, dtype='>f4', count=7)
         np.testing.assert_array_equal(data, bin_data)
         # read via ObsPy
         st2 = readMSEED(tempfile)
     # test results
     np.testing.assert_array_equal(data, st2[0].data)
示例#31
0
 def test_bugWriteReadFloat32SEEDWin32(self):
     """
     Test case for issue #64.
     """
     # create stream object
     data = np.array([
         395.07809448, 395.0782, 1060.28112793, -1157.37487793,
         -1236.56237793, 355.07028198, -1181.42175293
     ],
                     dtype=np.float32)
     st = Stream([Trace(data=data)])
     tempfile = NamedTemporaryFile().name
     writeMSEED(st, tempfile, format="MSEED")
     # read temp file directly without libmseed
     bin_data = open(tempfile, "rb").read()
     bin_data = np.array(unpack(">7f", bin_data[56:84]))
     np.testing.assert_array_equal(data, bin_data)
     # read via ObsPy
     st2 = readMSEED(tempfile)
     os.remove(tempfile)
     # test results
     np.testing.assert_array_equal(data, st2[0].data)
示例#32
0
 def test_bugWriteReadFloat32SEEDWin32(self):
     """
     Test case for issue #64.
     """
     # create stream object
     data = np.array([
         395.07809448, 395.0782, 1060.28112793, -1157.37487793,
         -1236.56237793, 355.07028198, -1181.42175293
     ],
                     dtype=np.float32)
     st = Stream([Trace(data=data)])
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         writeMSEED(st, tempfile, format="MSEED")
         # read temp file directly without libmseed
         with open(tempfile, 'rb') as fp:
             fp.seek(56)
             bin_data = np.fromfile(fp, dtype='>f4', count=7)
         np.testing.assert_array_equal(data, bin_data)
         # read via ObsPy
         st2 = readMSEED(tempfile)
     # test results
     np.testing.assert_array_equal(data, st2[0].data)
 def test_readPartialWithSourceName(self):
     """
     Uses obspy.mseed.mseed.readMSEED to read only part of a file that
     matches certain sourcename patterns.
     """
     testfile = os.path.join(self.path, 'data', 'two_channels.mseed')
     st1 = readMSEED(testfile)
     self.assertEqual(st1[0].stats.channel, 'EHE')
     self.assertEqual(st1[1].stats.channel, 'EHZ')
     st2 = readMSEED(testfile, sourcename='*')
     self.assertEqual(st2[0].stats.channel, 'EHE')
     self.assertEqual(st2[1].stats.channel, 'EHZ')
     st3 = readMSEED(testfile, sourcename='*.EH*')
     self.assertEqual(st3[0].stats.channel, 'EHE')
     self.assertEqual(st3[1].stats.channel, 'EHZ')
     st4 = readMSEED(testfile, sourcename='*E')
     self.assertEqual(st4[0].stats.channel, 'EHE')
     self.assertEqual(len(st4), 1)
     st5 = readMSEED(testfile, sourcename='*.EHZ')
     self.assertEqual(st5[0].stats.channel, 'EHZ')
     self.assertEqual(len(st5), 1)
     st6 = readMSEED(testfile, sourcename='*.BLA')
     self.assertEqual(len(st6), 0)