Exemple #1
0
def writeGSE2(stream, filename, inplace=False, **kwargs):  # @UnusedVariable
    """
    Write GSE2 file from a Stream object.

    .. warning::
        This function should NOT be called directly, it registers via the
        the :meth:`~obspy.core.stream.Stream.write` method of an
        ObsPy :class:`~obspy.core.stream.Stream` object, call this instead.

    :type stream: :class:`~obspy.core.stream.Stream`
    :param stream: The ObsPy Stream object to write.
    :type filename: string
    :param filename: Name of file to write.
    :type inplace: boolean, optional
    :param inplace: If True, do compression not on a copy of the data but
        on the data itself - note this will change the data values and make
        them therefore unusable!

    .. rubric:: Example

    >>> from obspy import read
    >>> st = read()
    >>> st.write('filename.gse', format='GSE2') #doctest: +SKIP
    """
    #
    # Translate the common (renamed) entries
    f = open(filename, "wb")
    for trace in stream:
        header = {}
        for _j, _k in convert_dict.iteritems():
            header[_j] = trace.stats[_k]
        for _j in gse2_extra:
            try:
                header[_j] = trace.stats.gse2[_j]
            except:
                pass
        # year, month, day, hour, min, sec
        (
            header["d_year"],
            header["d_mon"],
            header["d_day"],
            header["t_hour"],
            header["t_min"],
            header["t_sec"],
        ) = trace.stats.starttime.timetuple()[0:6]
        header["t_sec"] += trace.stats.starttime.microsecond / 1.0e6
        dtype = np.dtype("int32")
        if trace.data.dtype.name == dtype.name:
            trace.data = np.require(trace.data, dtype, ["C_CONTIGUOUS"])
        else:
            msg = "GSE2 data must be of type %s, but are of type %s" % (dtype.name, trace.data.dtype)
            raise Exception(msg)
        libgse2.write(header, trace.data, f, inplace)
    f.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)
Exemple #3
0
 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)
Exemple #4
0
 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)
Exemple #5
0
 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)
Exemple #6
0
 def write(self, filename, **kwargs):
     #
     # Assign all attributes which have same name in gse2head
     #
     header = {}
     for _i in libgse2.gse2head:
         try:
             header[_i] = getattr(self.stats,_i)
         except AttributeError:
             pass
     #
     # Translate the common (renamed) entries
     #
     # sampling rate
     if not header['samp_rate']:
         try:
             header['samp_rate'] = self.stats.sampling_rate
         except:
             raise ValueError("No sampling rate given")
     # number of samples
     if not header['n_samps']:
         try:
             header['n_samps'] = self.stats.sampling_rate
         except:
             header['n_samps'] = len(data)
     # year, month, day, hour, min, sec
     if not header['d_day']:
         try:
             (header['d_year'],
              header['d_mon'],
              header['d_day'],
              header['t_hour'],
              header['t_min'],
              header['t_sec']) = self.stats.starttime.timetuple()[0:6]
             header['t_sec'] += self.stats.starttime.microseconds/1.0e6
         except:
             pass
     try:
         libgse2.write(header,self.data,filename)
     except TypeError:
         libgse2.write(header,array(self.data,format='l'),filename)
Exemple #7
0
 def write(self, filename, **kwargs):
     #
     # Assign all attributes which have same name in gse2head
     #
     header = {}
     for _i in libgse2.gse2head:
         try:
             header[_i] = getattr(self.stats, _i)
         except AttributeError:
             pass
     #
     # Translate the common (renamed) entries
     #
     # sampling rate
     if not header['samp_rate']:
         try:
             header['samp_rate'] = self.stats.sampling_rate
         except:
             raise ValueError("No sampling rate given")
     # number of samples
     if not header['n_samps']:
         try:
             header['n_samps'] = self.stats.sampling_rate
         except:
             header['n_samps'] = len(data)
     # year, month, day, hour, min, sec
     if not header['d_day']:
         try:
             (header['d_year'], header['d_mon'], header['d_day'],
              header['t_hour'], header['t_min'],
              header['t_sec']) = self.stats.starttime.timetuple()[0:6]
             header['t_sec'] += self.stats.starttime.microseconds / 1.0e6
         except:
             pass
     try:
         libgse2.write(header, self.data, filename)
     except TypeError:
         libgse2.write(header, array(self.data, format='l'), filename)
Exemple #8
0
def writeGSE2(stream, filename, inplace=False, **kwargs):  # @UnusedVariable
    """
    Write GSE2 file from a Stream object.

    .. warning::
        This function should NOT be called directly, it registers via the
        the :meth:`~obspy.core.stream.Stream.write` method of an
        ObsPy :class:`~obspy.core.stream.Stream` object, call this instead.

    :type stream: :class:`~obspy.core.stream.Stream`
    :param stream: The ObsPy Stream object to write.
    :type filename: string
    :param filename: Name of file to write.
    :type inplace: boolean, optional
    :param inplace: If True, do compression not on a copy of the data but
        on the data itself - note this will change the data values and make
        them therefore unusable!

    .. rubric:: Example

    >>> from obspy import read
    >>> st = read()
    >>> st.write('filename.gse', format='GSE2') #doctest: +SKIP
    """
    #
    # Translate the common (renamed) entries
    with open(filename, 'wb') as f:
        # write multiple gse2 parts
        for trace in stream:
            dt = np.dtype('int32')
            if trace.data.dtype.name == dt.name:
                trace.data = np.require(trace.data, dt, ['C_CONTIGUOUS'])
            else:
                msg = "GSE2 data must be of type %s, but are of type %s" % \
                    (dt.name, trace.data.dtype)
                raise Exception(msg)
            libgse2.write(trace.stats, trace.data, f, inplace)
Exemple #9
0
    def write(self,gsefile):
        """Write seismogram to GSE2.0 file
        
        Necessary attribute for this operation is self.trace. Probably it's
        usefull to also fill self.df and self.julsec but anyway the
        remaining attributes are filled by defaults.
        
        >>> g = GseParser()
        >>> numpy.random.seed(815)
        >>> g.trace = numpy.random.random_integers(0,2**26,1000).tolist()
        >>> g.write("test.gse")
        0
        >>> h = GseParser("test.gse")
        >>> h.trace[0:5]
        [29627570, 66111839, 44843986, 32909075, 36408434]
        >>> sum(abs(numpy.array(h.trace)-numpy.array(g.trace)))
        0

        Here the raising of an exception is tested if the data exceed the
        maximim value 2^26
        >>> i = GseParser()
        >>> i.trace = [2**26+1]
        >>> i.write("testexcept.gse")
        Traceback (most recent call last):
        ...
        Exception: Compression Error, data must be less equal 2^26
        """
        # General attributes
        self.is_attr('trace',list,None,assertation=True)
        self.is_attr('df',float,200.)
        self.is_attr('station',str,'FUR',length=5)
        self.is_attr('channel',str,'SHZ',length=3)
        self.is_attr('julsec',float,0.0)
        self.is_attr('npts',int,len(self.trace))
        # GSE2 specific attributes
        self.is_attr('auxid',str,'VEL',length=4)
        self.is_attr('datatype',str,'CM6',length=3)
        self.is_attr('calib',float,1./(2*numpy.pi)) #calper not correct in gse_driver!
        self.is_attr('calper',float,1.)
        self.is_attr('instype',str,'LE-3D',length=6)
        self.is_attr('hang',float,-1.0)
        self.is_attr('vang',float,0.)
        
        intjulsec = int(self.julsec)
        (d_year,d_mon,d_day,t_hour,t_min,t_sec) = time.gmtime(intjulsec)[0:6]
        t_sec += self.julsec-intjulsec
        data = numpy.array(self.trace,dtype='l')

        # Maximum values above 2^26 will result in corrupted/wrong data!
        if data.max() > 2**26:
            raise Exception ,"Compression Error, data must be less equal 2^26"
        
        err = libgse2.write(
            {
            'd_year':d_year,
            'd_mon':d_mon,
            'd_day':d_day,
            't_hour':t_hour,
            't_min':t_min,
            't_sec':t_sec,
            'station':self.station,
            'channel':self.channel,
            'auxid':self.auxid,
            'datatype':self.datatype,
            'n_samps':self.npts,
            'samp_rate':self.df,
            'calib':self.calib,
            'calper':self.calper,
            'instype':self.instype,
            'hang':self.hang,
            'vang':self.vang
            }
            ,data,gsefile)
        # Old C wraped version
        #err = ext_gse.write((d_year, d_mon, d_day, t_hour, t_min, t_sec,
        #    self.station, self.channel, self.auxid, self.datatype, self.npts,
        #    self.df, self.calib, self.calper, self.instype, self.hang,
        #    self.vang), data, gsefile)
        return err