Beispiel #1
0
    def sum_up(self, best_depth, dist, MT_rot):
        ''' 
        Sum up Green's functions 
        Args:
            * best_depth: best depth in the database (in km)
            * dist:       distance (in km or deg, depending on the d)
            * MT_rot:     rotated moment tensor
        Outputs:
            * Z_sac: sac object for component Z
            * L_sac: sac object for component L
            * T_sac: sac object for component T
        '''

        # Init sac
        Z_sac = sacpy.sac()
        L_sac = sacpy.sac()
        T_sac = sacpy.sac()
        GF_Z_sac = sacpy.sac()
        GF_L_sac = sacpy.sac()
        GF_T_sac = sacpy.sac()

        # Get prefix
        H_path = path.join(self.GF_path, 'H%05.1f' % (best_depth))

        # Get best distance
        best_dist = self.bestDist(H_path, dist)

        # GF_filenames
        Z_file = 'GF.%04.0f.SY.LHZ.SAC' % (best_dist * 10.)
        L_file = 'GF.%04.0f.SY.LHL.SAC' % (best_dist * 10.)
        T_file = 'GF.%04.0f.SY.LHT.SAC' % (best_dist * 10.)

        # Sum up Green's functions for vertical/longitudinal components
        for MT_cmp in ['RR', 'TT', 'PP', 'RT']:
            # Read GFs
            GF_Z_file = path.join(H_path, MT_cmp, Z_file)
            GF_L_file = path.join(H_path, MT_cmp, L_file)
            GF_Z_sac.rsac(GF_Z_file)
            GF_L_sac.rsac(GF_L_file)
            # Set Output sacs
            if MT_cmp == 'RR':
                Z_sac = GF_Z_sac.copy()
                L_sac = GF_L_sac.copy()
                Z_sac.depvar *= MT_rot[MT_cmp]
                L_sac.depvar *= MT_rot[MT_cmp]
            else:
                assert Z_sac.npts == GF_Z_sac.npts, 'Inconsistent number of samples'
                assert L_sac.npts == GF_L_sac.npts, 'Inconsistent number of samples'
                Z_sac.depvar += GF_Z_sac.depvar * MT_rot[MT_cmp]
                L_sac.depvar += GF_L_sac.depvar * MT_rot[MT_cmp]

        # Sum up Green's functions for transverse components
        for MT_cmp in ['RP', 'TP']:
            # Read GFs
            GF_T_file = path.join(H_path, MT_cmp, T_file)
            GF_T_sac.rsac(GF_T_file)
            # Set Output sacs
            if MT_cmp == 'RP':
                T_sac = GF_T_sac.copy()
                T_sac.depvar *= MT_rot[MT_cmp]
            else:
                assert T_sac.npts == GF_T_sac.npts, 'Inconsistent number of samples: %d %d' % (
                    T_sac.npts, GF_T_sac.npts)
                T_sac.depvar += GF_T_sac.depvar * MT_rot[MT_cmp]

        # All done
        return Z_sac, L_sac, T_sac
Beispiel #2
0
def ch_kcmpnm(ifile,kcmpnm):
    s = sacpy.sac()
    s.read(ifile)
    s.kcmpnm = kcmpnm
    s.wsac(ifile)
Beispiel #3
0
def main(argv):
    # Input parameters
    try:
        opts, args = go.gnu_getopt(argv[1:],'i:nh',["ifort15=","noref","help"])
    except getopt.GetoptError as err:
        raise
    o_wpfile = O_WPINVERSION
    predfile = ''
    isref    = 1
    CHAN     = ['LHZ', 'LHN', 'LHE', 'LH1', 'LH2']
    for o, a in opts:
        if o == '-h' or o == '--help':
            disphelp(sys.argv[0])
            sys.exit(0)
        if o == '-i' or o == '--ifort15':
            predfile = a
        if o == '-n' or o == '--noref':
            isref = 0    
    if len(args):
        CHAN  = args
    if not os.path.exists(o_wpfile):
        sys.stderr.write('Error: file %s not available\n'%(o_wpfile))
    if len(predfile) and not os.path.exists(predfile):
        raise IOError('No fort.15 file named %s\n'%(predfile))
    if not len(predfile):
        predfile = 'xy_fort.15'
        if not os.path.exists(predfile):
            predfile = 'ts_fort.15'
            if not os.path.exists(predfile):
                predfile = 'fort.15'
                if not os.path.exists(predfile):
                    raise IOError('No fort.15 file found\n')
    sys.stdout.write('Input fort.15 file: %s\n'%predfile)
    count = 0
    sys.stdout.write('Input channels are: ')
    for chan in CHAN:
        if not os.path.exists('%s_%s'%(predfile,chan)):
            continue 
        else:
            count += 1
        sys.stdout.write('%5s'%chan)
    if not count:
        ErrMsg = 'Error: No fort.15_ file for'
        for chan in CHAN:
            ErrMsg += '%5s'%(chan)
        raise IOError(ErrMsg)
    sys.stdout.write('\nRead %s ...\n%s pages:\n'%(o_wpfile,count))

    # Main loop
    sac = sacpy.sac()
    L = open(o_wpfile).readlines()
    ppW = mpl.backends.backend_pdf.PdfPages('CWP_W.pdf')
    sys.stdout.write('CWP_W.pdf\n')
    if isref:
        ppR = mpl.backends.backend_pdf.PdfPages('CWP_R.pdf')
        sys.stdout.write('CWP_R.pdf')
    for chan in CHAN:
        cb = 0.0
        stat_label = []
        stat_posit = []
        # Read o_wpinversion
        for l in L:
            items = l.strip().split()
            sac.read(items[0])
            if sac.kcmpnm[2] != chan[2]:
                continue
            stat_label.append(sac.kstnm)
            i1 = int(items[3])
            i2 = int(items[4])
            npts = float(i2-i1)    
            stat_posit.append(cb+npts/2.0)
            cb += npts
        if not len(stat_label):
            sys.stderr.write('WARNING: No channel %s in %s\n'%(chan,o_wpfile))
            continue
        # Read predfile
        ifile = predfile+'_'+chan
        L2 = open(ifile).readlines()
        ncol = len(L2[0].strip().split())
        if ncol < 3 and isref:
            print('Warning No ref solution in %s'%ifile)
            isref = 0
        else:
            Wref = []
        Wdat = []
        Wsyn = []
        for l in L2:
            items = l.strip().split()
            Wdat.append(float(items[0])*1000.0)
            Wsyn.append(float(items[1])*1000.0)
            if isref:
                if len(items)<3:
                    raise IOError('ERROR: error reading %s\n'%(ifile))
                Wref.append(float(items[2])*1000.0)
        t = np.arange(0,len(Wdat),dtype='float')
        # Display
        fig=plt.figure(figsize=CWP_FIGSIZE) 
        fig.subplots_adjust(left=0.08,bottom=0.12,right=0.96,top=0.88,wspace=0.2,hspace=0.2)
        plt.plot(t,Wdat,'k')
        plt.plot(t,Wsyn,'r')
        ymin = 1.1*min(Wdat)
        ymax = 1.1*max(Wdat)
        for stnm,x in zip(stat_label,stat_posit):
            plt.text(x,ymax*0.6,stnm,rotation=90,fontsize=16,fontstyle='italic')
        plt.ylim([ymin,ymax])
        plt.xlim([0,t[-1]])
        plt.xlabel('time, sec')
        plt.ylabel('displacement, mm')
        plt.title('Data fit, W Phase solution, %s'%chan[2])
        ppW.savefig(papertype='a4',orientation='landscape')
        plt.close()
        if isref:
            fig = plt.figure(figsize=CWP_FIGSIZE) 
            fig.subplots_adjust(left=0.08,bottom=0.12,right=0.96,top=0.88,wspace=0.2,hspace=0.2)
            plt.plot(t,Wdat,'k')
            plt.plot(t,Wref,'r')
            ymin = 1.1*min(Wdat)
            ymax = 1.1*max(Wdat)
            for stnm,x in zip(stat_label,stat_posit):
                plt.text(x,ymax*0.6,stnm,rotation=90,fontsize=16,fontstyle='italic')
            plt.ylim([ymin,ymax])
            plt.xlim([0,t[-1]])
            plt.xlabel('time, sec')
            plt.ylabel('displacement, mm')
            plt.title('Data fit, Reference solution, %s'%chan[2])
            ppR.savefig(papertype='a4',orientation='landscape')
            plt.close()
        sys.stdout.write('\n')
    ppW.close()
    if isref:
        ppR.close()
Beispiel #4
0
    def sum_up(self,best_depth,dist,MT_rot):
        ''' 
        Sum up Green's functions 
        Args:
            * best_depth: best depth in the database (in km)
            * dist:       distance (in km or deg, depending on the d)
            * MT_rot:     rotated moment tensor
        Outputs:
            * Z_sac: sac object for component Z
            * L_sac: sac object for component L
            * T_sac: sac object for component T
        '''
        
        # Init sac
        Z_sac = sacpy.sac()
        L_sac = sacpy.sac()
        T_sac = sacpy.sac()
        GF_Z_sac = sacpy.sac()
        GF_L_sac = sacpy.sac()
        GF_T_sac = sacpy.sac()

        # Get prefix
        H_path   = path.join(self.GF_path,'H%05.1f'%(best_depth))
        
        # Get best distance
        best_dist = self.bestDist(H_path, dist)
        
        # GF_filenames
        Z_file = 'GF.%04.0f.SY.LHZ.SAC'%(best_dist*10.)
        L_file = 'GF.%04.0f.SY.LHL.SAC'%(best_dist*10.)
        T_file = 'GF.%04.0f.SY.LHT.SAC'%(best_dist*10.)

        # Sum up Green's functions for vertical/longitudinal components
        for MT_cmp in ['RR','TT','PP','RT']:
            # Read GFs
            GF_Z_file = path.join(H_path,MT_cmp,Z_file)
            GF_L_file = path.join(H_path,MT_cmp,L_file)
            GF_Z_sac.rsac(GF_Z_file)
            GF_L_sac.rsac(GF_L_file)
            # Set Output sacs
            if MT_cmp=='RR':
                Z_sac = GF_Z_sac.copy()
                L_sac = GF_L_sac.copy()
                Z_sac.depvar *= MT_rot[MT_cmp]
                L_sac.depvar *= MT_rot[MT_cmp]
            else:
                assert Z_sac.npts == GF_Z_sac.npts, 'Inconsistent number of samples'
                assert L_sac.npts == GF_L_sac.npts, 'Inconsistent number of samples'
                Z_sac.depvar += GF_Z_sac.depvar * MT_rot[MT_cmp]
                L_sac.depvar += GF_L_sac.depvar * MT_rot[MT_cmp]

        # Sum up Green's functions for transverse components
        for MT_cmp in ['RP','TP']:
            # Read GFs
            GF_T_file = path.join(H_path,MT_cmp,T_file)
            GF_T_sac.rsac(GF_T_file)
            # Set Output sacs
            if MT_cmp=='RP':
                T_sac = GF_T_sac.copy()
                T_sac.depvar *= MT_rot[MT_cmp]
            else:
                assert T_sac.npts == GF_T_sac.npts, 'Inconsistent number of samples: %d %d'%(T_sac.npts,GF_T_sac.npts)
                T_sac.depvar += GF_T_sac.depvar * MT_rot[MT_cmp]
        
        # All done
        return Z_sac, L_sac, T_sac
Beispiel #5
0
def main(argv):
    # Input parameters (from Arguments.py)
    imaster = IMASTER
    length = LENGTH_GLOBAL
    syndir = 'SYNTH_traces'
    o_wpinversion = O_WPINVERSION
    nc = NC
    nl = NL
    solfile = None
    flagreg = False

    # Parse options
    try:
        opts, args = go.gnu_getopt(argv[1:], 'i:d:rh',
                                   ["icmtf=", "osydir=", "regional", "help"])
    except go.GetoptError as err:
        sys.stderr.write('usage: %s [option] (for help see %s -h)\n' %
                         (sys.argv[0], sys.argv[0]))
        raise

    for o, a in opts:
        if o == '-h' or o == '--help':
            disphelp(sys.argv[0], solfile, syndir)
            sys.exit(0)
        if o == '-r' or o == '--regional':
            length = LENGTH_REGIONAL
            flagreg = True
        if o == '-i' or o == '--icmtf':
            solfile = a
            if not os.path.exists(solfile):
                raise IOError('No wcmtfile named %s' % (solfile))
        if o == '-d' or o == '--osyndir':
            syndir = a
    if not solfile:
        for f in ['xy_WCMTSOLUTION', 'ts_WCMTSOLUTION', 'WCMTSOLUTION']:
            if os.path.exists(f):
                solfile = f
                break
        if not solfile:
            raise IOError(
                'No wcmtfile available, can be specified with --icmtf')

    eq = EarthQuake()
    eq.rcmtfile(solfile)
    cmtla, cmtlo = eq.lat, eq.lon

    # Title
    conf = utils.parseConfig(imaster)
    title = '_'.join(conf['EVNAME'].split())
    title += ',  filter = (%s, %s, %s, %s)' % (
        conf['filt_cf1'], conf['filt_cf2'], conf['filt_order'],
        conf['filt_pass'])

    # Cleanup run dir
    if os.path.exists(syndir) and syndir != '.' and syndir != './':
        utils.rm(syndir)
    if syndir != '.' and syndir != './':
        os.mkdir(syndir)
    if not os.path.exists(LOGDIR):
        os.mkdir(LOGDIR)
    for l in os.listdir('.'):
        if l[:4] == 'page' and l[-4:] == '.pdf':
            utils.rm(l)

    # Compute synthetics
    cmd = SYNTHS + ' ' + imaster + ' ' + solfile + ' ' + o_wpinversion + ' ' + syndir
    print(cmd)
    #status = call(cmd, shell=True, stdin=sys.stdin, stdout=sys.stdout);
    status = os.system(SYNTHS + ' ' + imaster + ' ' + solfile + ' ' +
                       o_wpinversion + ' ' + syndir + ' > ' +
                       os.path.join(LOGDIR, '_tmp_synths'))
    if status:
        print('Error while running ' + SYNTHS)
        sys.exit(1)

    # Create Sac Objects
    sacdata = sacpy.sac()
    sacsynt = sacpy.sac()
    coords = []
    L = open(o_wpinversion).readlines()
    for l in L:
        sacf = l.strip().split()[0]
        sacdata.read(sacf, datflag=0)
        coords.append([sacdata.stla, sacdata.stlo, sacdata.az, sacdata.dist])
    coords = np.array(coords)

    # Main loop
    print('Input (W)CMTSOLUTION file is: %s' % (solfile))
    print('Output synthetic directory is: %s' % (syndir))
    perpage = nl * nc
    ntot = len(L)
    npages = np.ceil(float(ntot) / float(perpage))
    nchan = 1
    count = 1
    pages = 1
    fig = plt.figure()
    fig.subplots_adjust(bottom=0.06,
                        top=0.87,
                        left=0.06,
                        right=0.95,
                        wspace=0.25,
                        hspace=0.4)
    print('All pages will be saved in %s' % (OPDFFILE))
    pp = mpl.backends.backend_pdf.PdfPages(OPDFFILE)
    basem = None
    for l in L:
        # Parse line
        items = l.strip().split()
        fic1 = items[0]
        sacdata.read(fic1)
        chan = sacdata.kcmpnm[0:3]
        loc = sacdata.khole
        fic2 = syndir+'/%s.%s.%s.%s.complete_synth.bp.sac'\
               %(sacdata.kstnm,sacdata.knetwk,chan,loc)
        sacsynt.read(fic2)
        # pages
        if count > perpage:
            plt.suptitle(title + ',   p %d/%d' % (pages, npages),
                         fontsize=16,
                         y=0.95)
            print('page %d/%d' % (pages, npages))
            #fig.set_rasterized(True)
            pp.savefig(orientation='landscape')
            plt.close()
            pages += 1
            count = 1
            fig = plt.figure()
            fig.subplots_adjust(bottom=0.06,
                                top=0.87,
                                left=0.06,
                                right=0.95,
                                wspace=0.25,
                                hspace=0.4)
        # Time - W phase window
        t1 = np.arange(sacdata.npts,
                       dtype='double') * sacdata.delta + sacdata.b - sacdata.o
        t2 = np.arange(sacsynt.npts,
                       dtype='double') * sacsynt.delta + sacsynt.b - sacsynt.o
        wnb = float(items[5])
        wne = float(items[6])
        wtb = sacdata.b - sacdata.o + wnb * sacdata.delta
        wte = sacdata.b - sacdata.o + wne * sacdata.delta
        # Plot trace
        ax = plt.subplot(nl, nc, count)
        plt.plot(t1, sacdata.depvar * 1000., 'k')
        plt.plot(t2, sacsynt.depvar * 1000., 'r-')
        plt.plot([wtb, wte], [0., 0.], 'ro')
        # Axes limits
        B = wtb - 150.0
        if B < 0:
            B = 0.0
        plt.xlim([B, B + length * sacsynt.delta])
        if YLIM_AUTO:
            a = np.absolute(sacsynt.depvar[:length]).max() * 1000.
            ymin = -1.1 * a
            ymax = 1.1 * a
            ylims = [ymin, ymax]
        else:
            ylims = YLIMFIXED
        plt.ylim(ylims)
        # Annotations
        plt.rcParams['font.family'] = 'sans-serif'
        plt.rcParams['font.sans-serif'] = 'Arial'
        plt.rcParams['mathtext.fontset'] = 'custom'
        plt.rcParams['mathtext.rm'] = 'sans'
        plt.rcParams['mathtext.it'] = 'sans:italic'
        plt.rcParams['mathtext.default'] = 'it'

        if sacdata.kcmpnm[2] == 'Z':
            if sys.version_info >= (2, 7):
                label = r'%s %s %s %s $(\phi,\Delta) = %6.1f\degree, %6.1f\degree$' % (
                    sacdata.knetwk, sacdata.kstnm, sacdata.kcmpnm,
                    sacdata.khole, sacdata.az, sacdata.gcarc)
            else:
                label = r'%s %s %s %s Az=%3.0f, delta=%3.0f' % (
                    sacdata.knetwk, sacdata.kstnm, sacdata.kcmpnm,
                    sacdata.khole, sacdata.az, sacdata.gcarc)

        else:
            if sys.version_info >= (2, 7):
                label = r'%s %s %s %s $(\phi,\Delta,\alpha) = %6.1f\degree,'
                label += '%6.1f\degree, %6.1f\degree$'
                label = label % (sacdata.knetwk, sacdata.kstnm, sacdata.kcmpnm,
                                 sacdata.khole, sacdata.az, sacdata.gcarc,
                                 sacdata.cmpaz)
            else:
                label = r'%s %s %s %s Az=%3.0f, delta=%3.0f'
                label = label % (sacdata.knetwk, sacdata.kstnm, sacdata.kcmpnm,
                                 sacdata.khole, sacdata.az, sacdata.gcarc)

        plt.title(label, fontsize=10.0, va='center', ha='center')
        if not (count - 1) % nc:
            plt.ylabel('mm', fontsize=10)
        if (count - 1) / nc == nl - 1 or nchan + nc > ntot:
            plt.xlabel('time, sec', fontsize=10)
        plt.grid()
        try:
            basem = showBasemap(ax, cmtla, cmtlo, sacdata.stla, sacdata.stlo,
                                coords, flagreg, basem)
        except:
            showPolarmap(ax, sacdata.az, sacdata.dist, coords)
            print('Cannot use basemap')
        count += 1
        nchan += 1
    print('page %d/%d' % (pages, npages))
    #fig.set_rasterized(True)
    plt.suptitle(title + ',    p %d/%d' % (pages, npages), fontsize=16, y=0.95)
    pp.savefig(orientation='landscape')
    plt.close()
    pp.close()
Beispiel #6
0
def main(argv):
    # Input parameters (from Arguments.py)
    imaster = IMASTER
    length  = LENGTH_GLOBAL
    syndir  = 'SYNTH_traces'
    o_wpinversion = O_WPINVERSION
    nc = NC
    nl = NL
    solfile = None
    flagreg = False

    # Parse options
    try:
        opts, args = go.gnu_getopt(argv[1:],'i:d:rh',["icmtf=","osydir=","regional","help"])
    except go.GetoptError as err:
        sys.stderr.write('usage: %s [option] (for help see %s -h)\n'%(sys.argv[0],sys.argv[0]))            
        raise

    for o, a in opts:
        if o == '-h' or o == '--help':
            disphelp(sys.argv[0],solfile,syndir)
            sys.exit(0)
        if o == '-r' or o == '--regional':
            length  = LENGTH_REGIONAL
            flagreg = True
        if o == '-i' or o=='--icmtf':
            solfile = a
            if not os.path.exists(solfile):                
                raise IOError('No wcmtfile named %s'%(solfile))
        if o == '-d' or o == '--osyndir':
            syndir = a
    if not solfile:
        for f in ['xy_WCMTSOLUTION','ts_WCMTSOLUTION','WCMTSOLUTION']:
            if os.path.exists(f):
                solfile = f
                break
        if not solfile:
            raise IOError('No wcmtfile available, can be specified with --icmtf')
 
    eq   = EarthQuake()
    eq.rcmtfile(solfile)
    cmtla,cmtlo = eq.lat, eq.lon   

    # Title
    conf  = utils.parseConfig(imaster)
    title = '_'.join(conf['EVNAME'].split())
    title += ',  filter = (%s, %s, %s, %s)'%(conf['filt_cf1'],conf['filt_cf2'],conf['filt_order'],conf['filt_pass']) 

    # Cleanup run dir
    if os.path.exists(syndir) and syndir != '.' and syndir != './':
        utils.rm(syndir)
    if syndir != '.' and syndir != './':
        os.mkdir(syndir)
    if not os.path.exists(LOGDIR):
        os.mkdir(LOGDIR)
    for l in os.listdir('.'):
        if l[:4]=='page' and l[-4:]=='.pdf':
            utils.rm(l)
            
    # Compute synthetics
    cmd    = SYNTHS+' '+imaster+' '+solfile+' '+o_wpinversion+' '+syndir
    print(cmd)
    #status = call(cmd, shell=True, stdin=sys.stdin, stdout=sys.stdout);
    status = os.system(SYNTHS+' '+imaster+' '+solfile+' '+o_wpinversion+' '+syndir+' > '+os.path.join(LOGDIR,'_tmp_synths'))
    if status:        
        print('Error while running '+SYNTHS)
        sys.exit(1)
        
    # Create Sac Objects
    sacdata = sacpy.sac()
    sacsynt = sacpy.sac()
    coords = []
    L = open(o_wpinversion).readlines()
    for l in L:
        sacf = l.strip().split()[0]
        sacdata.read(sacf,datflag=0)
        coords.append([sacdata.stla,sacdata.stlo,sacdata.az,sacdata.dist])
    coords = np.array(coords)
    
    # Main loop
    print('Input (W)CMTSOLUTION file is: %s'%(solfile))
    print('Output synthetic directory is: %s'%(syndir))
    perpage = nl*nc
    ntot   = len(L)
    npages = np.ceil(float(ntot)/float(perpage))
    nchan = 1
    count = 1
    pages = 1
    fig = plt.figure()
    fig.subplots_adjust(bottom=0.06,top=0.87,left=0.06,right=0.95,wspace=0.25,hspace=0.35)
    print('All pages will be saved in %s'%(OPDFFILE))
    pp = mpl.backends.backend_pdf.PdfPages(OPDFFILE)
    basem = None
    for l in L:
        # Parse line
        items = l.strip().split()
        fic1 = items[0]
        sacdata.read(fic1)
        chan = sacdata.kcmpnm[0:3]
        loc  = sacdata.khole
        fic2 = syndir+'/%s.%s.%s.%s.complete_synth.bp.sac'\
               %(sacdata.kstnm,sacdata.knetwk,chan,loc)
        sacsynt.read(fic2)        
        # pages
        if count > perpage:
            plt.suptitle(title+ ',   p %d/%d'%(pages,npages), fontsize=16, y=0.95)
            print('page %d/%d'%(pages,npages))
            #fig.set_rasterized(True)
            pp.savefig(orientation='landscape')
            plt.close()
            pages += 1
            count = 1
            fig = plt.figure()
            fig.subplots_adjust(bottom=0.06,top=0.87,left=0.06,right=0.95,wspace=0.25,hspace=0.35)
        # Time - W phase window
        t1 = np.arange(sacdata.npts,dtype='double')*sacdata.delta + sacdata.b - sacdata.o
        t2 = np.arange(sacsynt.npts,dtype='double')*sacsynt.delta + sacsynt.b - sacsynt.o        
        wnb = float(items[5])
        wne = float(items[6])
        wtb = sacdata.b - sacdata.o + wnb * sacdata.delta
        wte = sacdata.b - sacdata.o + wne * sacdata.delta        
        # Plot trace
        ax = plt.subplot(nl,nc,count)
        plt.plot(t1,sacdata.depvar*1000.,'k')
        plt.plot(t2,sacsynt.depvar*1000.,'r-')
        plt.plot([wtb,wte],[0.,0.],'ro')
        # Axes limits
        B=wtb-150.0
        if B<0:
            B = 0.0
        plt.xlim([B,B+length*sacsynt.delta])        
        if YLIM_AUTO:
            a    = np.absolute(sacsynt.depvar[:length]).max()*1000.
            ymin = -1.1*a
            ymax =  1.1*a
            ylims = [ymin,ymax]
        else:
            ylims = YLIMFIXED
        plt.ylim(ylims)        
        # Annotations
        if sacdata.kcmpnm[2] == 'Z':
            label = u'%s %s %s %s (\u03C6,\u0394) = %6.1f\u00B0, %5.1f\u00B0'
            label = label%(sacdata.knetwk,sacdata.kstnm, sacdata.kcmpnm, sacdata.khole,
            sacdata.az, sacdata.gcarc)
        else:
            label = u'%s %s %s %s (\u03C6,\u0394,\u03B1) = %6.1f\u00B0, %5.1f\u00B0, %6.1f\u00B0'
            label = label%(sacdata.knetwk,sacdata.kstnm, sacdata.kcmpnm, sacdata.khole,
            sacdata.az, sacdata.gcarc, sacdata.cmpaz)    
        plt.title(label,fontsize=10.0,va='center',ha='center')
        if not (count-1)%nc:
            plt.ylabel('mm',fontsize=10)
        if (count-1)/nc == nl-1 or nchan+nc > ntot:
            plt.xlabel('time, sec',fontsize=10) 
        plt.grid()
        try:
            basem = showBasemap(ax,cmtla,cmtlo,sacdata.stla,sacdata.stlo,coords,flagreg,basem)
        except:
            showPolarmap(ax,sacdata.az,sacdata.dist,coords)
            print('No basemap module')
        count += 1
        nchan += 1
    print('page %d/%d'%(pages,npages))
    #fig.set_rasterized(True)
    plt.suptitle(title + ',    p %d/%d'%(pages,npages), fontsize=16, y=0.95)
    pp.savefig(orientation='landscape')
    plt.close()
    pp.close()
Beispiel #7
0
def main(argv):
    # Input parameters
    try:
        opts, args = go.gnu_getopt(argv[1:],'i:nh',["ifort15=","noref","help"])
    except getopt.GetoptError as err:
        raise
    o_wpfile = O_WPINVERSION
    predfile = ''
    isref    = 1
    CHAN     = ['LHZ', 'LHN', 'LHE', 'LH1', 'LH2']
    for o, a in opts:
        if o == '-h' or o == '--help':
            disphelp(sys.argv[0])
            sys.exit(0)
        if o == '-i' or o == '--ifort15':
            predfile = a
        if o == '-n' or o == '--noref':
            isref = 0    
    if len(args):
        CHAN  = args
    if not os.path.exists(o_wpfile):
        sys.stderr.write('Error: file %s not available\n'%(o_wpfile))
    if len(predfile) and not os.path.exists(predfile):
        raise IOError('No fort.15 file named %s\n'%(predfile))
    if not len(predfile):
        predfile = 'xy_fort.15'
        if not os.path.exists(predfile):
            predfile = 'ts_fort.15'
            if not os.path.exists(predfile):
                predfile = 'fort.15'
                if not os.path.exists(predfile):
                    raise IOError('No fort.15 file found\n')
    sys.stdout.write('Input fort.15 file: %s\n'%predfile)
    count = 0
    sys.stdout.write('Input channels are: ')
    for chan in CHAN:
        if not os.path.exists('%s_%s'%(predfile,chan)):
            continue 
        else:
            count += 1
        sys.stdout.write('%5s'%chan)
    if not count:
        ErrMsg = 'Error: No fort.15_ file for'
        for chan in CHAN:
            ErrMsg += '%5s'%(chan)
        raise IOError(ErrMsg)
    sys.stdout.write('\nRead %s ...\n%s pages:\n'%(o_wpfile,count))

    # Main loop
    sac = sacpy.sac()
    L = open(o_wpfile).readlines()
    ppW = matplotlib.backends.backend_pdf.PdfPages('CWP_W.pdf')
    sys.stdout.write('CWP_W.pdf\n')
    if isref:
        ppR = matplotlib.backends.backend_pdf.PdfPages('CWP_R.pdf')
        sys.stdout.write('CWP_R.pdf')
    for chan in CHAN:
        cb = 0.0
        stat_label = []
        stat_posit = []
        # Read o_wpinversion
        for l in L:
            items = l.strip().split()
            sac.rsac(items[0])
            if sac.kcmpnm[2] != chan[2]:
                continue
            stat_label.append(sac.kstnm)
            i1 = int(items[3])
            i2 = int(items[4])
            npts = float(i2-i1)    
            stat_posit.append(cb+npts/2.0)
            cb += npts
        if not len(stat_label):
            sys.stderr.write('WARNING: No channel %s in %s\n'%(chan,o_wpfile))
            continue
        # Read predfile
        ifile = predfile+'_'+chan
        L2 = open(ifile).readlines()
        ncol = len(L2[0].strip().split())
        if ncol < 3 and isref:
            print('Warning No ref solution in %s'%ifile)
            isref = 0
        else:
            Wref = []
        Wdat = []
        Wsyn = []
        for l in L2:
            items = l.strip().split()
            Wdat.append(float(items[0])*1000.0)
            Wsyn.append(float(items[1])*1000.0)
            if isref:
                if len(items)<3:
                    raise IOError('ERROR: error reading %s\n'%(ifile))
                Wref.append(float(items[2])*1000.0)
        t = np.arange(0,len(Wdat),dtype='float')
        # Display
        fig=plt.figure(figsize=CWP_FIGSIZE) 
        fig.subplots_adjust(left=0.08,bottom=0.12,right=0.96,top=0.88,wspace=0.2,hspace=0.2)
        plt.plot(t,Wdat,'k')
        plt.plot(t,Wsyn,'r')
        ymin = 1.1*min(Wdat)
        ymax = 1.1*max(Wdat)
        for stnm,x in zip(stat_label,stat_posit):
            plt.text(x,ymax*0.6,stnm,rotation=90,fontsize=16,fontstyle='italic')
        plt.ylim([ymin,ymax])
        plt.xlim([0,t[-1]])
        plt.xlabel('time, sec')
        plt.ylabel('displacement, mm')
        plt.title('Data fit, W Phase solution, %s'%chan[2])
        ppW.savefig(papertype='a4',orientation='landscape')
        plt.close()
        if isref:
            fig = plt.figure(figsize=CWP_FIGSIZE) 
            fig.subplots_adjust(left=0.08,bottom=0.12,right=0.96,top=0.88,wspace=0.2,hspace=0.2)
            plt.plot(t,Wdat,'k')
            plt.plot(t,Wref,'r')
            ymin = 1.1*min(Wdat)
            ymax = 1.1*max(Wdat)
            for stnm,x in zip(stat_label,stat_posit):
                plt.text(x,ymax*0.6,stnm,rotation=90,fontsize=16,fontstyle='italic')
            plt.ylim([ymin,ymax])
            plt.xlim([0,t[-1]])
            plt.xlabel('time, sec')
            plt.ylabel('displacement, mm')
            plt.title('Data fit, Reference solution, %s'%chan[2])
            ppR.savefig(papertype='a4',orientation='landscape')
            plt.close()
        sys.stdout.write('\n')
    ppW.close()
    if isref:
        ppR.close()