def _linearinterp(M, iava, dims=None, dir=0, dtype='float64'): """Linear interpolation. """ # ensure that samples are not beyond the last sample, in that case set to # penultimate sample and raise a warning if np.issubdtype(iava.dtype, np.integer): iava = iava.astype(np.float) if dims is None: lastsample = M dimsd = None else: lastsample = dims[dir] dimsd = list(dims) dimsd[dir] = len(iava) dimsd = tuple(dimsd) outside = (iava >= lastsample - 1) if sum(outside) > 0: logging.warning('at least one value is beyond penultimate sample, ' 'forced to be at penultimate sample') iava[outside] = lastsample - 1 - 1e-10 _checkunique(iava) # find indices and weights iva_l = np.floor(iava).astype(np.int) iva_r = iva_l + 1 weights = iava - iva_l # create operators op = Diagonal(1 - weights, dims=dimsd, dir=dir, dtype=dtype) * \ Restriction(M, iva_l, dims=dims, dir=dir, dtype=dtype) + \ Diagonal(weights, dims=dimsd, dir=dir, dtype=dtype) * \ Restriction(M, iva_r, dims=dims, dir=dir, dtype=dtype) return op, iava
def test_Restriction_1dsignal(par): """Dot-test, forward and adjoint for Restriction operator for 1d signal""" np.random.seed(10) Nsub = int(np.round(par["nx"] * perc_subsampling)) iava = np.sort(np.random.permutation(np.arange(par["nx"]))[:Nsub]) Rop = Restriction(par["nx"], iava, inplace=par["dtype"], dtype=par["dtype"]) assert dottest(Rop, Nsub, par["nx"], complexflag=0 if par["imag"] == 0 else 3) x = np.ones(par["nx"]) + par["imag"] * np.ones(par["nx"]) y = Rop * x x1 = Rop.H * y y1 = Rop.mask(x) assert_array_almost_equal(y, y1[iava]) assert_array_almost_equal(x[iava], x1[iava])
def test_Restriction_2dsignal(par): """Dot-test, forward and adjoint for Restriction operator for 2d signal """ np.random.seed(10) x = np.ones((par['nx'], par['nt'])) + \ par['imag'] * np.ones((par['nx'], par['nt'])) # 1st direction Nsub = int(np.round(par['nx'] * perc_subsampling)) iava = np.sort(np.random.permutation(np.arange(par['nx']))[:Nsub]) Rop = Restriction(par['nx'] * par['nt'], iava, dims=(par['nx'], par['nt']), dir=0, inplace=par['dtype'], dtype=par['dtype']) assert dottest(Rop, Nsub * par['nt'], par['nx'] * par['nt'], complexflag=0 if par['imag'] == 0 else 3) y = (Rop * x.ravel()).reshape(Nsub, par['nt']) x1 = (Rop.H * y.ravel()).reshape(par['nx'], par['nt']) y1_fromflat = Rop.mask(x.ravel()) y1 = Rop.mask(x) assert_array_almost_equal(y, y1_fromflat.reshape(par['nx'], par['nt'])[iava]) assert_array_almost_equal(y, y1[iava]) assert_array_almost_equal(x[iava], x1[iava]) # 2nd direction Nsub = int(np.round(par['nt'] * perc_subsampling)) iava = np.sort(np.random.permutation(np.arange(par['nt']))[:Nsub]) Rop = Restriction(par['nx'] * par['nt'], iava, dims=(par['nx'], par['nt']), dir=1, inplace=par['dtype'], dtype=par['dtype']) assert dottest(Rop, par['nx'] * Nsub, par['nx'] * par['nt'], complexflag=0 if par['imag'] == 0 else 3) y = (Rop * x.ravel()).reshape(par['nx'], Nsub) x1 = (Rop.H * y.ravel()).reshape(par['nx'], par['nt']) y1_fromflat = Rop.mask(x.ravel()) y1 = Rop.mask(x) assert_array_almost_equal(y, y1_fromflat[:, iava]) assert_array_almost_equal(y, y1[:, iava]) assert_array_almost_equal(x[:, iava], x1[:, iava])
def test_Restriction(par): """Dot-test, forward and adjoint for Restriction operator """ # subsampling locations np.random.seed(10) perc_subsampling = 0.4 Nsub = int(np.round(par['nx'] * perc_subsampling)) iava = np.sort(np.random.permutation(np.arange(par['nx']))[:Nsub]) Rop = Restriction(par['nx'], iava, dtype=par['dtype']) assert dottest(Rop, Nsub, par['nx'], complexflag=0 if par['imag'] == 0 else 3) x = np.ones(par['nx']) + par['imag'] * np.ones(par['nx']) y = Rop * x x1 = Rop.H * y y1 = Rop.mask(x) assert_array_almost_equal(y, y1[iava]) assert_array_almost_equal(x[iava], x1[iava])
def Sliding3D(Op, dims, dimsd, nwin, nover, nop, tapertype='hanning', design=False, nproc=1): """3D Sliding transform operator. Apply a transform operator ``Op`` repeatedly to patches of the model vector in forward mode and patches of the data vector in adjoint mode. More specifically, in forward mode the model vector is divided into patches each patch is transformed, and patches are then recombined in a sliding window fashion. Both model and data should be 3-dimensional arrays in nature as they are internally reshaped and interpreted as 3-dimensional arrays. Each patch contains in fact a portion of the array in the first and second dimensions (and the entire third dimension). This operator can be used to perform local, overlapping transforms (e.g., :obj:`pylops.signalprocessing.FFTND` or :obj:`pylops.signalprocessing.Radon3D`) of 3-dimensional arrays. .. note:: The shape of the model has to be consistent with the number of windows for this operator not to return an error. As the number of windows depends directly on the choice of ``nwin`` and ``nover``, it is recommended to use ``design=True`` if unsure about the choice ``dims`` and use the number of windows printed on screen to define such input parameter. .. warning:: Depending on the choice of `nwin` and `nover` as well as the size of the data, sliding windows may not cover the entire first and/or second dimensions. The start and end indeces of each window can be displayed using ``design=True`` while defining the best sliding window approach. Parameters ---------- Op : :obj:`pylops.LinearOperator` Transform operator dims : :obj:`tuple` Shape of 3-dimensional model. Note that ``dims[0]`` and ``dims[1]`` should be multiple of the model sizes of the transform in the first and second dimensions dimsd : :obj:`tuple` Shape of 3-dimensional data nwin : :obj:`tuple` Number of samples of window nover : :obj:`tuple` Number of samples of overlapping part of window nop : :obj:`tuple` Number of samples in axes of transformed domain associated to spatial axes in the data tapertype : :obj:`str`, optional Type of taper (``hanning``, ``cosine``, ``cosinesquare`` or ``None``) design : :obj:`bool`, optional Print number sliding window (``True``) or not (``False``) Returns ------- Sop : :obj:`pylops.LinearOperator` Sliding operator Raises ------ ValueError Identified number of windows is not consistent with provided model shape (``dims``). """ # model windows mwin0_ins, mwin0_ends = _slidingsteps(dims[0], Op.shape[1]//(nop[1]*dims[2]), 0) mwin1_ins, mwin1_ends = _slidingsteps(dims[1], Op.shape[1]//(nop[0]*dims[2]), 0) # data windows dwin0_ins, dwin0_ends = _slidingsteps(dimsd[0], nwin[0], nover[0]) dwin1_ins, dwin1_ends = _slidingsteps(dimsd[1], nwin[1], nover[1]) nwins0 = len(dwin0_ins) nwins1 = len(dwin1_ins) nwins = nwins0*nwins1 # create tapers if tapertype is not None: tap = taper3d(dimsd[2], nwin, nover, tapertype=tapertype) # check that identified number of windows agrees with mode size if design: logging.warning('(%d,%d) windows required...', nwins0, nwins1) logging.warning('model wins - start0:%s, end0:%s, start1:%s, end1:%s', str(mwin0_ins), str(mwin0_ends), str(mwin1_ins), str(mwin1_ends)) logging.warning('data wins - start0:%s, end0:%s, start1:%s, end1:%s', str(dwin0_ins), str(dwin0_ends), str(dwin1_ins), str(dwin1_ends)) if nwins*Op.shape[1]//dims[2] != dims[0]*dims[1]: raise ValueError('Model shape (dims=%s) is not consistent with chosen ' 'number of windows. Choose dims[0]=%d and ' 'dims[1]=%d for the operator to work with ' 'estimated number of windows, or create ' 'the operator with design=True to find out the' 'optimal number of windows for the current ' 'model size...' % (str(dims), nwins0*Op.shape[1]//(nop[1]*dims[2]), nwins1 * Op.shape[1]//(nop[0]*dims[2]))) # transform to apply if tapertype is None: OOp = BlockDiag([Op for _ in range(nwins)], nproc=nproc) else: OOp = BlockDiag([Diagonal(tap.flatten()) * Op for _ in range(nwins)], nproc=nproc) hstack = HStack([Restriction(dimsd[1] * dimsd[2] * nwin[0], range(win_in, win_end), dims=(nwin[0], dimsd[1], dimsd[2]), dir=1).H for win_in, win_end in zip(dwin1_ins, dwin1_ends)]) combining1 = BlockDiag([hstack]*nwins0) combining0 = HStack([Restriction(np.prod(dimsd), range(win_in, win_end), dims=dimsd, dir=0).H for win_in, win_end in zip(dwin0_ins, dwin0_ends)]) Sop = combining0 * combining1 * OOp return Sop
def Sliding1D(Op, dim, dimd, nwin, nover, tapertype="hanning", design=False): r"""1D Sliding transform operator. Apply a transform operator ``Op`` repeatedly to slices of the model vector in forward mode and slices of the data vector in adjoint mode. More specifically, in forward mode the model vector is divided into slices, each slice is transformed, and slices are then recombined in a sliding window fashion. This operator can be used to perform local, overlapping transforms (e.g., :obj:`pylops.signalprocessing.FFT`) on 1-dimensional arrays. .. note:: The shape of the model has to be consistent with the number of windows for this operator not to return an error. As the number of windows depends directly on the choice of ``nwin`` and ``nover``, it is recommended to use ``design=True`` if unsure about the choice ``dims`` and use the number of windows printed on screen to define such input parameter. .. warning:: Depending on the choice of `nwin` and `nover` as well as the size of the data, sliding windows may not cover the entire data. The start and end indices of each window can be displayed using ``design=True`` while defining the best sliding window approach. Parameters ---------- Op : :obj:`pylops.LinearOperator` Transform operator dim : :obj:`tuple` Shape of 1-dimensional model. dimd : :obj:`tuple` Shape of 1-dimensional data nwin : :obj:`int` Number of samples of window nover : :obj:`int` Number of samples of overlapping part of window tapertype : :obj:`str`, optional Type of taper (``hanning``, ``cosine``, ``cosinesquare`` or ``None``) design : :obj:`bool`, optional Print number of sliding window (``True``) or not (``False``) Returns ------- Sop : :obj:`pylops.LinearOperator` Sliding operator Raises ------ ValueError Identified number of windows is not consistent with provided model shape (``dims``). """ # model windows mwin_ins, mwin_ends = _slidingsteps(dim, Op.shape[1], 0) # data windows dwin_ins, dwin_ends = _slidingsteps(dimd, nwin, nover) nwins = len(dwin_ins) # create tapers if tapertype is not None: tap = taper(nwin, nover, tapertype=tapertype) tapin = tap.copy() tapin[:nover] = 1 tapend = tap.copy() tapend[-nover:] = 1 taps = {} taps[0] = tapin for i in range(1, nwins - 1): taps[i] = tap taps[nwins - 1] = tapend # check that identified number of windows agrees with mode size if design: logging.warning("%d windows required...", nwins) logging.warning("model wins - start:%s, end:%s", str(mwin_ins), str(mwin_ends)) logging.warning("data wins - start:%s, end:%s", str(dwin_ins), str(dwin_ends)) if nwins * Op.shape[1] != dim: raise ValueError( "Model shape (dim=%d) is not consistent with chosen " "number of windows. Choose dim=%d for the " "operator to work with estimated number of windows, " "or create the operator with design=True to find " "out the optimal number of windows for the current " "model size..." % (dim, nwins * Op.shape[1]) ) # transform to apply if tapertype is None: OOp = BlockDiag([Op for _ in range(nwins)]) else: OOp = BlockDiag([Diagonal(taps[itap].ravel()) * Op for itap in range(nwins)]) combining = HStack( [ Restriction(dimd, np.arange(win_in, win_end), dtype=Op.dtype).H for win_in, win_end in zip(dwin_ins, dwin_ends) ] ) Sop = combining * OOp return Sop
def Marchenko_depthloop_JointLsqr(zinvs, zendvs): toff = 0.045 # direct arrival time shift nfmax = 550 # max frequency for MDC (#samples) nfft = 2**11 jr = 3 # subsampling in r # subsurface array xinvs = 600 # receiver array initial point in x xendvs = 2400 # receiver array last point in x dvsx = 20 # receiver array sampling in x dvsz = 5 # receiver array sampling in z # line of subsurface points for virtual sources vsx = np.arange(xinvs, xendvs + dvsx, dvsx) nvsx = vsx.shape[0] vsz = np.arange(zinvs, zendvs + dvsz, dvsz) nvsz = vsz.shape[0] # geometry nz = 401 oz = 0 dz = 4 z = np.arange(oz, oz + nz * dz, dz) nx = 751 ox = 0 dx = 4 x = np.arange(ox, ox + nx * dx, dx) # time axis ot = 0 nt = 1081 dt = 0.0025 t = np.arange(ot, ot + nt * dt, dt) # Receivers r = np.loadtxt(path0 + 'r.dat', delimiter=',') nr = r.shape[1] # Sources s = np.loadtxt(path0 + 's.dat', delimiter=',') ns = s.shape[1] ds = s[0, 1] - s[0, 0] # restriction operators iava1 = np.loadtxt(path0 + 'select_rfrac70.dat', delimiter=',', dtype=int) - 1 iava2 = np.loadtxt(path0 + 'select_rfrac50.dat', delimiter=',', dtype=int) - 1 nava1 = iava1.shape[0] nava2 = iava2.shape[0] Restrop1 = Restriction(ns * (2 * nt - 1), iava1, dims=(ns, 2 * nt - 1), dir=0, dtype='float64') Restrop2 = Restriction(ns * (2 * nt - 1), iava2, dims=(ns, 2 * nt - 1), dir=0, dtype='float64') # data print('Loading reflection data...') R_1 = np.zeros((nt, ns, nr), 'f') R_2 = np.zeros((nt, ns, nr), 'f') for isrc in range(ns - 1): is_ = isrc * jr R_1[:, :, isrc] = np.loadtxt(path0 + 'R/dat1_' + str(is_) + '.dat', delimiter=',') R_2[:, :, isrc] = np.loadtxt(path0 + 'R/dat2_' + str(is_) + '.dat', delimiter=',') R_1 = 2 * np.swapaxes(R_1, 0, 2) R_2 = 2 * np.swapaxes(R_2, 0, 2) # Convolution operators print('Creating MDC operators...') Rtwosided_1 = np.concatenate((np.zeros((nr, ns, nt - 1)), R_1), axis=-1) R1twosided_1 = np.concatenate( (np.flip(R_1, axis=-1), np.zeros((nr, ns, nt - 1))), axis=-1) Rtwosided_fft_1 = np.fft.rfft(Rtwosided_1, 2 * nt - 1, axis=-1) / np.sqrt(2 * nt - 1) Rtwosided_fft_1 = Rtwosided_fft_1[..., :nfmax] R1twosided_fft_1 = np.fft.rfft(R1twosided_1, 2 * nt - 1, axis=-1) / np.sqrt(2 * nt - 1) R1twosided_fft_1 = R1twosided_fft_1[..., :nfmax] Rtwosided_2 = np.concatenate((np.zeros((nr, ns, nt - 1)), R_2), axis=-1) R1twosided_2 = np.concatenate( (np.flip(R_2, axis=-1), np.zeros((nr, ns, nt - 1))), axis=-1) Rtwosided_fft_2 = np.fft.rfft(Rtwosided_2, 2 * nt - 1, axis=-1) / np.sqrt(2 * nt - 1) Rtwosided_fft_2 = Rtwosided_fft_2[..., :nfmax] R1twosided_fft_2 = np.fft.rfft(R1twosided_2, 2 * nt - 1, axis=-1) / np.sqrt(2 * nt - 1) R1twosided_fft_2 = R1twosided_fft_2[..., :nfmax] Rop1 = MDC(Rtwosided_fft_1[iava1], nt=2 * nt - 1, nv=1, dt=dt, dr=ds, twosided=True, dtype='complex64') R1op1 = MDC(R1twosided_fft_1[iava1], nt=2 * nt - 1, nv=1, dt=dt, dr=ds, twosided=True, dtype='complex64') Rop2 = MDC(Rtwosided_fft_2[iava2], nt=2 * nt - 1, nv=1, dt=dt, dr=ds, twosided=True, dtype='complex64') R1op2 = MDC(R1twosided_fft_2[iava2], nt=2 * nt - 1, nv=1, dt=dt, dr=ds, twosided=True, dtype='complex64') # wavelet and traveltime print('Loading direct wave...') wav = np.loadtxt(path0 + 'wav.dat', delimiter=',') wav_c = wav[np.argmax(wav) - 60:np.argmax(wav) + 60] trav_eik = np.loadtxt(path0 + 'trav.dat', delimiter=',') trav_eik = np.reshape(trav_eik, (nz, ns, nx)) # the loop print('Entering loop...') for iz in range(nvsz): z_current = vsz[iz] PUP1 = np.zeros(shape=(nava1, nvsx, nt)) PDOWN1 = np.zeros(shape=(nava1, nvsx, nt)) PUP2 = np.zeros(shape=(nava2, nvsx, nt)) PDOWN2 = np.zeros(shape=(nava2, nvsx, nt)) for ix in range(nvsx): s = '############ Point ' + str(ix + 1) + ' of ' + str( nvsx) + ', line ' + str(iz + 1) + ' of ' + str( nvsz) + ' (z = ' + str(vsz[iz]) + ', x = ' + str( vsx[ix]) + ') ... ' + str(100 * (iz * nvsx + ix + 1) / (nvsx * nvsz)) + '%' print(s) # direct wave direct = trav_eik[find_closest(z_current, z), :, find_closest(vsx[ix], x)] W = np.abs(np.fft.rfft(wav, nfft)) * dt f = 2 * np.pi * np.arange(nfft) / (dt * nfft) g0VS = np.zeros((nfft, nr), dtype=np.complex128) for it in range(len(W)): g0VS[it] = W[it] * f[it] * hankel2(0, f[it] * direct + 1e-10) / 4 g0VS = np.fft.irfft(g0VS, nfft, axis=0) / dt g0VS = np.real(g0VS[:nt]) # Marchenko focusing f1_1_minus, f1_1_plus, f1_2_minus, f1_2_plus, g_1_minus, g_1_plus, g_2_minus, g_2_plus = focusing_wrapper( direct, toff, g0VS, iava1, Rop1, R1op1, Restrop1, iava2, Rop2, R1op2, Restrop2, t) # assemble wavefields PUP1[:, ix, :] = g_1_minus[:, nt - 1:] PDOWN1[:, ix, :] = g_1_plus[:, nt - 1:] PUP2[:, ix, :] = g_2_minus[:, nt - 1:] PDOWN2[:, ix, :] = g_2_plus[:, nt - 1:] # calculate and save redatumed wavefields (line-by-line) jt = 2 redatumed1 = MDD(PDOWN1[:, :, ::jt], PUP1[:, :, ::jt], dt=jt * dt, dr=dvsx, wav=wav_c[::jt], twosided=True, adjoint=False, psf=False, dtype='complex64', dottest=False, **dict(iter_lim=20, show=0)) redatumed2 = MDD(PDOWN2[:, :, ::jt], PUP2[:, :, ::jt], dt=jt * dt, dr=dvsx, wav=wav_c[::jt], twosided=True, adjoint=False, psf=False, dtype='complex64', dottest=False, **dict(iter_lim=20, show=0)) np.savetxt(path_save + 'Line1_' + str(z_current) + '.dat', np.diag(redatumed1[:, :, (nt + 1) // jt - 1]), delimiter=',') np.savetxt(path_save + 'Line2_' + str(z_current) + '.dat', np.diag(redatumed2[:, :, (nt + 1) // jt - 1]), delimiter=',') vel_sm = np.loadtxt(path0 + 'vel_sm.dat', delimiter=',') cp = vel_sm[find_closest(z_current, z), 751 // 2] # calculate and save angle gathers (line-by-line) irA = np.asarray([7, 15, 24, 35]) nalpha = 201 A1 = np.zeros((nalpha, len(irA))) A2 = np.zeros((nalpha, len(irA))) for i in np.arange(0, len(irA)): ir = irA[i] anglegath, alpha = AngleGather(np.swapaxes(redatumed1, 0, 2), nvsx, nalpha, dt * jt, ds, ir, cp) A1[:, i] = anglegath anglegath, alpha = AngleGather(np.swapaxes(redatumed2, 0, 2), nvsx, nalpha, dt * jt, ds, ir, cp) A2[:, i] = anglegath np.savetxt(path_save + 'AngleGather1_' + str(z_current) + '.dat', A1, delimiter=',') np.savetxt(path_save + 'AngleGather2_' + str(z_current) + '.dat', A2, delimiter=',')
def _nearestinterp(M, iava, dims=None, dir=0, dtype='float64'): """Nearest neighbour interpolation. """ iava = np.round(iava).astype(np.int) _checkunique(iava) return Restriction(M, iava, dims=dims, dir=dir, dtype=dtype), iava
def Sliding2D(Op, dims, dimsd, nwin, nover, tapertype='hanning', design=False): """2D Sliding transform operator. Apply a transform operator ``Op`` repeatedly to patches of the model vector in forward mode and patches of the data vector in adjoint mode. More specifically, in forward mode the model vector is divided into patches each patch is transformed, and patches are then recombined in a sliding window fashion. Both model and data should be 2-dimensional arrays in nature as they are internally reshaped and interpreted as 2-dimensional arrays. Each patch contains in fact a portion of the array in the first dimension (and the entire second dimension). This operator can be used to perform local, overlapping transforms (e.g., :obj:`pylops.signalprocessing.FFT2` or :obj:`pylops.signalprocessing.Radon2D`) of 2-dimensional arrays. .. note:: The shape of the model has to be consistent with the number of windows for this operator not to return an error. As the number of windows depends directly on the choice of ``nwin`` and ``nover``, it is recommended to use ``design=True`` if unsure about the choice ``dims`` and use the number of windows printed on screen to define such input parameter. .. warning:: Depending on the choice of `nwin` and `nover` as well as the size of the data, sliding windows may not cover the entire first dimension. The start and end indeces of each window can be displayed using ``design=True`` while defining the best sliding window approach. Parameters ---------- Op : :obj:`pylops.LinearOperator` Transform operator dims : :obj:`tuple` Shape of 2-dimensional model. Note that ``dims[0]`` should be multiple of the model size of the transform in the first dimension dimsd : :obj:`tuple` Shape of 2-dimensional data nwin : :obj:`int` Number of samples of window nover : :obj:`int` Number of samples of overlapping part of window tapertype : :obj:`str`, optional Type of taper (``hanning``, ``cosine``, ``cosinesquare`` or ``None``) design : :obj:`bool`, optional Print number of sliding window (``True``) or not (``False``) Returns ------- Sop : :obj:`pylops.LinearOperator` Sliding operator Raises ------ ValueError Identified number of windows is not consistent with provided model shape (``dims``). """ # model windows mwin_ins, mwin_ends = _slidingsteps(dims[0], Op.shape[1] // dims[1], 0) # data windows dwin_ins, dwin_ends = _slidingsteps(dimsd[0], nwin, nover) nwins = len(dwin_ins) # create tapers if tapertype is not None: tap = taper2d(dimsd[1], nwin, nover, tapertype=tapertype) tapin = tap.copy() tapin[:nover] = 1 tapend = tap.copy() tapend[-nover:] = 1 taps = {} taps[0] = tapin for i in range(1, nwins - 1): taps[i] = tap taps[nwins - 1] = tapend # check that identified number of windows agrees with mode size if design: logging.warning('%d windows required...', nwins) logging.warning('model wins - start:%s, end:%s', str(mwin_ins), str(mwin_ends)) logging.warning('data wins - start:%s, end:%s', str(dwin_ins), str(dwin_ends)) if nwins * Op.shape[1] // dims[1] != dims[0]: raise ValueError('Model shape (dims=%s) is not consistent with chosen ' 'number of windows. Choose dims[0]=%d for the ' 'operator to work with estimated number of windows, ' 'or create the operator with design=True to find ' 'out the optimal number of windows for the current ' 'model size...' % (str(dims), nwins * Op.shape[1] // dims[1])) # transform to apply if tapertype is None: OOp = BlockDiag([Op for _ in range(nwins)]) else: OOp = BlockDiag( [Diagonal(taps[itap].flatten()) * Op for itap in range(nwins)]) combining = HStack([ Restriction(np.prod(dimsd), range(win_in, win_end), dims=dimsd).H for win_in, win_end in zip(dwin_ins, dwin_ends) ]) Sop = combining * OOp return Sop
def Patch2D(Op, dims, dimsd, nwin, nover, nop, tapertype="hanning", design=False): """2D Patch transform operator. Apply a transform operator ``Op`` repeatedly to patches of the model vector in forward mode and patches of the data vector in adjoint mode. More specifically, in forward mode the model vector is divided into patches, each patch is transformed, and patches are then recombined together. Both model and data are internally reshaped and interpreted as 2-dimensional arrays: each patch contains a portion of the array in both the first and second dimension. This operator can be used to perform local, overlapping transforms (e.g., :obj:`pylops.signalprocessing.FFT2D` or :obj:`pylops.signalprocessing.Radon2D`) on 2-dimensional arrays. .. note:: The shape of the model has to be consistent with the number of windows for this operator not to return an error. As the number of windows depends directly on the choice of ``nwin`` and ``nover``, it is recommended to use ``design=True`` if unsure about the choice ``dims`` and use the number of windows printed on screen to define such input parameter. .. warning:: Depending on the choice of `nwin` and `nover` as well as the size of the data, patches may not cover the entire size of the data. The start and end indices of each window can be displayed using ``design=True`` while defining the best patching approach. Parameters ---------- Op : :obj:`pylops.LinearOperator` Transform operator dims : :obj:`tuple` Shape of 2-dimensional model. Note that ``dims[0]`` and ``dims[1]`` should be multiple of the model size of the transform in their respective dimensions dimsd : :obj:`tuple` Shape of 2-dimensional data nwin : :obj:`tuple` Number of samples of window nover : :obj:`tuple` Number of samples of overlapping part of window nop : :obj:`tuple` Size of model in the transformed domain tapertype : :obj:`str`, optional Type of taper (``hanning``, ``cosine``, ``cosinesquare`` or ``None``) design : :obj:`bool`, optional Print number of sliding window (``True``) or not (``False``) Returns ------- Sop : :obj:`pylops.LinearOperator` Sliding operator Raises ------ ValueError Identified number of windows is not consistent with provided model shape (``dims``). See Also -------- Sliding2d: 2D Sliding transform operator. """ # model windows mwin0_ins, mwin0_ends = _slidingsteps(dims[0], nop[0], 0) mwin1_ins, mwin1_ends = _slidingsteps(dims[1], nop[1], 0) # data windows dwin0_ins, dwin0_ends = _slidingsteps(dimsd[0], nwin[0], nover[0]) dwin1_ins, dwin1_ends = _slidingsteps(dimsd[1], nwin[1], nover[1]) nwins0 = len(dwin0_ins) nwins1 = len(dwin1_ins) nwins = nwins0 * nwins1 # create tapers if tapertype is not None: tap = taper2d(nwin[1], nwin[0], nover, tapertype=tapertype).astype(Op.dtype) taps = {itap: tap for itap in range(nwins)} # topmost tapers taptop = tap.copy() taptop[:nover[0]] = tap[nwin[0] // 2] for itap in range(0, nwins1): taps[itap] = taptop # bottommost tapers tapbottom = tap.copy() tapbottom[-nover[0]:] = tap[nwin[0] // 2] for itap in range(nwins - nwins1, nwins): taps[itap] = tapbottom # leftmost tapers tapleft = tap.copy() tapleft[:, :nover[1]] = tap[:, nwin[1] // 2][:, np.newaxis] for itap in range(0, nwins, nwins1): taps[itap] = tapleft # rightmost tapers tapright = tap.copy() tapright[:, -nover[1]:] = tap[:, nwin[1] // 2][:, np.newaxis] for itap in range(nwins1 - 1, nwins, nwins1): taps[itap] = tapright # lefttopcorner taper taplefttop = tap.copy() taplefttop[:, :nover[1]] = tap[:, nwin[1] // 2][:, np.newaxis] taplefttop[:nover[0]] = taplefttop[nwin[0] // 2] taps[0] = taplefttop # righttopcorner taper taprighttop = tap.copy() taprighttop[:, -nover[1]:] = tap[:, nwin[1] // 2][:, np.newaxis] taprighttop[:nover[0]] = taprighttop[nwin[0] // 2] taps[nwins1 - 1] = taprighttop # leftbottomcorner taper tapleftbottom = tap.copy() tapleftbottom[:, :nover[1]] = tap[:, nwin[1] // 2][:, np.newaxis] tapleftbottom[-nover[0]:] = tapleftbottom[nwin[0] // 2] taps[nwins - nwins1] = tapleftbottom # rightbottomcorner taper taprightbottom = tap.copy() taprightbottom[:, -nover[1]:] = tap[:, nwin[1] // 2][:, np.newaxis] taprightbottom[-nover[0]:] = taprightbottom[nwin[0] // 2] taps[nwins - 1] = taprightbottom # check that identified number of windows agrees with mode size if design: logging.warning("%d-%d windows required...", nwins0, nwins1) logging.warning( "model wins - start:%s, end:%s / start:%s, end:%s", str(mwin0_ins), str(mwin0_ends), str(mwin1_ins), str(mwin1_ends), ) logging.warning( "data wins - start:%s, end:%s / start:%s, end:%s", str(dwin0_ins), str(dwin0_ends), str(dwin1_ins), str(dwin1_ends), ) if nwins0 * nop[0] != dims[0] or nwins1 * nop[1] != dims[1]: raise ValueError("Model shape (dims=%s) is not consistent with chosen " "number of windows. Choose dims[0]=%d and " "dims[1]=%d for the operator to work with " "estimated number of windows, or create " "the operator with design=True to find out the" "optimal number of windows for the current " "model size..." % (str(dims), nwins0 * nop[0], nwins1 * nop[1])) # transform to apply if tapertype is None: OOp = BlockDiag([Op for _ in range(nwins)]) else: OOp = BlockDiag([ Diagonal(taps[itap].ravel(), dtype=Op.dtype) * Op for itap in range(nwins) ]) hstack = HStack([ Restriction( dimsd[1] * nwin[0], range(win_in, win_end), dims=(nwin[0], dimsd[1]), dir=1, dtype=Op.dtype, ).H for win_in, win_end in zip(dwin1_ins, dwin1_ends) ]) combining1 = BlockDiag([hstack] * nwins0) combining0 = HStack([ Restriction( np.prod(dimsd), range(win_in, win_end), dims=dimsd, dir=0, dtype=Op.dtype, ).H for win_in, win_end in zip(dwin0_ins, dwin0_ends) ]) Pop = combining0 * combining1 * OOp return Pop
def Marchenko_depthloop_IndepRadon(zinvs, zendvs): toff = 0.045 # direct arrival time shift nfmax = 550 # max frequency for MDC (#samples) nfft = 2**11 jr = 3 # subsampling in r # subsurface array xinvs = 600 # receiver array initial point in x xendvs = 2400 # receiver array last point in x dvsx = 20 # receiver array sampling in x dvsz = 5 # receiver array sampling in z # line of subsurface points for virtual sources vsx = np.arange(xinvs, xendvs + dvsx, dvsx) vsz = np.arange(zinvs, zendvs + dvsz, dvsz) # geometry nz = 401 oz = 0 dz = 4 z = np.arange(oz, oz + nz * dz, dz) nx = 751 ox = 0 dx = 4 x = np.arange(ox, ox + nx * dx, dx) # time axis ot = 0 nt = 1081 dt = 0.0025 t = np.arange(ot, ot + nt * dt, dt) # Receivers r = np.loadtxt(path0 + 'r.dat', delimiter=',') nr = r.shape[1] # Sources s = np.loadtxt(path0 + 's.dat', delimiter=',') ns = s.shape[1] ds = s[0, 1] - s[0, 0] # restriction operators iava = np.loadtxt(path0 + 'select_rfrac70.dat', delimiter=',', dtype=int) - 1 Restrop = Restriction(ns * (2 * nt - 1), iava, dims=(ns, 2 * nt - 1), dir=0, dtype='float64') # data print('Loading reflection data...') R = np.zeros((nt, ns, nr), 'f') for isrc in range(ns - 1): is_ = isrc * jr R[:, :, isrc] = np.loadtxt(path0 + 'R/dat1_' + str(is_) + '.dat', delimiter=',') R = 2 * np.swapaxes(R, 0, 2) # wavelet wav = np.loadtxt(path0 + 'wav.dat', delimiter=',') wav_c = wav[np.argmax(wav) - 60:np.argmax(wav) + 60] W = np.abs(np.fft.rfft(wav, nfft)) * dt # Convolution operators print('Creating MDC operators...') Rtwosided = np.concatenate((np.zeros((nr, ns, nt - 1)), R), axis=-1) R1twosided = np.concatenate((np.flip(R, axis=-1), np.zeros( (nr, ns, nt - 1))), axis=-1) Rtwosided_fft = np.fft.rfft(Rtwosided, 2 * nt - 1, axis=-1) / np.sqrt(2 * nt - 1) Rtwosided_fft = Rtwosided_fft[..., :nfmax] R1twosided_fft = np.fft.rfft(R1twosided, 2 * nt - 1, axis=-1) / np.sqrt(2 * nt - 1) R1twosided_fft = R1twosided_fft[..., :nfmax] Rop = MDC(Rtwosided_fft[iava], nt=2 * nt - 1, nv=1, dt=dt, dr=ds, twosided=True, dtype='complex64') R1op = MDC(R1twosided_fft[iava], nt=2 * nt - 1, nv=1, dt=dt, dr=ds, twosided=True, dtype='complex64') del wav, R, Rtwosided, R1twosided, Rtwosided_fft, R1twosided_fft # configuring radon transform nwin = 23 nwins = 14 nover = 10 npx = 101 pxmax = 0.006 px = np.linspace(-pxmax, pxmax, npx) t2 = np.concatenate([-t[::-1], t[1:]]) nt2 = t2.shape[0] dimsd = (nr, nt2) dimss = (nwins * npx, dimsd[1]) # sliding window radon with overlap RadOp = Radon2D(t2, np.linspace(-ds * nwin // 2, ds * nwin // 2, nwin), px, centeredh=True, kind='linear', engine='numba') Slidop = Sliding2D(RadOp, dimss, dimsd, nwin, nover, tapertype='cosine', design=True) Sparseop = BlockDiag([Slidop, Slidop]) del nwin, nwins, nover, npx, pxmax, px, t2, nt2, dimsd, dimss, RadOp, Slidop # the loop print('Entering loop...') z_steps = np.arange(zinvs, zendvs + 1, dvsz) for z_current in z_steps: redatuming_wrapper(toff, W, wav_c, iava, Rop, R1op, Restrop, Sparseop, vsx, vsz, x, z, z_current, nt, dt, nfft, nr, ds, dvsx)
perc_subsampling = 0.7 nysub = int(np.round(par["ny"] * perc_subsampling)) iava = np.sort(np.random.permutation(np.arange(par["ny"]))[:nysub]) taxis, taxis2, xaxis, yaxis = makeaxis(par) wav = ricker(taxis[:41], f0=par["f0"])[0] # 2d model _, x2d = linear2d(yaxis, taxis, v, t0, theta, amp, wav) _, x3d = linear3d(xaxis, yaxis, taxis, v, t0, theta, phi, amp, wav) # Create restriction operator Rop2d = Restriction(par["ny"] * par["nt"], iava, dims=(par["ny"], par["nt"]), dir=0, dtype="float64") y2d = Rop2d * x2d.ravel() y2d = y2d.reshape(nysub, par["nt"]) Rop3d = Restriction( par["ny"] * par["nx"] * par["nt"], iava, dims=(par["ny"], par["nx"], par["nt"]), dir=0, dtype="float64", ) y3d = Rop3d * x3d.ravel() y3d = y3d.reshape(nysub, par["nx"], par["nt"]) par1_2d = {
perc_subsampling = 0.7 nysub = int(np.round(par['ny'] * perc_subsampling)) iava = np.sort(np.random.permutation(np.arange(par['ny']))[:nysub]) taxis, taxis2, xaxis, yaxis = makeaxis(par) wav = ricker(taxis[:41], f0=par['f0'])[0] # 2d model _, x2d = linear2d(yaxis, taxis, v, t0, theta, amp, wav) _, x3d = linear3d(xaxis, yaxis, taxis, v, t0, theta, phi, amp, wav) # Create restriction operator Rop2d = Restriction(par['ny'] * par['nt'], iava, dims=(par['ny'], par['nt']), dir=0, dtype='float64') y2d = Rop2d * x2d.flatten() y2d = y2d.reshape(nysub, par['nt']) Rop3d = Restriction(par['ny'] * par['nx'] * par['nt'], iava, dims=(par['ny'], par['nx'], par['nt']), dir=0, dtype='float64') y3d = Rop3d * x3d.flatten() y3d = y3d.reshape(nysub, par['nx'], par['nt']) par1_2d = { 'kind': 'spatial', 'kwargs': dict(epsRs=[np.sqrt(0.1)],