Esempio n. 1
0
def eikonal_multithread(in_grder, workingdir, channel, tdiff, nearneighbor,
                        cdist, cdist2, nquant, cycle_thresh, cycle_period):
    working_per = workingdir + '/' + str(in_grder.period) + 'sec'
    if in_grder.period >= cycle_period:
        in_grder.correct_cycle_skip(thresh=cycle_thresh)
    if in_grder.interpolate_type == 'gmt':
        in_grder.interp_surface(do_blockmedian=True)
    else:
        in_grder.interp_verde()
    if not in_grder.check_curvature():
        return
    in_grder.eikonal(tdiff=tdiff,
                     nearneighbor=nearneighbor,
                     cdist=cdist,
                     cdist2=cdist2,
                     nquant=nquant)
    # amplitude Laplacian correction
    if in_grder.is_amplplc:
        amp_grd = _grid_class.SphereGridder(minlon = in_grder.minlon, maxlon = in_grder.maxlon, dlon = in_grder.dlon, \
                    minlat = in_grder.minlat, maxlat = in_grder.maxlat, dlat = in_grder.dlat, period = in_grder.period,\
                    lambda_factor = in_grder.lambda_factor, evlo = in_grder.evlo, evla = in_grder.evla, fieldtype = 'amp',\
                    evid = in_grder.evid, interpolate_type = in_grder.interpolate_type)
        amp_grd.read_array(inlons=in_grder.lons,
                           inlats=in_grder.lats,
                           inzarr=in_grder.amp)
        if in_grder.interpolate_type == 'gmt':
            amp_grd.interp_surface(do_blockmedian=True)
        elif in_grder.interpolate_type == 'verde':
            amp_grd.interp_verde()
        amp_grd.check_curvature_amp()
        amp_grd.helmholtz()
        in_grder.get_lplc_amp(fieldamp=amp_grd)
    outfname_npz = working_per + '/' + in_grder.evid + '_eikonal'
    in_grder.write_binary(outfname=outfname_npz, amplplc=in_grder.is_amplplc)
    return
Esempio n. 2
0
    def plot_disp_map(self, runid, period, width=-1., use_mask_all = False, semfactor=2., Nthresh=None, clabel='', cmap='surf',\
             projection='lambert', hillshade = False, vmin = None, vmax = None, showfig = True, v_rel = None):
        """plot maps from the tomographic inversion
        =================================================================================================================
        ::: input parameters :::
        runid           - id of run
        datatype        - datatype for plotting
        period          - period of data
        sem_factor      - factor multiplied to get the finalized uncertainties
        clabel          - label of colorbar
        cmap            - colormap
        projection      - projection type
        geopolygons     - geological polygons for plotting
        vmin, vmax      - min/max value of plotting
        showfig         - show figure or not
        =================================================================================================================
        """
        dataid = 'tomo_stack_' + str(runid)
        ingroup = self[dataid]
        pers = self.attrs['period_array']
        self._get_lon_lat_arr()
        mask = self.attrs['mask_inv']
        if not period in pers:
            raise KeyError('!!! period = ' + str(period) +
                           ' not included in the database')
        pergrp = ingroup['%g_sec' % (period)]
        if datatype == 'vel' or datatype == 'velocity' or datatype == 'v':
            datatype = 'vel_iso'
        elif datatype == 'sem' or datatype == 'un' or datatype == 'uncertainty':
            datatype = 'vel_sem'
        try:
            data = pergrp[datatype][()]
        except:
            outstr = ''
            for key in pergrp.keys():
                outstr += key
                outstr += ', '
            outstr = outstr[:-1]
            raise KeyError('Unexpected datatype: ' + datatype +
                           ', available datatypes are: ' + outstr)
        if datatype == 'vel_sem':
            data *= 1000. * semfactor

        # smoothing
        if width > 0.:
            gridder     = _grid_class.SphereGridder(minlon = self.minlon, maxlon = self.maxlon, dlon = self.dlon, \
                            minlat = self.minlat, maxlat = self.maxlat, dlat = self.dlat, period = period, \
                            evlo = 0., evla = 0., fieldtype = 'Tph', evid = 'plt')
            gridder.read_array(inlons=self.lonArr[np.logical_not(mask)],
                               inlats=self.latArr[np.logical_not(mask)],
                               inzarr=data[np.logical_not(mask)])
            outfname = 'plt_Tph.lst'
            prefix = 'plt_Tph_'
            gridder.gauss_smoothing(workingdir='./temp_plt',
                                    outfname=outfname,
                                    width=width)
            data[:] = gridder.Zarr

        mdata = ma.masked_array(data / factor, mask=mask)
        #-----------
        # plot data
        #-----------
        m = self._get_basemap(projection=projection)
        x, y = m(self.lonArr, self.latArr)
        try:
            import pycpt
            if os.path.isfile(cmap):
                cmap = pycpt.load.gmtColormap(cmap)
                # cmap    = cmap.reversed()
            elif os.path.isfile(cpt_path + '/' + cmap + '.cpt'):
                cmap = pycpt.load.gmtColormap(cpt_path + '/' + cmap + '.cpt')
        except:
            pass
        if v_rel is not None:
            mdata = (mdata - v_rel) / v_rel * 100.
        if hillshade:
            im = m.pcolormesh(x,
                              y,
                              mdata,
                              cmap=cmap,
                              shading='gouraud',
                              vmin=vmin,
                              vmax=vmax,
                              alpha=.5)
        else:
            im = m.pcolormesh(x,
                              y,
                              mdata,
                              cmap=cmap,
                              shading='gouraud',
                              vmin=vmin,
                              vmax=vmax)
            # m.contour(x, y, mask_eik, colors='white', lw=1)
        # cb          = m.colorbar(im, "bottom", size="3%", pad='2%', ticks=[10., 15., 20., 25., 30., 35., 40., 45., 50., 55., 60.])
        # cb          = m.colorbar(im, "bottom", size="3%", pad='2%', ticks=[20., 25., 30., 35., 40., 45., 50., 55., 60., 65., 70.])
        # cb          = m.colorbar(im, "bottom", size="5%", pad='2%', ticks=[4.0, 4.1, 4.2, 4.3, 4.4])
        cb = m.colorbar(im, "bottom", size="5%", pad='2%')
        cb.set_label(clabel, fontsize=40, rotation=0)
        # cb.outline.set_linewidth(2)
        plt.suptitle(str(period) + ' sec', fontsize=20)
        cb.ax.tick_params(labelsize=20)
        print('=== plotting data from ' + dataid)
        if showfig:
            plt.show()
        return
Esempio n. 3
0
 def load_eikonal(self,
                  inh5fname,
                  runid=0,
                  dtype='ph',
                  wtype='ray',
                  width=-1.,
                  Tmin=-999,
                  Tmax=999,
                  semfactor=2.):
     """read eikonal tomography results
     =================================================================================
     ::: input :::
     inh5fname   - input hdf5 file name
     runid       - id of run for the ray tomography
     dtype       - data type (ph or gr)
     wtype       - wave type (ray or lov)
     Tmin, Tmax  - minimum and maximum period to extract from the tomographic results
     semfactor   - factor to multiply for standard error of the mean (sem)
                     suggested by Lin et al. (2009)
     =================================================================================
     """
     if dtype is not 'ph' and dtype is not 'gr':
         raise ValueError('data type can only be ph or gr!')
     if wtype is not 'ray' and wtype is not 'lov':
         raise ValueError('wave type can only be ray or lov!')
     dset = eikonal_tomobase.baseh5(inh5fname)
     #--------------------------------------------
     # header information from input hdf5 file
     #--------------------------------------------
     pers = dset.pers
     minlon = dset.minlon
     maxlon = dset.maxlon
     minlat = dset.minlat
     maxlat = dset.maxlat
     dlon_eik = dset.dlon
     Nlon_eik = dset.Nlon
     dlat_eik = dset.dlat
     Nlat_eik = dset.Nlat
     try:
         mask_eik = dset.attrs['mask']
     except:
         dset.get_mask(runid=runid, Tmin=Tmin, Tmax=Tmax)
         mask_eik = dset.attrs['mask']
     proj_name = dset.proj_name
     outdir = os.path.dirname(self.filename) + '/in_eikonal_interp'
     # save attributes
     self.attrs.create(name='minlon', data=minlon, dtype=np.float64)
     self.attrs.create(name='maxlon', data=maxlon, dtype=np.float64)
     self.attrs.create(name='minlat', data=minlat, dtype=np.float64)
     self.attrs.create(name='maxlat', data=maxlat, dtype=np.float64)
     self.attrs.create(name='proj_name', data=proj_name)
     self.attrs.create(name='dlon_eik', data=dlon_eik, dtype=np.float64)
     self.attrs.create(name='dlat_eik', data=dlat_eik, dtype=np.float64)
     self.attrs.create(name='Nlon_eik', data=Nlon_eik, dtype=np.int64)
     self.attrs.create(name='Nlat_eik', data=Nlat_eik, dtype=np.int64)
     self.attrs.create(name='mask_eik', data=mask_eik, dtype=bool)
     self.update_attrs()
     self._get_lon_lat_arr()
     # mask of the model
     mask        = _model_funcs.mask_interp(dlon = dlon_eik, dlat = dlat_eik, minlon = self.minlon, \
                 minlat = self.minlat, maxlon = self.maxlon, maxlat = self.maxlat, mask_in = mask_eik,\
                 dlon_out = self.dlon, dlat_out = self.dlat, inear_true_false = False)
     self.attrs.create(name='mask', data=mask)
     # mask of inversion
     mask_inv    = _model_funcs.mask_interp(dlon = dlon_eik, dlat = dlat_eik, minlon = self.minlon, \
                 minlat = self.minlat, maxlon = self.maxlon, maxlat = self.maxlat, mask_in = mask_eik,\
                 dlon_out = self.dlon_inv, dlat_out = self.dlat_inv, inear_true_false = False)
     self.attrs.create(name='mask_inv', data=mask_inv)
     #====================================================
     # store interpolate eikonal maps to inversion grid
     #====================================================
     dat_grp = self.create_group(name='interp_eikonal_data_' + wtype + '_' +
                                 dtype)
     period_arr = []
     dataid = 'tomo_stack_' + str(runid)
     eik_grp = dset[dataid]
     for per in pers:
         try:
             pergrp = eik_grp['%d_sec' % per]
         except KeyError:
             continue
         period_arr.append(per)
         dat_per_grp = dat_grp.create_group(name='%d_sec' % per)
         mask_per = pergrp['mask'][()]
         vel_per = pergrp['vel_iso'][()]
         un_per = pergrp['vel_sem'][()]
         lons = dset.lonArr[np.logical_not(mask_per)]
         lats = dset.latArr[np.logical_not(mask_per)]
         # interpolate velocity
         C = vel_per[np.logical_not(mask_per)]
         gridder     = _grid_class.SphereGridder(minlon = self.minlon, maxlon = self.maxlon, dlon = self.dlon_inv, \
                         minlat = self.minlat, maxlat = self.maxlat, dlat = self.dlat_inv, period = per, \
                         evlo = -1., evla = -1., fieldtype = 'phvel', evid = 'INEIK')
         gridder.read_array(inlons=lons, inlats=lats, inzarr=C)
         gridder.interp_surface(do_blockmedian=True)
         if width > 0.:
             outfname = 'inv_C.lst'
             prefix = 'inv_C_'
             gridder.gauss_smoothing(workingdir='./temp_inv',
                                     outfname=outfname,
                                     width=width)
         dat_per_grp.create_dataset(name='vel_iso', data=gridder.Zarr)
         # interpolate uncertainties
         un = un_per[np.logical_not(mask_per)]
         gridder     = _grid_class.SphereGridder(minlon = self.minlon, maxlon = self.maxlon, dlon = self.dlon_inv, \
                         minlat = self.minlat, maxlat = self.maxlat, dlat = self.dlat_inv, period = per, \
                         evlo = -1., evla = -1., fieldtype = 'phvelun', evid = 'INEIK')
         gridder.read_array(inlons=lons, inlats=lats, inzarr=un)
         gridder.interp_surface(do_blockmedian=True)
         if width > 0.:
             outfname = 'inv_sem.lst'
             prefix = 'inv_sem_'
             gridder.gauss_smoothing(workingdir='./temp_inv',
                                     outfname=outfname,
                                     width=width)
         dat_per_grp.create_dataset(name='vel_sem', data=gridder.Zarr)
     grd_grp = self.require_group('grd_pts')
     for ilat in range(self.Nlat_inv):
         for ilon in range(self.Nlon_inv):
             if mask_inv[ilat, ilon]:
                 continue
             data_str = '%g_%g' % (self.lons_inv[ilon], self.lats_inv[ilat])
             group = grd_grp.require_group(name=data_str)
             disp_v = np.array([])
             disp_un = np.array([])
             T = np.array([])
             for per in period_arr:
                 if per < Tmin or per > Tmax:
                     continue
                 try:
                     dat_per_grp = dat_grp['%g_sec' % (per)]
                     vel = dat_per_grp['vel_iso'][()]
                     vel_sem = dat_per_grp['vel_sem'][()]
                 except KeyError:
                     print('No data for T = ' + str(per) + ' sec')
                     continue
                 T = np.append(T, per)
                 disp_v = np.append(disp_v, vel[ilat, ilon])
                 disp_un = np.append(disp_un, vel_sem[ilat, ilon])
             data = np.zeros((3, T.size))
             data[0, :] = T[:]
             data[1, :] = disp_v[:]
             data[2, :] = disp_un[:] * semfactor
             group.create_dataset(name='disp_' + dtype + '_' + wtype,
                                  data=data)
     self.attrs.create(name='period_array',
                       data=np.asarray(period_arr),
                       dtype=np.float64)
     self.attrs.create(name='sem_factor', data=semfactor, dtype=np.float64)
     dset.close()
     return
Esempio n. 4
0
 def plot(self, runid, datatype, period, width=-1., use_mask_all = False, semfactor=2., Nthresh=None, clabel='', cmap='surf',\
          projection='lambert', hillshade = False, vmin = None, vmax = None, showfig = True, v_rel = None):
     """plot maps from the tomographic inversion
     =================================================================================================================
     ::: input parameters :::
     runid           - id of run
     datatype        - datatype for plotting
     period          - period of data
     sem_factor      - factor multiplied to get the finalized uncertainties
     clabel          - label of colorbar
     cmap            - colormap
     projection      - projection type
     vmin, vmax      - min/max value of plotting
     showfig         - show figure or not
     =================================================================================================================
     """
     dataid          = 'tomo_stack_'+str(runid)
     ingroup         = self[dataid]
     pers            = self.attrs['period_array']
     self._get_lon_lat_arr()
     if not period in pers:
         raise KeyError('!!! period = '+str(period)+' not included in the database')
     pergrp          = ingroup['%g_sec'%( period )]
     if datatype == 'vel' or datatype=='velocity' or datatype == 'v':
         datatype    = 'vel_iso'
     elif datatype == 'sem' or datatype == 'un' or datatype == 'uncertainty':
         datatype    = 'vel_sem'
     elif datatype == 'std':
         datatype    = 'slowness_std'
     try:
         data        = pergrp[datatype][()]
     except:
         outstr      = ''
         for key in pergrp.keys():
             outstr  +=key
             outstr  +=', '
         outstr      = outstr[:-1]
         raise KeyError('Unexpected datatype: '+datatype+ ', available datatypes are: '+outstr)
     
     if datatype=='Nmeasure_aniso':
         factor      = ingroup.attrs['grid_lon'] * ingroup.attrs['grid_lat']
     else:
         factor      = 1
     if datatype=='Nmeasure_aniso' or datatype=='unpsi' or datatype=='unamp' or datatype=='amparr':
         mask        = pergrp['mask_aniso'][()] + pergrp['mask'][()]
     else:
         mask        = pergrp['mask'][()]
     if use_mask_all:
         mask        = self.attrs['mask']            
     if not (Nthresh is None):
         Narr        = pergrp['NmeasureQC'][()]
         mask        += Narr < Nthresh
     if datatype == 'vel_sem':
         data        *= 1000.*semfactor
     
     # smoothing
     if width > 0.:
         gridder     = _grid_class.SphereGridder(minlon = self.minlon, maxlon = self.maxlon, dlon = self.dlon, \
                         minlat = self.minlat, maxlat = self.maxlat, dlat = self.dlat, period = period, \
                         evlo = 0., evla = 0., fieldtype = 'Tph', evid = 'plt')
         gridder.read_array(inlons = self.lonArr[np.logical_not(mask)], inlats = self.latArr[np.logical_not(mask)], inzarr = data[np.logical_not(mask)])
         outfname    = 'plt_Tph.lst'
         prefix      = 'plt_Tph_'
         gridder.gauss_smoothing(workingdir = './temp_plt', outfname = outfname, width = width)
         data[:]     = gridder.Zarr
     
     mdata           = ma.masked_array(data/factor, mask=mask )
     #-----------
     # plot data
     #-----------
     m               = self._get_basemap(projection = projection)
     x, y            = m(self.lonArr, self.latArr)
     try:
         import pycpt
         if os.path.isfile(cmap):
             cmap    = pycpt.load.gmtColormap(cmap)
             # cmap    = cmap.reversed()
         elif os.path.isfile(cpt_path+'/'+ cmap + '.cpt'):
             cmap    = pycpt.load.gmtColormap(cpt_path+'/'+ cmap + '.cpt')
         cmap.set_bad('silver', alpha = 0.)
     except:
         pass
     ###################################################################
     # shapefname  = '/home/lili/data_marin/map_data/geological_maps/qfaults'
     # m.readshapefile(shapefname, 'faultline', linewidth = 3, color='black')
     # m.readshapefile(shapefname, 'faultline', linewidth = 1.5, color='white')
     
     shapefname  = '/home/lili/code/gem-global-active-faults/shapefile/gem_active_faults'
     # m.readshapefile(shapefname, 'faultline', linewidth = 4, color='black', default_encoding='windows-1252')
     if projection=='lambert':
         shapefname  = '/home/lili/data_marin/map_data/geological_maps/qfaults'
         m.readshapefile(shapefname, 'faultline', linewidth = 3, color='black')
         m.readshapefile(shapefname, 'faultline', linewidth = 1.5, color='white')
     else:
         m.readshapefile(shapefname, 'faultline', linewidth = 2., color='grey', default_encoding='windows-1252')
     
     # shapefname  = '/home/lili/data_mongo/fault_shp/doc-line'
     # # m.readshapefile(shapefname, 'faultline', linewidth = 4, color='black')
     # m.readshapefile(shapefname, 'faultline', linewidth = 2., color='grey')
     
     shapefname  = '/home/lili/data_marin/map_data/volcano_locs/SDE_GLB_VOLC.shp'
     shplst      = shapefile.Reader(shapefname)
     for rec in shplst.records():
         lon_vol = rec[4]
         lat_vol = rec[3]
         xvol, yvol            = m(lon_vol, lat_vol)
         m.plot(xvol, yvol, '^', mfc='white', mec='k', ms=10)
     ###################################################################
     if hillshade:
         from netCDF4 import Dataset
         from matplotlib.colors import LightSource
         import pycpt
         etopodata   = Dataset('/home/lili/gebco_mongo.nc')
         etopo       = (etopodata.variables['elevation'][:]).data
         lons        = (etopodata.variables['lon'][:]).data
         lons[lons>180.] = lons[lons>180.] - 360.
         lats        = (etopodata.variables['lat'][:]).data
         ls          = LightSource(azdeg=315, altdeg=45)
         ny, nx      = etopo.shape
         topodat,xtopo,ytopo = m.transform_scalar(etopo,lons,lats,nx, ny, returnxy=True)
         m.imshow(ls.hillshade(topodat, vert_exag=1., dx=1., dy=1.), cmap='gray')
         
     
     if v_rel is not None:
         mdata       = (mdata - v_rel)/v_rel * 100.
     if hillshade:
         im          = m.pcolormesh(x, y, mdata, cmap = cmap, shading = 'gouraud', vmin = vmin, vmax = vmax, alpha=.5)
     else:
         im          = m.pcolormesh(x, y, mdata, cmap = cmap, shading = 'gouraud', vmin = vmin, vmax = vmax)
     
     m.fillcontinents(color='silver', lake_color='none',zorder=0.2, alpha=1.)
     m.drawcountries(linewidth=1.)
     # m.fillcontinents(color='none', lake_color='#99ffff',zorder=100., alpha=1.)
     
         # m.contour(x, y, mask_eik, colors='white', lw=1)
     # cb          = m.colorbar(im, "bottom", size="3%", pad='2%', ticks=[10., 15., 20., 25., 30., 35., 40., 45., 50., 55., 60.])
     # cb          = m.colorbar(im, "bottom", size="3%", pad='2%', ticks=[20., 25., 30., 35., 40., 45., 50., 55., 60., 65., 70.])
     # cb          = m.colorbar(im, "bottom", size="5%", pad='2%', ticks=[4.0, 4.1, 4.2, 4.3, 4.4])
     cb          = m.colorbar(im, "bottom", size="5%", pad='2%')
     
     cb.set_label(clabel, fontsize=40, rotation=0)
     # cb.outline.set_linewidth(2)
     plt.suptitle(str(period)+' sec', fontsize=20)
     cb.ax.tick_params(labelsize = 20)
     print ('=== plotting data from '+dataid)
     if showfig:
         plt.show()
     return
Esempio n. 5
0
 def generate_corrected_map(self, outdir, pers = [], runid = 0, wavetype = 'R'):
     """generate corrected global phase velocity map using a regional phase velocity map.
     =================================================================================================================
     ::: input parameters :::
     outdir              - output directory
     pers                - period array for correction (default is 4)
     -----------------------------------------------------------------------------------------------------------------
     ::: output format ::::
     outdir/outpfx+str(int(per))
     =================================================================================================================
     """
     if not os.path.isdir(outdir):
         os.makedirs(outdir)
     if len(pers) == 0:
         pers            = np.arange(7.)*10.+40.
     dataid          = 'tomo_stack_'+str(runid)
     ingroup         = self[dataid]
     self._get_lon_lat_arr()
     minlon          = self.minlon
     maxlon          = self.maxlon
     minlat          = self.minlat
     maxlat          = self.maxlat
     for per in pers:
         if not per in self.pers:
             print ('!!! period = %g sec NOT in database!' %per)
             continue
         pergrp      = ingroup['%g_sec'%( per )]
         velocity    = pergrp['vel_iso'][()]
         mask        = pergrp['mask'][()]
         mapfile     = global_map_path + '/smpkolya_phv_'+wavetype+'_%d' %per
         out_mapfile = outdir + '/smpkolya_phv_'+wavetype+'_%d' %per
         if not os.path.isfile(mapfile):
             print ('!!! period = %g sec global reference map NOT exists!' %per)
             continue
         outarr      = np.loadtxt(mapfile)
         # interpolate to 1 deg x 1 deg
         lons        = self.lonArr[np.logical_not(mask)]
         lats        = self.latArr[np.logical_not(mask)]
         C           = velocity[np.logical_not(mask)]
         gridder     = _grid_class.SphereGridder(minlon = minlon, maxlon = maxlon, dlon = 1., \
                         minlat = minlat, maxlat = maxlat, dlat = 1., period = per, \
                         evlo = -1., evla = -1., fieldtype = 'phvel', evid = 'REF')
         gridder.read_array(inlons = lons, inlats = lats, inzarr = C)
         # outfname    = 'REF_phvel_'+wavetype+'.lst'
         # prefix      = 'REF_'+wavetype+'_'
         # working_per = outdir + '/%g_sec' %per
         # if not os.path.isdir(working_per):
         #     os.makedirs(working_per)
         # gridder.interp_surface(workingdir = working_per, outfname = outfname)
         gridder.interp_surface()   
         for ig in range(outarr.shape[0]):
             glb_lon = outarr[ig,0]
             glb_lat = outarr[ig,1]
             glb_C   = outarr[ig,2]
             for ilat in range(gridder.Nlat):
                 for ilon in range(gridder.Nlon):
                     reg_lon     = gridder.lons[ilon]
                     if reg_lon < 0.:
                         reg_lon += 360.
                     reg_lat     = gridder.lats[ilat]
                     reg_C       = gridder.Zarr[ilat, ilon]
                 if abs(reg_lon-glb_lon)<0.05 and abs(reg_lat-glb_lat)<0.05 and reg_C != 0 :
                     if abs(glb_C - reg_C) < 0.5:
                         outarr[ig, 2]     = reg_C
                     else:
                         print ('Large changes in regional map: \
                                 vel_glb = '+str(glb_C)+' km/s'+' vel_reg = '+str(reg_C)+' km/sec, '+str(reg_lon)+' '+str(reg_lat))
         np.savetxt(out_mapfile, outarr, fmt='%g %g %.4f')
         # return gridder
     return