def write2sac(d, header, output):
    '''
    Function to write the data and header to sac files
    Inputs:
    d - data array
    header - dictionary of the header info
    output - filename of the output sac file
    '''
    sacio = SacIO()
    sacio.fromarray(d)
    # set the date
    t = header['record_time']
    sacio.SetHvalue('nzyear',t.year)
    sacio.SetHvalue('nzjday',t.julday)
    sacio.SetHvalue('delta', 1./header['df'])
    sacio.SetHvalue('nzhour',t.hour)
    sacio.SetHvalue('nzmin',t.minute)
    sacio.SetHvalue('nzsec',t.second)
    sacio.SetHvalue('kstnm',header['stnm'])
    sacio.SetHvalue('stla',header['stla'])
    sacio.SetHvalue('stlo',header['stlo'])
    sacio.SetHvalue('stel',header['stel'])
    sacio.SetHvalue('kcmpnm',header['comp'])
    sacio.SetHvalue('evla',header['evla'])
    sacio.SetHvalue('evlo',header['evlo'])
    sacio.SetHvalue('o',header['o'])
    sacio.SetHvalue('mag',header['mag'])
    sacio.SetHvalue('o',header['o'])
    #TRUE if DIST AZ BAZ and GCARC are to be calculated from st event coordinates.
    sacio.SetHvalue('LCALDA', 1)
        
    #set the type of the dependent variable as acceleration nm/sec/sec
    #sacio.SetHvalue('idep',8)
                    
    sacio.WriteSacBinary(output)
Beispiel #2
0
 def test_Date(self):
     """
     Test for SacIO '_get_date_'-function to calculate timestamp
     """
     fn = os.path.join(os.path.dirname(__file__), 'data', 'test.sac')
     t = SacIO(fn)
     self.assertEqual(t.reftime.timestamp, 269596800.0)
     diff = t.GetHvalue('npts')
     self.assertEqual(int(t.endtime - t.starttime), diff)
Beispiel #3
0
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
Beispiel #4
0
 def test_readBigEnd(self):
     """
     Test reading big endian binary files
     """
     tfilel = os.path.join(os.path.dirname(__file__), 'data', 'test.sac')
     tfileb = os.path.join(os.path.dirname(__file__), 'data',
                           'test.sac.swap')
     tl = SacIO(tfilel)
     tb = SacIO(tfileb)
     self.assertEqual(tl.GetHvalue('kevnm'), tb.GetHvalue('kevnm'))
     self.assertEqual(tl.GetHvalue('npts'), tb.GetHvalue('npts'))
     self.assertEqual(tl.GetHvalue('delta'), tb.GetHvalue('delta'))
     np.testing.assert_array_equal(tl.seis, tb.seis)
Beispiel #5
0
 def test_swapbytes(self):
     tfilel = os.path.join(os.path.dirname(__file__), 'data', 'test.sac')
     tfileb = os.path.join(os.path.dirname(__file__), 'data',
                           'test.sac.swap')
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         tb = SacIO(tfileb)
         tb.swap_byte_order()
         tb.WriteSacBinary(tempfile)
         t = SacIO(tempfile)
         tl = SacIO(tfilel)
         self.assertEqual(t.GetHvalue('kevnm'), tl.GetHvalue('kevnm'))
         self.assertEqual(t.GetHvalue('npts'), tl.GetHvalue('npts'))
         self.assertEqual(t.GetHvalue('delta'), tl.GetHvalue('delta'))
         np.testing.assert_array_equal(t.seis, tl.seis)
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         tl = SacIO(tfilel)
         tl.swap_byte_order()
         tl.WriteSacBinary(tempfile)
         t = SacIO(tempfile)
         tb = SacIO(tfileb)
         self.assertEqual(t.GetHvalue('kevnm'), tb.GetHvalue('kevnm'))
         self.assertEqual(t.GetHvalue('npts'), tb.GetHvalue('npts'))
         self.assertEqual(t.GetHvalue('delta'), tb.GetHvalue('delta'))
         np.testing.assert_array_equal(t.seis, tb.seis)
Beispiel #6
0
 def test_swapbytes(self):
     tfilel = os.path.join(os.path.dirname(__file__), "data", "test.sac")
     tfileb = os.path.join(os.path.dirname(__file__), "data", "test.sac.swap")
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         tb = SacIO(tfileb)
         tb.swap_byte_order()
         tb.WriteSacBinary(tempfile)
         tr1 = SacIO(tempfile)
         tl = SacIO(tfilel)
         np.testing.assert_array_equal(tl.seis, tr1.seis)
         self.assertEqual(tl.GetHvalue("kevnm"), tr1.GetHvalue("kevnm"))
         self.assertEqual(tl.GetHvalue("npts"), tr1.GetHvalue("npts"))
         self.assertEqual(tl.GetHvalueFromFile(tfilel, "kcmpnm"), tr1.GetHvalueFromFile(tempfile, "kcmpnm"))
Beispiel #7
0
 def test_read(self):
     """
     Tests for SacIO read and write
     """
     data = np.array([-8.7422776573475858e-08, -0.30901697278022766,
                      -0.58778536319732666, -0.8090171217918396,
                      -0.95105659961700439, -1.0, -0.95105630159378052,
                      -0.80901658535003662, -0.5877845287322998,
                      -0.30901604890823364, 1.1285198979749111e-06],
                     dtype=native_str('<f4'))
     sacfile = os.path.join(self.path, 'test.sac')
     t = SacIO()
     t.ReadSacFile(sacfile)
     np.testing.assert_array_equal(t.seis[0:11], data)
     self.assertEqual(t.GetHvalue('npts'), 100)
     self.assertEqual(t.GetHvalue("kstnm"), "STA     ")
Beispiel #8
0
 def test_swapbytes(self):
     tfilel = os.path.join(os.path.dirname(__file__), 'data', 'test.sac')
     tfileb = os.path.join(os.path.dirname(__file__), 'data',
                           'test.sac.swap')
     tempfile = NamedTemporaryFile().name
     tb = SacIO(tfileb)
     tb.swap_byte_order()
     tb.WriteSacBinary(tempfile)
     tr1 = SacIO(tempfile)
     tl = SacIO(tfilel)
     np.testing.assert_array_equal(tl.seis, tr1.seis)
     self.assertEqual(tl.GetHvalue('kevnm'), tr1.GetHvalue('kevnm'))
     self.assertEqual(tl.GetHvalue('npts'), tr1.GetHvalue('npts'))
     self.assertEqual(tl.GetHvalueFromFile(tfilel, 'kcmpnm'),
                      tr1.GetHvalueFromFile(tempfile, 'kcmpnm'))
     os.remove(tempfile)
Beispiel #9
0
 def test_iztype11(self):
     # test that iztype 11 is read correctly
     sod_file = os.path.join(self.path, 'data', 'dis.G.SCZ.__.BHE_short')
     tr = read(sod_file)[0]
     sac = SacIO(sod_file)
     t1 = tr.stats.starttime - float(tr.stats.sac.b)
     t2 = sac.reftime
     self.assertAlmostEqual(t1.timestamp, t2.timestamp, 5)
     # see that iztype is written corretly
     tempfile = NamedTemporaryFile().name
     tr.write(tempfile, format="SAC")
     sac2 = SacIO(tempfile)
     os.remove(tempfile)
     self.assertEqual(sac2.iztype, 11)
     self.assertAlmostEqual(tr.stats.sac.b, sac2.b)
     self.assertAlmostEqual(t2.timestamp, sac2.reftime.timestamp, 5)
def updateSacHeader(sac,dir,latStaz,lonStaz,evla,evlo):

    # load sac trace, update headers, write and close
    tr = SacIO(dir + os.sep + sac)
    tr.SetHvalue('evla',evla)
    tr.SetHvalue('evlo',evlo)
    tr.SetHvalue('stla',latStaz)
    tr.SetHvalue('stlo',lonStaz)
    (distD,Az,Baz,distkm)=dlaz(evla,evlo,latStaz,lonStaz)
    tr.SetHvalue('dist',distkm)
    tr.SetHvalue('gcarc',distD)
    tr.SetHvalue('baz',Baz)
    tr.SetHvalue('az',Az)
    tr.WriteSacHeader(dir + os.sep + sac)

    return 1
Beispiel #11
0
 def test_undefinedB(self):
     """
     Test that an undefined B value (-12345.0) is not messing up the
     starttime
     """
     # read in the test file an see that sac reference time and
     # starttime of seismogram are correct
     tr = read(self.file)[0]
     self.assertEqual(tr.stats.starttime.timestamp, 269596810.0)
     self.assertEqual(tr.stats.sac.b, 10.0)
     sac_ref_time = SacIO(self.file).reftime
     self.assertEqual(sac_ref_time.timestamp, 269596800.0)
     # change b to undefined and write (same case as if b == 0.0)
     # now sac reference time and reftime of seismogram must be the
     # same
     tr.stats.sac.b = -12345.0
     tmpfile = NamedTemporaryFile().name
     tr.write(tmpfile, format="SAC")
     tr2 = read(tmpfile)[0]
     self.assertEqual(tr2.stats.starttime.timestamp, 269596810.0)
     self.assertEqual(tr2.stats.sac.b, -12345.0)
     sac_ref_time2 = SacIO(tmpfile).reftime
     self.assertEqual(sac_ref_time2.timestamp, 269596810.0)
     os.remove(tmpfile)
def write2sac(d, header, evla, evlo, evdp, mag, output):
    sacio = SacIO()
    sacio.fromarray(d)
    # set the date to today
    sacio.SetHvalue('nzyear',header['nzyear'])
    sacio.SetHvalue('nzjday',header['nzjday'])
    sacio.SetHvalue('delta',0.02)
    sacio.SetHvalue('nzhour',header['nzhour'])
    sacio.SetHvalue('nzmin',header['nzmin'])
    sacio.SetHvalue('nzsec',header['nzsec'])
    sacio.SetHvalue('nzmsec',header['nzmsec'])
    sacio.SetHvalue('kstnm',header['stnm'])
    sacio.SetHvalue('stla',header['stla'])
    sacio.SetHvalue('stlo',header['stlo'])
    sacio.SetHvalue('kcmpnm',header['comp'])
    sacio.SetHvalue('evla',evla)
    sacio.SetHvalue('evlo',evlo)
    sacio.SetHvalue('evdp',evdp)
    sacio.SetHvalue('mag',mag)
    
    #dist = sacio.GetHvalue('dist')
    #print dist
    dist = gps2DistAzimuth(stla, stlo, evla, evlo)[0] /1000.
    sacio.SetHvalue('dist',dist)
    
    #sacio.SetHvalue('knetwk','phones')
    #sacio.SetHvalue('kstnm',phone)
    #sacio.SetHvalue('kcmpnm',comp)
    #sacio.SetHvalue('kevnm',loc)
    #sacio.SetHvalue('kuser0',test + ' test')
    #sacio.SetHvalue('kuser0',version)
    #sacio.SetHvalue('kuser1',brand)
    #set the type of the dependent variable as acceleration nm/sec/sec
    #sacio.SetHvalue('idep',8)
                    
    sacio.WriteSacBinary(output)
Beispiel #13
0
 def test_issue171(self):
     """
     Test for issue #171.
     """
     tr = read()[0]
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         tr.write(tempfile, format="SAC")
         trace = SacIO(tempfile)
         trace.SetHvalue('stel', 91.0)
         trace.WriteSacHeader(tempfile)
         trace = SacIO(tempfile)
def updateSacHeaderEida(sacFiles, sourceFileFormat, outFileFormat, dir,evla,evlo): 

   # this operation works only if the source seed file is a fseed
   if sourceFileFormat == "FSEED" and outFileFormat == "SAC":

      # open rdseed.station file
#     file = open(dir + "/rdseed.stations")


      # loop over sac files to find stations
      for sac in sacFiles:

          info = sac.split('.')
          staz = info[0]

          #loop over line of rdseed.stations
          file = open(dir + os.sep + "rdseed.stations")
          for line in file:
             a = line.split(' ')
             station = a[0]
             network = a[1]
             latStaz = eval(a[2])
             lonStaz = eval(a[3])
             # if stations are the same, upadte header and exit this loop
             if station == staz:
  
                # load sac trace, update headers, write and close
                tr = SacIO(dir + os.sep + sac)            
                tr.SetHvalue('evla',evla)
                tr.SetHvalue('evlo',evlo)
                tr.SetHvalue('stla',latStaz)
                tr.SetHvalue('stlo',lonStaz)
                (distD,Az,Baz,distkm)=dlaz(evla,evlo,latStaz,lonStaz)
                tr.SetHvalue('dist',distkm)
                tr.SetHvalue('gcarc',distD)
                tr.SetHvalue('baz',Baz)
                tr.SetHvalue('az',Az)
                #distkm=dlaz(evla,evlo,latStaz,lonStaz)
                tr.WriteSacHeader(dir + os.sep + sac)
                break
                 
   return sacFiles
Beispiel #15
0
 def test_getdist(self):
     tfile = os.path.join(os.path.dirname(__file__), 'data', 'test.sac')
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         t = SacIO(tfile)
         t.SetHvalue('evla', 48.15)
         t.SetHvalue('evlo', 11.58333)
         t.SetHvalue('stla', -41.2869)
         t.SetHvalue('stlo', 174.7746)
         t.SetHvalue('lcalda', 1)
         t.WriteSacBinary(tempfile)
         t2 = SacIO(tempfile)
     b = np.array([18486532.5788 / 1000., 65.654154562, 305.975459869],
                  dtype=native_str('>f4'))
     self.assertEqual(t2.GetHvalue('dist'), b[0])
     self.assertEqual(t2.GetHvalue('az'), b[1])
     self.assertEqual(t2.GetHvalue('baz'), b[2])
Beispiel #16
0
 def test_readWrite(self):
     """
     Tests for SacIO read and write
     """
     sacfile = os.path.join(self.path, 'test.sac')
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         t = SacIO()
         t.ReadSacFile(sacfile)
         self.assertEqual(t.GetHvalue('npts'), 100)
         self.assertEqual(t.GetHvalue("kcmpnm"), "Q       ")
         self.assertEqual(t.GetHvalue("kstnm"), "STA     ")
         t.SetHvalue("kstnm", "spiff")
         self.assertEqual(t.GetHvalue('kstnm'), 'spiff   ')
         t.WriteSacBinary(tempfile)
         self.assertEqual(os.stat(sacfile)[6], os.stat(tempfile)[6])
         self.assertEqual(os.path.exists(tempfile), True)
         t.ReadSacHeader(tempfile)
         self.assertEqual((t.hf is not None), True)
         t.SetHvalue("kstnm", "spoff")
         self.assertEqual(t.GetHvalue('kstnm'), 'spoff   ')
         t.WriteSacHeader(tempfile)
         t.SetHvalueInFile(tempfile, "kcmpnm", 'Z       ')
         self.assertEqual(t.GetHvalueFromFile(tempfile, "kcmpnm"),
                          'Z       ')
         self.assertEqual(
             SacIO(tempfile, headonly=True).GetHvalue('kcmpnm'), 'Z       ')
         self.assertEqual(t.IsValidSacFile(tempfile), True)
         self.assertEqual(t.IsValidXYSacFile(tempfile), False)
         self.assertEqual(SacIO().GetHvalueFromFile(sacfile, 'npts'), 100)
         self.assertEqual(SacIO(sacfile).GetHvalue('npts'), 100)
Beispiel #17
0
 def test_readWriteXY(self):
     """
     Tests for ascii sac io
     """
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         tfile = os.path.join(os.path.dirname(__file__), 'data', 'test.sac')
         t = SacIO(tfile)
         t.WriteSacXY(tempfile)
         d = SacIO(tempfile, alpha=True)
         e = SacIO()
         e.ReadSacXY(tempfile)
         self.assertEqual(e.GetHvalue('npts'), d.GetHvalue('npts'))
         self.assertEqual(e.IsValidXYSacFile(tempfile), True)
         self.assertEqual(e.IsValidSacFile(tempfile), False)
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         d.WriteSacBinary(tempfile)
         size1 = os.stat(tempfile)[6]
         size2 = os.stat(tfile)[6]
     self.assertEqual(size1, size2)
     np.testing.assert_array_almost_equal(t.seis, d.seis, decimal=5)
Beispiel #18
0
def asc2sac(infile,netnames):
#                              These are defaults to be overwritten in either cconstant or stinfo.
# stinfo[0] = Network name ( prompt from user)
# stinfo[1] = station name ( prompt from user)
# stinfo[2] = station latitude ( taken from nmea data)
# stinfo[3] = station longitude ( taken from nmea data)
# stinfo[4] = channel 0 name ( found in header at header[26][3]) 
# stinfo[5] = channel 1 name header[27]
# stinfo[6] = channel 2 name header[28]
# stinfo[7] = channel 3 name
# stinfo[8] = channel 5 name (mark)
# stinfo[9] = delta, which is the sample period
# stinfo[10] = number of samples
# stinfo[11] = start year
# stinfo[12] = start day
# stinfo[13] = start hour
# stinfo[14] = start minute
# stinfo[15] = start second
# stinfo[16] = start fractions of second
 
    Channel = ["","","","",""]
    units = ['Counts  ','Counts  ','Counts  ','Counts  ','Counts  ']
    comment = ['Velocity','Velocity','Velocity','Velocity','microvlt']
    idep = [4,4,4,4,1]


#    cconstant = getcal(calcontrol)


    (ftype,header,data,stinfo,stack) = load(infile) # Load function will search out the type of ascii file.  
#    time is now handled in stinfo and is managed in the load definition.
#    data contains the list of time history for the channels 
    nzyear = int(stinfo[11])
    nzjday = int(datetime.datetime.strptime(stinfo[11]+stinfo[12]+stinfo[13], '%Y%m%d').timetuple().tm_yday)
    nzhour = int(stinfo[14])
    nzmin = int(stinfo[15])
    nzsec = int(stinfo[16])
    nzmsec = int(int(stinfo[17])/1000)
    Delta = stinfo[9]
    Samplecount = stinfo[10]
    Network = netnames[0]
    Station = netnames[1]

    for i in range(0,len(data[0])):        # Channel names are now taken from stinfo in the load definition
        Channel[i]=stinfo[4+i]

    outfile = infile[0:string.rfind(infile,'.')]



    print "Sample count stands at {} samples.".format(Samplecount)

    sacfile = outfile[:string.find(infile,'.')]+'{}'.format(i)+'.sac'
        #
        # stack[1] = channel 1 time history
        # .
        #
        # stack[4] = channel 4 time history
        #
        #    cconstant[0] = calconstants[0]        # (test) Station name
        #    cconstant[1] = header[1]              # (text) Channel name for CH0
        #    cconstant[2] = float(calconstants[1]) # (float) adccal[0]: cal constant for ch 0 (microvolts / count)
        #    cconstant[3] = header[2]              # (text) Channel name for CH1
        #    cconstant[4] = float(calconstants[2]) # (float) adccal[1]: cal constant for ch 1 (microvolts / count)
        #    cconstant[5] = header[3]              # (text) Channel name for CH2
        #    cconstant[6] = float(calconstants[3]) # (float) adccal[2]: cal constant for ch 2 (microvolts / count)
        #    cconstant[7] = header[4]              # (text) Channel name for CH3
        #    cconstant[8] = float(calconstants[4]) # (float) adccal[3]: cal constant for ch 3 (microvolts / count)
        #    cconstant[9] = float(calconstants[5]) # (float) laserres: cal constant for the laser ( mV / micron)
        #    cconstant[10] = float(calconstants[6])# (float) lcalconst: cal constant for geometry correction factor
        #    cconstant[11] = float(calconstants[7])# (float) h: Damping ratio for the seismometer as measured by engineer.
        #    cconstant[12] = float(calconstants[8])# (float) resfreq: Free period resonance freq. as measured by engineer.
        #    cconstant[13] = int(selection[0])     # channel number of channel being tested
        #    cconstant[14] = int(selection[1])     # channel number of the laser position sensor data

    for i in range(0,len(data[0])): # Build each channel
        t = SacIO()
        b = np.arange(len(data),dtype=np.float32)   #   Establishes the size of the datastream
        for n in range(len(data)):        #   Load the array with time-history data
            b[n] = np.float32(data[n][i]) #   Convert the measurement from counts to volts.
        t.fromarray(b)

             #                     set the SAC header values
        t.SetHvalue('scale',1.00) # Set the scale for each channel. This one is important to declare.
        t.SetHvalue('delta', Delta)
        t.SetHvalue('nzyear',nzyear)
        t.SetHvalue('nzjday',nzjday)
        t.SetHvalue('nzhour',nzhour)
        t.SetHvalue('nzmin',nzmin)
        t.SetHvalue('nzsec', nzsec)
        t.SetHvalue('nzmsec', nzmsec)
        t.SetHvalue('kstnm',Station)
        t.SetHvalue('kcmpnm',Channel[i])
        t.SetHvalue('idep',idep[i]) # 4 = units of velocity (in Volts)
                              # Dependent variable choices: (1)unknown, (2)displacement(nm), 
                              # (3)velocity(nm/sec), (4)velocity(volts), 
                              # (5)nm/sec/sec
        t.SetHvalue('kinst',comment[i])       # Instrument type
        t.SetHvalue('knetwk',Network)         # Network designator
        t.SetHvalue('kuser0',units[i])        # Place the system of units into the user text field 0
        t.WriteSacBinary(outfile+"_{}.sac".format(Channel[i]))
        print " File successfully written: {0}_{1}.sac".format(outfile,Channel[i])       
Beispiel #19
0
 def test_read_with_fsize(self):
     """
     Testing fsize option on SacIO.ReadSacFile()
     """
     # reading sac file with wrong file size should raise error
     longer_file = os.path.join(self.path, 'seism-longer.sac')
     shorter_file = os.path.join(self.path, 'seism-shorter.sac')
     t = SacIO()
     # default
     self.assertRaises(SacError, t.ReadSacFile, longer_file)
     self.assertRaises(SacError, t.ReadSacFile, shorter_file)
     # fsize=True
     self.assertRaises(SacError, t.ReadSacFile, longer_file, fsize=True)
     self.assertRaises(SacError, t.ReadSacFile, shorter_file, fsize=True)
     # using fsize=False should not work for shorter file
     # (this is not supported by SAC) ...
     self.assertRaises(SacIOError, t.ReadSacFile, shorter_file, fsize=False)
     # ...but it should work for longer file
     t.ReadSacFile(longer_file, fsize=False)
     # checking trace
     self.assertEqual(t.GetHvalue('nzyear'), 1981)
     self.assertEqual(t.GetHvalue('nzjday'), 88)
     self.assertEqual(t.GetHvalue('nzhour'), 10)
     self.assertEqual(t.GetHvalue('nzmin'), 38)
     self.assertEqual(t.GetHvalue('nzsec'), 14)
     self.assertEqual(t.GetHvalue('nzmsec'), 0)
     # we should never test equality for float values:
     self.assertTrue(abs(t.GetHvalue('delta') - 0.01) <= 1e-9)
     self.assertEqual(t.GetHvalue('scale'), -12345.0)
     self.assertEqual(t.GetHvalue('npts'), 998)
     self.assertEqual(t.GetHvalue('knetwk'), '-12345  ')
     self.assertEqual(t.GetHvalue('kstnm'), 'CDV     ')
     self.assertEqual(t.GetHvalue('kcmpnm'), 'Q       ')
Beispiel #20
0
def convert(infile,outfile,stname):
            #       Look for the header file by parsing out the directory. 
            #       If it doesn't exist, the program will error.
            #
#    print "The infile specified into the conversion is {}".format(infile)
#    print "The outfile specified into the conversion is {}".format(outfile)
    headerfile = infile[:infile.rfind('\\')+1]+'vdaq.txt'
    hexfile = infile   #  
    header = vdaq(headerfile)
    Samplecount = header['RecordPts:']


        # Extract the start time to the nearest second from the file name
        # File name is an established standard of 14 characters
        # hexfile[-18:-4] represents st.tiome to nearest second
        # 20130314000509
        # Note!! This is computer system time, NOT the start time. So don't do this.
        # Use the start time as encoded within the timing channel (channel 0) as found
        # within the first two samples.

        #    St_time = time.strptime(hexfile[-18:-4],"%Y%m%d%H%M%S")
 
            # Import the binary data
            # Each channel sample comprises of four bytes
            # Epoch time is taken from bytes 1, 0, 13, 12 in that order.
            # Create a data type object of four channels each of which consist of a 32bit integer

    dt = np.dtype([(header['Ch0ID:'],np.int32),(header['Ch1ID:'],np.int32),(header['Ch2ID:'],np.int32),(header['Ch3ID:'],np.int32)])

            # Calculate sample rate and seconds remainder for adding onto file start time.
            # Load timing signal into an array and calculate mean. 
            # Find first sample representing the first positive edge trigger that's greater than sample 5
            # Note that if signal starts high, it must drop low before counting.
            # Count the number of excursions where timing signal goes initially high, starting with the second timing signal
            # and en
            # Find the first sample where gps tick-mark goes high.
            # If tickmark is already high on the 4th sample, go to the next tick mark and count back.


    Data = np.fromfile(hexfile,dtype = dt)      # load all data from the binary file using our specified format dt

            # Data[0][0] represents MSBaLSBa 0000 of epoch start time from gps
            # Data[1][0] represents MSBbLSBb 0000 of epoch start time from gps
            # Epoch start time must be arranged thus: MSBa LSBa MSBb LSBb            
    data = []
    data.append(Data[0][0]) # MSB of start time from file
    data.append(Data[1][0]) # LSB of start time from file
    timestamp = long(int(data[0])<<16|int(data[1])) # Assemble them into the timestamp
    St_time = time.gmtime(timestamp) # Convert them into a tuple representing start time to nearest second
            # Note that rest of the Data is simply a list of raw counts from the ADC and is a 32 bit integer value.
            # It would be nice if each channel was converted to a measurement in terms of volts as a float value.
            # The Symres PAR4CH system is 24 bits for +-10V, and the USB4CH is listed as +-4V
            # but practical measurements in the lab put it more like +-8V. 
            # Therefore, this code is going to ASSUME a nominal value of 0.94 microvolts / count.
            # This converter will convert raw counts into millivolts using this gain factor. Future versions
            # will enable us to input the gain factor as it becomes available.
            #
            #
    Channelgain = [0.94*1e-6,0.94*1e-6,0.94*1e-6,0.94*1e-6] # volts per count
            #

    GPS = []                   # declare our GPS stream which will be loaded from the Data
    Latch = False
    Count = -1                                  # First time Count is incremented is on tic mark number zero.
    Initial_sample = 0
    Final_sample = 0
    Frac_second = 0.0
    Sps = 0.0
    units = ['Volts   ','Volts   ','Volts   ','Volts   ']
    comment = ['TIME    ','Velocity','Velocity','Velocity']
    for n in range(len(Data)):                  # Load the GPS array
        GPS.append(Data[n][0])
    Gpsmean15 = (1.5 * np.median(GPS))            # Use a value that is 1.5 times the median as the pulse break


            # Check to see if the signal started out on a high pulse
    if GPS[4] > np.mean(GPS): 
        Latch = True
                # Set latch as rising edge has been missed

    for n in range (4,(len(GPS))):
        if (Latch == True):             # Look for falling edge to reset latch#
            if GPS[n] < Gpsmean15:
                Latch = False
        else:             
            if GPS[n] > Gpsmean15:
                Latch = True
        # Rising edge found so set latch
                Count += 1
          # and increment edge count starting at zero.
                if Initial_sample == 0:
                    Initial_sample = n  # Set the first known good rising edge
                else:    
                    Final_sample = n    # Keep updating last known good rising edge


    Sps = float((Final_sample-Initial_sample)/Count)


            #                       Calculate time remainder which equals 
            #                 1000 milliseconds - (#samples before first impulse)

    if (Initial_sample - Sps) > 1:
        Frac_second = 1 - ((Initial_sample - Sps)/Sps)
    else: 
        Frac_second = 1 - (Initial_sample / Sps)

            #                        Create a start time string for ascii file exports

    Start_time = time.strftime("%d-%b-%Y_%H:%M:%S.",St_time)
    Start_time +=str.format("{0:0.3f}",Frac_second)[2:]


    
            # At this point, we have our header information in an index, and we have calculated the true sample rate, 
            # We have extracted the true start time and we've 
            # verified the true second remainder for placing into the start time.

#    print "Initial_sample: {}  VALUE: {}".format(Initial_sample,GPS[Initial_sample])
#    print "Final_sample: {} VALUE: {}".format(Final_sample,GPS[Final_sample])
#    print "Total samples between tic marks = {}".format((Final_sample-Initial_sample))
#    print "Total count of tickmarks: {}".format(Count)
#    print "Samples per second: {}".format(Sps)
#    print "Fraction of a second for start time = {0:1.3f}".format(Frac_second)
#    print "Sample Count from the header file: ",Samplecount
#    print "Start time as calculated:", Start_time
#    print "Delta: {0:8.6e}".format((1/Sps))
#    print "Channel gains used:"
#    for i in range(4):
#        print "    Channel {0}: {1} Volts / count.".format(i,Channelgain[0])

             #                      Create the obspy SAC stream
    for i in range(4):
        t = SacIO()
        b = np.arange(len(Data),dtype=np.float32)   #   Establishes the size of the datastream
        for n in range(len(Data)):        #   Load the array with time-history data
            b[n] = Channelgain[i] * np.float32(Data[n][i]) #   Convert the measurement from counts to volts.
        t.fromarray(b)

             #                     set the SAC header values
        t.SetHvalue('scale',1.00) # Set the scale for each channel. This one is important to declare.
        t.SetHvalue('delta', (1/Sps))
        t.SetHvalue('nzyear',St_time.tm_year)
        t.SetHvalue('nzjday',St_time.tm_yday)
        t.SetHvalue('nzhour',St_time.tm_hour)
        t.SetHvalue('nzmin',St_time.tm_min)
        t.SetHvalue('nzsec', St_time.tm_sec)
        t.SetHvalue('nzmsec', int(Frac_second*1000))
        t.SetHvalue('kstnm',header['A-DInfo:'])
        t.SetHvalue('kcmpnm',header["Ch{}ID:".format(i)])
#        print "Channel name is listed as '{}'".format(header["Ch{}ID:".format(i)])
        t.SetHvalue('idep',4) # 4 = units of velocity (in Volts)
                              # Dependent variable choices: (1)unknown, (2)displacement(nm), 
                              # (3)velocity(nm/sec), (4)velocity(volts), 
                              # (5)nm/sec/sec
        t.SetHvalue('kinst',comment[i-1])       # Instrument type
        t.SetHvalue('knetwk','OUT2SAC ')         # Network designator
        t.SetHvalue('kuser0',units[i-1])        # Place the system of units into the user text field 0

        f = outfile+"_{}.sac".format(header["Ch{}ID:".format(i)])
#        print "filename for SACoutput file = '{}'".format(f)
        with open(f,'wb') as sacfile:
Beispiel #21
0
 def test_getattr(self):
     tfile = os.path.join(os.path.dirname(__file__), 'data', 'test.sac')
     tr = SacIO(tfile)
     self.assertEqual(tr.npts, tr.GetHvalue('npts'))
     self.assertEqual(tr.kstnm, tr.GetHvalue('kstnm'))
Beispiel #22
0
    templateDateTime = UTCDateTime(template) # converts the event name to a datetime class
    templateJulDay = templateDateTime.julday # int
    templateYear = templateDateTime.year # int
    backgroundTime = 10 #Amount of time in longer event file before event origin time in seconds
    # phaseMarkerList = []
    # staList = []
    # compList = []
    phaseDict[template] = {}
#########################################################
for file in os.listdir('%s/event%s' %(templateDir,template)):
    os.chdir('%s/event%s' %(templateDir,template))
    if file.endswith('.SAC'):
        file1 = file
        station = file1[3:7]
        component = file1[13]
        quality_amarker=str(SacIO().GetHvalueFromFile(file1,'ka')) #P phase
        aMarker = SacIO().GetHvalueFromFile(file1,'a')#P phase
        quality_t0marker=str(SacIO().GetHvalueFromFile(file1,'kt0')) #S phase
        t0Marker = SacIO().GetHvalueFromFile(file1,'t0')#S phase
        if float(aMarker)!=-12345.0:
            if (not phaseDict[template].has_key(station)):
                phaseDict[template][station]=[]
                phaseDict[template][station].append(aMarker)
                aMarkerDateTime = templateDateTime - backgroundTime + aMarker
                phaseDict[template][station].append(aMarkerDateTime)
            elif float(t0Marker)!=-12345.0 and component =='E':
                if (not phaseDict[template].has_key(station)):
                    phaseDict[template][station]=[]
                    phaseDict[template][station].append(t0Marker)
                    t0MarkerDateTime = templateDateTime - backgroundTime + t0Marker
                    phaseDict[template][station].append(t0MarkerDateTime)
Beispiel #23
0
 def test_readXYheader(self):
     tfile = os.path.join(os.path.dirname(__file__), 'data', 'test.sac')
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         t = SacIO(tfile)
         t.WriteSacXY(tempfile)
         d = SacIO(tempfile, alpha=True)
         e = SacIO()
         e.ReadSacXYHeader(tempfile)
         self.assertEqual(e.GetHvalue('npts'), d.GetHvalue('npts'))
         self.assertEqual(e.GetHvalue('depmen'), d.GetHvalue('depmen'))
         self.assertEqual(e.starttime, d.starttime)
         self.assertNotEqual(e.seis.size, d.seis.size)
         c = SacIO(tempfile, alpha=True, headonly=True)
     self.assertEqual(e.seis.size, c.seis.size)
Beispiel #24
0
 def test_swapbytes(self):
     tfilel = os.path.join(os.path.dirname(__file__), 'data', 'test.sac')
     tfileb = os.path.join(os.path.dirname(__file__), 'data',
                           'test.sac.swap')
     tempfile = NamedTemporaryFile().name
     tb = SacIO(tfileb)
     tb.swap_byte_order()
     tb.WriteSacBinary(tempfile)
     tr1 = SacIO(tempfile)
     tl = SacIO(tfilel)
     np.testing.assert_array_equal(tl.seis, tr1.seis)
     self.assertEqual(tl.GetHvalue('kevnm'), tr1.GetHvalue('kevnm'))
     self.assertEqual(tl.GetHvalue('npts'), tr1.GetHvalue('npts'))
     self.assertEqual(tl.GetHvalueFromFile(tfilel, 'kcmpnm'),
                      tr1.GetHvalueFromFile(tempfile, 'kcmpnm'))
     os.remove(tempfile)
Beispiel #25
0
 def test_isSAC(self):
     """
     Assertion is raised if file is not a SAC file
     """
     t = SacIO()
     self.assertRaises(SacError, t.ReadSacFile, __file__)
Beispiel #26
0
def write2sac(d, header, evla, evlo, evdp, mag, output):
    sacio = SacIO()
    sacio.fromarray(d)
    # set the date to today
    sacio.SetHvalue('nzyear', header['nzyear'])
    sacio.SetHvalue('nzjday', header['nzjday'])
    sacio.SetHvalue('delta', 0.02)
    sacio.SetHvalue('nzhour', header['nzhour'])
    sacio.SetHvalue('nzmin', header['nzmin'])
    sacio.SetHvalue('nzsec', header['nzsec'])
    sacio.SetHvalue('nzmsec', header['nzmsec'])
    sacio.SetHvalue('kstnm', header['stnm'])
    sacio.SetHvalue('stla', header['stla'])
    sacio.SetHvalue('stlo', header['stlo'])
    sacio.SetHvalue('kcmpnm', header['comp'])
    sacio.SetHvalue('evla', evla)
    sacio.SetHvalue('evlo', evlo)
    sacio.SetHvalue('evdp', evdp)
    sacio.SetHvalue('mag', mag)

    #dist = sacio.GetHvalue('dist')
    #print dist
    dist = gps2DistAzimuth(stla, stlo, evla, evlo)[0] / 1000.
    sacio.SetHvalue('dist', dist)

    #sacio.SetHvalue('knetwk','phones')
    #sacio.SetHvalue('kstnm',phone)
    #sacio.SetHvalue('kcmpnm',comp)
    #sacio.SetHvalue('kevnm',loc)
    #sacio.SetHvalue('kuser0',test + ' test')
    #sacio.SetHvalue('kuser0',version)
    #sacio.SetHvalue('kuser1',brand)
    #set the type of the dependent variable as acceleration nm/sec/sec
    #sacio.SetHvalue('idep',8)

    sacio.WriteSacBinary(output)
Beispiel #27
0
 def test_swapbytes(self):
     tfilel = os.path.join(os.path.dirname(__file__), 'data', 'test.sac')
     tfileb = os.path.join(os.path.dirname(__file__), 'data',
                           'test.sac.swap')
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         tb = SacIO(tfileb)
         tb.swap_byte_order()
         tb.WriteSacBinary(tempfile)
         t = SacIO(tempfile)
         tl = SacIO(tfilel)
         self.assertEqual(t.GetHvalue('kevnm'), tl.GetHvalue('kevnm'))
         self.assertEqual(t.GetHvalue('npts'), tl.GetHvalue('npts'))
         self.assertEqual(t.GetHvalue('delta'), tl.GetHvalue('delta'))
         np.testing.assert_array_equal(t.seis, tl.seis)
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         tl = SacIO(tfilel)
         tl.swap_byte_order()
         tl.WriteSacBinary(tempfile)
         t = SacIO(tempfile)
         tb = SacIO(tfileb)
         self.assertEqual(t.GetHvalue('kevnm'), tb.GetHvalue('kevnm'))
         self.assertEqual(t.GetHvalue('npts'), tb.GetHvalue('npts'))
         self.assertEqual(t.GetHvalue('delta'), tb.GetHvalue('delta'))
         np.testing.assert_array_equal(t.seis, tb.seis)
Beispiel #28
0
def write2sac(d, header, output):
    '''
    Function to write the data and header to sac files
    Inputs:
    d - data array
    header - dictionary of the header info
    output - filename of the output sac file
    '''
    sacio = SacIO()
    sacio.fromarray(d)
    # set the date
    t = header['record_time']
    sacio.SetHvalue('nzyear', t.year)
    sacio.SetHvalue('nzjday', t.julday)
    sacio.SetHvalue('delta', 1. / header['df'])
    sacio.SetHvalue('nzhour', t.hour)
    sacio.SetHvalue('nzmin', t.minute)
    sacio.SetHvalue('nzsec', t.second)
    sacio.SetHvalue('kstnm', header['stnm'])
    sacio.SetHvalue('stla', header['stla'])
    sacio.SetHvalue('stlo', header['stlo'])
    sacio.SetHvalue('stel', header['stel'])
    sacio.SetHvalue('kcmpnm', header['comp'])
    sacio.SetHvalue('evla', header['evla'])
    sacio.SetHvalue('evlo', header['evlo'])
    sacio.SetHvalue('o', header['o'])
    sacio.SetHvalue('mag', header['mag'])
    sacio.SetHvalue('o', header['o'])
    #TRUE if DIST AZ BAZ and GCARC are to be calculated from st event coordinates.
    sacio.SetHvalue('LCALDA', 1)

    #set the type of the dependent variable as acceleration nm/sec/sec
    #sacio.SetHvalue('idep',8)

    sacio.WriteSacBinary(output)