Coverage for /opt/obspy/update-docs/src/obspy/obspy/mseed/util : 90%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# -*- coding: utf-8 -*- Mini-SEED specific utilities. """
""" Returns the start- and endtime of a Mini-SEED file or file-like object.
:type file_or_file_object: basestring or open file-like object. :param file_or_file_object: Mini-SEED file name or open file-like object containing a Mini-SEED record. :return: tuple (start time of first record, end time of last record)
This method will return the start time of the first record and the end time of the last record. Keep in mind that it will not return the correct result if the records in the Mini-SEED file do not have a chronological ordering.
The returned endtime is the time of the last data sample and not the time that the last sample covers.
.. rubric:: Example
>>> from obspy.core.util import getExampleFile >>> filename = getExampleFile("BW.BGLD.__.EHE.D.2008.001.first_10_records") >>> getStartAndEndTime(filename) # doctest: +NORMALIZE_WHITESPACE (UTCDateTime(2007, 12, 31, 23, 59, 59, 915000), UTCDateTime(2008, 1, 1, 0, 0, 20, 510000))
It also works with an open file pointer. The file pointer itself will not be changed.
>>> f = open(filename, 'rb') >>> getStartAndEndTime(f) # doctest: +NORMALIZE_WHITESPACE (UTCDateTime(2007, 12, 31, 23, 59, 59, 915000), UTCDateTime(2008, 1, 1, 0, 0, 20, 510000))
And also with a Mini-SEED file stored in a StringIO.
>>> from StringIO import StringIO >>> file_object = StringIO(f.read()) >>> getStartAndEndTime(file_object) # doctest: +NORMALIZE_WHITESPACE (UTCDateTime(2007, 12, 31, 23, 59, 59, 915000), UTCDateTime(2008, 1, 1, 0, 0, 20, 510000)) >>> file_object.close()
If the file pointer does not point to the first record, the start time will refer to the record it points to.
>>> f.seek(512) >>> getStartAndEndTime(f) # doctest: +NORMALIZE_WHITESPACE (UTCDateTime(2008, 1, 1, 0, 0, 1, 975000), UTCDateTime(2008, 1, 1, 0, 0, 20, 510000))
The same is valid for a file-like object.
>>> file_object = StringIO(f.read()) >>> getStartAndEndTime(file_object) # doctest: +NORMALIZE_WHITESPACE (UTCDateTime(2008, 1, 1, 0, 0, 1, 975000), UTCDateTime(2008, 1, 1, 0, 0, 20, 510000)) >>> f.close() """ # Get the starttime of the first record. # Get the endtime of the last record. (info['number_of_records'] - 1) * info['record_length'])
""" Counts all data quality flags of the given Mini-SEED file and returns statistics about the timing quality if applicable.
:type file_or_file_object: basestring or open file-like object. :param file_or_file_object: Mini-SEED file name or open file-like object containing a Mini-SEED record.
:return: Dictionary with information about the timing quality and the data quality flags.
.. rubric:: Data quality
This method will count all set data quality flag bits in the fixed section of the data header in a Mini-SEED file and returns the total count for each flag type.
======== ================================================= Bit Description ======== ================================================= [Bit 0] Amplifier saturation detected (station dependent) [Bit 1] Digitizer clipping detected [Bit 2] Spikes detected [Bit 3] Glitches detected [Bit 4] Missing/padded data present [Bit 5] Telemetry synchronization error [Bit 6] A digital filter may be charging [Bit 7] Time tag is questionable ======== =================================================
.. rubric:: Timing quality
If the file has a Blockette 1001 statistics about the timing quality will also be returned. See the doctests for more information.
This method will read the timing quality in Blockette 1001 for each record in the file if available and return the following statistics: Minima, maxima, average, median and upper and lower quantile. Quantiles are calculated using a integer round outwards policy: lower quantiles are rounded down (probability < 0.5), and upper quantiles (probability > 0.5) are rounded up. This gives no more than the requested probability in the tails, and at least the requested probability in the central area. The median is calculating by either taking the middle value or, with an even numbers of values, the average between the two middle values.
.. rubric:: Example
>>> from obspy.core.util import getExampleFile >>> filename = getExampleFile("qualityflags.mseed") >>> getTimingAndDataQuality(filename) {'data_quality_flags': [9, 8, 7, 6, 5, 4, 3, 2]}
Also works with file pointers and StringIOs.
>>> f = open(filename, 'rb') >>> getTimingAndDataQuality(f) {'data_quality_flags': [9, 8, 7, 6, 5, 4, 3, 2]}
>>> from StringIO import StringIO >>> file_object = StringIO(f.read()) >>> f.close() >>> getTimingAndDataQuality(file_object) {'data_quality_flags': [9, 8, 7, 6, 5, 4, 3, 2]}
If the file pointer or StringIO position does not correspond to the first record the omitted records will be skipped.
>>> file_object.seek(1024, 1) >>> getTimingAndDataQuality(file_object) {'data_quality_flags': [8, 8, 7, 6, 5, 4, 3, 2]} >>> file_object.close()
Reading a file with Blockette 1001 will return timing quality statistics. The data quality flags will always exists because they are part of the fixed Mini-SEED header and therefore need to be in every Mini-SEED file.
>>> filename = getExampleFile("timingquality.mseed") >>> getTimingAndDataQuality(filename) # doctest: +NORMALIZE_WHITESPACE {'timing_quality_upper_quantile': 75.0, 'data_quality_flags': [0, 0, 0, 0, 0, 0, 0, 0], 'timing_quality_min': 0.0, 'timing_quality_lower_quantile': 25.0, 'timing_quality_average': 50.0, 'timing_quality_median': 50.0, 'timing_quality_max': 100.0}
Also works with file pointers and StringIOs.
>>> f = open(filename, 'rb') >>> getTimingAndDataQuality(f) # doctest: +NORMALIZE_WHITESPACE {'timing_quality_upper_quantile': 75.0, 'data_quality_flags': [0, 0, 0, 0, 0, 0, 0, 0], 'timing_quality_min': 0.0, 'timing_quality_lower_quantile': 25.0, 'timing_quality_average': 50.0, 'timing_quality_median': 50.0, 'timing_quality_max': 100.0}
>>> file_object = StringIO(f.read()) >>> f.close() >>> getTimingAndDataQuality(file_object) # doctest: +NORMALIZE_WHITESPACE {'timing_quality_upper_quantile': 75.0, 'data_quality_flags': [0, 0, 0, 0, 0, 0, 0, 0], 'timing_quality_min': 0.0, 'timing_quality_lower_quantile': 25.0, 'timing_quality_average': 50.0, 'timing_quality_median': 50.0, 'timing_quality_max': 100.0} >>> file_object.close() """ # Read the first record to get a starting point and. # Keep track of the extracted information.
# Loop over each record. A valid record needs to have a record length of at # least 256 bytes. # Add the timing quality. # Add the value of each bit to the quality_count.
# Collect the results in a dictionary.
# Parse of the timing quality list. # If no timing_quality was collected just return an empty dictionary. # Otherwise calculate some statistical values from the timing quality. scoreatpercentile(timing_quality, 50, issorted=False) scoreatpercentile(timing_quality, 25, issorted=False) scoreatpercentile(timing_quality, 75, issorted=False)
""" Returns record information about given files and file-like object.
.. rubric:: Example
>>> from obspy.core.util import getExampleFile >>> filename = getExampleFile("test.mseed") >>> getRecordInformation(filename) # doctest: +NORMALIZE_WHITESPACE {'record_length': 4096, 'data_quality_flags': 0, 'activity_flags': 0, 'byteorder': '>', 'encoding': 11, 'samp_rate': 40.0, 'excess_bytes': 0L, 'filesize': 8192L, 'starttime': UTCDateTime(2003, 5, 29, 2, 13, 22, 43400), 'npts': 5980, 'endtime': UTCDateTime(2003, 5, 29, 2, 15, 51, 518400), 'number_of_records': 2L, 'io_and_clock_flags': 0} """ else:
""" Searches the first Mini-SEED record stored in file_object at the current position and returns some information about it.
If offset is given, the Mini-SEED record is assumed to start at current position + offset in file_object. """
# Apply the offset.
# Get the size of the buffer.
# check current position # if a multiple of minimal record length 256 # if valid data record start at all starting with D, R, Q or M
# check if full SEED or Mini-SEED # found a full SEED record - seek first Mini-SEED record # search blockette 005, 008 or 010 which contain the record length msg = "SEED Volume Index Control Headers: blockette 0xx" + \ " expected, got %s" raise Exception(msg % blockette_id) # get length and jump to end of current blockette # read next blockette id # Skip the next bytes containing length of the blockette and version # get record length # reset file pointer # cycle through file using record length until first data record found
# Figure out the byteorder. # Get the year. else:
# Seek back and read more information. # Capital letters indicate unsigned quantities. minute=values[3], second=values[4], microsecond=values[5] * 100) # Bit 1 of the activity flags.
# Correct the starttime if applicable. # Time correction is in units of 0.0001 seconds.
# Traverse the blockettes and parse Blockettes 100, 500, 1000 and/or 1001 # if any of those is found. # Parse in order of likeliness. file_object.read(3)) file_object.read(2)) file_object.seek(14, 1) mu_sec = unpack('%sb' % endian, file_object.read(1))[0] starttime += float(mu_sec) / 1E6
# If samprate not set via blockette 100 calculate the sample rate according # to the SEED manual. elif (samp_rate_factor < 0) and (samp_rate_mult) > 0: samp_rate = -1.0 * float(samp_rate_mult) / float(samp_rate_factor) elif (samp_rate_factor < 0) and (samp_rate_mult) < 0: samp_rate = -1.0 / float(samp_rate_factor * samp_rate_mult) else: # if everything is unset or 0 set sample rate to 1 samp_rate = 1
# Endtime is the time of the last sample.
info['record_length'])
# Reset file pointer.
""" Takes a Ctypes array and its length and type and returns it as a NumPy array.
This works by reference and no data is copied.
:param buffer: Ctypes c_void_p pointer to buffer. :param buffer_elements: length of the whole buffer :param sampletype: type of sample, on of "a", "i", "f", "d" """ # Allocate NumPy array to move memory to numpy_array = np.empty(buffer_elements, dtype=sampletype) datptr = numpy_array.ctypes.get_data() # Manually copy the contents of the C allocated memory area to # the address of the previously created NumPy array C.memmove(datptr, buffer, buffer_elements * SAMPLESIZES[sampletype]) return numpy_array
""" Internal method used for setting header attributes. """ h = {} attributes = ('network', 'station', 'location', 'channel', 'dataquality', 'starttime', 'samprate', 'samplecnt', 'numsamples', 'sampletype') # loop over attributes for _i in attributes: h[_i] = getattr(m, _i) return h
""" Takes a obspy.util.UTCDateTime object and returns an epoch time in ms.
:param dt: obspy.util.UTCDateTime object. """
""" Takes a Mini-SEED timestamp and returns a obspy.util.UTCDateTime object.
:param timestamp: Mini-SEED timestring (Epoch time string in ms). """
""" Unpack steim1 compressed data given as string.
:param data_string: data as string :param npts: number of data points :param swapflag: Swap bytes, defaults to 0 :return: Return data as numpy.ndarray of dtype int32 """ C.cast(dbuf, C.POINTER(FRAME)), datasize, samplecnt, samplecnt, datasamples, diffbuff, C.byref(x0), C.byref(xn), swapflag, verbose) raise Exception("Error in unpack_steim1")
""" Unpack steim2 compressed data given as string.
:param data_string: data as string :param npts: number of data points :param swapflag: Swap bytes, defaults to 0 :return: Return data as numpy.ndarray of dtype int32 """ C.cast(dbuf, C.POINTER(FRAME)), datasize, samplecnt, samplecnt, datasamples, diffbuff, C.byref(x0), C.byref(xn), swapflag, verbose) raise Exception("Error in unpack_steim2")
""" Takes a MiniSEED file and shifts the time of every record by the given amount.
The same could be achieved by reading the MiniSEED file with ObsPy, modifying the starttime and writing it again. The problem with this approach is that some record specific flags and special blockettes might not be conserved. This function directly operates on the file and simply changes some header fields, not touching the rest, thus preserving it.
Will only work correctly if all records have the same record length which usually should be the case.
All times are in 0.0001 seconds, that is in 1/10000 seconds. NOT ms but one order of magnitude smaller! This is due to the way time corrections are stored in the MiniSEED format.
:type input_file: str :param input_file: The input filename. :type output_file: str :param output_file: The output filename. :type timeshift: int :param timeshift: The time-shift to be applied in 0.0001, e.g. 1E-4 seconds. Use an integer number.
Please do NOT use identical input and output files because if something goes wrong, your data WILL be corrupted/destroyed. Also always check the resulting output file.
.. rubric:: Technical details
The function will loop over every record and change the "Time correction" field in the fixed section of the MiniSEED data header by the specified amount. Unfortunately a further flag (bit 1 in the "Activity flags" field) determines whether or not the time correction has already been applied to the record start time. If it has not, all is fine and changing the "Time correction" field is enough. Otherwise the actual time also needs to be changed.
One further detail: If bit 1 in the "Activity flags" field is 1 (True) and the "Time correction" field is 0, then the bit will be set to 0 and only the time correction will be changed thus avoiding the need to change the record start time which is preferable. """ # A timeshift of zero makes no sense. msg = "The timeshift must to be not equal to 0." raise ValueError(msg)
# Get the necessary information from the file.
# This is in this scenario somewhat easier to use than StringIO because one # can directly modify the data array. # Loop over every record. msg = "%i excessive byte(s) in the file. " % remaining_bytes msg += "They will be appended to the output file." warnings.warn(msg) # Use a slice for the current record.
# If the time correction has been applied, but there is no actual # time correction, then simply set the time correction applied # field to false and process normally. # This should rarely be the case. # This sets bit 2 of the activity flags to 0. # This is the case if the time correction has been applied. This # requires some more work by changing both, the actual time and the # time correction field. # The whole process is not particularly fast or optimized but # instead intends to avoid errors. # Get the time variables. # Change dtype of multibyte values. minute=minute[0], second=second[0], microsecond=msecs[0] * 100) # Swap again. # Change dtypes back. # Write to current record.
# Now modify the time correction flag.
# Write to the output file.
if __name__ == '__main__': import doctest doctest.testmod(exclude_empty=True) |