コード例 #1
0
def proj_polar(N,mag,color='k',simbolo='o',size=10):
    
    '''
    Generates a figure of a polar projection of estimates
    
    input
    
    N: int - number of prisms
    
    mag: array - Matrix with shape (N x 3) containing intensity, declination and inclination
    
    proj: array - list of projection values
    
    return
    
    Figure with polar projections of the estimates
    
    '''
       
    projections = []
    for i in range(N):
        projections.append(np.sqrt((np.cos(np.deg2rad(mag[i,1]))*np.cos(np.deg2rad(mag[i,2])))**2 +(np.cos(np.deg2rad(mag[i,1]))*np.sin(np.deg2rad(mag[i,2])))**2))
        proj = np.array(projections)
    for i in range(N):
        if mag[i,1] >= 0.0:
            mpl.plot(np.deg2rad(mag[i,2]), proj[i], marker=simbolo, ms=size,mec= color, mew=3, mfc= color, fillstyle='full')
        else:
            mpl.plot(np.deg2rad(mag[i,2]), proj[i], marker=simbolo, ms=size, mec= color, mew=3, fillstyle='none') 
コード例 #2
0
def fwd_grav_fatiando():
    """
    GravMag: 3D imaging using the migration method on synthetic gravity data
    (more complex model + noisy data)
    """

    # Make some synthetic gravity data from a simple prism model
    za = 5000
    zb = 7000
    model = [mesher.Prism(-4000, 0, -4000, -2000, za, zb,
                          {'density': 1200})]  #,
    #         mesher.Prism(-1000, 1000, -1000, 1000, 1000, 7000, {'density': -800}),
    #         mesher.Prism(2000, 4000, 3000, 4000, 0, 2000, {'density': 600})]
    # Calculate on a scatter of points to show that migration doesn't need gridded
    # data
    # xp, yp, zp = gridder.scatter((-6000, 6000, -6000, 6000), 1000, z=0)
    shape = (25, 25)
    xp, yp, zp = gridder.regular((-5000, 5000, -5000, 5000), shape, z=0)

    #gz = utils.contaminate(prism.gz(xp, yp, zp, model), 0.1)
    gz = prism.gz(xp, yp, zp, model)

    # Plot the data
    shape = (50, 50)
    mpl.figure()
    mpl.axis('scaled')
    mpl.contourf(yp, xp, gz, shape, 30, interp=True)
    mpl.colorbar()
    mpl.plot(yp, xp, '.k')
    mpl.xlabel('East (km)')
    mpl.ylabel('North (km)')
    mpl.m2km()
    mpl.show()

    return xp, yp, zp, gz, shape, model
コード例 #3
0
def plot_vnmo(cmp_gather, offsets, vnmo, dt, inc=70,
              vmin=None, vmax=None, aspect='auto'):
    r"""
    Given nmo functions defined by t0 and vnmo, draw
    it over the specified gather using `seismic_image`

    Parameters:

    * cmp_gather : 2D-array
        traces of this gather from near to far-offset
        (nsamples, ntraces)
    * offsets : 1D-array
        off-sets for each cmp in this gather
        in the same sequence as ntraces
    * vnmo : 1D-array
        velocity parameter of all nmo functions for this cmp gather
        must have same size as (nsamples)
    * dt : float
        sample rate
    * inc: int
        plotting option, step in time samples between hyperbolas
        to avoid overlapping totally the seismic image bellow
    * vmin, vmax : float
        min and max values for imshow
    * aspect : float
        matplotlib imshow aspect parameter, ratio between axes


    Returns:

    * cmp_nmo : 2D array
        nmo corrected cmp traces

    """
    ns, nx = cmp_gather.shape

    for i in range(0, ns, inc): # each (t0, vnmo) hyperbola
        t0 = i*dt
        t = np.sqrt(t0**2+(offsets/vnmo[i])**2)
        mpl.seismic_image(cmp_gather, dt, aspect=aspect, vmin=vmin, vmax=vmax)
        mpl.plot(range(nx), t, '+b')
コード例 #4
0
maxit = int(duration/dt)
stations = [[75*ds, 125*ds]] # x, z coordinate of the seismometer
snapshots = 3 # every 3 iterations plots one
simulation = wavefd.scalar(velocity, area, dt, maxit, sources, stations, snapshots)

# This part makes an animation using matplotlibs animation API
background = (velocity-4000)*10**-1
fig = mpl.figure(figsize=(8, 6))
mpl.subplots_adjust(right=0.98, left=0.11, hspace=0.5, top=0.93)
mpl.subplot2grid((4, 3), (0,0), colspan=3,rowspan=3)
wavefield = mpl.imshow(np.zeros_like(velocity), extent=area, cmap=mpl.cm.gray_r,
                       vmin=-1000, vmax=1000)
mpl.points(stations, '^b', size=8)
mpl.ylim(area[2:][::-1])
mpl.xlabel('x (km)')
mpl.ylabel('z (km)')
mpl.m2km()
mpl.subplot2grid((4,3), (3,0), colspan=3)
seismogram1, = mpl.plot([],[],'-k')
mpl.xlim(0, duration)
mpl.ylim(-200, 200)
mpl.ylabel('Amplitude')
times = np.linspace(0, dt*maxit, maxit)
# This function updates the plot every few timesteps
def animate(i):
    t, u, seismogram = simulation.next()
    seismogram1.set_data(times[:t+1], seismogram[0][:t+1])
    wavefield.set_array(background[::-1]+u[::-1])
    return wavefield, seismogram1
anim = animation.FuncAnimation(fig, animate, frames=maxit/snapshots, interval=1)
mpl.show()
コード例 #5
0
"""
GravMag: Generate synthetic gravity data on an irregular grid
"""
from fatiando import mesher, gridder, gravmag
from fatiando.vis import mpl

prisms = [mesher.Prism(-2000, 2000, -2000, 2000, 0, 2000, {'density':1000})]
xp, yp, zp = gridder.scatter((-5000, 5000, -5000, 5000), n=100, z=-100)
gz = gravmag.prism.gz(xp, yp, zp, prisms)

shape = (100,100)
mpl.axis('scaled')
mpl.title("gz produced by prism model on an irregular grid (mGal)")
mpl.plot(xp, yp, '.k', label='Grid points')
levels = mpl.contourf(xp, yp, gz, shape, 12, interp=True)
mpl.contour(xp, yp, gz, shape, levels, interp=True)
mpl.legend(loc='lower right', numpoints=1)
mpl.m2km()
mpl.show()
コード例 #6
0
tts, error = utils.contaminate(layered_straight_ray(thickness, velocity, zp),
                               0.02,
                               percent=True,
                               return_stddev=True)
# Make the solver and run the inversion using damping regularization
# (assumes known thicknesses of the layers)
solver = (LayeredStraight(tts, zp, thickness) +
          0.1 * Damping(len(thickness))).fit()
velocity_ = solver.estimate_

# Plot the results
mpl.figure(figsize=(12, 5))
mpl.subplot(1, 2, 1)
mpl.grid()
mpl.title("Vertical seismic profile")
mpl.plot(tts, zp, 'ok', label='Observed')
mpl.plot(solver[0].predicted(), zp, '-r', linewidth=3, label='Predicted')
mpl.legend(loc='upper right', numpoints=1)
mpl.xlabel("Travel-time (s)")
mpl.ylabel("Z (m)")
mpl.ylim(sum(thickness), 0)
mpl.subplot(1, 2, 2)
mpl.grid()
mpl.title("Velocity profile")
mpl.layers(thickness, velocity_, 'o-k', linewidth=2, label='Estimated')
mpl.layers(thickness, velocity, '--b', linewidth=2, label='True')
mpl.ylim(zmax, zmin)
mpl.xlim(vmin, vmax)
leg = mpl.legend(loc='upper right', numpoints=1)
leg.get_frame().set_alpha(0.5)
mpl.xlabel("Velocity (m/s)")
コード例 #7
0
from fatiando.vis import mpl

verts = [(10000, 1.), (90000, 1.), (80000, 5000)]
model = mesher.Polygon(verts, {'density': -100})
xp = numpy.arange(0., 100000., 1000.)
zp = numpy.zeros_like(xp)
gz = utils.contaminate(gravmag.talwani.gz(xp, zp, [model]), 1)

solver = inversion.gradient.levmarq(initial=(10000, 1000))
estimate, residuals = gravmag.basin2d.triangular(xp, zp, gz, verts[0:2], -100,
                                                 solver)

mpl.figure()
mpl.subplot(2, 1, 1)
mpl.title("Gravity anomaly")
mpl.plot(xp, gz, 'ok', label='Observed')
mpl.plot(xp, gz - residuals, '-r', linewidth=2, label='Predicted')
mpl.legend(loc='lower left')
mpl.ylabel("mGal")
mpl.xlim(0, 100000)
mpl.subplot(2, 1, 2)
mpl.polygon(estimate,
            'o-r',
            linewidth=2,
            fill='r',
            alpha=0.3,
            label='Estimated')
mpl.polygon(model, '--k', linewidth=2, label='True')
mpl.legend(loc='lower left', numpoints=1)
mpl.xlabel("X")
mpl.ylabel("Z")
コード例 #8
0
x, y = gridder.scatter((-2, 2, -2, 2), n=300, seed=1)


# And calculate 2D Gaussians on these points as sample data
def data(x, y):
    return (utils.gaussian2d(x, y, -0.6, -1) -
            utils.gaussian2d(x, y, 1.5, 1.5))


d = data(x, y)

# Extract a profile along the diagonal
p1, p2 = [-1.5, 0], [1.5, 1.5]
xp, yp, distance, dp = gridder.profile(x, y, d, p1, p2, 100)
dp_true = data(xp, yp)

mpl.figure()
mpl.subplot(2, 1, 2)
mpl.title("Irregular grid")
mpl.plot(xp, yp, '-k', label='Profile', linewidth=2)
mpl.contourf(x, y, d, (100, 100), 50, interp=True)
mpl.colorbar(orientation='horizontal')
mpl.legend(loc='lower right')
mpl.subplot(2, 1, 1)
mpl.title('Profile')
mpl.plot(distance, dp, '.b', label='Extracted')
mpl.plot(distance, dp_true, '-k', label='True')
mpl.xlim(distance.min(), distance.max())
mpl.legend(loc='lower right')
mpl.show()
コード例 #9
0
ファイル: grid_interpolate.py プロジェクト: peace001/fatiando
def data(x, y):
    return utils.gaussian2d(x, y, -0.6, -1) - utils.gaussian2d(x, y, 1.5, 1.5)


z = data(x, y)

shape = (100, 100)

# First, we need to know the real data at the grid points
grdx, grdy = gridder.regular(area, shape)
grdz = data(grdx, grdy)
mpl.figure()
mpl.subplot(2, 2, 1)
mpl.axis("scaled")
mpl.title("True grid data")
mpl.plot(x, y, ".k", label="Data points")
mpl.contourf(grdx, grdy, grdz, shape, 50)
mpl.colorbar()
mpl.legend(loc="lower right", numpoints=1)

# Use the default interpolation (cubic)
grdx, grdy, grdz = gridder.interp(x, y, z, shape)
mpl.subplot(2, 2, 2)
mpl.axis("scaled")
mpl.title("Interpolated using cubic minimum-curvature")
mpl.plot(x, y, ".k", label="Data points")
mpl.contourf(grdx, grdy, grdz, shape, 50)
mpl.colorbar()
mpl.legend(loc="lower right", numpoints=1)

# Use the nearest neighbors interpolation
コード例 #10
0
                               snapshot, padding=50, taper=0.01)

# This part makes an animation using matplotlibs animation API
fig = mpl.figure(figsize=(14, 5))
ax = mpl.subplot(1, 2, 2)
mpl.title('Wavefield')
# Start with everything zero and grab the plot so that it can be updated later
wavefield_plt = mpl.imshow(np.zeros(shape), extent=area, vmin=-10 ** (-5),
                           vmax=10 ** (-5), cmap=mpl.cm.gray_r)
mpl.points(stations, '^b')
mpl.xlim(area[:2])
mpl.ylim(area[2:][::-1])
mpl.xlabel('x (km)')
mpl.ylabel('z (km)')
mpl.subplot(1, 2, 1)
seismogram_plt, = mpl.plot([], [], '-k')
mpl.xlim(0, duration)
mpl.ylim(-10 ** (-4), 10 ** (-4))
mpl.xlabel('time (s)')
mpl.ylabel('Amplitude')
times = np.linspace(0, duration, maxit)
# Update the plot everytime the simulation yields


def animate(i):
    """
    Grab the iteration number, displacment panel and seismograms
    """
    t, u, seismograms = simulation.next()
    mpl.title('time: %0.1f s' % (times[t]))
    wavefield_plt.set_array(u[::-1])  # Revert the z axis so that 0 is top
コード例 #11
0
# Make some synthetic gravity data from a simple prism model
model = [mesher.Prism(-4000, 0, -4000, -2000, 2000, 5000, {'density': 1200}),
         mesher.Prism(-1000, 1000, -1000, 1000, 1000, 7000, {'density': -800}),
         mesher.Prism(2000, 4000, 3000, 4000, 0, 2000, {'density': 600})]
# Calculate on a scatter of points to show that migration doesn't need gridded
# data
xp, yp, zp = gridder.scatter((-6000, 6000, -6000, 6000), 1000, z=-10)
gz = utils.contaminate(prism.gz(xp, yp, zp, model), 0.1)

# Plot the data
shape = (50, 50)
mpl.figure()
mpl.axis('scaled')
mpl.contourf(yp, xp, gz, shape, 30, interp=True)
mpl.colorbar()
mpl.plot(yp, xp, '.k')
mpl.xlabel('East (km)')
mpl.ylabel('North (km)')
mpl.m2km()
mpl.show()

mesh = imaging.migrate(xp, yp, zp, gz, 0, 10000, (30, 30, 30), power=0.8)

# Plot the results
myv.figure()
myv.prisms(model, 'density', style='wireframe', linewidth=2)
myv.prisms(mesh, 'density', edges=False)
axes = myv.axes(myv.outline())
myv.wall_bottom(axes.axes.bounds)
myv.wall_north(axes.axes.bounds)
myv.show()
コード例 #12
0
# Get the iterator. This part only generates an iterator object. The actual
# computations take place at each iteration in the for loop below
dt = wavefd.maxdt(area, shape, svel.max())
duration = 250
maxit = int(duration / dt)
stations = [[100000, 0], [700000, 0]]
snapshots = int(1.0 / dt)
simulation = wavefd.elastic_sh(mu, density, area, dt, maxit, sources, stations, snapshots, padding=70, taper=0.005)

# This part makes an animation using matplotlibs animation API
background = svel * 5 * 10 ** -7
fig = mpl.figure(figsize=(10, 8))
mpl.subplots_adjust(right=0.98, left=0.11, hspace=0.3, top=0.93)
mpl.subplot(3, 1, 1)
mpl.title("Seismogram 1")
seismogram1, = mpl.plot([], [], "-k")
mpl.xlim(0, duration)
mpl.ylim(-0.1, 0.1)
mpl.ylabel("Amplitude")
mpl.subplot(3, 1, 2)
mpl.title("Seismogram 2")
seismogram2, = mpl.plot([], [], "-k")
mpl.xlim(0, duration)
mpl.ylim(-0.1, 0.1)
mpl.ylabel("Amplitude")
ax = mpl.subplot(3, 1, 3)
mpl.title("time: 0.0 s")
wavefield = mpl.imshow(background, extent=area, cmap=mpl.cm.gray_r, vmin=-0.005, vmax=0.005)
mpl.points(stations, "^b", size=8)
mpl.text(750000, 20000, "Crust")
mpl.text(740000, 100000, "Mantle")
コード例 #13
0
"""
from fatiando import mesher, gridder, utils, gravmag
from fatiando.vis import mpl

spheres = [mesher.Sphere(0, 0, 2000, 1000, {'density': 1000})]
# Create a set of points at 100m height
area = (-5000, 5000, -5000, 5000)
xp, yp, zp = gridder.scatter(area, 500, z=-100)
# Calculate the anomaly
gz = utils.contaminate(gravmag.sphere.gz(xp, yp, zp, spheres), 0.1)
gzz = utils.contaminate(gravmag.sphere.gzz(xp, yp, zp, spheres), 5.0)
# Plot
shape = (100, 100)
mpl.figure()
mpl.title("gz (mGal)")
mpl.axis('scaled')
mpl.plot(yp * 0.001, xp * 0.001, '.k')
mpl.contourf(yp * 0.001, xp * 0.001, gz, shape, 15, interp=True)
mpl.colorbar()
mpl.xlabel('East y (km)')
mpl.ylabel('North x (km)')
mpl.figure()
mpl.title("gzz (Eotvos)")
mpl.axis('scaled')
mpl.plot(yp * 0.001, xp * 0.001, '.k')
mpl.contourf(yp * 0.001, xp * 0.001, gzz, shape, 15, interp=True)
mpl.colorbar()
mpl.xlabel('East y (km)')
mpl.ylabel('North x (km)')
mpl.show()
コード例 #14
0
fig = mpl.figure(figsize=(14, 5))
ax = mpl.subplot(1, 2, 2)
mpl.title('Wavefield')
# Start with everything zero and grab the plot so that it can be updated later
wavefield_plt = mpl.imshow(np.zeros(shape),
                           extent=area,
                           vmin=-10**(-5),
                           vmax=10**(-5),
                           cmap=mpl.cm.gray_r)
mpl.points(stations, '^b')
mpl.xlim(area[:2])
mpl.ylim(area[2:][::-1])
mpl.xlabel('x (km)')
mpl.ylabel('z (km)')
mpl.subplot(1, 2, 1)
seismogram_plt, = mpl.plot([], [], '-k')
mpl.xlim(0, duration)
mpl.ylim(-10**(-4), 10**(-4))
mpl.xlabel('time (s)')
mpl.ylabel('Amplitude')
times = np.linspace(0, duration, maxit)
# Update the plot everytime the simulation yields


def animate(i):
    """
    Grab the iteration number, displacment panel and seismograms
    """
    t, u, seismograms = simulation.next()
    mpl.title('time: %0.1f s' % (times[t]))
    wavefield_plt.set_array(u[::-1])  # Revert the z axis so that 0 is top
コード例 #15
0
    return (utils.gaussian2d(x, y, -0.6, -1) -
            utils.gaussian2d(x, y, 1.5, 1.5))


z = data(x, y)

shape = (100, 100)

# First, we need to know the real data at the grid points
grdx, grdy = gridder.regular(area, shape)
grdz = data(grdx, grdy)
mpl.figure()
mpl.subplot(2, 2, 1)
mpl.axis('scaled')
mpl.title("True grid data")
mpl.plot(x, y, '.k', label='Data points')
mpl.contourf(grdx, grdy, grdz, shape, 50)
mpl.colorbar()
mpl.legend(loc='lower right', numpoints=1)

# Use the default interpolation (cubic)
grdx, grdy, grdz = gridder.interp(x, y, z, shape)
mpl.subplot(2, 2, 2)
mpl.axis('scaled')
mpl.title("Interpolated using cubic minimum-curvature")
mpl.plot(x, y, '.k', label='Data points')
mpl.contourf(grdx, grdy, grdz, shape, 50)
mpl.colorbar()
mpl.legend(loc='lower right', numpoints=1)

# Use the nearest neighbors interpolation
コード例 #16
0
verts = [(10000, 1.), (90000, 1.), (90000, 7000), (10000, 3330)]
model = Polygon(verts, {'density': -100})
x = numpy.arange(0., 100000., 1000.)
z = numpy.zeros_like(x)
gz = utils.contaminate(talwani.gz(x, z, [model]), 0.5)

solver = basin2d.Trapezoidal(x, z, gz, verts[0:2],
                             density=-100).config('levmarq',
                                                  initial=[9000, 500]).fit()
estimate = solver.estimate_

mpl.figure()
mpl.subplot(2, 1, 1)
mpl.title("Gravity anomaly")
mpl.plot(x, gz, 'ok', label='Observed')
mpl.plot(x, solver.predicted(), '-r', linewidth=2, label='Predicted')
mpl.legend(loc='lower left', numpoints=1)
mpl.ylabel("mGal")
mpl.xlim(0, 100000)
mpl.subplot(2, 1, 2)
mpl.polygon(estimate,
            'o-r',
            linewidth=2,
            fill='r',
            alpha=0.3,
            label='Estimated')
mpl.polygon(model, '--k', linewidth=2, label='True')
mpl.legend(loc='lower left', numpoints=1)
mpl.xlabel("X")
mpl.ylabel("Z")
コード例 #17
0
"""
GravMag: Generate synthetic gravity data on an irregular grid
"""
from fatiando import mesher, gridder, gravmag
from fatiando.vis import mpl

prisms = [mesher.Prism(-2000, 2000, -2000, 2000, 0, 2000, {'density': 1000})]
xp, yp, zp = gridder.scatter((-5000, 5000, -5000, 5000), n=100, z=-100)
gz = gravmag.prism.gz(xp, yp, zp, prisms)

shape = (100, 100)
mpl.axis('scaled')
mpl.title("gz produced by prism model on an irregular grid (mGal)")
mpl.plot(xp, yp, '.k', label='Grid points')
levels = mpl.contourf(xp, yp, gz, shape, 12, interp=True)
mpl.contour(xp, yp, gz, shape, levels, interp=True)
mpl.legend(loc='lower right', numpoints=1)
mpl.m2km()
mpl.show()
from fatiando.gravmag import talwani, basin2d
from fatiando.vis import mpl

verts = [(10000, 1.), (90000, 1.), (90000, 7000), (10000, 3330)]
model = Polygon(verts, {'density':-100})
x = numpy.arange(0., 100000., 1000.)
z = numpy.zeros_like(x)
gz = utils.contaminate(talwani.gz(x, z, [model]), 0.5)

solver = basin2d.Trapezoidal(x, z, gz, verts[0:2], density=-100).config(
        'levmarq', initial=[9000, 500]).fit()
estimate = solver.estimate_

mpl.figure()
mpl.subplot(2, 1, 1)
mpl.title("Gravity anomaly")
mpl.plot(x, gz, 'ok', label='Observed')
mpl.plot(x, solver.predicted(), '-r', linewidth=2, label='Predicted')
mpl.legend(loc='lower left', numpoints=1)
mpl.ylabel("mGal")
mpl.xlim(0, 100000)
mpl.subplot(2, 1, 2)
mpl.polygon(estimate, 'o-r', linewidth=2, fill='r',
    alpha=0.3, label='Estimated')
mpl.polygon(model, '--k', linewidth=2, label='True')
mpl.legend(loc='lower left', numpoints=1)
mpl.xlabel("X")
mpl.ylabel("Z")
mpl.set_area((0, 100000, 10000, -500))
mpl.show()
コード例 #19
0
depths = (-1e-15*(xs - 50000)**4 + 8000 -
          3000*np.exp(-(xs - 70000)**2/(10000**2)))
depths -= depths.min()  # Reduce depths to zero
props = {'density': -300}
model = Polygon(np.transpose([xs, depths]), props)
x = np.linspace(0, 100000, 100)
z = -100*np.ones_like(x)
data = utils.contaminate(talwani.gz(x, z, [model]), 0.5, seed=0)

# Make the solver using smoothness regularization and run the inversion
misfit = PolygonalBasinGravity(x, z, data, 50, props, top=0)
regul = Smoothness1D(misfit.nparams)
solver = misfit + 1e-4*regul
# This is a non-linear problem so we need to pick an initial estimate
initial = 3000*np.ones(misfit.nparams)
solver.config('levmarq', initial=initial).fit()

mpl.figure()
mpl.subplot(2, 1, 1)
mpl.plot(x, data, 'ok', label='observed')
mpl.plot(x, solver[0].predicted(), '-r', linewidth=2, label='predicted')
mpl.legend()
ax = mpl.subplot(2, 1, 2)
mpl.polygon(model, fill='gray', alpha=0.5, label='True')
# The estimate_ property of our solver gives us the estimate basin as a polygon
# So we can directly pass it to plotting and forward modeling functions
mpl.polygon(solver.estimate_, style='o-r', label='Estimated')
ax.invert_yaxis()
mpl.legend()
mpl.show()
コード例 #20
0
# Get the iterator for the simulation
dt = wavefd.maxdt(area, shape, pvel)
duration = 20
maxit = int(duration / dt)
stations = [[55000, 0]]  # x, z coordinate of the seismometer
snapshot = int(0.5 / dt)  # Plot a snapshot of the simulation every 0.5 seconds
simulation = wavefd.elastic_psv(lamb, mu, density, area, dt, maxit, sources,
                                stations, snapshot, padding=50, taper=0.01,
                                xz2ps=True)

# This part makes an animation using matplotlibs animation API
fig = mpl.figure(figsize=(12, 5))
mpl.subplot(2, 2, 2)
mpl.title('x component')
xseismogram, = mpl.plot([], [], '-k')
mpl.xlim(0, duration)
mpl.ylim(-10 ** (-3), 10 ** (-3))
mpl.subplot(2, 2, 4)
mpl.title('z component')
zseismogram, = mpl.plot([], [], '-k')
mpl.xlim(0, duration)
mpl.ylim(-10 ** (-3), 10 ** (-3))
mpl.subplot(1, 2, 1)
# Start with everything zero and grab the plot so that it can be updated later
wavefield = mpl.imshow(np.zeros(shape), extent=area, vmin=-10 ** -6,
                       vmax=10 ** -6, cmap=mpl.cm.gray_r)
mpl.points(stations, '^k')
mpl.ylim(area[2:][::-1])
mpl.xlabel('x (km)')
mpl.ylabel('z (km)')
コード例 #21
0
ファイル: grid_profile.py プロジェクト: SamuelMarks/fatiando
# Generate random points
x, y = gridder.scatter((-2, 2, -2, 2), n=300, seed=1)
# And calculate 2D Gaussians on these points as sample data
def data(x, y):
    return (utils.gaussian2d(x, y, -0.6, -1)
            - utils.gaussian2d(x, y, 1.5, 1.5))


d = data(x, y)

# Extract a profile along the diagonal
p1, p2 = [-1.5, 0], [1.5, 1.5]
xp, yp, distance, dp = gridder.profile(x, y, d, p1, p2, 100)
dp_true = data(xp, yp)

mpl.figure()
mpl.subplot(2, 1, 2)
mpl.title("Irregular grid")
mpl.plot(xp, yp, '-k', label='Profile', linewidth=2)
mpl.contourf(x, y, d, (100, 100), 50, interp=True)
mpl.colorbar(orientation='horizontal')
mpl.legend(loc='lower right')
mpl.subplot(2, 1, 1)
mpl.title('Profile')
mpl.plot(distance, dp, '.b', label='Extracted')
mpl.plot(distance, dp_true, '-k', label='True')
mpl.xlim(distance.min(), distance.max())
mpl.legend(loc='lower right')
mpl.show()
コード例 #22
0
# And calculate 2D Gaussians on these points as sample data
def data(x, y):
    return (utils.gaussian2d(x, y, -0.6, -1)
            - utils.gaussian2d(x, y, 1.5, 1.5))
z = data(x, y)

shape = (100, 100)

# First, we need to know the real data at the grid points
grdx, grdy = gridder.regular(area, shape)
grdz = data(grdx, grdy)
mpl.figure()
mpl.subplot(2, 2, 1)
mpl.axis('scaled')
mpl.title("True grid data")
mpl.plot(x, y, '.k', label='Data points')
mpl.contourf(grdx, grdy, grdz, shape, 50)
mpl.colorbar()
mpl.legend(loc='lower right', numpoints=1)

# Use the default interpolation (cubic)
grdx, grdy, grdz = gridder.interp(x, y, z, shape)
mpl.subplot(2, 2, 2)
mpl.axis('scaled')
mpl.title("Interpolated using cubic minimum-curvature")
mpl.plot(x, y, '.k', label='Data points')
mpl.contourf(grdx, grdy, grdz, shape, 50)
mpl.colorbar()
mpl.legend(loc='lower right', numpoints=1)

# Use the nearest neighbors interpolation
from fatiando import utils, mesher
from fatiando.gravmag import talwani
from fatiando.vis import mpl

# Notice that the last two number are switched.
# This way, the z axis in the plots points down.
area = (-5000, 5000, 5000, 0)
axes = mpl.figure().gca()
mpl.xlabel("X")
mpl.ylabel("Z")
mpl.axis('scaled')
polygons = [mesher.Polygon(mpl.draw_polygon(area, axes),
                              {'density':500})]
xp = numpy.arange(-4500, 4500, 100)
zp = numpy.zeros_like(xp)
gz = talwani.gz(xp, zp, polygons)

mpl.figure()
mpl.axis('scaled')
mpl.subplot(2,1,1)
mpl.title(r"Gravity anomaly produced by the model")
mpl.plot(xp, gz, '-k', linewidth=2)
mpl.ylabel("mGal")
mpl.xlim(-5000, 5000)
mpl.subplot(2,1,2)
mpl.polygon(polygons[0], 'o-k', linewidth=2, fill='k', alpha=0.5)
mpl.xlabel("X")
mpl.ylabel("Z")
mpl.set_area(area)
mpl.show()
tts, error = utils.contaminate(
    layered_straight_ray(thickness, velocity, zp),
    0.02, percent=True, return_stddev=True)
# Assume that the thicknesses are unknown. In this case, use a mesh of many
# thin layers and invert for each slowness
thick = 10.
mesh = [thick]*int(sum(thickness)/thick)
solver = (LayeredStraight(tts, zp, mesh) +
          5*Smoothness1D(len(mesh))).fit()
velocity_ = solver.estimate_

mpl.figure(figsize=(12,5))
mpl.subplot(1, 2, 1)
mpl.grid()
mpl.title("Vertical seismic profile")
mpl.plot(tts, zp, 'ok', label='Observed')
mpl.plot(solver.predicted(), zp, '-r', linewidth=3, label='Predicted')
mpl.legend(loc='upper right', numpoints=1)
mpl.xlabel("Travel-time (s)")
mpl.ylabel("Z (m)")
mpl.ylim(sum(mesh), 0)
mpl.subplot(1, 2, 2)
mpl.grid()
mpl.title("True velocity + smooth estimate")
mpl.layers(mesh, velocity_, '.-k', linewidth=2, label='Estimated')
mpl.layers(thickness, velocity, '--b', linewidth=2, label='True')
mpl.ylim(sum(mesh), 0)
mpl.xlim(0, 10000)
mpl.legend(loc='upper right', numpoints=1)
mpl.xlabel("Velocity (m/s)")
mpl.ylabel("Z (m)")
コード例 #25
0
from fatiando.geothermal.climsig import abrupt, SingleChange
from fatiando.vis import mpl

# Generating synthetic data using an ABRUPT model
amp = 3
age = 54
# along a well at these depths
zp = numpy.arange(0, 100, 1)
temp, error = utils.contaminate(abrupt(amp, age, zp),
                                0.02,
                                percent=True,
                                return_stddev=True)

# Preparing for the inversion
data = SingleChange(temp, zp, mode='linear').config('levmarq', initial=[1, 1])
amp_, age_ = data.fit().estimate_

print "Trying to invert an abrupt change as linear"
print "  true:      amp=%.3f age=%.3f" % (amp, age)
print "  estimated: amp=%.3f age=%.3f" % (amp_, age_)

mpl.figure(figsize=(4, 5))
mpl.title("Residual well temperature")
mpl.plot(temp, zp, 'ok', label='Observed')
mpl.plot(data.predicted(), zp, '--r', linewidth=3, label='Predicted')
mpl.legend(loc='lower right', numpoints=1)
mpl.xlabel("Temperature (C)")
mpl.ylabel("Z (m)")
mpl.ylim(100, 0)
mpl.show()
コード例 #26
0
# Generating synthetic data using an ABRUPT model
amp = 3
age = 54
zp = numpy.arange(0, 100, 1)
temp, error = utils.contaminate(climsig.abrupt(amp, age, zp),
    0.02, percent=True, return_stddev=True)

# Preparing for the inversion assuming that the change was LINEAR
p, residuals = climsig.ilinear(temp, zp)
est_amp, est_age = p

mpl.figure(figsize=(12,5))
mpl.subplot(1, 2, 1)
mpl.title("Climate signal\n(true is abrupt but inverted using linear)")
mpl.plot(temp, zp, 'ok', label='Observed')
mpl.plot(temp - residuals, zp, '--r', linewidth=3, label='Predicted')
mpl.legend(loc='lower right', numpoints=1)
mpl.xlabel("Temperature (C)")
mpl.ylabel("Z")
mpl.ylim(100, 0)
ax = mpl.subplot(1, 2, 2)
ax2 = mpl.twinx()
mpl.title("Age and amplitude")
width = 0.3
ax.bar([1 - width], [age], width, color='b', label="True")
ax.bar([1], [est_age], width, color='r', label="Estimate")
ax2.bar([2 - width], [amp], width, color='b')
ax2.bar([2], [est_amp], width, color='r')
ax.legend(loc='upper center', numpoints=1)
ax.set_ylabel("Age (years)")
コード例 #27
0
points2pad = raw_input("\nAmmount of spectrum points (default = "+
                    str(default_spectrum_points) + ", 0 means no padding): ")
if points2pad == "":
    points2pad = default_spectrum_points
else:
    points2pad = int(points2pad)
points2pad *= 2


# Seleccion de la ventana
bool_plot = False
while bool_plot == False:
    fig, (ax1,ax2) = plt.subplots(1,2)
    ax2.set_aspect('equal')
    if tmp_exists == True:
        mpl.plot(x_last_point,y_last_point,'o',color='w')
    if outfile_exists == True:
        mpl.plot(x_done_points[:-1],y_done_points[:-1],'o',color='k')
        mpl.plot(x_done_points[-1],y_done_points[-1],'s',color='k')
    mpl.contourf(x,y,anomaly,shape,50,interp=False)
    mpl.colorbar()
    window = WindowConstruction(x,y,shape,anomaly,ax2,ax1,points2pad)
    mpl.show()
    
    if window.x_center != None:
        bool_plot = True
    
# Recupero los datos de la ventana
x_center, y_center = window.x_center, window.y_center
width = 2*window.half_width
print "(x,y)=",(x_center,y_center),"Width:",width
コード例 #28
0
                                density,
                                area,
                                dt,
                                maxit,
                                sources,
                                stations,
                                snapshot,
                                padding=50,
                                taper=0.01,
                                xz2ps=True)

# This part makes an animation using matplotlibs animation API
fig = mpl.figure(figsize=(12, 5))
mpl.subplot(2, 2, 2)
mpl.title('x component')
xseismogram, = mpl.plot([], [], '-k')
mpl.xlim(0, duration)
mpl.ylim(-10**(-3), 10**(-3))
mpl.subplot(2, 2, 4)
mpl.title('z component')
zseismogram, = mpl.plot([], [], '-k')
mpl.xlim(0, duration)
mpl.ylim(-10**(-3), 10**(-3))
mpl.subplot(1, 2, 1)
# Start with everything zero and grab the plot so that it can be updated later
wavefield = mpl.imshow(np.zeros(shape),
                       extent=area,
                       vmin=-10**-6,
                       vmax=10**-6,
                       cmap=mpl.cm.gray_r)
mpl.points(stations, '^k')
コード例 #29
0
ファイル: grid_scatter.py プロジェクト: zyex1108/fatiando
"""
Gridding: Generate and plot irregular grids (scatter)
"""
from fatiando import gridder, utils
from fatiando.vis import mpl

# Generate random points
x, y = gridder.scatter((-2, 2, -2, 2), n=200)
# And calculate a 2D Gaussian on these points
z = utils.gaussian2d(x, y, 1, 1)

mpl.axis('scaled')
mpl.title("Irregular grid")
mpl.plot(x, y, '.k', label='Grid points')
# Make a filled contour plot and tell the function to automatically interpolate
# the data on a 100x100 grid
mpl.contourf(x, y, z, (100, 100), 50, interp=True)
mpl.colorbar()
mpl.legend(loc='lower right', numpoints=1)
mpl.show()
コード例 #30
0
log.info("Generating synthetic data")
verts = [(10000, 1.), (90000, 1.), (90000, 7000), (10000, 3330)]
model = mesher.Polygon(verts, {'density':-100})
xp = numpy.arange(0., 100000., 1000.)
zp = numpy.zeros_like(xp)
gz = utils.contaminate(gravmag.talwani.gz(xp, zp, [model]), 0.5)

log.info("Preparing for the inversion")
solver = inversion.gradient.levmarq(initial=(9000, 500))
estimate, residuals = gravmag.basin2d.trapezoidal(xp, zp, gz, verts[0:2], -100,
    solver)

mpl.figure()
mpl.subplot(2, 1, 1)
mpl.title("Gravity anomaly")
mpl.plot(xp, gz, 'ok', label='Observed')
mpl.plot(xp, gz - residuals, '-r', linewidth=2, label='Predicted')
mpl.legend(loc='lower left', numpoints=1)
mpl.ylabel("mGal")
mpl.xlim(0, 100000)
mpl.subplot(2, 1, 2)
mpl.polygon(estimate, 'o-r', linewidth=2, fill='r', alpha=0.3,
                label='Estimated')
mpl.polygon(model, '--k', linewidth=2, label='True')
mpl.legend(loc='lower left', numpoints=1)
mpl.xlabel("X")
mpl.ylabel("Z")
mpl.set_area((0, 100000, 10000, -500))
mpl.show()
コード例 #31
0
# Plot the layer and the fit
mpl.figure(figsize=(14, 4))
mpl.suptitle('Observed data (black) | Predicted by layer (red)')
mpl.subplot(1, 3, 1)
mpl.axis('scaled')
mpl.title('Layer (kg.m^-3)')
mpl.pcolor(layer.y, layer.x, layer.props['density'], layer.shape)
mpl.colorbar().set_label(r'Density $kg.m^{-3}$')
mpl.m2km()
mpl.subplot(1, 3, 2)
mpl.axis('scaled')
mpl.title('Fit gz (mGal)')
levels = mpl.contour(y1, x1, gz, shape, 15, color='k', interp=True)
mpl.contour(y1, x1, solver.predicted()[0], shape, levels, color='r',
            interp=True)
mpl.plot(y1, x1, 'xk', label='Data points')
mpl.legend()
mpl.m2km()
mpl.subplot(1, 3, 3)
mpl.axis('scaled')
mpl.title('Fit gzz (Eotvos)')
levels = mpl.contour(y2, x2, gzz, shape, 10, color='k', interp=True)
mpl.contour(y2, x2, solver.predicted()[1], shape, levels, color='r',
            interp=True)
mpl.plot(y2, x2, 'xk', label='Data points')
mpl.legend()
mpl.m2km()

mpl.figure()
mpl.suptitle('Interpolated gz at ground level')
mpl.subplot(1, 2, 1)
コード例 #32
0
amp = 3
age = 54
zp = numpy.arange(0, 100, 1)
temp, error = utils.contaminate(climsig.abrupt(amp, age, zp),
                                0.02,
                                percent=True,
                                return_stddev=True)

# Preparing for the inversion
p, residuals = climsig.iabrupt(temp, zp)
est_amp, est_age = p

mpl.figure(figsize=(12, 5))
mpl.subplot(1, 2, 1)
mpl.title("Climate signal (abrupt)")
mpl.plot(temp, zp, 'ok', label='Observed')
mpl.plot(temp - residuals, zp, '--r', linewidth=3, label='Predicted')
mpl.legend(loc='lower right', numpoints=1)
mpl.xlabel("Temperature (C)")
mpl.ylabel("Z")
mpl.ylim(100, 0)
ax = mpl.subplot(1, 2, 2)
ax2 = mpl.twinx()
mpl.title("Age and amplitude")
width = 0.3
ax.bar([1 - width], [age], width, color='b', label="True")
ax.bar([1], [est_age], width, color='r', label="Estimate")
ax2.bar([2 - width], [amp], width, color='b')
ax2.bar([2], [est_amp], width, color='r')
ax.legend(loc='upper center', numpoints=1)
ax.set_ylabel("Age (years)")
コード例 #33
0
"""
GravMag: Forward modeling of the gravity anomaly using spheres (calculate on
random points)
"""
from fatiando import logger, mesher, gridder, utils, gravmag
from fatiando.vis import mpl

log = logger.get()
log.info(logger.header())
log.info(__doc__)

spheres = [mesher.Sphere(0, 0, -2000, 1000, {'density':1000})]
# Create a set of points at 100m height
area = (-5000, 5000, -5000, 5000)
xp, yp, zp = gridder.scatter(area, 500, z=-100)
# Calculate the anomaly
gz = utils.contaminate(gravmag.sphere.gz(xp, yp, zp, spheres), 0.1)
# Plot
shape = (100, 100)
mpl.figure()
mpl.title("gz (mGal)")
mpl.axis('scaled')
mpl.plot(yp*0.001, xp*0.001, '.k')
mpl.contourf(yp*0.001, xp*0.001, gz, shape, 15, interp=True)
mpl.colorbar()
mpl.xlabel('East y (km)')
mpl.ylabel('North x (km)')
mpl.show()
コード例 #34
0
import numpy
from fatiando import utils, mesher
from fatiando.gravmag import talwani
from fatiando.vis import mpl

# Notice that the last two number are switched.
# This way, the z axis in the plots points down.
area = (-5000, 5000, 5000, 0)
axes = mpl.figure().gca()
mpl.xlabel("X")
mpl.ylabel("Z")
mpl.axis('scaled')
polygons = [mesher.Polygon(mpl.draw_polygon(area, axes),
                           {'density': 500})]
xp = numpy.arange(-4500, 4500, 100)
zp = numpy.zeros_like(xp)
gz = talwani.gz(xp, zp, polygons)

mpl.figure()
mpl.axis('scaled')
mpl.subplot(2, 1, 1)
mpl.title(r"Gravity anomaly produced by the model")
mpl.plot(xp, gz, '-k', linewidth=2)
mpl.ylabel("mGal")
mpl.xlim(-5000, 5000)
mpl.subplot(2, 1, 2)
mpl.polygon(polygons[0], 'o-k', linewidth=2, fill='k', alpha=0.5)
mpl.xlabel("X")
mpl.ylabel("Z")
mpl.set_area(area)
mpl.show()
コード例 #35
0
background = (velocity - 4000) * 10**-1
fig = mpl.figure(figsize=(8, 6))
mpl.subplots_adjust(right=0.98, left=0.11, hspace=0.5, top=0.93)
mpl.subplot2grid((4, 3), (0, 0), colspan=3, rowspan=3)
wavefield = mpl.imshow(np.zeros_like(velocity),
                       extent=area,
                       cmap=mpl.cm.gray_r,
                       vmin=-1000,
                       vmax=1000)
mpl.points(stations, '^b', size=8)
mpl.ylim(area[2:][::-1])
mpl.xlabel('x (km)')
mpl.ylabel('z (km)')
mpl.m2km()
mpl.subplot2grid((4, 3), (3, 0), colspan=3)
seismogram1, = mpl.plot([], [], '-k')
mpl.xlim(0, duration)
mpl.ylim(-200, 200)
mpl.ylabel('Amplitude')
times = np.linspace(0, dt * maxit, maxit)
# This function updates the plot every few timesteps


def animate(i):
    t, u, seismogram = simulation.next()
    seismogram1.set_data(times[:t + 1], seismogram[0][:t + 1])
    wavefield.set_array(background[::-1] + u[::-1])
    return wavefield, seismogram1


anim = animation.FuncAnimation(fig,
コード例 #36
0
    mesher.Prism(-4000, 0, -4000, -2000, 2000, 5000, {'density': 1200}),
    mesher.Prism(-1000, 1000, -1000, 1000, 1000, 7000, {'density': -800}),
    mesher.Prism(2000, 4000, 3000, 4000, 0, 2000, {'density': 600})
]
# Calculate on a scatter of points to show that migration doesn't need gridded
# data
xp, yp, zp = gridder.scatter((-6000, 6000, -6000, 6000), 1000, z=-10)
gz = utils.contaminate(prism.gz(xp, yp, zp, model), 0.1)

# Plot the data
shape = (50, 50)
mpl.figure()
mpl.axis('scaled')
mpl.contourf(yp, xp, gz, shape, 30, interp=True)
mpl.colorbar()
mpl.plot(yp, xp, '.k')
mpl.xlabel('East (km)')
mpl.ylabel('North (km)')
mpl.m2km()
mpl.show()

mesh = imaging.migrate(xp, yp, zp, gz, 0, 10000, (30, 30, 30), power=0.8)

# Plot the results
myv.figure()
myv.prisms(model, 'density', style='wireframe', linewidth=2)
myv.prisms(mesh, 'density', edges=False)
axes = myv.axes(myv.outline())
myv.wall_bottom(axes.axes.bounds)
myv.wall_north(axes.axes.bounds)
myv.show()
コード例 #37
0
mpl.title('Layer (kg.m^-3)')
mpl.pcolor(layer.y, layer.x, layer.props['density'], layer.shape)
mpl.colorbar().set_label(r'Density $kg.m^{-3}$')
mpl.m2km()
mpl.subplot(1, 3, 2)
mpl.axis('scaled')
mpl.title('Fit gz (mGal)')
levels = mpl.contour(y1, x1, gz, shape, 15, color='k', interp=True)
mpl.contour(y1,
            x1,
            solver.predicted()[0],
            shape,
            levels,
            color='r',
            interp=True)
mpl.plot(y1, x1, 'xk', label='Data points')
mpl.legend()
mpl.m2km()
mpl.subplot(1, 3, 3)
mpl.axis('scaled')
mpl.title('Fit gzz (Eotvos)')
levels = mpl.contour(y2, x2, gzz, shape, 10, color='k', interp=True)
mpl.contour(y2,
            x2,
            solver.predicted()[1],
            shape,
            levels,
            color='r',
            interp=True)
mpl.plot(y2, x2, 'xk', label='Data points')
mpl.legend()
コード例 #38
0
from fatiando import utils
from fatiando.geothermal.climsig import linear, SingleChange
from fatiando.vis import mpl


# Generating synthetic data
amp = 5.43
age = 78.2
# along a well at these depths
zp = numpy.arange(0, 100, 1)
temp, error = utils.contaminate(linear(amp, age, zp), 0.02,
                                percent=True, return_stddev=True)

# Preparing for the inversion
data = SingleChange(temp, zp, mode='linear').config('levmarq', initial=[1, 1])
amp_, age_ = data.fit().estimate_

print "Linear change in temperature"
print "  true:      amp=%.3f age=%.3f" % (amp, age)
print "  estimated: amp=%.3f age=%.3f" % (amp_, age_)

mpl.figure(figsize=(4, 5))
mpl.title("Residual well temperature")
mpl.plot(temp, zp, 'ok', label='Observed')
mpl.plot(data.predicted(), zp, '--r', linewidth=3, label='Predicted')
mpl.legend(loc='lower right', numpoints=1)
mpl.xlabel("Temperature (C)")
mpl.ylabel("Z (m)")
mpl.ylim(100, 0)
mpl.show()
コード例 #39
0
x = np.linspace(0, 100000, 100)
z = -100*np.ones_like(x)
data = utils.contaminate(talwani.gz(x, z, [model]), 0.5, seed=0)

# Make the solver using smoothness regularization and run the inversion
misfit = PolygonalBasinGravity(x, z, data, 50, props, top=0)
regul = Smoothness1D(misfit.nparams)
solver = misfit + 1e-4*regul

# This is a non-linear problem so we need to pick an initial estimate
initial = 3000*np.ones(misfit.nparams)
solver.config('levmarq', initial=initial).fit()

mpl.figure()
mpl.subplot(2, 1, 1)
mpl.plot(x, data, 'ok', label='Gravity Data')
mpl.plot(x, solver[0].predicted(), '-r', linewidth=2, label='predicted Gravity')
mpl.legend()
ax = mpl.subplot(2, 1, 2)
mpl.polygon(model, fill='gray', alpha=0.5, label='Polygon')
# The estimate_ property of our solver gives us the estimate basin as a polygon
# So we can directly pass it to plotting and forward modeling functions
mpl.polygon(solver.estimate_, style='o-r', label='Inverted')
ax.invert_yaxis()
mpl.legend()
mpl.show()

# columns = ['data','depths']
# values = np.array([data,depths])
# df = pd.DataFrame(data=values.T,columns=columns, index = xs)
# df.to_csv('Fatiando_2DBasin_forGMSYS.csv')