Ejemplo n.º 1
1
def main():
    print('QSSP input file is', sys.argv[1])
    print('QSSP output file is', sys.argv[2])
    qsspinput = sys.argv[1]
    qsspoutput = sys.argv[2]
    # read header info.s from QSSP input file
    deltat, spara, prfx, nr, rdepth, rpara, rnames = readinput(qsspinput)
    # read seismograms from QSSP output files
    seis = readoutput(qsspoutput)
    # read channel code and observable types
    chan, caz, cin, datatype = datatype_channel(prfx, qsspoutput)
    # write SAC files for each receiver/station
    for i in range(0, nr):
        # name for SAC file
        sacname = prfx.upper() + '.' + rnames[i].upper(
        ) + '.' + datatype + '.' + chan + '.SAC'
        header = {'iztype': 'io', 'o': 0, 'b': rpara[i,2], 'delta': deltat, \
        'kevnm': prfx, 'evla': spara[0], 'evlo': spara[1], 'evdp': spara[2],\
        'kstnm': rnames[i], 'kcmpnm': chan, 'cmpaz': caz, 'cmpinc': cin, \
        'stla': rpara[i,0], 'stlo': rpara[i,1], 'stdp': rdepth*1e3, \
        'lcalda': True}
        tr = SACTrace(data=seis[:, i], **header)
        tr.write(sacname)
        print('Create SAC file:', sacname)
Ejemplo n.º 2
0
def writesac(velfile,site,stalat,stalon,doy,year,samprate,event):
    a = numpy.loadtxt(velfile)
    tind = a[:,0]
    gtime = a[:,1]
    leapsec = gpsleapsec(gtime[0])
    
    #Get the start time of the file in UTC
    date = datetime.datetime(int(year), 1, 1) + datetime.timedelta(int(doy) - 1)
    gpstime = (numpy.datetime64(date) - numpy.datetime64('1980-01-06T00:00:00'))/ numpy.timedelta64(1, 's')
    stime = (gtime[0]-leapsec)*numpy.timedelta64(1, 's')+ numpy.datetime64('1980-01-06T00:00:00')
    sitem = stime.item()
    print(sitem)
    styr = sitem.year
    stdy = sitem.day
    stmon = sitem.month
    sthr = sitem.hour
    stmin = sitem.minute
    stsec = sitem.second

    
    nv = a[:,2]
    ev = a[:,3]
    uv = a[:,4]
    print('Writing SAC file ' + 'output/' + site + '.LXN.sac')
    headN = {'kstnm': site, 'kcmpnm': 'LXN', 'stla': float(stalat),'stlo': float(stalon),
             'nzyear': int(year), 'nzjday': int(doy), 'nzhour': int(sthr), 'nzmin': int(stmin),
             'nzsec': int(stsec), 'nzmsec': int(0), 'delta': float(samprate)}

    sacn = SACTrace(data=nv, **headN)
    sacn.write('output/' + site.upper() + '.vel.n')
    print('Writing SAC file ' + 'output/' + site + '.LXE.sac')

    headE = {'kstnm': site, 'kcmpnm': 'LXE', 'stla': float(stalat),'stlo': float(stalon),
         'nzyear': int(year), 'nzjday': int(doy), 'nzhour': int(sthr), 'nzmin': int(stmin),
         'nzsec': int(stsec), 'nzmsec': int(0), 'delta': float(samprate)}
    sace = SACTrace(data=ev, **headE)
    sace.write('output/' + site.upper() + '.vel.e')
    print('Writing SAC file ' + 'output/' + site + '.LXZ.sac')

    headZ = {'kstnm': site, 'kcmpnm': 'LXZ', 'stla': float(stalat),'stlo': float(stalon),
             'nzyear': int(year), 'nzjday': int(doy), 'nzhour': int(sthr), 'nzmin': int(stmin),
             'nzsec': int(stsec), 'nzmsec': int(0), 'delta': float(samprate)}
    sacu = SACTrace(data=uv, **headZ)
    sacu.write('output/' + site.upper() + '.vel.u')
Ejemplo n.º 3
0
    def write_constant(self, out_sac_path='./'):
        """ Write constant component to SAC file.

        :param out_sac_path: Output path, defaults to './'
        :type out_sac_path: str, optional
        """
        sac = SACTrace(data=self.harmonic_trans[0, :])
        sac.b = self.tmin
        sac.delta = self.rfsta.sampling
        sac.user0 = 0.0
        sac.user1 = self.rfsta.f0[0]
        sac.stla = self.rfsta.stla
        sac.stlo = self.rfsta.stlo
        sac.stel = self.rfsta.stel
        sac.write(
            join(out_sac_path, '{}_constant_R.sac'.format(self.rfsta.staname)))
Ejemplo n.º 4
0
def csv2sac(infile, cconstant):
    #
    Channel = ["", "", "", ""]
    units = ['Counts  ', 'Counts  ', 'Counts  ', 'Counts  ']
    comment = ['Velocity', 'Velocity', 'Velocity', 'Velocity']
    (header, stack) = load(infile)

    first_sample, medsps = timingvalidate(stack)

    if first_sample <> 0:
        print "\n\nA timing error exists in the 1st sample of the 1st record in this DAT series.\n"
        print "Remove the first DAT file in the folder and try again."
        sys.exit()

# print "The first sample shows instantaneous sample rate of {} S/second.".format(medsps)

# datetime = stack[0][13]+","+stack[0][14]
# Frac_second = float(stack[0][17])

    datetime = stack[0][15] + "," + stack[0][
        16]  # New cs4 format the fields are offset by two more columns
    Frac_second = float(stack[0][17])

    St_time = time.strptime(datetime, "%Y/%m/%d,%H:%M:%S")
    stdate = str(St_time.tm_year) + "_" + str(St_time.tm_mon) + "_" + str(
        St_time.tm_mday)
    stmin = str(St_time.tm_hour) + "_" + str(St_time.tm_min) + "_" + str(
        St_time.tm_sec) + "_" + str(int(Frac_second * 1000))
    Filetime = stdate + "_" + stmin + "_"
    Station = cconstant[0]
    Network = cconstant[15]
    #     File naming convention: YYYY.DDD.HH.MM.SS.SSS.NN.STATION.CHANNEL

    seedfil = infile[0:string.rfind(
        infile, '\\')] + "/" + Filetime + Network + "_" + Station
    sacfil = infile[0:string.rfind(infile, '.')]

    for i in range(0, 4):
        Channel[i] = cconstant[(2 * i) + 1]

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

    Delta = 1.0 / float(getsps(stack))

    #    Delta = 1/medsps

    print "Delta = {0:.8f}, Sample rate = {1:.8f}".format(Delta, 1 / Delta)

    #
    # stack[1] = channel 1 time history
    # .
    #
    # stack[4] = channel 4 time history
    #

    for i in range(0, 4):  # Build each channel

        b = np.arange(
            len(stack),
            dtype=np.float32)  #   Establishes the size of the datastream
        for n in range(len(stack)):  #   Load the array with time-history data
            b[n] = np.float32(
                stack[n][i +
                         1])  #   Convert the measurement from counts to volts.

        t = SACTrace(data=b)
        #                     set the SAC header values
        t.scale = 1.0  # Set the scale for each channel for use with DIMAS software
        t.delta = Delta
        t.nzyear = St_time.tm_year
        t.nzjday = St_time.tm_yday
        t.nzhour = St_time.tm_hour
        t.nzmin = St_time.tm_min
        t.nzsec = St_time.tm_sec
        t.nzmsec = int((Frac_second) * 1000)
        t.kstnm = Station
        t.kcmpnm = Channel[i]
        t.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.kinst = comment[i - 1]  # Instrument type
        t.knetwk = Network  # Network designator
        t.kuser0 = units[
            i - 1]  # Place the system of units into the user text field 0

        out = sacfil + "_{}.sac".format(Channel[i])
        seed = seedfil + "_{}.mseed".format(Channel[i])

        if Channel[
                i] != "UNK":  # We do not write streams in which the channel name is UNK
            with open(out, 'wb') as sacfile:
                t.write(sacfile)
            print " File successfully written: {0}".format(out)
            sacfile.close()
            st = read(out)
            st.write(seed, format="mseed")
            print " File successfully written: {0}".format(seed)

#            subprocess.call(["del",f],shell=True)

#    for i in range(0,1): # Build special channel for timing

    b = np.arange(len(stack),
                  dtype=np.float32)  #   Establishes the size of the datastream
    for n in range(len(stack)):  #   Load the array with time-history data
        b[n] = np.float32(stack[n][13])  #   Get the timing value.
    t = SACTrace(data=b)

    #                     set the SAC header values
    t.scale = 1.0  # Set the scale for each channel. This one is important to declare.
    t.delta = Delta
    t.nzyear = St_time.tm_year
    t.nzjday = St_time.tm_yday
    t.nzhour = St_time.tm_hour
    t.nzmin = St_time.tm_min
    t.nzsec = St_time.tm_sec
    t.nzmsec = int((Frac_second) * 1000)
    t.kstnm = Station
    t.kcmpnm = 'GPS'  # This is a GPS timing signal.
    t.IDEP = 1  # 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.kinst = 'GPS'  # Instrument type
    t.knetwk = Network  # Network designator
    t.kuser0 = 'digital'  # Place the system of units into the user text field 0

    out = sacfil + "_{}.sac".format('GPS')
    with open(out, 'wb') as sacfile:
        t.write(sacfile)


#    print " File successfully written: {}.sac".format(out)
#    print "Published sample rate in sac file = {}".format(t.stats.sampling_rate)
    sacfile.close()
Ejemplo n.º 5
0
def test_sac2asdf_script(tmpdir, capsys):
    tmpdir = tmpdir.strpath

    # Create some test data
    data_1 = np.arange(10, dtype=np.float32)
    header = {
        "kstnm": "ANMO",
        "knetwk": "IU",
        "kcmpnm": "BHZ",
        "stla": 40.5,
        "stlo": -108.23,
        "stel": 100.0,
        "stdp": 3.4,
        "evla": -15.123,
        "evlo": 123,
        "evdp": 50,
        "nzyear": 2012,
        "nzjday": 123,
        "nzhour": 13,
        "nzmin": 43,
        "nzsec": 17,
        "nzmsec": 100,
        "delta": 1.0 / 40,
        "o": -10.0,
    }
    sac = SACTrace(data=data_1, **header)
    sac.write(os.path.join(tmpdir, "a.sac"))

    data_2 = 2.0 * np.arange(10, dtype=np.float32)
    header = {
        "kstnm": "BBBB",
        "knetwk": "AA",
        "kcmpnm": "CCC",
        "stla": 40.5,
        "stlo": -108.23,
        "stel": 200.0,
        "stdp": 2.4,
        "evla": -14.123,
        "evlo": 125,
        "evdp": 30,
        "nzyear": 2013,
        "nzjday": 123,
        "nzhour": 13,
        "nzmin": 43,
        "nzsec": 17,
        "nzmsec": 100,
        "delta": 1.0 / 40,
        "o": 10.0,
    }
    sac = SACTrace(data=data_2, **header)
    sac.write(os.path.join(tmpdir, "b.sac"))

    output_file = os.path.join(tmpdir, "out.h5")
    assert not os.path.exists(output_file)

    sys_argv_backup = copy.copy(sys.argv)
    try:
        sys.argv = sys.argv[:1]
        sys.argv.append(tmpdir)
        sys.argv.append(output_file)
        sys.argv.append("random")
        sac2asdf.__main__()
    finally:
        # Restore to not mess with any of pytests logic.
        sys.argv = sys_argv_backup

    non_verbose_out, non_verbose_err = capsys.readouterr()
    assert not non_verbose_err

    assert os.path.exists(output_file)
    with pyasdf.ASDFDataSet(output_file, mode="r") as ds:
        # 2 Events.
        assert len(ds.events) == 2
        # 2 Stations.
        assert len(ds.waveforms) == 2

        events = ds.events  # NOQA

        # Data should actually be fully identical
        np.testing.assert_equal(data_1, ds.waveforms.IU_ANMO.random[0].data)
        np.testing.assert_equal(data_2, ds.waveforms.AA_BBBB.random[0].data)

        assert ds.waveforms.IU_ANMO.random[0].id == "IU.ANMO..BHZ"
        assert ds.waveforms.AA_BBBB.random[0].id == "AA.BBBB..CCC"

        c = ds.waveforms.IU_ANMO.coordinates
        np.testing.assert_allclose(
            [c["latitude"], c["longitude"], c["elevation_in_m"]],
            [40.5, -108.23, 100.0],
        )
        c = ds.waveforms.AA_BBBB.coordinates
        np.testing.assert_allclose(
            [c["latitude"], c["longitude"], c["elevation_in_m"]],
            [40.5, -108.23, 200.0],
        )

        c = ds.waveforms.IU_ANMO.channel_coordinates["IU.ANMO..BHZ"][0]
        np.testing.assert_allclose(
            [
                c["latitude"],
                c["longitude"],
                c["elevation_in_m"],
                c["local_depth_in_m"],
            ],
            [40.5, -108.23, 100.0, 3.4],
        )
        c = ds.waveforms.AA_BBBB.channel_coordinates["AA.BBBB..CCC"][0]
        np.testing.assert_allclose(
            [
                c["latitude"],
                c["longitude"],
                c["elevation_in_m"],
                c["local_depth_in_m"],
            ],
            [40.5, -108.23, 200.0, 2.4],
        )

        # Events
        origin = (ds.waveforms.IU_ANMO.random[0].stats.asdf.event_ids[0].
                  get_referred_object().origins[0])
        np.testing.assert_allclose(
            [origin.latitude, origin.longitude, origin.depth],
            [-15.123, 123.0, 50.0],
        )
        assert (origin.time == obspy.UTCDateTime(
            year=2012,
            julday=123,
            hour=13,
            minute=43,
            second=17,
            microsecond=100000,
        ) - 10.0)

        origin = (ds.waveforms.AA_BBBB.random[0].stats.asdf.event_ids[0].
                  get_referred_object().origins[0])
        np.testing.assert_allclose(
            [origin.latitude, origin.longitude, origin.depth],
            [-14.123, 125.0, 30.0],
        )
        assert (origin.time == obspy.UTCDateTime(
            year=2013,
            julday=123,
            hour=13,
            minute=43,
            second=17,
            microsecond=100000,
        ) + 10.0)

    # Run once again in verbose mode but just test that the output is
    # actually more.
    os.remove(output_file)
    sys_argv_backup = copy.copy(sys.argv)
    try:
        sys.argv = sys.argv[:1]
        sys.argv.append("--verbose")
        sys.argv.append(tmpdir)
        sys.argv.append(output_file)
        sys.argv.append("random")
        sac2asdf.__main__()
    finally:
        # Restore to not mess with any of pytests logic.
        sys.argv = sys_argv_backup
    verbose_out, verbose_err = capsys.readouterr()
    assert not verbose_err
    assert len(verbose_out) > len(non_verbose_out)
Ejemplo n.º 6
0
def tosac(filename, outpath, parfile="None"):
    """
    Convert to SAC format

    Parameters
    ----------
    filename : string
        the filename of waveform data

    outpath : string
        the path name saving sac file, no back slash

    parfile : string
        input pararameter file for calculating response


    """

    with open(filename, "r") as fp:
        lst = fp.readlines()

    row = lst[0].split()
    # print row

    npx = int(row[0])
    ncomp = int(row[1])

    try:
        os.makedirs(outpath)
    except:
        pass

    k = -1
    for i in range(1, npx * ncomp * 2 + 1, 2):

        k += 1
        stno = k / ncomp + 1

        row = lst[i].split()
        # XS(JX)
        stlo = float(row[0])
        stla = 0.0
        az = float(row[1])
        kcmpnm = row[2]
        delta = float(row[3])
        npts = int(row[4])
        # reduced slowness, unit is
        pr = float(row[5])
        # reduced time, STMIN+PR*XS(JX), where STMIN is starting reduced time
        tcal = float(row[6])
        # not clear what smp mean
        smp = float(row[7])

        evla = 0.0
        evlo = 0.0

        # print stlo, az, kcmpnm, delta, npts, pr, tcal, smp

        row = lst[i + 1].split()
        data = np.array(row)
        data = data.astype(np.float32)

        if parfile == "None":
            evdp = -12345.0
        else:
            with open(parfile, "r") as fp:
                parlst = fp.readlines()
                row = parlst[20].split()[0]
                evdp = float(row)

        knetwk = "S"
        kstnm = str(stno).zfill(3)
        header = {
            "kcmpnm": kcmpnm,
            "knetwk": knetwk,
            "kstnm": kstnm,
            "stlo": stlo,
            "stla": stla,
            "delta": delta,
            "npts": npts,
            "evlo": evlo,
            "evla": evla,
            "evdp": evdp
        }
        sac = SACTrace(data=data, **header)
        fn = outpath + "/" + ".".join([knetwk, kstnm, "", kcmpnm, "sac"])
        # print fn
        sac.write(dest=fn)