def loadrsf(file_name):
    mat = m8r.Input('%s.rsf' % file_name)
    n1 = mat.int("n1")
    n2 = mat.int("n2")
    D = mat.read(shape=(n2, n1))
    shot = int(file_name[9:])
    return D, shot
Esempio n. 2
0
    def m8rInput(self):
        #model=m8r.Input('model.rsf')
        model=m8r.Input('foldplot1.rsf')
        self.vals = model[:,:,:]
        npts_x, npts_y, npts_z = self.vals.shape
        print("vals.shape=",self.vals.shape)

        self.min_x=model.float("o1")
        self.min_y=model.float("o2")
        self.min_z=model.float("o3")
        print("min x,y,z=",self.min_x,self.min_y,self.min_z)

        dx=model.float("d1")
        dy=model.float("d2")
        dz=model.float("d3")
        print("dx,dy,dz=",dx,dy,dz)

        self.max_x=self.min_x+dx*(npts_x-1)
        self.max_y=self.min_y+dy*(npts_y-1)
        self.max_z=self.min_z+dz*(npts_z-1)

        self.xs = linspace(self.min_x, self.max_x, self.npts_x)
        self.ys = linspace(self.min_y, self.max_y, self.npts_y)
        self.zs = linspace(self.min_z, self.max_z, self.npts_z)

        self.minval = nanmin(self.vals)
        self.maxval = nanmax(self.vals)
        self.model_changed = True
def loadrsf(file_name):
    mat = m8r.Input('/quanta1/home/ruan/OceanTurb_share_Jan2019/%s.rsf' % file_name)
    n1 = mat.int("n1")
    n2 = mat.int("n2")
    D = mat.read(shape=(n2,n1))
    shot = int(file_name[9:])
    return D, shot
Esempio n. 4
0
def generate_rsf_data(model_name="marm.rsf", central_freq=central_freq, dt=dt, dx=const.dx, 
                        nt=nt, sxbeg=sxbeg, gxbeg=gxbeg, szbeg=szbeg, 
                        jsx=jsx, jgx=jgx, jdt=jdt,
                        logs_out="logs.rsf", shots_out="shots_cmp.rsf",
                        full_shots_out=None): 
    
    #get size of the model
    model_orig = sf.Input(model_name)
    Nx = model_orig.int("n2")
    print(Nx)
    ns = (Nx - 2*sxbeg)//jgx 
    ng = 2*(sxbeg-gxbeg)//jgx + 1
    print(f"Total number of shots = {ns}")
    t_start = time.time()
    
    cmd((f"sfgenshots < {model_name} csdgather=y fm={central_freq} amp=1 dt={dt} ns={ns} ng={ng} nt={nt} "
                            f"sxbeg={sxbeg} chk=n szbeg=2 jsx={jgx} jsz=0 gxbeg={gxbeg} gzbeg={szbeg} jgx={jgx} jgz=0 > shots.rsf"))
    print(f"Modeling time for {ns} shots = {time.time()-t_start}")
    if full_shots_out != None:
        cmd(f"sfcp < shots.rsf > {full_shots_out}")

    #   ## Analyze and filter the data set generated
    # correct header and reduce sampling in time jdt (usually 4) times
    cmd(f"sfput < shots.rsf d3={jgx*dx} | sfwindow j1={jdt} | sfbandpass flo=2 fhi=4 > shots_decimated.rsf")
    cmd(f"sfrm shots.rsf")
    # sort into cmp gathers and discard odd cmps and not full cmps
    cmd(f"sfshot2cmp < shots_decimated.rsf half=n | sfwindow j3=2 min3={(-1.5*gxbeg+1.5*sxbeg)*dx} max3={(Nx-(2.5*sxbeg-.5*gxbeg))*dx} > {shots_out}")
    cmd(f"sfrm shots_decimated.rsf")
    # create the logs -- training outputs
    cmd(f"sfwindow < {model_name} min2={(-gxbeg+2*sxbeg)*dx} j2={jsx} max2={(Nx-(2*sxbeg-gxbeg))*dx} > {logs_out}")
    cmd(f"sfin < {logs_out}")
    return 0
Esempio n. 5
0
    def __init__(self, filename):
        super(SeisData, self).__init__()
        
        self.model=m8r.Input(filename)
        self.vals = self.model[:,:,:]
        print "vals.shape=",self.vals.shape
        for i in range(0,self.vals.shape[1]):
            print "max(vals[:,%d,:])="%i,max(self.vals[:,i,:])

        self.dim=len(self.vals.shape)
        self.axis_start=self.read_axis_float_info("o")
        print "self.axis_start=",self.axis_start
        self.axis_delta=self.read_axis_float_info("d")
        print "self.axis_delta=",self.axis_delta

        self.axis_end=[]
        for i in range(0,self.dim):
            self.axis_end.append(self.axis_start[i]+
                                 (self.vals.shape[i]-1)*self.axis_delta[i])
        print "self.axis_end=",self.axis_end
        
        print "compute min"
        self.minval = nanmin(self.vals)
        print "compute max"
        self.maxval = nanmax(self.vals)
        print "set model changed"
        self.model_changed = True
        print "leaving m8rInput"
Esempio n. 6
0
def read_rsf_to_np(shots_rsf='shots_cmp_full.rsf', logs_rsf='logs_full.rsf',
                  n_offsets=None, j_log_z=jlogz):
    shots_cmp = sf.Input(shots_rsf)
    X_data = shots_cmp.read()
    
    if n_offsets==None :
        X_data = X_data[:,:(np.shape(X_data)[1] + 1) // 2,:]
    
    X_data = np.expand_dims(X_data, axis=3)
    X_size = np.shape(X_data)
    logs = sf.Input(logs_rsf)
    T_data = logs.read()
    
    # decimate logs in vertical direction --2 times by default
    T_data = resize(T_data, (np.shape(T_data)[0], np.shape(T_data)[1] // j_log_z))
    T_size = np.shape(T_data)
    print(T_size)

    # ensure that the number of logs is equal to the number of CMPs
    assert (X_size[0] == T_size[0])
    return X_data, T_data
Esempio n. 7
0
    def m8rInput(self):
        #model=m8r.Input('model.rsf')
        # get files names from command line
        filenames=[]
        for parameter in sys.argv[1:]:
            print "processing parameter",parameter
            if parameter.find("=")==-1 :
                print "no = in parameter",parameter,"must be a file name"
                filenames.append(parameter)
        if len(filenames)<1:
            print "just to help me test, if there are no files in the list, "
            print "I will append the file foldplot1.rsf"
            filenames.append('foldplot1.rsf')

        model=m8r.Input(filenames[0])
        self.vals = model[:,:,:]
        # this makes seg fault in nanmin self.vals = model[:,:,::-1]
        npts_x, npts_y, npts_z = self.vals.shape
        print "vals.shape=",self.vals.shape

        self.min_x=model.float("o3")
        self.min_y=model.float("o2")
        self.min_z=model.float("o1")
        print "min x,y,z=",self.min_x,self.min_y,self.min_z
        
        dx=model.float("d3")
        dy=model.float("d2")
        dz=model.float("d1")
        print "dx,dy,dz=",dx,dy,dz

        self.max_x=self.min_x+dx*(npts_x-1)
        self.max_y=self.min_y+dy*(npts_y-1)
        self.max_z=self.min_z+dz*(npts_z-1)

        print "compute linspace"

        print "compute min"
        self.minval = nanmin(self.vals)
        print "compute max"
        self.maxval = nanmax(self.vals)
        print "set model changed"
        self.model_changed = True
        print "leaving m8rInput"
Esempio n. 8
0
    def __init__(self, filename):
        super(SeisData, self).__init__()

        self.model = m8r.Input(filename)
        self.vals = self.model[:, :, :]

        print "input file shape=", self.vals.shape
        self.dim = len(self.vals.shape)
        self.axis_start = self.read_axis_float_info("o")
        print "self.axis_start=", self.axis_start
        self.axis_delta = self.read_axis_float_info("d")
        print "self.axis_delta=", self.axis_delta

        self.axis_end = []
        for i in range(0, self.dim):
            self.axis_end.append(self.axis_start[i] +
                                 (self.vals.shape[i] - 1) * self.axis_delta[i])
        print "self.axis_end=", self.axis_end

        print "compute min/max"

        max_n_samples = 100
        inc = ones(self.dim, dtype=int)
        last = ones(self.dim, dtype=int)
        for i in range(0, self.dim):
            inc[i] = self.vals.shape[i] / 100
            #print "self.vals.shape=", self.vals.shape ,"inc=",inc
            if (inc[i] < 1):
                inc[i] = 1
            last[i] = (self.vals.shape[i] / inc[i] - 1) * inc[i]
            #print "self.vals.shape=", self.vals.shape
            #print "inc=",inc,"last=",last
        subsetvals = self.vals[:last[0]:inc[0], :last[1]:inc[1], :last[2]:
                               inc[2]]
        #print "subsetvals.shape=",subsetvals.shape
        mymin = min(subsetvals)
        mymax = max(subsetvals)
        print "min/max", mymin, mymax
        self.maxval = max([abs(mymin), mymax])
        self.minval = -self.maxval
        print "min=", self.minval, "max=", self.maxval

        print "leaving m8rInput"
Esempio n. 9
0
    def __init__(self, filename):
        super(SeisData, self).__init__()

        self.model = m8r.Input(filename)
        self.vals = self.model[:, :, :]

        self.dim = len(self.vals.shape)
        self.axis_start = self.read_axis_float_info("o")
        print("self.axis_start=", self.axis_start)
        self.axis_delta = self.read_axis_float_info("d")
        print("self.axis_delta=", self.axis_delta)

        self.axis_end = []
        for i in range(0, self.dim):
            self.axis_end.append(self.axis_start[i] +
                                 (self.vals.shape[i] - 1) * self.axis_delta[i])
        print("self.axis_end=", self.axis_end)

        print("compute min/max")

        max_n_samples = 100
        inc = ones(self.dim, dtype=int)
        last = ones(self.dim, dtype=int)
        for i in range(0, self.dim):
            inc[i] = self.vals.shape[i] / 100
            print("self.vals.shape=", self.vals.shape, "inc=", inc)
            if (inc[i] < 1):
                inc[i] = 1
            last[i] = (self.vals.shape[i] / inc[i] - 1) * inc[i]
            print("self.vals.shape=", self.vals.shape)
            print("inc=", inc, "last=", last)
        subsetvals = self.vals[:last[0]:inc[0], :last[1]:inc[1], :last[2]:
                               inc[2]]
        print("subsetvals.shape=", subsetvals.shape)
        self.minval = min(subsetvals)
        print("compute max")
        self.maxval = max(subsetvals)
        print("min=", self.minval)
        print("max=", self.maxval)

        print("leaving m8rInput")
Esempio n. 10
0
        self.c0  = -2.0*(self.c11+self.c12+self.c21+self.c22)
    
    def apply(self,uin,uout):
        n1,n2 = uin.shape
    
        uout[2:n1-2,2:n2-2] = \
         self.c11*(uin[1:n1-3,2:n2-2]+uin[3:n1-1,2:n2-2]) + \
         self.c12*(uin[0:n1-4,2:n2-2]+uin[4:n1  ,2:n2-2]) + \
         self.c21*(uin[2:n1-2,1:n2-3]+uin[2:n1-2,3:n2-1]) + \
         self.c22*(uin[2:n1-2,0:n2-4]+uin[2:n1-2,4:n2  ]) + \
         self.c0*uin[2:n1-2,2:n2-2]

par = m8r.Par()

# setup I/O files
Fr=m8r.Input()       # source position
Fo=m8r.Output()      # output wavefield

Fv=m8r.Input ("v")   # velocity
Fw=m8r.Input ("wav") # source wavefield


# Read/Write axes
a1 = Fr.axis(1); n1 = a1['n']; d1 = a1['d']
a2 = Fr.axis(2); n2 = a2['n']; d2 = a2['d']
at = Fw.axis(1); nt = at['n']; dt = at['d']

ft = par.int('ft',0)
jt = par.int('jt',0)

Fo.put('n3',(nt-ft)/jt)
Esempio n. 11
0
              if a < treshold])  # No. of elements with 0 alpha
    N3 = (N - N2) / 2  # No. of elements with nonzero alpha
    N4 = (N + N2) / 2

    # These next commands will taper alphas, so that no abrupt transition
    # between zero and nonzero elements occur
    window = np.kaiser(N - N2, 2)
    alphas[:N3] *= window[N3:]
    alphas[N4:] *= window[:N3]
    cmap._lut[:, -1] = alphas
    return cmap


if __name__ == "__main__":
    par = m8r.Par()
    inp = m8r.Input()
    shape = inp.shape()
    if len(shape) != 3:
        sf_error("Must have 3 axes")
    if inp.type != 'float':
        sf_error("Only supports float")
    bgf = par.string("bg",
                     None)  # Background for animation. Zero if not supplied
    if bgf:
        bg = m8r.Input(bgf)
        if bg.type != 'float':
            sf_error("Only supports float")
        bgshape = bg.shape()
        if len(bgshape) != 2 or bgshape != shape[1:]:
            sf_error(
                "Background must have the same two last dimensions of input")
Esempio n. 12
0
'''

# key imports
import m8r
import numpy as np
try:
   import varitools as vt
except:
    import rsf.user.varitools as vt

# the actual program...
par = m8r.Par()

# files
Fvel  = m8r.Input()
Fsemb = m8r.Input("semb")



assert 'float' == Fsemb.type
assert 'float' == Fvel.type

# get axis sampling
o1,d1,n1 = vt.get_axis(Fsemb,1)
o2,d2,n2 = vt.get_axis(Fsemb,2)
o3,d3,n3 = vt.get_axis(Fsemb,3)
# get number of velocities
ov,dv,nv = vt.get_axis(Fvel,3)

# put in helpful arrays
Esempio n. 13
0
# i do not think I want to have option to input data on stdin
#if not(os.isatty(file.fileno(sys.stdin))):
#    filenames.append("in")

for parameter in sys.argv[1:]:
    print("processing parameter", parameter)
    if parameter.find("=") == -1:
        print("no = in parameter")
        filenames.append(parameter)

if len(filenames) < 1:
    print("just to help me test, if there are no files in the list, I will")
    print("append the file:")
    print("/home/karl/m8r/madagascar-1.3/user/karl/model.rsf")
    filenames.append('/home/karl/m8r/madagascar-1.3/user/karl/model.rsf')

print("list of file names:", filenames)

fin = {}
for filename in filenames:
    fin[filename] = m8r.Input(filename)

nsubplot = 4

(n3, n2, n1) = fin[filename].shape()
for subplot in range(nsubplot):
    plt.subplot(1, nsubplot + 1, subplot + 1)
    plt.imshow(fin[filenames[0]][int(n3 * float(subplot) / nsubplot), :, :].T)

plt.show()
Esempio n. 14
0
#!/usr/bin/env python

import sys
import numpy
import m8r

c0 = -30. / 12.
c1 = +16. / 12.
c2 = -1. / 12.

par = m8r.Par()
verb = par.bool("verb", False)  # verbosity

# setup I/O files
Fw = m8r.Input()
Fv = m8r.Input("vel")
Fr = m8r.Input("ref")
Fo = m8r.Output()

# Read/Write axes
at = Fw.axis(1)
nt = at['n']
dt = at['d']
az = Fv.axis(1)
nz = az['n']
dz = az['d']
ax = Fv.axis(2)
nx = ax['n']
dx = ax['d']

Fo.putaxis(az, 1)
import numpy as np
import m8r
import pylops
from pylops.utils.seismicevents import makeaxis
from pylops.optimization.sparsity import *

mat = m8r.Input('dat_full-151.rsf')
n1 = mat.int("n1")
n2 = mat.int("n2")
D = mat.read(shape=(n2, n1))

D = D.T
nr, nt = D.shape
N = nt * nr
print(nr, nt)
# model parameters

par = {'ox': 0, 'dx': 10, 'nx': nr, 'ot': 0, 'dt': 0.0025, 'nt': nt}
taxis, t2, xaxis, y = makeaxis(par)
nx_mod = 1601
nz_mod = 801
dx_mod = 2.5
dx = 10
dz_mod = 2.5
nt_mod = 6001
dt_mod = 0.0005
dt = 0.0025

interval = 6
node = np.arange(0, nr, interval)
jitter = np.random.randint(interval, size=node.size - 1)
Esempio n. 16
0
def generate_model(model_input=c.trmodel,
                   model_output="marm.rsf",
                   dx=c.dx,
                   stretch_X=1,
                   training_flag=False,
                   random_state_number=c.random_state_number,
                   distort_flag=True,
                   crop_flag=True,
                   verbose=False,
                   test_flag=False,
                   show_flag=False):
    # downscale marmousi
    #def rescale_to_dx(rsf_file_in, rsf_file_out, dx)
    model_orig = sf.Input(model_input)
    vel = model_orig.read()

    if test_flag:
        n_cut = int(((const.sxbeg + const.gxbeg) * const.dx) //
                    (model_orig.float("d1")))
        vel = np.concatenate((vel[-n_cut:, :], np.flipud(vel), vel[:n_cut, :]),
                             axis=0)
    else:
        vel = np.concatenate((vel, np.flipud(vel), vel), axis=0)

    if show_flag:
        np.random.RandomState(random_state_number)
        random.seed(random_state_number)
        np.random.seed(random_state_number)

    if crop_flag:
        vel_log_res = vel
        #vel_log_res = resize(vel_log_res[:,:], (np.shape(vel)[0]//2, np.shape(vel)[1]//2))
        if verbose:
            print(f"Random state number = {random_state_number}")
        #vel = resize(vel_log_res, vel.shape)

        l0 = randint(np.shape(vel)[0])
        #print(f"l0={l0}")

        h0 = min(l0 + np.shape(vel)[0] // 4 + randint(np.shape(vel)[0] // 2),
                 np.shape(vel)[0])
        l1 = randint(np.shape(vel)[1] // 3)
        h1 = min(l1 + np.shape(vel)[1] // 3 + randint(np.shape(vel)[1] // 2),
                 np.shape(vel)[1])
        if verbose:
            print(l0, l1, h0, h1)
        vel_log_res = vel_log_res[l0:h0, l1:h1]

        vel = resize(vel_log_res, vel.shape)
    # we downscale
    scale_factor = dx / model_orig.float("d1")

    vel = resize(vel[:, :], (stretch_X * np.shape(vel)[0] // scale_factor,
                             np.shape(vel)[1] // scale_factor))

    if verbose:
        print(np.shape(vel))
        print(f"Model downscaled {scale_factor} times to {dx} meter sampling")
        if stretch_X != 1:
            print(
                f"Model stretched {stretch_X} times to {dx} meter sampling \n")

    # we concatenate horizontally, this is confusing because of flipped axis in madagascar

    vel = np.atleast_3d(vel)

    if distort_flag:
        vel = elastic_transform(vel,
                                alpha_deform,
                                sigma_deform,
                                v_dx=dx,
                                random_state_number=random_state_number)
    vel = np.squeeze(vel)

    if distort_flag:
        vel_alpha = (0.8 + 0.4 * resize(np.random.rand(5, 10), vel.shape))
        #print(vel_alpha)
        vel *= vel_alpha
    # add water
    # vel = np.concatenate((1500*np.ones((vel.shape[0], 20)), vel),
    #                      axis=1)
    #vel = ndimage.median_filter(vel, size=(7,3))
    #vel = 1500 * np.ones_like(vel)
    if verbose:
        print(f"Writing to {model_output}")

    np_to_rsf(vel, model_output)
    return vel
Esempio n. 17
0
'''

# key imports
import m8r
import numpy as np

try:
    import varitools as vt
except:
    import rsf.user.varitools as vt

# the actual program...
par = m8r.Par()

# files
Fsemb = m8r.Input()
# semblance volume
Fvel = m8r.Input("vo")
# starting model
Fdsemb = m8r.Input("dsemb")
# partial derivative of semblance volume with respect to v

assert 'float' == Fsemb.type
assert 'float' == Fvel.type
assert 'float' == Fdsemb.type

# get axis sampling
o1, d1, n1 = vt.get_axis(Fsemb, 1)
o2, d2, n2 = vt.get_axis(Fsemb, 2)
o3, d3, n3 = vt.get_axis(Fsemb, 3)
Esempio n. 18
0
#!/usr/bin/env python
import m8r
import matplotlib.pyplot as plt

model = m8r.Input('model.rsf')

model.grey(color='j', gainpanel='a', title='RSF').show()

plt.imshow(model[0, :, :])
plt.show()
Esempio n. 19
0
#!/usr/bin/env python

import numpy
import m8r
import sys
if sys.version_info[0] > 2:
    xrange = range

par = m8r.Par()
input  = m8r.Input()
output = m8r.Output()

n1 = input.int("n1") # trace length
n2 = input.size(1)   # number of traces

clip = par.float("clip")

trace = numpy.zeros(n1,'f')
for i2 in xrange(n2): # loop over traces
    input.read(trace)
    trace = numpy.clip(trace,-clip,clip)
    output.write(trace)
Esempio n. 20
0
def set_size(w, h, ax=None):
    """ w, h: width, height in inches """
    if not ax: ax = plt.gca()
    l = ax.figure.subplotpars.left
    r = ax.figure.subplotpars.right
    t = ax.figure.subplotpars.top
    b = ax.figure.subplotpars.bottom
    figw = float(w) / (r - l)
    figh = float(h) / (t - b)
    return figw, figh
    # ax.figure.set_size_inches(figw, figh)


if __name__ == "__main__":
    inp = m8r.Input()
    par = m8r.Par()
    # n1 = inp.int("n1")
    # n2 = inp.int("n2")
    (n1, d1, o1, u1, l1) = read_axis(inp, 1)
    (n2, d2, o2, u2, l2) = read_axis(inp, 2)
    ymax = o1 + d1 * (n1 - 1)
    xmax = o2 + d2 * (n2 - 1)

    data = np.zeros([n2, n1], 'f')
    inp.read(data)
    inp.close()

    savefile = par.string("savefile")
    cmap = par.string("cmap", 'gray')
    figx = par.float("figx", 3.66)  # Figure x size in inches, actually 8.46 cm
Esempio n. 21
0
#!/usr/bin/env python

import sys
import numpy
import m8r

# initialize
par = m8r.Par()
inp = m8r.Input()
out = m8r.Output()
oth = m8r.Input('other')

adj = par.bool('adj',False) # adjoint flag 

if adj:
    # input data, output filter
    n1 = inp.int('n1')
    n2 = inp.int('n2')
    nf = par.int('nf') # filter size

    out.put('n1',nf)
    out.put('n2',1)
else:
	# input filter, output data
    nf = inp.int('n1')
    n1 = oth.int('n1')
    n2 = oth.int('n2')

    out.put('n1',n1)
    out.put('n2',n2)
    
Esempio n. 22
0
def rsf_to_np(file_name):
    f = sf.Input(file_name)
    vel = f.read()
    return vel
Esempio n. 23
0
#!/usr/bin/env python

import numpy
from math import sqrt
import m8r

# initialize parameters
par = m8r.Par()

# input and output
vel = m8r.Input()
tim = m8r.Output()

# time axis from input
nt = vel.int('n1')
dt = vel.float('d1')

# offset axis from command line
nh = par.int('nh', 1)  # number of offsets
dh = par.float('dh', 0.01)  # offset sampling
h0 = par.float('h0', 0.0)  # first offset

# get reflectors
nr = par.int('nr', 1)  # number of reflectors
r = par.ints('r', nr)

type = par.string('type', 'hyperbolic')
# traveltime computation type

niter = par.int('niter', 10)
# maximum number of shooting iterations