Пример #1
0
    def wavePropagation(domain, h, tend, lam, mu, rho, xc, src_radius, U0):
        # lists to collect displacement at point source
        ts, u_pc0, u_pc1, u_pc2 = [], [], [], []
        x = domain.getX()
        # ... open new PDE ...
        mypde = LinearPDE(domain)
        mypde.getSolverOptions().setSolverMethod(SolverOptions.HRZ_LUMPING)
        kron = kronecker(mypde.getDim())

        dunit = numpy.array([1., 0., 0.])  # defines direction of point source

        mypde.setValue(D=kron * rho,
                       q=whereNegative(length(x - xc) - src_radius) * dunit)
        # ... set initial values ....
        n = 0
        # for first two time steps
        u = Vector(0., Solution(domain))
        u_last = Vector(0., Solution(domain))
        t = 0

        # define the location of the point source
        L = Locator(domain, xc)
        # find potential at point source
        u_pc = L.getValue(u)
        print("u at point charge = %s" % u_pc)
        ts.append(t)
        u_pc0.append(u_pc[0]), u_pc1.append(u_pc[1]), u_pc2.append(u_pc[2])

        while t < tend:
            t += h
            # ... get current stress ....
            g = grad(u)
            stress = lam * trace(g) * kron + mu * (g + transpose(g))
            # ... get new acceleration ....
            amplitude = U0 * (4 * (t - t0)**3 / alpha**3 - 6 *
                              (t - t0) / alpha) * sqrt(2.) / alpha**2 * exp(
                                  1. / 2. - (t - t0)**2 / alpha**2)
            mypde.setValue(X=-stress, r=dunit * amplitude)
            a = mypde.getSolution()
            # ... get new displacement ...
            u_new = 2 * u - u_last + h**2 * a
            # ... shift displacements ....
            u_last = u
            u = u_new
            n += 1
            print("time step %d, t = %s" % (n, t))
            u_pc = L.getValue(u)
            print("u at point charge = %s" % u_pc)
            ts.append(t)
            u_pc0.append(u_pc[0]), u_pc1.append(u_pc[1]), u_pc2.append(u_pc[2])

            # ... save current acceleration in units of gravity and displacements
            if n == 1 or n % 10 == 0:
                saveVTK("./data/usoln.%i.vtu" % (n / 10),
                        acceleration=length(a) / 9.81,
                        displacement=length(u),
                        tensor=stress,
                        Ux=u[0])
        return ts, u_pc0, u_pc1, u_pc2
Пример #2
0
 def doInitialPostprocessing(self):
     """
     writes vtk file at the end of initial iteration
     """
     super(WriteVTK,self).doInitialPostprocessing()
     kwargs=self.collectData()
     if len(kwargs)>0:
        saveVTK(self.getFrameFileName(),**kwargs)
        self.trace("%s-th frame at time %s is writen to %s"%(self.getFrameCounter(),self.t,self.getFrameFileName()))
Пример #3
0
 def doInitialPostprocessing(self):
     """
     writes vtk file at the end of initial iteration
     """
     super(WriteVTK, self).doInitialPostprocessing()
     kwargs = self.collectData()
     if len(kwargs) > 0:
         saveVTK(self.getFrameFileName(), **kwargs)
         self.trace(
             "%s-th frame at time %s is writen to %s" %
             (self.getFrameCounter(), self.t, self.getFrameFileName()))
Пример #4
0
    res=1000.0
    con=1/res
    cur=10.

    ################################################ESTABLISHING PARAMETERS
    #the folder to put our outputs in, leave blank "" for script path 
    save_path= os.path.join("data","example11")
    #ensure the dir exists
    mkDir(save_path)

    ####################################################DOMAIN CONSTRUCTION
    domain = Rectangle(l0=mx,l1=my,n0=ndx, n1=ndy)
    x=Solution(domain).getX()

    kro=kronecker(domain)
    source1=[mx/4.,0]; source2=[3.*mx/4.,0]

    sourceg=length(exp(-length(x-source1)/(100.)))+length(exp(-length(x-source2)/(100.)))
    sourceg=sourceg/integrate(sourceg)

    q=whereZero(x[1]-my)+whereZero(x[0])+whereZero(x[0]-mx)
    ###############################################ESCRIPT PDE CONSTRUCTION

    mypde=LinearPDE(domain)
    mypde.setValue(A=kro*con,Y=sourceg,q=q,r=0)
    mypde.setSymmetryOn()
    sol=mypde.getSolution()

    # Save the output to file.
    saveVTK(os.path.join(save_path,"ex11a.vtu"),source=sourceg,res_pot=sol)
Пример #5
0
        src_cut.append([xstep * i, xc[1]])
    # locate the nearest nodes to the points in src_cut
    src = Locator(mydomain, src_cut)
    src_cut = src.getValue(u)  #retrieve the values from the nodes
    # plot the x locations vs value and save the figure
    pl.plot(cut_loc, src_cut)
    pl.axis([xc[0] - src_radius * 3, xc[0] + src_radius * 3, 0., 2. * U0])
    pl.savefig(os.path.join(savepath, "source_line.png"))

    ####################################################ITERATION VARIABLES
    n = 0  # iteration counter
    t = 0  # time counter
    ##############################################################ITERATION
    while t < tend:
        g = grad(u)
        pres = csq * h * h * g  # get current pressure
        mypde.setValue(X=-pres, Y=(2. * u - u_m1))  # set values in pde
        u_p1 = mypde.getSolution()  # get the new displacement
        u_m1 = u
        u = u_p1  # shift values back one time step for next iteration
        # save current displacement, acceleration and pressure
        if (t >= rtime):
            saveVTK(os.path.join(savepath, "ex07a.%i.vtu" % n),
                    displacement=length(u),
                    tensor=pres)
            rtime = rtime + rtime_inc  #increment data save time
        # increment loop values
        t = t + h
        n = n + 1
        print("time step %d, t=%s" % (n, t))
Пример #6
0
    ####################################################ITERATION VARIABLES
    n = 0  # iteration counter
    t = 0  # time counter
    ##############################################################ITERATION
    while t < tend:
        # get current stress
        g = grad(u)
        stress = lam * trace(g) * kmat + mu * (g + transpose(g))
        mypde.setValue(X=-stress * abc)  # set PDE values
        accel = mypde.getSolution()  #get PDE solution for accelleration
        u_p1 = (2. * u - u_m1) + h * h * accel  #calculate displacement
        u_p1 = u_p1 * abc  # apply boundary conditions
        u_m1 = u
        u = u_p1  # shift values by 1
        # save current displacement, acceleration and pressure
        if (t >= rtime):
            saveVTK(os.path.join(save_path,"ex08c.%05d.vtu"%n),\
                        vector_displacement=u,displacement=length(u),\
                        vector_acceleration=accel,acceleration=length(accel),\
                        tensor=stress)
            rtime = rtime + rtime_inc  #increment data save time
        # increment loop values
        t = t + h
        n = n + 1
        if (n < ls):
            y = source[n] * (cos(length(x - xc) * 3.1415 / src_length) +
                             1) * whereNegative(length(x - xc) - src_length)
            y = y * src_dir
            mypde.setValue(y=y)  #set the source as a function on the boundary
        print("time step %d, t=%s" % (n, t))
Пример #7
0
    # ... create a slip distribution on the fault:
    p, m=fs.getParametrization(mydomain.getX(),tag=1)
    p0,p1= fs.getW0Range(tag=1)
    s=m*(p-p0)*(p1-p)/((p1-p0)/2)**2*slip_max*[0.,1.]
    # ... calculate stress according to slip:
    D=symmetric(grad(s))
    chi, d=fs.getSideAndDistance(D.getFunctionSpace().getX(),tag=1)
    sigma_s=(mu*D+lam*trace(D)*kronecker(mydomain))*chi
    #... open symmetric PDE ...
    mypde=LinearPDE(mydomain)
    mypde.setSymmetryOn()
    #... set coefficients ...
    C=Tensor4(0.,Function(mydomain))
    for i in range(mydomain.getDim()):
      for j in range(mydomain.getDim()):
         C[i,i,j,j]+=lam
         C[j,i,j,i]+=mu
         C[j,i,i,j]+=mu
    # ... fix displacement in normal direction 
    x=mydomain.getX()
    msk=whereZero(x[0])*[1.,0.] + whereZero(x[0]-1.)*[1.,0.] \
       +whereZero(x[1])*[0.,1.] + whereZero(x[1]-1.)*[0.,1.]
    mypde.setValue(A=C,X=-0.5*sigma_s,q=msk)
    #... solve pde ...
    mypde.getSolverOptions().setVerbosityOn()
    v=mypde.getSolution()
    # .. write the displacement to file:
    D=symmetric(grad(v))
    sigma=(mu*D+lam*trace(D)*kronecker(mydomain))+0.5*sigma_s
    saveVTK("slip.vtu",disp=v+0.5*chi*s, stress= sigma)
Пример #8
0
fc = TransportPDE(dom, num_equations=1, theta=THETA)
x = Function(dom).getX()
fc.setValue(M=Scalar(1., Function(dom)),
            C=V,
            A=-Scalar(E, Function(dom)) * kronecker(dom))
#==============
if TEST_SUPG:
    supg = LinearSinglePDE(dom)
    supg.setValue(D=1.)
    supg.setSolverMethod(supg.LUMPING)
    dt_supg = 1. / (1. / inf(dom.getSize() / length(V)) +
                    1. / inf(dom.getSize()**2 / E)) * 0.3
    u_supg = u0 * 1.

c = 0
saveVTK("u.%s.vtu" % c, u=u0)
fc.setInitialSolution(u0)
t = T0
while t < T_END:
    print("time step t=", t + dt)
    u = fc.solve(dt)
    if TEST_SUPG:
        #========== supg tests ================
        nn = max(ceil(dt / dt_supg), 1.)
        dt2 = dt / nn
        nnn = 0
        while nnn < nn:
            supg.setValue(X=-dt2 / 2 * E * grad(u_supg),
                          Y=u_supg + dt2 / 2 * inner(V, grad(u_supg)))
            u2 = supg.getSolution()
            supg.setValue(X=-dt2 * E * grad(u2),
Пример #9
0
def wavesolver2d(domain,
                 h,
                 tend,
                 lam,
                 mu,
                 rho,
                 U0,
                 xc,
                 savepath,
                 output="vtk"):
    from esys.escript.linearPDEs import LinearPDE
    x = domain.getX()
    # ... open new PDE ...
    mypde = LinearPDE(domain)
    #mypde.setSolverMethod(LinearPDE.LUMPING)
    mypde.setSymmetryOn()
    kmat = kronecker(domain)
    mypde.setValue(D=kmat * rho)

    # define small radius around point xc
    # Lsup(x) returns the maximum value of the argument x
    src_radius = 50  #2*Lsup(domain.getSize())
    print("src_radius = ", src_radius)

    dunit = numpy.array([0., 1.])  # defines direction of point source

    # ... set initial values ....
    n = 0
    # initial value of displacement at point source is constant (U0=0.01)
    # for first two time steps
    u = U0 * (cos(length(x - xc) * 3.1415 / src_radius) +
              1) * whereNegative(length(x - xc) - src_radius) * dunit
    u_m1 = u
    t = 0

    u_pot = cbphones(domain, u, [[0, 500], [250, 500], [400, 500]], 2)
    u_pc_x1 = u_pot[0, 0]
    u_pc_y1 = u_pot[0, 1]
    u_pc_x2 = u_pot[1, 0]
    u_pc_y2 = u_pot[1, 1]
    u_pc_x3 = u_pot[2, 0]
    u_pc_y3 = u_pot[2, 1]

    # open file to save displacement at point source
    u_pc_data = open(os.path.join(savepath, 'U_pc.out'), 'w')
    u_pc_data.write("%f %f %f %f %f %f %f\n" %
                    (t, u_pc_x1, u_pc_y1, u_pc_x2, u_pc_y2, u_pc_x3, u_pc_y3))

    #   while t<tend:
    while t < 1.:

        # ... get current stress ....
        t = 1.
        ##OLD WAY
        break
        g = grad(u)
        stress = lam * trace(g) * kmat + mu * (g + transpose(g))
        ### ... get new acceleration ....
        #mypde.setValue(X=-stress)
        #a=mypde.getSolution()
        ### ... get new displacement ...
        #u_p1=2*u-u_m1+h*h*a
        ###NEW WAY
        mypde.setValue(X=-stress * (h * h), Y=(rho * 2 * u - rho * u_m1))
        u_p1 = mypde.getSolution()
        # ... shift displacements ....
        u_m1 = u
        u = u_p1
        #stress =
        t += h
        n += 1
        print(n, "-th time step t ", t)
        u_pot = cbphones(domain, u, [[300., 200.], [500., 200.], [750., 200.]],
                         2)

        #     print "u at point charge=",u_pc
        u_pc_x1 = u_pot[0, 0]
        u_pc_y1 = u_pot[0, 1]
        u_pc_x2 = u_pot[1, 0]
        u_pc_y2 = u_pot[1, 1]
        u_pc_x3 = u_pot[2, 0]
        u_pc_y3 = u_pot[2, 1]

        # save displacements at point source to file for t > 0
        u_pc_data.write(
            "%f %f %f %f %f %f %f\n" %
            (t, u_pc_x1, u_pc_y1, u_pc_x2, u_pc_y2, u_pc_x3, u_pc_y3))

        # ... save current acceleration in units of gravity and displacements
        #saveVTK(os.path.join(savepath,"usoln.%i.vtu"%n),acceleration=length(a)/9.81,
        #displacement = length(u), tensor = stress, Ux = u[0] )
        if output == "vtk":
            saveVTK(os.path.join(savepath, "tonysol.%i.vtu" % n),
                    output1=length(u),
                    tensor=stress)
        else:
            quT = qu.toListOfTuples()
            #Projector is used to smooth the data.
            proj = Projector(mymesh)
            smthT = proj(T)

            #move data to a regular grid for plotting
            xi, yi, zi = toRegGrid(smthT, mymesh, 200, 200, width, depth)

            # contour the gridded data,
            # select colour
            pl.matplotlib.pyplot.autumn()
            pl.clf()
            # contour temperature
            CS = pl.contour(xi, yi, zi, 5, linewidths=0.5, colors='k')
            # labels and formatting
            pl.clabel(CS, inline=1, fontsize=8)
            pl.title("Heat Refraction across a clinal structure.")
            pl.xlabel("Horizontal Displacement (m)")
            pl.ylabel("Depth (m)")
            pl.legend()
            if getMPIRankWorld() == 0:  #check for MPI processing
                pl.savefig(
                    os.path.join(saved_path, "heatrefraction001_cont.png"))

    u_pc_data.close()
Пример #10
0
def wavesolver2df(domain, h, tend, lam, mu, rho, U0, xc, savepath):
    x = domain.getX()
    # ... open new PDE ...
    mypde = LinearPDE(domain)
    #mypde.setSolverMethod(LinearPDE.LUMPING)
    mypde.setSymmetryOn()
    kmat = kronecker(domain)
    mypde.setValue(D=kmat)
    b = 0.9

    # define small radius around point xc
    # Lsup(x) returns the maximum value of the argument x
    src_radius = 50  #2*Lsup(domain.getSize())
    print("src_radius = ", src_radius)

    dunit = numpy.array([0., 1.])  # defines direction of point source

    # ... set initial values ....
    n = 0
    # initial value of displacement at point source is constant (U0=0.01)
    # for first two time steps
    u = U0 * (cos(length(x - xc) * 3.1415 / src_radius) +
              1) * whereNegative(length(x - xc) - src_radius) * dunit
    u_m1 = u
    t = 0

    u_pot = cbphones(domain, u, [[0, 500], [250, 500], [400, 500]], 2)
    u_pc_x1 = u_pot[0, 0]
    u_pc_y1 = u_pot[0, 1]
    u_pc_x2 = u_pot[1, 0]
    u_pc_y2 = u_pot[1, 1]
    u_pc_x3 = u_pot[2, 0]
    u_pc_y3 = u_pot[2, 1]

    # open file to save displacement at point source
    u_pc_data = open(os.path.join(savepath, 'U_pc.out'), 'w')
    u_pc_data.write("%f %f %f %f %f %f %f\n" %
                    (t, u_pc_x1, u_pc_y1, u_pc_x2, u_pc_y2, u_pc_x3, u_pc_y3))

    while t < tend:
        # ... get current stress ....

        ##OLD WAY
        g = grad(u)
        stress = lam * trace(g) * kmat + mu * (g + transpose(g))
        ### ... get new acceleration ....
        #mypde.setValue(X=-stress)
        #a=mypde.getSolution()
        ### ... get new displacement ...
        #u_p1=2*u-u_m1+h*h*a
        ###NEW WAY
        y = ((rho / (-rho - b * h)) *
             (u_m1 - 2 * u)) + (((b * h) / (-rho - (b * h))) * -u)
        mypde.setValue(X=-stress * ((h * h) / (-rho - h * b)), Y=y)
        u_p1 = mypde.getSolution()
        # ... shift displacements ....
        u_m1 = u
        u = u_p1
        #stress =
        t += h
        n += 1
        print(n, "-th time step t ", t)
        u_pot = cbphones(domain, u, [[300., 200.], [500., 200.], [750., 200.]],
                         2)

        #     print "u at point charge=",u_pc
        u_pc_x1 = u_pot[0, 0]
        u_pc_y1 = u_pot[0, 1]
        u_pc_x2 = u_pot[1, 0]
        u_pc_y2 = u_pot[1, 1]
        u_pc_x3 = u_pot[2, 0]
        u_pc_y3 = u_pot[2, 1]

        # save displacements at point source to file for t > 0
        u_pc_data.write(
            "%f %f %f %f %f %f %f\n" %
            (t, u_pc_x1, u_pc_y1, u_pc_x2, u_pc_y2, u_pc_x3, u_pc_y3))

        # ... save current acceleration in units of gravity and displacements
        #saveVTK(os.path.join(savepath,"usoln.%i.vtu"%n),acceleration=length(a)/9.81,
        #displacement = length(u), tensor = stress, Ux = u[0] )
        saveVTK(os.path.join(savepath, "tonysol.%i.vtu" % n),
                output1=length(u),
                tensor=stress)

    u_pc_data.close()
Пример #11
0
            sys.exit(1)

        pressure -= penalty * eta * (trace(grad(velocity)))
        error = penalty * Lsup(trace(grad(velocity))) / Lsup(grad(velocity))
        print("\nPressure iteration number:", p_iter)
        print("error", error)
        ref = pressure * 1.0

    return velocity, pressure


### MAIN LOOP, OVER TIME ###
while t_step <= t_step_end:
    print("######################")
    print("Time step:", t_step)
    print("######################")
    rho = update_parameter(phi, rho1, rho2)
    eta = update_parameter(phi, eta1, eta2)

    velocity, pressure = solve_vel_uszawa(rho, eta, velocity, pressure)
    dt = 0.3 * Lsup(mesh.getSize()) / Lsup(velocity)
    phi = update_phi(phi, velocity, dt, t_step)

    ### PSEUDO POST-PROCESSING ###
    print("##########  Saving image", t_step, " ###########")
    saveVTK("phi3D.%2.2i.vtk" % t_step, layer=phi)

    t_step += 1

# vim: expandtab shiftwidth=4:
Пример #12
0
   du=prob.solve(iter_max=100) # get solution: nodal displacement

   disp += du
   stress=prob.getCurrentStress()
   
   dom = prob.getDomain() # domain is updated Lagrangian formulation
   proj = Projector(dom)
   sig = proj(stress)

   sig_bounda = interpolate(sig,FunctionOnBoundary(dom))
   traction = matrix_mult(sig_bounda,dom.getNormal())
   tractTop = traction*topSurf
   forceTop = integrate(tractTop,where=FunctionOnBoundary(dom))
   lengthTop = integrate(topSurf,where=FunctionOnBoundary(dom))
   fout.write(str(t*vel/ly)+' '+str(forceTop[1])+' '+str(lengthTop)+'\n')
      
   vR=prob.getLocalVoidRatio()
   fabric=prob.getLocalFabric()
   strain = prob.getCurrentStrain()
   saveGauss2D(name='./result/gauss/time_'+str(t)+'.dat',strain=strain,stress=stress,fabric=fabric)
   volume_strain = trace(strain)
   dev_strain = symmetric(strain) - volume_strain*k/dim
   shear = sqrt(2*inner(dev_strain,dev_strain))
   saveVTK("./result/vtk/biaxialSmooth_%d.vtu"%t,disp=disp,shear=shear,e=vR)

prob.getCurrentPacking(pos=(),time=t,prefix='./result/packing/')
time_elapse = time.time() - time_start
fout.write("#Elapsed time in hours: "+str(time_elapse/3600.)+'\n')   
fout.close()
prob.exitSimulation()
Пример #13
0
NE = 50
dom = Rectangle(NE, 1, l1=1. / NE)
dom = Rectangle(NE, NE)
fc = TransportPDE(dom, numEquations=1)
fc.getSolverOptions().setVerbosityOn()
fc.getSolverOptions().setODESolver(SolverOptions.LINEAR_CRANK_NICOLSON)
fc.getSolverOptions().setODESolver(SolverOptions.BACKWARD_EULER)
fc.getSolverOptions().setODESolver(SolverOptions.CRANK_NICOLSON)
fc.setValue(M=1, C=[-1, 0])
x = dom.getX()
u0 = whereNegative(x[0] - 1. / NE)

c = 0
t = 0

saveVTK("u.%s.vtu" % c, u=u0)
fc.setInitialSolution(u0)
dt = fc.getSafeTimeStepSize()

print("u0 =", u0)
T_END = dt
print("dt = ", dt)
while t < T_END:
    print("time step t=", t + dt)
    u = fc.getSolution(dt)
    saveVTK("u.%s.vtu" % (c + 1, ), u=u)
    print("u =", u)
    c += 1
    t += dt
Пример #14
0
while t_step <= t_step_end:
    #update density and viscosity
    rho = levelset.update_parameter(rho1, rho2)
    eta = levelset.update_parameter(eta1, eta2)

    #get velocity and pressure of fluid
    Y[1] = -rho * g
    solution.initialize(fixed_u_mask=b_c, eta=eta, f=Y)
    velocity, pressure = solution.solve(velocity,
                                        pressure,
                                        max_iter=max_iter,
                                        verbose=verbose,
                                        useUzawa=useUzawa)

    #update the interface
    func = levelset.update_phi(velocity, dt, t_step)

    print("##########################################################")
    print("time step:", t_step, " completed with dt:", dt)
    print("Velocity: min =", inf(velocity), "max =", Lsup(velocity))
    print("##########################################################")

    #save interface, velocity and pressure
    saveVTK("phi2D.%2.4i.vtu" % t_step,
            interface=func,
            velocity=velocity,
            pressure=pressure)
    #courant condition
    dt = 0.4 * Lsup(mesh.getSize()) / Lsup(velocity)
    t_step += 1
Пример #15
0
__license__="""Licensed under the Apache License, version 2.0
http://www.apache.org/licenses/LICENSE-2.0"""
__url__="https://launchpad.net/escript-finley"

import sys

# get the tools we want to use
from esys.escript import *
from esys.weipa import saveVTK
try:
    from esys.dudley import Rectangle
    # some parameters
    L0=1.
    L1=1. 
    T_bot=100
    # generate n0 x n1 elements over [0,l0] x [0,l1]
    mydomain=Rectangle(l0=L0,l1=L1,n0=20,n1=20)
    # print spatial dimension:
    print("dimension = ",mydomain.getDim())
    # get coordinates of points in domain:
    x=mydomain.getX()
    print(x) 
    # set a function 
    T_D=T_bot/L1*(L1-x[1])
    # save T_D for visualisation
    saveVTK("u.vtu",T=T_D)
except ImportError:
    print("Dudley module not available")


def wavePropagation(dom, rho, mu, lmbd, eta):
    x = Function(dom).getX()
    # ... open new PDE ...
    mypde = LinearPDE(dom)
    mypde.setSolverMethod(LinearPDE.LUMPING)
    k = kronecker(Function(dom))
    mypde.setValue(D=k * rho)

    dt = (1. / 5.) * inf(dom.getSize() / sqrt((2 * mu + lmbd) / rho))
    if output: print("time step size = ", dt)
    # ... set initial values ....
    n = 0
    t = 0
    t_write = 0.
    n_write = 0
    # initial value of displacement at point source is constant (U0=0.01)
    # for first two time steps
    u = Vector(0., Solution(dom))
    v = Vector(0., Solution(dom))
    a = Vector(0., Solution(dom))
    a2 = Vector(0., Solution(dom))
    v = Vector(0., Solution(dom))

    if not os.path.isdir(WORKDIR): os.mkdir(WORKDIR)

    starttime = time.clock()
    while t < t_end and n < n_end:
        if output:
            print(n + 1,
                  "-th time step t ",
                  t + dt,
                  " max u and F: ",
                  Lsup(u),
                  end=' ')
        # prediction:
        u_pr = u + dt * v + (dt**2 / 2) * a + (dt**3 / 6) * a2
        v_pr = v + dt * a + (dt**2 / 2) * a2
        a_pr = a + dt * a2
        # ... get current stress ....
        eps = symmetric(grad(u_pr))
        stress = lmbd * trace(eps) * k + 2 * mu * eps
        # ... force due to event:
        if abs(t - tc) < 5 * tc_length:
            F = exp(-((t - tc) / tc_length)**2) * exp(-(length(x - xc) /
                                                        src_radius)**2) * event
            if output: print(Lsup(F))
        else:
            if output: print(0.)
        # ... get new acceleration ....
        mypde.setValue(X=-stress, Y=F - eta * v_pr)
        a = mypde.getSolution()
        # ... get new displacement ...
        da = a - a_pr
        u = u_pr + (dt**2 / 12.) * da
        v = v_pr + (5 * dt / 12.) * da
        a2 += da / dt
        # ... save current acceleration in units of gravity and displacements
        if output:
            if t >= t_write:
                saveVTK(os.path.join(WORKDIR, "disp.%i.vtu" % n_write),
                        displacement=u,
                        amplitude=length(u))
                t_write += dt_write
                n_write += 1
        t += dt
        n += 1

    endtime = time.clock()
    totaltime = endtime - starttime
    global netotal
    print(">>number of elements: %s, total time: %s, per time step: %s <<" %
          (netotal, totaltime, totaltime / n))
Пример #17
0
http://www.apache.org/licenses/LICENSE-2.0"""
__url__ = "https://launchpad.net/escript-finley"

# $Id:$

from esys.escript import *
from esys.weipa import saveVTK
from esys.escript.models import StokesProblemCartesian

try:
    from esys.finley import Rectangle
    HAVE_FINLEY = True
except ImportError as e:
    print("Finley module required but not available")
    HAVE_FINLEY = False

if HAVE_FINLEY:
    NE = 25
    dom = Rectangle(NE, NE, order=-1,
                    useElementsOnFace=0)  # use macro elements for pressure
    x = dom.getX()
    sc = StokesProblemCartesian(dom)
    mask = (whereZero(x[0]) * [1., 0] + whereZero(x[0] - 1)) * [1., 0] + (
        whereZero(x[1]) * [0., 1.] + whereZero(x[1] - 1)) * [1., 1]
    sc.initialize(eta=.01, fixed_u_mask=mask)
    v = Vector(0., Solution(dom))
    v[0] += whereZero(x[1] - 1.)
    p = Scalar(0., ReducedSolution(dom))
    v, p = sc.solve(v, p, verbose=True)
    saveVTK("u.vtu", velocity=v, pressure=p)
Пример #18
0
    print("volume : ",integrate(r))
    #
    #  step 1:
    #
    # calculate normal 
    n_d=dom.getNormal()
    t_d=matrixmult(numpy.array([[0.,-1.],[1.,0]]),n_d)
    sigma_d=(sign(inner(t_d,U))*alpha_w*t_d-n_d)*Pen*clip(inner(n_d,U),0.)
    print("sigma_d =",inf(sigma_d),sup(sigma_d))

    momentumStep1.setValue(D=r*ro*kronecker(dom),
                           Y=r*ro*U+dt*r*[0.,-ro*g], 
                           X=-dt*r*(dev_stress-teta3*p*kronecker(dom)), 
                           y=sigma_d*face_mask*r_b)
    U_star=momentumStep1.getSolution()
    saveVTK("u.vtu",u=U_star,u0=U)
    #
    #  step 2:
    #
    # U2=U+teta1*(U_star-U)
    U2=U+teta1*U_star
    gg2=grad(U2)
    div_U2=gg2[0,0]+gg2[1,1]+U2[0]/r

    grad_p=grad(p)

    pressureStep2.setValue(A=r*dt*B*teta1*teta2/ro*dt*kronecker(dom), 
                           D=r,                            
                           Y=-dt*B*r*div_U2,
                           X=-r*B*dt**2/ro*teta1*(1-teta3)*grad_p)
    dp=pressureStep2.getSolution()
Пример #19
0
    x=mydomain.getX()
    #... set temperature ...
    T=T_0*exp(-beta*length(x-xc))
    #... open symmetric PDE ...
    mypde=LinearPDE(mydomain)
    mypde.setSymmetryOn()
    #... set coefficients ...
    C=Tensor4(0.,Function(mydomain))
    for i in range(mydomain.getDim()):
      for j in range(mydomain.getDim()):
         C[i,i,j,j]+=lam
         C[i,j,i,j]+=mu
         C[i,j,j,i]+=mu
    msk=whereZero(x[0])*[1.,0.,0.] \
       +whereZero(x[1])*[0.,1.,0.] \
       +whereZero(x[2])*[0.,0.,1.]
    sigma0=(lam+2./3.*mu)*alpha*(T-T_ref)*kronecker(mydomain)
    mypde.setValue(A=C,X=sigma0,q=msk)
    mypde.getSolverOptions().setVerbosityOn()
    #... solve pde ...
    u=mypde.getSolution()
    #... calculate von-Misses
    g=grad(u)
    sigma=mu*(g+transpose(g))+lam*trace(g)*kronecker(mydomain)-sigma0
    sigma_mises=sqrt(((sigma[0,0]-sigma[1,1])**2+(sigma[1,1]-sigma[2,2])**2+ \
                      (sigma[2,2]-sigma[0,0])**2)/2. \
                       +3*(sigma[0,1]**2 + sigma[1,2]**2 + sigma[2,0]**2))
    #... output ...
    saveVTK("deform.vtu",disp=u,stress=sigma_mises)
 
Пример #20
0
   disp += du
   stress=prob.getCurrentStress()
   
   dom = prob.getDomain()
   proj = Projector(dom)
   sig = proj(stress)

   sig_bounda = interpolate(sig,FunctionOnBoundary(dom))
   traction = matrix_mult(sig_bounda,dom.getNormal())
   tract = traction*wallBF
   forceWall = integrate(tract,where=FunctionOnBoundary(dom))
   lengthWall = integrate(wallBF,where=FunctionOnBoundary(dom))
   fout.write(str(t*vel)+' '+str(forceWall[0])+' '+str(lengthWall)+'\n')
      
   vR=prob.getLocalVoidRatio()
   rotation=prob.getLocalAvgRotation()
   fabric=prob.getLocalFabric()
   strain = prob.getCurrentStrain()
   saveGauss2D(name='./result/gauss/time_'+str(t)+'.dat',strain=strain,stress=stress,fabric=fabric)
   volume_strain = trace(strain)
   dev_strain = symmetric(strain) - volume_strain*k/dim
   shear = sqrt(2*inner(dev_strain,dev_strain))
   saveVTK("./result/vtk/retainingSmooth_%d.vtu"%t,disp=disp,stress=stress,shear=shear,e=vR,rot=rotation)

prob.getCurrentPacking(pos=packNo,time=t,prefix='./result/packing/')
time_elapse = time.time() - time_start
fout.write("#Elapsed time in hours: "+str(time_elapse/3600.)+'\n')
fout.close()
prob.exitSimulation()
Пример #21
0
    qc=50.e6
    Tref=0.
    rhocp=2.6e6
    eta=75.
    kappa=240.
    tend=5.
    # ... time, time step size and counter ...
    t=0
    h=0.1
    i=0
    #... generate domain ...
    mydomain = Rectangle(l0=0.05,l1=0.01,n0=250, n1=50)
    #... open PDE ...
    mypde=LinearPDE(mydomain)
    mypde.setSymmetryOn()
    mypde.setValue(A=kappa*kronecker(mydomain),D=rhocp/h,d=eta,y=eta*Tref)
    # ... set heat source: ....
    x=mydomain.getX()
    qH=qc*whereNegative(length(x-xc)-r)
    # ... set initial temperature ....
    T=Tref
    # ... start iteration:
    while t<tend:
          i+=1
          t+=h
          print("time step :",t)
          mypde.setValue(Y=qH+rhocp/h*T)
          T=mypde.getSolution()
          saveVTK("T.%d.vtu"%i,temp=T)

Пример #22
0
        a0 = 1
        n0 = 1
        n1 = 0.5
        a1 = -(a0 * n0) / n1
        v[0] = a0 * sin(pi * n0 * x[0]) * cos(pi * n1 * x[1])
        v[1] = a1 * cos(pi * n0 * x[0]) * sin(pi * n1 * x[1])
    else:
        a0 = 1
        a1 = 1
        n0 = 2
        n1 = 2
        n2 = 0.5
        a2 = -(a0 * n0 + a1 * n1) / n2
        v[0] = a0 * sin(pi * n0 * x[0]) * cos(pi * n1 * x[1]) * cos(
            pi * n2 * x[2])
        v[1] = a1 * cos(pi * n0 * x[0]) * sin(pi * n1 * x[1]) * cos(
            pi * n2 * x[2])
        v[2] = a2 * cos(pi * n0 * x[0]) * cos(pi * n1 * x[1]) * sin(
            pi * n2 * x[2])

    mts = Mountains(mydomain, eps=EPS)
    while t < T_END:
        print("STEP ", t)
        mts.setVelocity(v * cos(OMEGA * t))
        Z = mts.update()

        saveVTK("state.%d.vtu" % n, sol=Z, v=mts.getVelocity())
        print("Integral(Z)=", integrate(Z), Lsup(mts.getVelocity()[DIM - 1]))
        n += 1
        t += mts.getSafeTimeStepSize()
Пример #23
0
   disp += du
   stress=prob.getCurrentStress()
   
   dom = prob.getDomain()
   proj = Projector(dom)
   sig = proj(stress)

   sig_bounda = interpolate(sig,FunctionOnBoundary(dom))
   traction = matrix_mult(sig_bounda,dom.getNormal())
   tractTop = traction*topSurf
   forceTop = integrate(tractTop,where=FunctionOnBoundary(dom))
   areaTop = integrate(topSurf,where=FunctionOnBoundary(dom))
   fout.write(str(t*vel/lz)+' '+str(forceTop[2])+' '+str(areaTop)+'\n')
      
   vR=prob.getLocalVoidRatio()
   rotation=prob.getLocalAvgRotation()
   fabric=prob.getLocalFabric()
   strain = prob.getCurrentStrain()
   saveGauss3D(name='./result/gauss/time_'+str(t)+'.dat',strain=strain,stress=stress,fabric=fabric)
   volume_strain = trace(strain)
   dev_strain = symmetric(strain) - volume_strain*k/dim
   shear = sqrt(2./3.*inner(dev_strain,dev_strain))
   saveVTK("./result/vtk/triaxialRough_%d.vtu"%t,disp=disp,shear=shear,e=vR,rot=rotation)
   
prob.getCurrentPacking(pos=packNo,time=t,prefix='./result/packing/')
time_elapse = time.time() - time_start
fout.write("#Elapsed time in hours: "+str(time_elapse/3600.)+'\n')   
fout.close()
prob.exitSimulation()
Пример #24
0
    #~ u_pc_x1 = u_pot[0,0]
    #~ u_pc_y1 = u_pot[0,1]
    #~ u_pc_x2 = u_pot[1,0]
    #~ u_pc_y2 = u_pot[1,1]
    #~ u_pc_x3 = u_pot[2,0]
    #~ u_pc_y3 = u_pot[2,1]

    # save displacements at point source to file for t > 0
    #~ u_pc_data.write("%f %f %f %f %f %f %f\n"%(t,u_pc_x1,u_pc_y1,u_pc_x2,u_pc_y2,u_pc_x3,u_pc_y3))

    # ... save current acceleration in units of gravity and displacements
    #saveVTK(os.path.join(savepath,"usoln.%i.vtu"%n),acceleration=length(a)/9.81,
    #displacement = length(u), tensor = stress, Ux = u[0] )
    if output == "vtk":
        saveVTK(os.path.join(savepath, "tonysol.%i.vtu" % n),
                output1=length(u),
                tensor=stress)
    if output == "mpl":
        uT = np.array(u.toListOfTuples())
        uT = np.reshape(uT, (ndx + 1, ndy + 1, 2))
        uTz = uT[:, :, 1] + uT[:, :, 0]
        uTz = np.transpose(uTz)
        pl.clf()
        # plot wave
        uTz[0, 0] = maxi
        uTz[0, 1] = -maxi
        CS = pl.imshow(uTz, cmap=cm.spectral)
        pl.colorbar()
        # labels and formatting
        pl.title("Wave Equation Cookbook Example ABC.")
        pl.xlabel("Horizontal Displacement (m)")
  
# generate mesh: here 10x20 mesh of order 2
domain=dudley.Rectangle(10,20,1,l0=0.5,l1=1.0)
# get handel to nodes and elements:
e=Function(domain)
fe=FunctionOnBoundary(domain)
n=ContinuousFunction(domain)
#
# set a mask msk of type vector which is one for nodes and components set be a constraint:
#
msk=whereZero(n.getX()[0])*[1.,1.]
#
#  set the normal stress components on face elements.
#  faces tagged with 21 get the normal stress [0,-press0].
#
# now the pressure is set to zero for x0 coordinates bigger then 0.1
press=whereNegative(fe.getX()[0]-0.1)*200000.*[1.,0.]
# assemble the linear system:
mypde=LinearPDE(domain)
mypde.setValue(A=setHookTensor(e,lamb,nu),y=press,q=msk,r=[0,0])
mypde.setSymmetryOn()
mypde.getSolverOptions().setVerbosityOn()
mypde.getSolverOptions().setPreconditioner(mypde.getSolverOptions().AMG)
# solve for the displacements:
u_d=mypde.getSolution()
# get the gradient and calculate the stress:
g=grad(u_d)
stress=lamb*trace(g)*kronecker(domain)+nu*(g+transpose(g))
# write the hydrostatic pressure:
saveVTK("result.vtu",displacement=u_d,pressure=trace(stress)/domain.getDim())
Пример #26
0
    # for first two time steps
    u = [0.0, 0.0, 0.0] * wherePositive(x)
    u_m1 = u

    ####################################################ITERATION VARIABLES
    n = 0  # iteration counter
    t = 0  # time counter
    ##############################################################ITERATION
    while t < tend:
        # get current stress
        g = grad(u)
        stress = lam * trace(g) * kmat + mu * (g + transpose(g))  #*abc
        mypde.setValue(X=-stress)  # set PDE values
        accel = mypde.getSolution()  #get PDE solution for accelleration
        u_p1 = (2. * u - u_m1) + h * h * accel  #calculate displacement
        u_p1 = u_p1  #*abc          # apply boundary conditions
        u_m1 = u
        u = u_p1  # shift values by 1
        # save current displacement, acceleration and pressure
        if (t >= rtime):
            saveVTK(os.path.join(savepath,"ex09b.%05d.vtu"%n),displacement=length(u),\
                                        acceleration=length(accel),tensor=stress)
            rtime = rtime + rtime_inc  #increment data save time
        # increment loop values
        t = t + h
        n = n + 1
        if (n < ls):
            mypde.setValue(y=source[n] * yx * src_dir *
                           stop)  #set the source as a function on the boundary
        print("time step %d, t=%s" % (n, t))
Пример #27
0
                             ],
                             g=CONST_G)
# this needs to be revised:.
model.setInitialState(S_fg=0, c_mg=None, p_top=p_top, p_bottom=p_bottom)
model.getPDEOptions().setVerbosityOn()
model.getPDEOptions().setSolverMethod(model.getPDEOptions().DIRECT)
model.setIterationControl(iter_max=10, rtol=1.e-4, verbose=True)
print("<%s> Problem set up completed." % time.asctime())
t = 0
n_t = 0

p, S_fg, c_mg, BHP, q_gas, q_water = model.getState()

if SAVE_VTK:
    FN = os.path.join(OUTPUT_DIR, "state.%d.vtu" % n_t)
    saveVTK(FN, p=p, S_fg=S_fg, c_mg=c_mg)
    print("<%s> Initial state saved to file %s." % (time.asctime(), FN))
    print(t / U.day,
          well_P1.locator(p) / U.psi, well_P1.locator(S_fg),
          well_P1.locator(c_mg) / U.Mscf * U.ft**3)
    print(t / U.day,
          well_P1.locator(BHP) / U.psi,
          well_P1.locator(q_gas) / U.Mcf * U.day,
          well_P1.locator(q_water) / U.Barrel * U.day)

for dt in DT:
    print("<%s>Time step %d, time = %e days started:" %
          (time.asctime(), n_t + 1, (t + dt) / U.day))

    model.update(dt)
Пример #28
0
    ##############################################################ITERATION
    while t < tend:
        # get current stress
        g = grad(u)
        stress = lam * trace(g) * kmat + mu * (g + transpose(g))
        mypde.setValue(X=-stress * abc)  # set PDE values
        accel = mypde.getSolution()  # get PDE solution for accelleration
        u_p1 = (2.0 * u - u_m1) + h * h * accel  # calculate displacement
        u_p1 = u_p1 * abc  # apply boundary conditions
        u_m1 = u
        u = u_p1  # shift values by 1
        # save current displacement, acceleration and pressure
        if t >= rtime:
            saveVTK(
                os.path.join(save_path, "ex08c.%05d.vtu" % n),
                vector_displacement=u,
                displacement=length(u),
                vector_acceleration=accel,
                acceleration=length(accel),
                tensor=stress,
            )
            rtime = rtime + rtime_inc  # increment data save time
        # increment loop values
        t = t + h
        n = n + 1
        if n < ls:
            y = source[n] * (cos(length(x - xc) * 3.1415 / src_length) + 1) * whereNegative(length(x - xc) - src_length)
            y = y * src_dir
            mypde.setValue(y=y)  # set the source as a function on the boundary
        print("time step %d, t=%s" % (n, t))
Пример #29
0
    cut_loc=[] #where the cross section of the source along x will be
    src_cut=[] #where the cross section of the source will be
    # create locations for source cross section
    for i in range(ndx//2-ndx//10,ndx//2+ndx//10):
        cut_loc.append(xstep*i)
        src_cut.append([xstep*i,xc[1]])
    # locate the nearest nodes to the points in src_cut
    src=Locator(mydomain,src_cut)
    src_cut=src.getValue(u) #retrieve the values from the nodes
    # plot the x locations vs value and save the figure
    pl.plot(cut_loc,src_cut)
    pl.axis([xc[0]-src_radius*3,xc[0]+src_radius*3,0.,2.*U0])
    pl.savefig(os.path.join(savepath,"source_line.png"))

    ####################################################ITERATION VARIABLES
    n=0 # iteration counter
    t=0 # time counter
    ##############################################################ITERATION
    while t<tend:
        g=grad(u); pres=csq*h*h*g # get current pressure
        mypde.setValue(X=-pres,Y=(2.*u-u_m1)) # set values in pde
        u_p1 = mypde.getSolution() # get the new displacement
        u_m1=u; u=u_p1 # shift values back one time step for next iteration
            # save current displacement, acceleration and pressure
        if (t >= rtime):
            saveVTK(os.path.join(savepath,"ex07a.%i.vtu"%n),displacement=length(u),tensor=pres)
            rtime=rtime+rtime_inc #increment data save time
        # increment loop values
        t=t+h; n=n+1
        print("time step %d, t=%s"%(n,t))
Пример #30
0
    kro = kronecker(domain)
    source1 = [3. * mx / 8., 0]
    source2 = [5. * mx / 8., 0]

    c1 = length(exp(-length(x - source1) / (10.)))
    c1 = c1 / integrate(c1)
    c2 = -length(exp(-length(x - source2) / (10.)))
    c2 = c2 / integrate(c2)
    sourceg = cur * (c1 - c2)

    res = res1 * wherePositive(x[1] - my / 3) + res2 * whereNegative(
        x[1] - my / 3) * wherePositive(
            x[1] - my * 2 / 3) + res3 * whereNegative(x[1] - my * 2 / 3)
    con = 1 / res
    q = whereZero(x[1] - my) + whereZero(x[0]) + whereZero(x[0] - mx)
    ###############################################ESCRIPT PDE CONSTRUCTION

    mypde = LinearPDE(domain)
    mypde.setValue(A=con * kro, Y=sourceg, q=q, r=0)
    #mypde.setSymmetryOn()
    sol = mypde.getSolution()

    # Save the output to file.
    saveVTK(os.path.join(save_path,"ex11b.vtu"),\
            source=sourceg,\
            res_pot=sol,\
            res=res,\
            curden=-con*grad(sol),\
            efield=-grad(sol))
Пример #31
0
def wavePropagation(dom,rho,mu,lmbd,eta):
   x=Function(dom).getX()
   # ... open new PDE ...
   mypde=LinearPDE(dom)
   mypde.setSolverMethod(LinearPDE.LUMPING)
   k=kronecker(Function(dom))
   mypde.setValue(D=k*rho)

   dt=(1./5.)*inf(dom.getSize()/sqrt((2*mu+lmbd)/rho))
   if output: print("time step size = ",dt)
   # ... set initial values ....
   n=0
   t=0
   t_write=0.
   n_write=0
   # initial value of displacement at point source is constant (U0=0.01)
   # for first two time steps
   u=Vector(0.,Solution(dom))
   v=Vector(0.,Solution(dom))
   a=Vector(0.,Solution(dom))
   a2=Vector(0.,Solution(dom))
   v=Vector(0.,Solution(dom))

   if not os.path.isdir(WORKDIR): os.mkdir(WORKDIR)

   starttime = time.clock()
   while t<t_end and n<n_end:
     if output: print(n+1,"-th time step t ",t+dt," max u and F: ",Lsup(u), end=' ')
     # prediction:
     u_pr=u+dt*v+(dt**2/2)*a+(dt**3/6)*a2
     v_pr=v+dt*a+(dt**2/2)*a2
     a_pr=a+dt*a2
     # ... get current stress ....
     eps=symmetric(grad(u_pr))
     stress=lmbd*trace(eps)*k+2*mu*eps
     # ... force due to event:
     if abs(t-tc)<5*tc_length:
        F=exp(-((t-tc)/tc_length)**2)*exp(-(length(x-xc)/src_radius)**2)*event
        if output: print(Lsup(F))
     else:
        if output: print(0.)
     # ... get new acceleration ....
     mypde.setValue(X=-stress,Y=F-eta*v_pr)
     a=mypde.getSolution()
     # ... get new displacement ...
     da=a-a_pr
     u=u_pr+(dt**2/12.)*da
     v=v_pr+(5*dt/12.)*da
     a2+=da/dt
     # ... save current acceleration in units of gravity and displacements 
     if output:
          if t>=t_write: 
             saveVTK(os.path.join(WORKDIR,"disp.%i.vtu"%n_write),displacement=u, amplitude=length(u))
             t_write+=dt_write
             n_write+=1
     t+=dt
     n+=1

   endtime = time.clock()
   totaltime = endtime-starttime
   global netotal
   print(">>number of elements: %s, total time: %s, per time step: %s <<"%(netotal,totaltime,totaltime/n))
Пример #32
0
    traction = matrix_mult(sig_bounda, dom.getNormal())
    tract = traction * wallBF
    forceWall = integrate(tract, where=FunctionOnBoundary(dom))
    lengthWall = integrate(wallBF, where=FunctionOnBoundary(dom))
    fout.write(
        str(t * vel) + ' ' + str(forceWall[0]) + ' ' + str(lengthWall) + '\n')

    vR = prob.getLocalVoidRatio()
    rotation = prob.getLocalAvgRotation()
    fabric = prob.getLocalFabric()
    strain = prob.getCurrentStrain()
    saveGauss2D(name='./result/gauss/time_' + str(t) + '.dat',
                strain=strain,
                stress=stress,
                fabric=fabric)
    volume_strain = trace(strain)
    dev_strain = symmetric(strain) - volume_strain * k / dim
    shear = sqrt(2 * inner(dev_strain, dev_strain))
    saveVTK("./result/vtk/retainingSmooth_%d.vtu" % t,
            disp=disp,
            stress=stress,
            shear=shear,
            e=vR,
            rot=rotation)

prob.getCurrentPacking(pos=packNo, time=t, prefix='./result/packing/')
time_elapse = time.time() - time_start
fout.write("#Elapsed time in hours: " + str(time_elapse / 3600.) + '\n')
fout.close()
prob.exitSimulation()
Пример #33
0
    ####################################################ITERATION VARIABLES
    n = 0  # iteration counter
    t = 0  # time counter
    ##############################################################ITERATION
    while t < tend:
        g = grad(u)
        pres = csq * g  # get current pressure
        mypde.setValue(X=-pres)  # set values in pde
        accel = mypde.getSolution()  # get new acceleration
        u_p1 = (2.0 * u - u_m1) + h * h * accel  # calculate the displacement for the next time step
        u_m1 = u
        u = u_p1  # shift values back one time step for next iteration
        # save current displacement, acceleration and pressure
        if t >= rtime:
            saveVTK(
                os.path.join(savepath, "ex07b.%i.vtu" % n),
                displacement=length(u),
                acceleration=length(accel),
                tensor=pres,
            )
            rtime = rtime + rtime_inc  # increment data save time
        u_rec0.append(rec.getValue(u))  # location specific recording
        # increment loop values
        t = t + h
        n = n + 1
        print("time step %d, t=%s" % (n, t))

    # save location specific recording to file
    pl.savetxt(os.path.join(savepath, "u_rec.asc"), u_rec0)
Пример #34
0
                       f_rg=DIFFCOAL["f_r"],
                 wells=[ well_P1, ], g= CONST_G)
# this needs to be revised:.
model.setInitialState(S_fg=0,  c_mg=None, p_top=p_top, p_bottom=p_bottom)
model.getPDEOptions().setVerbosityOn()
model.getPDEOptions().setSolverMethod(model.getPDEOptions().DIRECT)
model.setIterationControl(iter_max=10, rtol=1.e-4, verbose=True)
print("<%s> Problem set up completed."%time.asctime())
t=0
n_t = 0

p, S_fg, c_mg, BHP, q_gas,q_water =model.getState()

if SAVE_VTK:
    FN=os.path.join(OUTPUT_DIR, "state.%d.vtu"%n_t)
    saveVTK(FN,p=p, S_fg=S_fg, c_mg=c_mg)
    print("<%s> Initial state saved to file %s."%(time.asctime(),FN))
    print(t/U.day, well_P1.locator(p)/U.psi, well_P1.locator(S_fg), well_P1.locator(c_mg)/U.Mscf*U.ft**3)
    print(t/U.day, well_P1.locator(BHP)/U.psi, well_P1.locator(q_gas)/U.Mcf*U.day, well_P1.locator(q_water)/U.Barrel*U.day)


for dt in DT:
    print("<%s>Time step %d, time = %e days started:"%(time.asctime(), n_t+1, (t+dt)/U.day))

    model.update(dt)

    p, S_fg, c_mg, BHP, q_gas,q_water = model.getState()

    if SAVE_VTK:
        FN=os.path.join(OUTPUT_DIR, "state.%d.vtu"%(n_t+1))
        saveVTK(FN,p=p, S_fg=S_fg, c_mg=c_mg)
Пример #35
0
    kro=kronecker(domain)

    q=whereZero(x[1]-my)+whereZero(x[1])+whereZero(x[0])+whereZero(x[0]-mx)
    ###############################################ESCRIPT PDE CONSTRUCTION

    mypde=LinearPDE(domain)
    mypde.setValue(A=kro,Y=4.*3.1415*G*rho)
    mypde.setValue(q=q,r=0)
    mypde.setSymmetryOn()
    sol=mypde.getSolution()

    g_field=grad(sol) #The gravitational acceleration g.
    g_fieldz=g_field*[0,1] #The vertical component of the g field.
    gz=length(g_fieldz) #The magnitude of the vertical component.
    # Save the output to file.
    saveVTK(os.path.join(save_path,"ex10a.vtu"),\
            grav_pot=sol,g_field=g_field,g_fieldz=g_fieldz,gz=gz)

    ##################################################REGRIDDING & PLOTTING


    xi, yi, zi = toRegGrid(sol, nx=50, ny=50)
    pl.matplotlib.pyplot.autumn()
    pl.contourf(xi,yi,zi,10)
    pl.xlabel("Horizontal Displacement (m)")
    pl.ylabel("Depth (m)")
    pl.savefig(os.path.join(save_path,"Ucontour.png"))
    print("Solution has been plotted  ...")

    cut=int(len(xi)//2)

    pl.clf()
Пример #36
0
from esys.escript.linearPDEs import LinearPDE
try:
    from esys.finley import Rectangle
    HAVE_FINLEY = True
except ImportError:
    HAVE_FINLEY = False
from esys.weipa import saveVTK

if not HAVE_FINLEY:
    print("Finley module not available")
else:
    #... set some parameters ...
    kappa=1.
    omega=0.1
    eta=10.
    #... generate domain ...
    mydomain = Rectangle(l0=5.,l1=1.,n0=50, n1=10)
    #... open PDE and set coefficients ...
    mypde=LinearPDE(mydomain)
    mypde.setSymmetryOn()
    n=mydomain.getNormal()
    x=mydomain.getX()
    mypde.setValue(A=kappa*kronecker(mydomain),D=omega,Y=omega*x[0], \
                   d=eta,y=kappa*n[0]+eta*x[0])
    #... calculate error of the PDE solution ...
    u=mypde.getSolution()
    print("error is ",Lsup(u-x[0]))
    # output should be similar to "error is 1.e-7"
    saveVTK("x0.vtu",sol=u)
 
Пример #37
0
        dp[2] = (self.slip[2] - jump(u[2])) * lam_mu / h
        return dp


dom = ReadMesh("meshfault3D.fly", integrationOrder=-1)
prop = SlippingFault(dom)
d = dom.getDim()
x = dom.getX()[0]
# x=dom.getX()[d-1]
mask = whereZero(x - inf(x)) * numpy.ones((d, ))
x = FunctionOnContactZero(dom).getX()
s = numpy.array([-100000., 1., 1.])
for i in range(3):
    d = fend[i] - fstart[i]
    if d > 0:
        q = (x[i] - fstart[i]) / d
        s = q * (1 - q) * 4 * s
    elif d < 0:
        q = (x[i] - fend[i]) / d
        s = q * (1 - q) * 4 * s
u0 = Vector(0., Solution(dom))
p0 = Vector(1., FunctionOnContactZero(dom))
prop.initialize(fixed_u_mask=mask,
                slip=Data(s, FunctionOnContactZero(dom)),
                density=rho,
                lmbd=lam_lmbd,
                mu=lam_mu)
u, p = prop.solve(u0, p0, iter_max=50, tolerance=0.13, accepted_reduction=1.)
saveVTK("dis.vtu", u=u)
saveVTK("fault.vtu", sigma=p, s=jump(u))
Пример #38
0
    rho=rho*mask
    kro=kronecker(domain)

    mass=rho*vol(domain)
    ipot=FunctionOnBoundary(domain)
    xb=ipot.getX()

    q=whereZero(x[2]-inf(x[2]))
    ###############################################ESCRIPT PDE CONSTRUCTION

    mypde=LinearPDE(domain)
    mypde.setValue(A=kro,Y=4.*3.1415*G*rho,q=q,r=0)
    mypde.setSymmetryOn()
    sol=mypde.getSolution()
    saveVTK(os.path.join(save_path,"ex10b.vtu"),\
            grav_pot=sol,\
            g_field=-grad(sol),\
            g_fieldz=-grad(sol)*[0,0,1],\
            gz=length(-grad(sol)*[0,0,1]))

    ################################################MODEL SIZE SAMPLING
    sampler=[]
    for i in range(-250,250,1):
        sampler.append([i,0,250])

    sample=[] # array to hold values
    rec=Locator(domain,sampler) #location to record
    psol=rec.getValue(sol)
    np.savetxt(os.path.join(save_path,"example10b_%04d.asc"%mx),psol)

Пример #39
0
    sig_bounda = interpolate(sig, FunctionOnBoundary(dom))
    traction = matrix_mult(sig_bounda, dom.getNormal())
    tractTop = traction * topSurf
    forceTop = integrate(tractTop, where=FunctionOnBoundary(dom))
    areaTop = integrate(topSurf, where=FunctionOnBoundary(dom))
    fout.write(
        str(t * vel / lz) + ' ' + str(forceTop[2]) + ' ' + str(areaTop) + '\n')

    vR = prob.getLocalVoidRatio()
    rotation = prob.getLocalAvgRotation()
    fabric = prob.getLocalFabric()
    strain = prob.getCurrentStrain()
    saveGauss3D(name='./result/gauss/time_' + str(t) + '.dat',
                strain=strain,
                stress=stress,
                fabric=fabric)
    volume_strain = trace(strain)
    dev_strain = symmetric(strain) - volume_strain * k / dim
    shear = sqrt(2. / 3. * inner(dev_strain, dev_strain))
    saveVTK("./result/vtk/triaxialRough_%d.vtu" % t,
            disp=disp,
            shear=shear,
            e=vR,
            rot=rotation)

prob.getCurrentPacking(pos=packNo, time=t, prefix='./result/packing/')
time_elapse = time.time() - time_start
fout.write("#Elapsed time in hours: " + str(time_elapse / 3600.) + '\n')
fout.close()
prob.exitSimulation()
Пример #40
0
    # ... create a slip distribution on the fault:
    p, m = fs.getParametrization(mydomain.getX(), tag=1)
    p0, p1 = fs.getW0Range(tag=1)
    s = m * (p - p0) * (p1 - p) / ((p1 - p0) / 2)**2 * slip_max * [0., 1.]
    # ... calculate stress according to slip:
    D = symmetric(grad(s))
    chi, d = fs.getSideAndDistance(D.getFunctionSpace().getX(), tag=1)
    sigma_s = (mu * D + lam * trace(D) * kronecker(mydomain)) * chi
    #... open symmetric PDE ...
    mypde = LinearPDE(mydomain)
    mypde.setSymmetryOn()
    #... set coefficients ...
    C = Tensor4(0., Function(mydomain))
    for i in range(mydomain.getDim()):
        for j in range(mydomain.getDim()):
            C[i, i, j, j] += lam
            C[j, i, j, i] += mu
            C[j, i, i, j] += mu
    # ... fix displacement in normal direction
    x = mydomain.getX()
    msk=whereZero(x[0])*[1.,0.] + whereZero(x[0]-1.)*[1.,0.] \
       +whereZero(x[1])*[0.,1.] + whereZero(x[1]-1.)*[0.,1.]
    mypde.setValue(A=C, X=-0.5 * sigma_s, q=msk)
    #... solve pde ...
    mypde.getSolverOptions().setVerbosityOn()
    v = mypde.getSolution()
    # .. write the displacement to file:
    D = symmetric(grad(v))
    sigma = (mu * D + lam * trace(D) * kronecker(mydomain)) + 0.5 * sigma_s
    saveVTK("slip.vtu", disp=v + 0.5 * chi * s, stress=sigma)
Пример #41
0
NE=50
dom=Rectangle(NE,1,l1=1./NE)
dom=Rectangle(NE,NE)
fc=TransportPDE(dom,numEquations=1)
fc.getSolverOptions().setVerbosityOn()
fc.getSolverOptions().setODESolver(SolverOptions.LINEAR_CRANK_NICOLSON)
fc.getSolverOptions().setODESolver(SolverOptions.BACKWARD_EULER)
fc.getSolverOptions().setODESolver(SolverOptions.CRANK_NICOLSON)
fc.setValue(M=1,C=[-1,0])
x=dom.getX()
u0=whereNegative(x[0]-1./NE)

c=0
t=0

saveVTK("u.%s.vtu"%c,u=u0)
fc.setInitialSolution(u0)
dt=fc.getSafeTimeStepSize() 

print("u0 =",u0)
T_END=dt
print("dt = ",dt)
while t<T_END:
    print("time step t=",t+dt)
    u=fc.getSolution(dt)
    saveVTK("u.%s.vtu"%(c+1,),u=u)
    print("u =",u)
    c+=1
    t+=dt
Пример #42
0
    # bottom temperature:
    T_bot=100
    # generate domain:
    mydomain=Rectangle(l0=L0,l1=L1,n0=20,n1=20)
    x=mydomain.getX()
    # set boundray temperature:
    T_D=T_bot/L1*(L1-x[1])
    # set heat source:
    Q=Qc*whereNegative(length(x-xc)-r)
    # generate domain:
    mypde=LinearPDE(mydomain)
    mypde.setSymmetryOn()
    # set PDE coefficients:
    mypde.setValue(A=dt*k*kronecker(mydomain), D=dt*rhocp, 
                    r=T_D, q=whereZero(x[1])+whereZero(x[1]-L1))
    # initial temperature
    T=T_D 
    # step counter and time marker:
    N=0; t=0
    # stop when t_end is reached:
    while t<t_end:
        print("time step %d, t=%s"%(N,t))
        # update PDE coefficient:
        mypde.setValue(Y=dt*rhocp*T+dt*Q)
        # new temperature:
        T=mypde.getSolution()
        # save as VTK for visualisation:
        saveVTK("u.%s.vtu"%N,T=T)
        # increase counter and marker:
        N+=1; t+=dt
Пример #43
0
    mypde=LinearPDE(model) #assigns a domain to our PDE
    mypde.setSymmetryOn() #set the fast solver on for symmetry
    #establish location of boundary between two materials
    x=Function(model).getX()
    bound = length(x-ic)-r #where the boundary will be located
    kappa = kappai*whereNegative(bound)+kappac*(1-whereNegative(bound))
    rhocp = rhocpi*whereNegative(bound)+rhocpc*(1-whereNegative(bound))
    #define our PDE coeffs
    mypde.setValue(A=kappa*kronecker(model),D=rhocp/h)
    #set initial temperature (make sure we use the right sample points)
    x=Solution(model).getX()
    bound = length(x-ic)-r #where the boundary will be located
    T= Ti*whereNegative(bound)+Tc*(1-whereNegative(bound))

    ########################################################START ITERATION
    while t<=tend:
          i+=1 #counter
          t+=h #current time
          mypde.setValue(Y=qH+T*rhocp/h)
          T=mypde.getSolution()
          saveVTK(os.path.join(save_path,"data.%03d.vtu"%i), T=T)
          print("time step %s at t=%e days completed."%(i,t/day))

    # use 
    #
    #  cd data/example03
    #  mayavi2 -d data.001.vtu -m Surface
    #
    # to visualize the results (mayavi2 must be installed on your system).
    #
    print("volume : ",integrate(r))
    #
    #  step 1:
    #
    # calculate normal 
    n_d=dom.getNormal()
    t_d=matrixmult(numpy.array([[0.,-1.],[1.,0]]),n_d)
    sigma_d=(sign(inner(t_d,U))*alpha_w*t_d-n_d)*Pen*clip(inner(n_d,U),0.)
    print("sigma_d =",inf(sigma_d),sup(sigma_d))

    momentumStep1.setValue(D=r*ro*kronecker(dom),
                           Y=r*ro*U+dt*r*[0.,-ro*g], 
                           X=-dt*r*(dev_stress-teta3*p*kronecker(dom)), 
                           y=sigma_d*face_mask*r_b)
    U_star=momentumStep1.getSolution()
    saveVTK("u.vtu",u=U_star,u0=U)
    #
    #  step 2:
    #
    # U2=U+teta1*(U_star-U)
    U2=U+teta1*U_star
    gg2=grad(U2)
    div_U2=gg2[0,0]+gg2[1,1]+U2[0]/r

    grad_p=grad(p)

    pressureStep2.setValue(A=r*dt*B*teta1*teta2/ro*dt*kronecker(dom), 
                           D=r,                            
                           Y=-dt*B*r*div_U2,
                           X=-r*B*dt**2/ro*teta1*(1-teta3)*grad_p)
    dp=pressureStep2.getSolution()
Пример #45
0
  
# generate mesh: here 10x20 mesh of order 2
domain=dudley.Rectangle(10,20,1,l0=0.5,l1=1.0)
# get handel to nodes and elements:
e=Function(domain)
fe=FunctionOnBoundary(domain)
n=ContinuousFunction(domain)
#
# set a mask msk of type vector which is one for nodes and components set be a constraint:
#
msk=whereZero(n.getX()[0])*[1.,1.]
#
#  set the normal stress components on face elements.
#  faces tagged with 21 get the normal stress [0,-press0].
#
# now the pressure is set to zero for x0 coordinates bigger then 0.1
press=whereNegative(fe.getX()[0]-0.1)*200000.*[1.,0.]
# assemble the linear system:
mypde=LinearPDE(domain)
mypde.setValue(A=setHookTensor(e,lamb,nu),y=press,q=msk,r=[0,0])
mypde.setSymmetryOn()
mypde.getSolverOptions().setVerbosityOn()
mypde.getSolverOptions().setPreconditioner(mypde.getSolverOptions().AMG)
# solve for the displacements:
u_d=mypde.getSolution()
# get the gradient and calculate the stress:
g=grad(u_d)
stress=lamb*trace(g)*kronecker(domain)+nu*(g+transpose(g))
# write the hydrostatic pressure:
saveVTK("result.vtu",displacement=u_d,pressure=trace(stress)/domain.getDim())
Пример #46
0
         h=FunctionOnContactZero(self.domain).getSize()
         # print jump(u)-self.slip
         dp[0]=(self.slip[0]-jump(u[0]))*lam_mu/h
         dp[1]=(self.slip[1]-jump(u[1]))*lam_mu/h
         dp[2]=(self.slip[2]-jump(u[2]))*lam_mu/h
         return  dp


dom=ReadMesh("meshfault3D.fly",integrationOrder=-1)
prop=SlippingFault(dom)
d=dom.getDim()
x=dom.getX()[0]
# x=dom.getX()[d-1]
mask=whereZero(x-inf(x))*numpy.ones((d,))
x=FunctionOnContactZero(dom).getX()
s=numpy.array([-100000.,1.,1.])
for i in range(3):
     d=fend[i]-fstart[i]
     if d>0:
         q=(x[i]-fstart[i])/d
         s=q*(1-q)*4*s
     elif d<0:
         q=(x[i]-fend[i])/d
         s=q*(1-q)*4*s
u0=Vector(0.,Solution(dom))
p0=Vector(1.,FunctionOnContactZero(dom))
prop.initialize(fixed_u_mask=mask,slip=Data(s,FunctionOnContactZero(dom)), density=rho,lmbd=lam_lmbd, mu=lam_mu)
u,p=prop.solve(u0,p0,iter_max=50,tolerance=0.13,accepted_reduction=1.)
saveVTK("dis.vtu",u=u)
saveVTK("fault.vtu",sigma=p,s=jump(u))
Пример #47
0
    res=1000.0
    con=1/res
    cur=10.

    ################################################ESTABLISHING PARAMETERS
    #the folder to put our outputs in, leave blank "" for script path 
    save_path= os.path.join("data","example11")
    #ensure the dir exists
    mkDir(save_path)

    ####################################################DOMAIN CONSTRUCTION
    domain = Rectangle(l0=mx,l1=my,n0=ndx, n1=ndy)
    x=Solution(domain).getX()

    kro=kronecker(domain)
    source1=[mx/4.,0]; source2=[3.*mx/4.,0]

    sourceg=length(exp(-length(x-source1)/(100.)))+length(exp(-length(x-source2)/(100.)))
    sourceg=sourceg/integrate(sourceg)

    q=whereZero(x[1]-my)+whereZero(x[0])+whereZero(x[0]-mx)
    ###############################################ESCRIPT PDE CONSTRUCTION

    mypde=LinearPDE(domain)
    mypde.setValue(A=kro*con,Y=sourceg,q=q,r=0)
    mypde.setSymmetryOn()
    sol=mypde.getSolution()

    # Save the output to file.
    saveVTK(os.path.join(save_path,"ex11a.vtu"),source=sourceg,res_pot=sol)
Пример #48
0
         meanValue(lame_eff),
         meanValue(xi),
         meanValue(gamma),
         meanValue(alpha),
         meanValue(alpha_dot),
     )
 )
 print("time step %s (t=%s) completed." % (n, t))
 #
 #  .... visualization
 #
 if t >= t_vis or n > n_vis:
     saveVTK(
         os.path.join(VIS_DIR, "state.%d.vtu" % counter_vis),
         u=u,
         dalpha=alpha,
         I1=trace(eps_e),
         I2=length(eps_e) ** 2,
         xi=safeDiv(trace(eps_e), length(eps_e)),
     )
     print("visualization file %d for time step %e generated." % (counter_vis, t))
     counter_vis += 1
     t_vis += DT_VIS
     n_vis += DN_VIS
 #
 #   control time step size:
 #
 ss = sup(length(deps))
 if ss > 0:
     dt_new = DEPS_MAX / ss * dt
     print("\ttime step size to control strain increment %s." % (dt_new,))
 else:
Пример #49
0
        solution.initialize(fixed_u_mask=boundary_cond, eta=eta, f=Y)
        velocity, pressure = solution.solve(velocity,
                                            pressure,
                                            max_iter=max_iter,
                                            verbose=verbose,
                                            usePCG=True)

        print("Max velocity =", Lsup(velocity), "m/s")

        #Courant condition
        dt = 0.4 * h / (Lsup(velocity))
        print("dt", dt)

        #displace the mesh
        displacement = velocity * dt
        coordinates = mesh.getX()
        newx = interpolate(coordinates + displacement,
                           ContinuousFunction(mesh))
        mesh.setX(newx)

        time += dt

        vel_mag = length(velocity)

        #save velocity and pressure output
        saveVTK("vel.%2.2i.vtu" % (t),
                vel=vel_mag,
                vec=velocity,
                pressure=pressure)
        t = t + 1.0
Пример #50
0
else:
    S = numpy.array([sin(STRIKE), cos(STRIKE), 0.])
    X0 = [bb[0][0], bb[1][0], bb[2][1]]
    dd = [-cos(ALPHA), 0., -sin(ALPHA)]
r = sqrt(length(x - X0)**2 - inner(X0 - x, S)**2)
v = V_MAX * r * dd
mask = MaskFromBoundaryTag(dom, "subduction") * [1. for i in range(DIM)]
#
#  back of the domain
#
v = v * (1. - whereZero(x[0] - bb[0][1]) * kronecker(DIM)[0])
mask += whereZero(x[0] - bb[0][1]) * kronecker(DIM)[0]
#
#  bottom of the domain
#
v = v * (1. -
         ((bb[DIM - 1][1] - x[DIM - 1]) / DEPTH)**N * kronecker(DIM)[DIM - 1])
mask += whereZero(x[DIM - 1] - bb[DIM - 1][0]) * kronecker(DIM)[DIM - 1]
#
#  faces of the domain:
#
if DIM == 3:
    v = v * (1. - (((x[1] - bb[1][0]) * (bb[1][1] - x[1]) /
                    (0.5 * LY)**2)**N * kronecker(DIM)[1]))
    mask += (whereZero(x[1] - bb[1][0]) +
             whereZero(x[1] - bb[1][1])) * kronecker(DIM)[1]
sc.initialize(eta=ETA, fixed_u_mask=mask)
p = Scalar(0., ReducedSolution(dom))
v, p = sc.solve(v, p, verbose=True)
saveVTK("u.vtu", velocity=v, pressure=p, m=mask)
      print("You're screwed...")
      sys.exit(1)    
    
    pressure -= penalty*eta*(trace(grad(velocity)))
    error = penalty*Lsup(trace(grad(velocity)))/Lsup(grad(velocity))
    print("\nPressure iteration number:", p_iter)
    print("error", error)
    ref = pressure*1.0
    
  return velocity, pressure
  
### MAIN LOOP, OVER TIME ###
while t_step <= t_step_end:
  print("######################")
  print("Time step:", t_step)
  print("######################")
  rho = update_parameter(phi, rho1, rho2)
  eta = update_parameter(phi, eta1, eta2)

  velocity, pressure = solve_vel_uszawa(rho, eta,  velocity, pressure)
  dt = 0.3*Lsup(mesh.getSize())/Lsup(velocity)
  phi = update_phi(phi, velocity, dt, t_step)

### PSEUDO POST-PROCESSING ###
  print("##########  Saving image", t_step, " ###########") 
  saveVTK("phi3D.%2.2i.vtk"%t_step,layer=phi)  

  t_step += 1

# vim: expandtab shiftwidth=4:
Пример #52
0
http://www.uq.edu.au
Primary Business: Queensland, Australia"""
__license__="""Licensed under the Apache License, version 2.0
http://www.apache.org/licenses/LICENSE-2.0"""
__url__="https://launchpad.net/escript-finley"

from esys.escript import *
from esys.escript.linearPDEs import Poisson
try:
    from esys.finley import Rectangle
    HAVE_FINLEY = True
except ImportError:
    HAVE_FINLEY = False
from esys.weipa import saveVTK

if not HAVE_FINLEY:
    print("Finley module not available")
else:
    # generate domain:
    mydomain = Rectangle(l0=1.,l1=1.,n0=40, n1=20)
    # define characteristic function of Gamma^D
    x = mydomain.getX()
    gammaD = whereZero(x[0])+whereZero(x[1])
    # define PDE and get its solution u
    mypde = Poisson(domain=mydomain)
    mypde.setValue(f=1,q=gammaD)
    u = mypde.getSolution()
    # write u to an external file
    saveVTK("u.vtu",sol=u)

Пример #53
0
    rot = prob.getLocalAvgRotation()  # average rotation at GP
    saveGauss2D(name='./result/gauss/time_' + str(t) + '.dat',
                strain=strain,
                fabric=fab,
                stress=stress)
    dom = prob.getDomain()  # domain updated (Lagrangian)
    proj = Projector(dom)
    flux = proj(flux)  # Darcy flux at node (reduced)
    p = proj(p)  # porosity at node (reduced)
    shear = proj(shear)  # shear strain at node (reduced)
    anis = proj(anis)
    rot = proj(rot)
    saveVTK("./result/vtk/undrain_%d.vtu" % t,
            disp=disp,
            pore=pore,
            flux=flux,
            shear=shear,
            p=p,
            anis=anis,
            rot=rot)
    sig = proj(stress)  # effective stress at node (reduced)
    sig_bound = interpolate(sig, FunctionOnBoundary(dom))
    traction = matrix_mult(sig_bound, dom.getNormal())
    tractTop = traction * topSurf
    forceTop = integrate(tractTop, where=FunctionOnBoundary(dom))
    lengthTop = integrate(topSurf, where=FunctionOnBoundary(dom))
    fout.write(
        str(t * vel * dt / ly) + ' ' + str(forceTop[1]) + ' ' +
        str(lengthTop) + '\n')

prob.getCurrentPacking(time=t, prefix='./result/packing/')
time_elapse = time.time() - time_start
Пример #54
0
    res.setTaggedValue("volume_3",res4)
    con=1/res
    x=Solution(domain).getX()

    kro=kronecker(domain)
    source1=[3.*mx/8.,my/2,0]; source2=[5.*mx/8.,my/2,0]

    c1=length(exp(-length(x-source1)/(10.))); c1=c1/integrate(c1)
    c2=-length(exp(-length(x-source2)/(10.))); c2=c2/integrate(c2)
    sourceg=cur*(c1-c2)

    q=whereZero(x[1]-my)+whereZero(x[1])+whereZero(x[0])+whereZero(x[0]-mx)+whereZero(x[2]-mz)
    ###############################################ESCRIPT PDE CONSTRUCTION

    mypde=LinearPDE(domain)
    mypde.setValue(A=con*kro,Y=sourceg,q=q,r=0)
    #mypde.setSymmetryOn()
    sol=mypde.getSolution()

    res.expand()

    # Save the output to file.
    saveVTK(os.path.join(save_path,"ex11c.vtu"),\
            source=sourceg,\
            res_pot=sol,\
            res=res,\
            curden=-con*grad(sol),\
            abscd=length(-con*grad(sol)),\
            efield=-grad(sol))

Пример #55
0
    if DIM==2:
        a0=1
        n0=1
        n1=0.5
        a1=-(a0*n0)/n1
        v[0]=a0*sin(pi*n0*x[0])* cos(pi*n1*x[1])
        v[1]=a1*cos(pi*n0*x[0])* sin(pi*n1*x[1])
    else:
        a0=1
        a1=1
        n0=2
        n1=2
        n2=0.5
        a2=-(a0*n0+a1*n1)/n2
        v[0]=a0*sin(pi*n0*x[0])* cos(pi*n1*x[1])* cos(pi*n2*x[2])
        v[1]=a1*cos(pi*n0*x[0])* sin(pi*n1*x[1])* cos(pi*n2*x[2])
        v[2]=a2*cos(pi*n0*x[0])* cos(pi*n1*x[1])* sin(pi*n2*x[2])


    mts=Mountains(mydomain,eps=EPS)
    while t<T_END:
        print("STEP ", t)
        mts.setVelocity(v*cos(OMEGA*t))
        Z=mts.update()
        
        saveVTK("state.%d.vtu"%n,sol=Z, v=mts.getVelocity())
        print("Integral(Z)=",integrate(Z),Lsup(mts.getVelocity()[DIM-1]))
        n+=1
        t+=mts.getSafeTimeStepSize()

Пример #56
0
    q = whereZero(x[1] - my) + whereZero(x[1]) + whereZero(
        x[0]) + whereZero(x[0] - mx)
    ###############################################ESCRIPT PDE CONSTRUCTION

    mypde = LinearPDE(domain)
    mypde.setValue(A=kro, Y=4. * 3.1415 * G * rho)
    mypde.setValue(q=q, r=0)
    mypde.setSymmetryOn()
    sol = mypde.getSolution()

    g_field = grad(sol)  #The gravitational acceleration g.
    g_fieldz = g_field * [0, 1]  #The vertical component of the g field.
    gz = length(g_fieldz)  #The magnitude of the vertical component.
    # Save the output to file.
    saveVTK(os.path.join(save_path,"ex10a.vtu"),\
            grav_pot=sol,g_field=g_field,g_fieldz=g_fieldz,gz=gz)

    ##################################################REGRIDDING & PLOTTING

    xi, yi, zi = toRegGrid(sol, nx=50, ny=50)
    pl.matplotlib.pyplot.autumn()
    pl.contourf(xi, yi, zi, 10)
    pl.xlabel("Horizontal Displacement (m)")
    pl.ylabel("Depth (m)")
    pl.savefig(os.path.join(save_path, "Ucontour.png"))
    print("Solution has been plotted  ...")

    cut = int(len(xi) // 2)

    pl.clf()
Пример #57
0
    S = numpy.array([0.0, 0.0])
    X0 = [bb[0][0], bb[1][1]]
    dd = [-cos(ALPHA), -sin(ALPHA)]
else:
    S = numpy.array([sin(STRIKE), cos(STRIKE), 0.0])
    X0 = [bb[0][0], bb[1][0], bb[2][1]]
    dd = [-cos(ALPHA), 0.0, -sin(ALPHA)]
r = sqrt(length(x - X0) ** 2 - inner(X0 - x, S) ** 2)
v = V_MAX * r * dd
mask = MaskFromBoundaryTag(dom, "subduction") * [1.0 for i in range(DIM)]
#
#  back of the domain
#
v = v * (1.0 - whereZero(x[0] - bb[0][1]) * kronecker(DIM)[0])
mask += whereZero(x[0] - bb[0][1]) * kronecker(DIM)[0]
#
#  bottom of the domain
#
v = v * (1.0 - ((bb[DIM - 1][1] - x[DIM - 1]) / DEPTH) ** N * kronecker(DIM)[DIM - 1])
mask += whereZero(x[DIM - 1] - bb[DIM - 1][0]) * kronecker(DIM)[DIM - 1]
#
#  faces of the domain:
#
if DIM == 3:
    v = v * (1.0 - (((x[1] - bb[1][0]) * (bb[1][1] - x[1]) / (0.5 * LY) ** 2) ** N * kronecker(DIM)[1]))
    mask += (whereZero(x[1] - bb[1][0]) + whereZero(x[1] - bb[1][1])) * kronecker(DIM)[1]
sc.initialize(eta=ETA, fixed_u_mask=mask)
p = Scalar(0.0, ReducedSolution(dom))
v, p = sc.solve(v, p, verbose=True)
saveVTK("u.vtu", velocity=v, pressure=p, m=mask)
Пример #58
0
   disp += du
   stress=prob.getCurrentStress()
   
   dom = prob.getDomain() # domain updated (Lagrangian)
   proj = Projector(dom)
   sig = proj(stress)

   sig_bounda = interpolate(sig,FunctionOnBoundary(dom))
   traction = matrix_mult(sig_bounda,dom.getNormal())
   tractFoot = traction*footingBase
   forceFoot = integrate(tractFoot,where=FunctionOnBoundary(dom))
   lengthFoot = integrate(footingBase,where=FunctionOnBoundary(dom))
   fout.write(str(t*vel)+' '+str(forceFoot[0])+' '+str(forceFoot[1])+' '+str(lengthFoot)+'\n')
      
   vR=prob.getLocalVoidRatio()
   rotation=prob.getLocalAvgRotation()
   fabric=prob.getLocalFabric()
   strain = prob.getCurrentStrain()
   saveGauss2D(name='./result/gauss/time_'+str(t)+'.dat',strain=strain,stress=stress,fabric=fabric)
   volume_strain = trace(strain)
   dev_strain = symmetric(strain) - volume_strain*k/dim
   shear = sqrt(2*inner(dev_strain,dev_strain))
   saveVTK("./result/vtk/footing_%d.vtu"%t,disp=disp,stress=stress,shear=shear,e=vR,rot=rotation)

prob.getCurrentPacking(pos=packNo,time=t,prefix='./result/packing/') # output packing
time_elapse = time.time() - time_start
fout.write("#Elapsed time in hours: "+str(time_elapse/3600.)+'\n')   
fout.close()
prob.exitSimulation()
Пример #59
0
    #~ #     print "u at point charge=",u_pc
    #~ u_pc_x1 = u_pot[0,0]
    #~ u_pc_y1 = u_pot[0,1]
    #~ u_pc_x2 = u_pot[1,0]
    #~ u_pc_y2 = u_pot[1,1]
    #~ u_pc_x3 = u_pot[2,0]
    #~ u_pc_y3 = u_pot[2,1]

    # save displacements at point source to file for t > 0
    #~ u_pc_data.write("%f %f %f %f %f %f %f\n"%(t,u_pc_x1,u_pc_y1,u_pc_x2,u_pc_y2,u_pc_x3,u_pc_y3))

    # ... save current acceleration in units of gravity and displacements 
    #saveVTK(os.path.join(savepath,"usoln.%i.vtu"%n),acceleration=length(a)/9.81,
    #displacement = length(u), tensor = stress, Ux = u[0] )
    if output == "vtk":
        saveVTK(os.path.join(savepath,"tonysol.%i.vtu"%n),output1 = length(u),tensor=stress)
    if output == "mpl":
        uT=np.array(u.toListOfTuples())
        uT=np.reshape(uT,(ndx+1,ndy+1,2))
        uTz=uT[:,:,1]+uT[:,:,0]
        uTz=np.transpose(uTz)
        pl.clf()
        # plot wave
        uTz[0,0]=maxi
        uTz[0,1]=-maxi
        CS = pl.imshow(uTz,cmap=cm.spectral)
        pl.colorbar()
        # labels and formatting
        pl.title("Wave Equation Cookbook Example ABC.")
        pl.xlabel("Horizontal Displacement (m)")
        pl.ylabel("Depth (m)")