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 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 #3
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)
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 #5
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 #6
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])