示例#1
0
def shocktube(kernel_language='Fortran',
              solver_type='classic',
              use_petsc=False,
              outdir='shocktube_output',
              output_format='hdf5',
              disable_output=False,
              mx=10,
              my=10,
              mz=128,
              tfinal=1.0,
              num_output_times=10):

    if use_petsc:
        import clawpack.petclaw as pyclaw
    else:
        from clawpack import pyclaw

    if solver_type == 'classic':
        solver = pyclaw.ClawSolver3D(riemann.euler_3D)
        solver.dimensional_split = True
        solver.limiters = pyclaw.limiters.tvd.MC
        solver.cfl_max = 1.0
        solver.cfl_desired = 0.80
    elif solver_type == 'sharpclaw':
        solver = pyclaw.SharpClawSolver3D(riemann.euler_3D)
    else:
        raise Exception('Unrecognized solver_type.')

    domain = pyclaw.Domain((-1., -1., -1.), (1., 1., 1.), (mx, my, mz))

    state = pyclaw.State(domain, num_eqn)
    state.problem_data['gamma'] = gamma

    grid = state.grid

    X, Y, Z = grid.p_centers

    pressure = 3. * (Z <= 0) + 1. * (Z > 0)
    state.q[density, :, :, :] = 3. * (Z <= 0) + 1. * (Z > 0)
    state.q[x_momentum, :, :, :] = 0.
    state.q[y_momentum, :, :, :] = 0.
    state.q[z_momentum, :, :, :] = 0.
    state.q[energy, :, :, :] = pressure / (gamma - 1.)

    solver.all_bcs = pyclaw.BC.extrap

    claw = pyclaw.Controller()
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver
    claw.output_format = output_format
    claw.keep_copy = True
    if disable_output:
        claw.output_format = None
    claw.tfinal = tfinal
    claw.num_output_times = num_output_times
    claw.outdir = outdir

    return claw
示例#2
0
def setup(use_petsc=False,
          outdir='./_output',
          solver_type='classic',
          mx=30,
          my=30,
          mz=30,
          disable_output=False,
          problem='heterogeneous',
          **kwargs):
    """
    Example python script for solving the 3d acoustics equations.
    """
    from clawpack import riemann

    if use_petsc:
        import clawpack.petclaw as pyclaw
    else:
        from clawpack import pyclaw

    if solver_type == 'classic':
        solver = pyclaw.ClawSolver3D(riemann.vc_acoustics_3D)
        solver.limiters = pyclaw.limiters.tvd.MC
    elif solver_type == 'sharpclaw':
        solver = pyclaw.SharpClawSolver3D(riemann.vc_acoustics_3D)

    else:
        raise Exception('Unrecognized solver_type.')

    solver.bc_lower[0] = pyclaw.BC.periodic
    solver.bc_upper[0] = pyclaw.BC.periodic
    solver.bc_lower[1] = pyclaw.BC.periodic
    solver.bc_upper[1] = pyclaw.BC.periodic
    solver.bc_lower[2] = pyclaw.BC.periodic
    solver.bc_upper[2] = pyclaw.BC.periodic

    solver.aux_bc_lower[0] = pyclaw.BC.periodic
    solver.aux_bc_upper[0] = pyclaw.BC.periodic
    solver.aux_bc_lower[1] = pyclaw.BC.periodic
    solver.aux_bc_upper[1] = pyclaw.BC.periodic
    solver.aux_bc_lower[2] = pyclaw.BC.periodic
    solver.aux_bc_upper[2] = pyclaw.BC.periodic

    zl = 1.0  # Impedance in left half
    cl = 1.0  # Sound speed in left half

    if problem == 'homogeneous':
        if solver_type == 'classic':
            solver.dimensional_split = True
        else:
            solver.lim_type = 1

        solver.limiters = [4]

        mx = mx
        my = my
        mz = mz  # Grid resolution

        zr = 1.0  # Impedance in right half
        cr = 1.0  # Sound speed in right half

    if problem == 'heterogeneous':
        if solver_type == 'classic':
            solver.dimensional_split = False

        solver.bc_lower[0] = pyclaw.BC.wall
        solver.bc_lower[1] = pyclaw.BC.wall
        solver.bc_lower[2] = pyclaw.BC.wall
        solver.aux_bc_lower[0] = pyclaw.BC.wall
        solver.aux_bc_lower[1] = pyclaw.BC.wall
        solver.aux_bc_lower[2] = pyclaw.BC.wall

        mx = mx
        my = my
        mz = mz  # Grid resolution

        zr = 2.0  # Impedance in right half
        cr = 2.0  # Sound speed in right half

    solver.limiters = pyclaw.limiters.tvd.MC

    # Initialize domain
    x = pyclaw.Dimension('x', -1.0, 1.0, mx)
    y = pyclaw.Dimension('y', -1.0, 1.0, my)
    z = pyclaw.Dimension('z', -1.0, 1.0, mz)
    domain = pyclaw.Domain([x, y, z])

    num_eqn = 4
    num_aux = 2  # density, sound speed
    state = pyclaw.State(domain, num_eqn, num_aux)

    X, Y, Z = state.grid.p_centers

    state.aux[0, :, :, :] = zl * (X < 0.) + zr * (X >= 0.)  # Impedance
    state.aux[1, :, :, :] = cl * (X < 0.) + cr * (X >= 0.)  # Sound speed

    # Set initial density
    x0 = -0.5
    y0 = 0.
    z0 = 0.
    if problem == 'homogeneous':
        r = np.sqrt((X - x0)**2)
        width = 0.2
        state.q[0, :, :, :] = (np.abs(r) <= width) * (1. + np.cos(np.pi *
                                                                  (r) / width))
    elif problem == 'heterogeneous':
        r = np.sqrt((X - x0)**2 + (Y - y0)**2 + (Z - z0)**2)
        width = 0.1
        state.q[0, :, :, :] = (np.abs(r - 0.3) <= width) * (
            1. + np.cos(np.pi * (r - 0.3) / width))
    else:
        raise Exception('Unrecognized problem name')

    # Set initial velocities to zero
    state.q[1, :, :, :] = 0.
    state.q[2, :, :, :] = 0.
    state.q[3, :, :, :] = 0.

    claw = pyclaw.Controller()
    claw.keep_copy = True
    if disable_output:
        claw.output_format = None
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver
    claw.outdir = outdir
    claw.tfinal = 2.0

    return claw
示例#3
0
def euler3d(kernel_language='Fortran',solver_type='classic',\
            use_petsc=False,outdir='./_output',\
            output_format='hdf5',file_prefix='equil',disable_output=False,\
            mx=mxyz[0],my=mxyz[1],mz=mxyz[2],\
            tfinal=64.0,num_output_times=1):

    if use_petsc:
        import clawpack.petclaw as pyclaw
    else:
        from clawpack import pyclaw

    if solver_type == 'classic':
        solver = pyclaw.ClawSolver3D()
        solver.dimensional_split = True
        solver.limiters = pyclaw.limiters.tvd.minmod
        solver.num_ghost = 2
        solver.order = 2
        solver.fwave = True
    elif solver_type == 'sharpclaw':
        solver = pyclaw.SharpClawSolver3D()
    else:
        raise Exception('Unrecognized solver_type.')

    import logging
    solver.logger.setLevel(logging.DEBUG)

    import euler_3d_gmap
    solver.rp = euler_3d_gmap
    solver.num_eqn = 5
    solver.num_waves = 3
    solver.cfl_max = 0.6
    solver.cfl_desired = 0.5
    solver.dt_initial = 1.e-0
    solver.max_steps = 10000

    # Initialize Domain
    x = pyclaw.Dimension(0.0, 1.0, mx, name='x')
    y = pyclaw.Dimension(0.0, 1.0, my, name='y')
    z = pyclaw.Dimension(0.0, 1.0, mz, name='z')
    domain = pyclaw.Domain([x, y, z])

    num_aux = 15
    state = pyclaw.State(domain, solver.num_eqn, num_aux)
    state.problem_data['gamma'] = gamma
    state.problem_data['g_r'] = gR
    state.problem_data['gravity'] = gravityTerm
    state.problem_data['gravityflux'] = gravityEflux

    # Grids
    mbc = solver.num_ghost
    grid = state.grid

    # Computational Grid Sizes
    dxc = domain.grid.delta[0]
    dyc = domain.grid.delta[1]
    dzc = domain.grid.delta[2]
    pmx, pmy, pmz = grid.num_cells[0], grid.num_cells[1], grid.num_cells[2]

    # Computational Grid Centers and Edges
    centers = grid.c_centers  # centers (Comp.)
    centersBC = grid.c_centers_with_ghost(mbc)  # centers w Ghost (Comp.)
    edgesBC = grid.c_edges_with_ghost(mbc)  # edges w Ghost (Comp.)

    # Grid Centers Without Boundary Cells (1D Slice) - Comp. and Phys.
    xcc = grid.x.centers  # x centers (Comp.)
    ycc = grid.y.centers  # y centers (Comp.)
    zcc = grid.z.centers  # z centers (Comp.)
    xcp, ycp, zcp = mg.mapc2pwrapper(xcc, ycc, zcc, pmz, xyzMin, xyzMax,
                                     mapType)

    # Grid Centers Without Boundary Cells (3D Arrays)
    Xcc, Ycc, Zcc = centers[0][:][:][:], centers[1][:][:][:], centers[
        2][:][:][:]
    Xcp, Ycp, Zcp = mg.mapc2pwrapper(Xcc, Ycc, Zcc, pmz, xyzMin, xyzMax,
                                     mapType)
    Xcp = np.reshape(Xcp, [pmx, pmy, pmz], order='F')  # x centers (Phys.)
    Ycp = np.reshape(Ycp, [pmx, pmy, pmz], order='F')  # y centers (Phys.)
    Zcp = np.reshape(Zcp, [pmx, pmy, pmz], order='F')  # z centers (Phys.)

    # Grid Edges With Boundary Cells (1D Slice along z)- Comp. and Phys.
    xecZ = edgesBC[0][0][0][:]  # x edges along z (Comp.)
    yecZ = edgesBC[1][0][0][:]  # y edges along z (Comp.)
    zecZ = edgesBC[2][0][0][:]  # z edges along z (Comp.)
    xepZ, yepZ, zepZ = mg.mapc2pwrapper(xecZ, yecZ, zecZ, pmz, xyzMin, xyzMax,
                                        mapType)

    # Grid Centers With Boundary Cells (1D Slice along z) - Comp. and Phys.
    global zcpZ
    xccZ = centersBC[0][0][0][:]  # x centers along z (Comp.)
    yccZ = centersBC[1][0][0][:]  # y centers along z (Comp.)
    zccZ = centersBC[2][0][0][:]  # z centers along z (Comp.)
    xcpZ, ycpZ, zcpZ = mg.mapc2pwrapper(xccZ, yccZ, zccZ, pmz, xyzMin, xyzMax,
                                        mapType)

    if np.sqrt(xepZ[0]**2 + yepZ[0]**2 + zepZ[0]**2) <= 0:
        print "WARNING: z may go below Earth's surface", " zepZ: ", zepZ[0:10]

    # Create vectors for 1D pressure and density column with boundary cells
    mz0 = pmz + 2 * mbc
    global p0, rho0, Mavg
    p0 = np.zeros([mz0], dtype='float', order='F')
    rho0 = np.zeros([mz0], dtype='float', order='F')
    Mavg = np.zeros([mz0], dtype='float', order='F')

    # Set the equilibrium pressure such that dp/dz = -rho*gR
    p0, rho0, Mavg = setEquilibriumAtmosphere(p0, rho0, Mavg)

    # Modify the equilibrium such that dp/dz = -rho*gR is held numerically
    p0 = modifyEquilibriumAtmosphere(zepZ, p0, rho0)

    # Set the auxiliary variables
    xlower, ylower, zlower = edgesBC[0][0][0][0], edgesBC[1][0][0][0], edgesBC[
        2][0][0][0]
    dxc, dyc, dzc = domain.grid.delta[0], domain.grid.delta[
        1], domain.grid.delta[2]

    global auxtmp
    auxtmp = np.zeros([num_aux, pmx + 2 * mbc, pmy + 2 * mbc, pmz + 2 * mbc],
                      dtype='float',
                      order='F')
    auxtmp = mg.setauxiliaryvariables(num_aux, mbc, pmx, pmy, pmz, xlower,
                                      ylower, zlower, dxc, dyc, dzc, xyzMin,
                                      xyzMax, mapType)
    state.aux[:, :, :, :] = auxtmp[:, mbc:-mbc, mbc:-mbc, mbc:-mbc]

    # Set Index for Capcaity Function in state.aux (Python 0-based)
    state.index_capa = 12

    # Set the state variables (Initial Conditions)

    # Initialize p,T,velSqrd
    p = np.zeros([pmx, pmy, pmz], dtype='float', order='F')
    T = np.zeros([pmx, pmy, pmz], dtype='float', order='F')
    velSqrd = np.zeros([pmx, pmy, pmz], dtype='float', order='F')

    # Density
    for i in range(pmx):
        for j in range(pmy):
            # NEEDS TO BE FIXED WHEN MPI SLICES NORMAL TO Z
            state.q[0, i, j, :] = rho0[mbc:pmz + mbc]

    # Momentum
    state.q[1, :, :, :] = 0.  # x-momentum (rho*u)
    state.q[2, :, :, :] = 0.  # y-momentum (rho*v)
    state.q[3, :, :, :] = 0.  # z-momentum (rho*w)

    # Velocity Squared (u**2+v**2+w**2)
    velSqrd[:, :, :] = (state.q[1, :, :, :]**2 + state.q[2, :, :, :]**2 +
                        state.q[3, :, :, :]**2) / state.q[0, :, :, :]**2

    # Energy
    for i in range(pmx):
        for j in range(pmy):
            # NEEDS TO BE FIXED WHEN MPI SLICES NORMAL TO Z
            p[i, j, :] = p0[mbc:pmz + mbc]
    state.q[4, :, :, :] = p / gamma1 + 0.5 * state.q[
        0, :, :, :] * velSqrd + state.q[0, :, :, :] * (
            gR) * Zcp[:, :, :] * gFlux

    # Add Temperature Perturbation
    T = p / state.q[0, :, :, :]
    L = np.sqrt((Xcp - xSphere)**2 + (Ycp - ySphere)**2 + (Zcp - zSphere)**2)
    for i in range(pmx):
        for j in range(pmy):
            for k in range(pmz):
                if L[i, j, k] <= rSphere:
                    mu = Mavg[k + mbc] / nAvogadro
                    T[i, j, k] += TSphere * (kBoltzmann /
                                             mu) * (1.0 - L[i, j, k] / rSphere)
                    p[i, j, k] = T[i, j, k] * state.q[0, i, j, k]
    state.q[4, :, :, :] = p / gamma1 + 0.5 * state.q[
        0, :, :, :] * velSqrd + state.q[0, :, :, :] * (
            gR) * Zcp[:, :, :] * gFlux  # energy (e)

    # Setup Boundary Conditions

    # X - Boundary Conditions
    solver.bc_lower[0] = pyclaw.BC.extrap
    solver.bc_upper[0] = pyclaw.BC.extrap

    # Y - Boundary Conditions
    solver.bc_lower[1] = pyclaw.BC.extrap
    solver.bc_upper[1] = pyclaw.BC.extrap

    # Z - Boundary Conditions
    solver.bc_lower[2] = pyclaw.BC.custom
    solver.bc_upper[2] = pyclaw.BC.custom
    solver.user_bc_lower = customBCLowerZ
    solver.user_bc_upper = customBCUpperZ

    # Aux - Boundary Conditions
    solver.aux_bc_lower[0] = pyclaw.BC.extrap
    solver.aux_bc_upper[0] = pyclaw.BC.extrap
    solver.aux_bc_lower[1] = pyclaw.BC.extrap
    solver.aux_bc_upper[1] = pyclaw.BC.extrap
    solver.aux_bc_lower[2] = pyclaw.BC.custom
    solver.aux_bc_upper[2] = pyclaw.BC.custom
    solver.user_aux_bc_lower = customAuxBCLowerZ
    solver.user_aux_bc_upper = customAuxBCUpperZ

    # Solver Parameters
    claw = pyclaw.Controller()
    claw.verbosity = 4
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver
    claw.output_format = output_format
    claw.output_file_prefix = file_prefix
    claw.keep_copy = False
    if disable_output:
        claw.output_format = None
    claw.tfinal = tfinal
    claw.num_output_times = num_output_times
    claw.outdir = outdir
    #state.mp = 1
    #claw.compute_p = outputDensity

    return claw
示例#4
0
def acoustics3D(iplot=False,
                htmlplot=False,
                use_petsc=False,
                outdir='./_output',
                solver_type='classic',
                disable_output=False,
                **kwargs):
    """
    Example python script for solving the 3d acoustics equations.
    """

    if use_petsc:
        import clawpack.petclaw as pyclaw
    else:
        from clawpack import pyclaw

    if solver_type == 'classic':
        solver = pyclaw.ClawSolver3D()
    else:
        raise Exception('Unrecognized solver_type.')

    from clawpack import riemann
    solver.rp = riemann.rp3_vc_acoustics
    solver.num_waves = 2
    solver.limiters = pyclaw.limiters.tvd.MC

    solver.bc_lower[0] = pyclaw.BC.periodic
    solver.bc_upper[0] = pyclaw.BC.periodic
    solver.bc_lower[1] = pyclaw.BC.periodic
    solver.bc_upper[1] = pyclaw.BC.periodic
    solver.bc_lower[2] = pyclaw.BC.periodic
    solver.bc_upper[2] = pyclaw.BC.periodic

    solver.aux_bc_lower[0] = pyclaw.BC.periodic
    solver.aux_bc_upper[0] = pyclaw.BC.periodic
    solver.aux_bc_lower[1] = pyclaw.BC.periodic
    solver.aux_bc_upper[1] = pyclaw.BC.periodic
    solver.aux_bc_lower[2] = pyclaw.BC.periodic
    solver.aux_bc_upper[2] = pyclaw.BC.periodic

    app = None
    if 'test' in kwargs:
        test = kwargs['test']
        if test == 'homogeneous':
            app = 'test_homogeneous'
        elif test == 'heterogeneous':
            app = 'test_heterogeneous'
        else:
            raise Exception('Unrecognized test')

    if app == 'test_homogeneous':
        solver.dimensional_split = True
        mx = 256
        my = 4
        mz = 4
        zr = 1.0  # Impedance in right half
        cr = 1.0  # Sound speed in right half

    if app == 'test_heterogeneous' or app == None:
        solver.dimensional_split = False
        solver.dimensional_split = False
        solver.bc_lower[0] = pyclaw.BC.wall
        solver.bc_lower[1] = pyclaw.BC.wall
        solver.bc_lower[2] = pyclaw.BC.wall
        solver.aux_bc_lower[0] = pyclaw.BC.wall
        solver.aux_bc_lower[1] = pyclaw.BC.wall
        solver.aux_bc_lower[2] = pyclaw.BC.wall
        mx = 30
        my = 30
        mz = 30
        zr = 2.0  # Impedance in right half
        cr = 2.0  # Sound speed in right half

    solver.limiters = pyclaw.limiters.tvd.MC

    # Initialize domain
    x = pyclaw.Dimension('x', -1.0, 1.0, mx)
    y = pyclaw.Dimension('y', -1.0, 1.0, my)
    z = pyclaw.Dimension('z', -1.0, 1.0, mz)
    domain = pyclaw.Domain([x, y, z])

    num_eqn = 4
    num_aux = 2  # density, sound speed
    state = pyclaw.State(domain, num_eqn, num_aux)

    zl = 1.0  # Impedance in left half
    cl = 1.0  # Sound speed in left half

    grid = state.grid
    grid.compute_c_centers()
    X, Y, Z = grid._c_centers

    state.aux[0, :, :, :] = zl * (X < 0.) + zr * (X >= 0.)  # Impedance
    state.aux[1, :, :, :] = cl * (X < 0.) + cr * (X >= 0.)  # Sound speed

    x0 = -0.5
    y0 = 0.
    z0 = 0.
    if app == 'test_homogeneous':
        r = np.sqrt((X - x0)**2)
        width = 0.2
        state.q[0, :, :, :] = (np.abs(r) <= width) * (1. + np.cos(np.pi *
                                                                  (r) / width))

    elif app == 'test_heterogeneous' or app == None:
        r = np.sqrt((X - x0)**2 + (Y - y0)**2 + (Z - z0)**2)
        width = 0.1
        state.q[0, :, :, :] = (np.abs(r - 0.3) <= width) * (
            1. + np.cos(np.pi * (r - 0.3) / width))

    else:
        raise Exception('Unexpected application')

    state.q[1, :, :, :] = 0.
    state.q[2, :, :, :] = 0.
    state.q[3, :, :, :] = 0.

    claw = pyclaw.Controller()
    claw.keep_copy = True
    if disable_output:
        claw.output_format = None
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver
    claw.outdir = outdir

    # Solve
    claw.tfinal = 2.0
    status = claw.run()

    if htmlplot:
        pyclaw.plot.html_plot(outdir=outdir, file_format=claw.output_format)
    if iplot:
        pyclaw.plot.interactive_plot(outdir=outdir,
                                     file_format=claw.output_format)

    pinitial = claw.frames[0].state.get_q_global()
    pmiddle = claw.frames[3].state.get_q_global()
    pfinal = claw.frames[claw.num_output_times].state.get_q_global()

    if pinitial != None and pmiddle != None and pfinal != None:
        pinitial = pinitial[0, :, :, :].reshape(-1)
        pmiddle = pmiddle[0, :, :, :].reshape(-1)
        pfinal = pfinal[0, :, :, :].reshape(-1)
        final_difference = np.prod(grid.delta) * np.linalg.norm(
            pfinal - pinitial, ord=1)
        middle_difference = np.prod(grid.delta) * np.linalg.norm(
            pmiddle - pinitial, ord=1)

        if app == None:
            print 'Final error: ', final_difference
            print 'Middle error: ', middle_difference

        #import matplotlib.pyplot as plt
        #for i in range(claw.num_output_times):
        #    plt.pcolor(claw.frames[i].state.q[0,:,:,mz/2])
        #    plt.figure()
        #plt.show()

        return pfinal, final_difference

    else:

        return
示例#5
0
文件: Sedov.py 项目: cr2940/pyclaw-1
def setup(kernel_language='Fortran', solver_type='classic', use_petsc=False,
          dimensional_split=False, outdir='Sedov_output', output_format='hdf5',
          disable_output=False, num_cells=(64,64,64),
          tfinal=0.10, num_output_times=10):

    if use_petsc:
        import clawpack.petclaw as pyclaw
    else:
        from clawpack import pyclaw

    if solver_type=='classic':
        solver = pyclaw.ClawSolver3D(riemann.euler_3D)
        solver.dimensional_split = dimensional_split
        solver.limiters = pyclaw.limiters.tvd.minmod
        solver.cfl_max = 0.6
        solver.cfl_desired = 0.55
        solver.dt_initial = 3e-4
    else:
        raise Exception('Unrecognized solver_type.')

    x = pyclaw.Dimension(-1.0, 1.0, num_cells[0], name='x')
    y = pyclaw.Dimension(-1.0, 1.0, num_cells[1], name='y')
    z = pyclaw.Dimension(-1.0, 1.0, num_cells[2], name='z')
    domain = pyclaw.Domain([x,y,z])

    state = pyclaw.State(domain,num_eqn)

    state.problem_data['gamma']=gamma
    
    grid = state.grid
    X,Y,Z = grid.p_centers
    r = np.sqrt((X-x0)**2 + (Y-y0)**2 + (Z-z0)**2)

    state.q[density,   :,:,:] = 1.0
    state.q[x_momentum,:,:,:] = 0.
    state.q[y_momentum,:,:,:] = 0.
    state.q[z_momentum,:,:,:] = 0.
    
    background_pressure = 1.0e-2
    Eblast = 0.851072
    pressure_in = Eblast*(gamma-1.)/(4./3.*np.pi*rmax**3)
    state.q[energy,:,:,:] = background_pressure/(gamma-1.) # energy (e)

    # Compute cell fraction inside initial perturbed sphere
    dx, dy, dz = state.grid.delta
    dx2, dy2, dz2 = [d/2. for d in state.grid.delta]
    dmax = max(state.grid.delta)

    for i in range(state.q.shape[1]):
        for j in range(state.q.shape[2]):
            for k in range(state.q.shape[3]):
                if r[i,j,k] - dmax > rmax:
                    continue
                xdown = X[i,j,k] - dx2
                xup   = X[i,j,k] + dx2
                ydown = lambda x : Y[i,j,k] - dy2
                yup   = lambda x : Y[i,j,k] + dy2
                zdown = Z[i,j,k] - dz2
                zup   = Z[i,j,k] + dz2

                infrac,abserr = integrate.dblquad(f,xdown,xup,ydown,yup,args=(zdown,zup),epsabs=1.e-3,epsrel=1.e-2)
                infrac=infrac/(dx*dy*dz)

                p = background_pressure + pressure_in*infrac # pressure
                state.q[energy,i,j,k] = p/(gamma-1.) # energy (e)

    solver.all_bcs = pyclaw.BC.extrap

    claw = pyclaw.Controller()
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver
    claw.output_format = output_format
    claw.keep_copy = True
    if disable_output:
        claw.output_format = None
    claw.tfinal = tfinal
    claw.num_output_times = num_output_times
    claw.outdir = outdir

    return claw
示例#6
0
def setup(kernel_language='Fortran',
          solver_type='classic',
          use_petsc=False,
          dimensional_split=False,
          outdir='_output',
          output_format='hdf5',
          disable_output=False,
          num_cells=(256, 64, 64),
          tfinal=0.6,
          num_output_times=10):

    from clawpack import riemann
    if use_petsc:
        import clawpack.petclaw as pyclaw
    else:
        from clawpack import pyclaw

    if solver_type == 'classic':
        solver = pyclaw.ClawSolver3D(riemann.euler_3D)
        solver.dimensional_split = dimensional_split
    else:
        raise Exception('Unrecognized solver_type.')

    x = pyclaw.Dimension(0.0, 2.0, num_cells[0], name='x')
    y = pyclaw.Dimension(0.0, 0.5, num_cells[1], name='y')
    z = pyclaw.Dimension(0.0, 0.5, num_cells[2], name='z')
    domain = pyclaw.Domain([x, y, z])

    solver.all_bcs = pyclaw.BC.extrap
    solver.bc_lower[0] = pyclaw.BC.custom
    solver.user_bc_lower = incoming_shock
    solver.bc_lower[1] = pyclaw.BC.wall
    solver.bc_lower[2] = pyclaw.BC.wall

    state = pyclaw.State(domain, solver.num_eqn)

    state.problem_data['gamma'] = gamma

    grid = state.grid
    X, Y, Z = grid.p_centers
    r0 = np.sqrt((X - x0)**2 + (Y - y0)**2 + (Z - z0)**2)

    state.q[0, :, :, :] = rho_shock * (X < xshock) + rhoout * (
        X >= xshock)  # density (rho)
    state.q[1, :, :, :] = rho_shock * v_shock * (X < xshock
                                                 )  # x-momentum (rho*u)
    state.q[2, :, :, :] = 0.  # y-momentum (rho*v)
    state.q[3, :, :, :] = 0.  # z-momentum (rho*w)
    state.q[4, :, :, :] = e_shock * (X < xshock) + pout / gamma1 * (
        X >= xshock)  # energy (e)

    # Compute cell fraction inside bubble
    dx, dy, dz = state.grid.delta
    dx2, dy2, dz2 = [d / 2. for d in state.grid.delta]
    dmax = max(state.grid.delta)

    for i in range(state.q.shape[1]):
        for j in range(state.q.shape[2]):
            for k in range(state.q.shape[3]):
                if (r0[i, j, k] - dmax > r_bubble):
                    continue
                xdown = X[i, j, k] - dx2
                xup = X[i, j, k] + dx2
                ydown = lambda x: Y[i, j, k] - dy2
                yup = lambda x: Y[i, j, k] + dy2
                zdown = Z[i, j, k] - dz2
                zup = Z[i, j, k] + dz2

                infrac, abserr = integrate.dblquad(bubble,
                                                   xdown,
                                                   xup,
                                                   ydown,
                                                   yup,
                                                   args=(zdown, zup, 0),
                                                   epsabs=1.e-3,
                                                   epsrel=1.e-2)
                infrac = infrac / (dx * dy * dz)

                state.q[0, i, j, k] = rhoout * (1. - infrac) + rhoin * infrac
                state.q[4, i, j, k] = (pout * (1. - infrac) +
                                       pin * infrac) / gamma1  # energy (e)

    claw = pyclaw.Controller()
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver
    claw.output_format = output_format
    claw.keep_copy = True
    if disable_output:
        claw.output_format = None
    claw.tfinal = tfinal
    claw.num_output_times = num_output_times
    claw.outdir = outdir

    return claw
示例#7
0
def setup(use_petsc=False,outdir='./_output',solver_type='classic',disable_output=False,**kwargs):
    """
    Example python script for solving the 3d acoustics equations.
    """
    from clawpack import riemann

    if use_petsc:
        import clawpack.petclaw as pyclaw
    else:
        from clawpack import pyclaw

    if solver_type=='classic':
        solver=pyclaw.ClawSolver3D(riemann.vc_acoustics_3D)
    else:
        raise Exception('Unrecognized solver_type.')

    solver.limiters = pyclaw.limiters.tvd.MC

    solver.bc_lower[0]=pyclaw.BC.periodic
    solver.bc_upper[0]=pyclaw.BC.periodic
    solver.bc_lower[1]=pyclaw.BC.periodic
    solver.bc_upper[1]=pyclaw.BC.periodic
    solver.bc_lower[2]=pyclaw.BC.periodic
    solver.bc_upper[2]=pyclaw.BC.periodic

    solver.aux_bc_lower[0]=pyclaw.BC.periodic
    solver.aux_bc_upper[0]=pyclaw.BC.periodic
    solver.aux_bc_lower[1]=pyclaw.BC.periodic
    solver.aux_bc_upper[1]=pyclaw.BC.periodic
    solver.aux_bc_lower[2]=pyclaw.BC.periodic
    solver.aux_bc_upper[2]=pyclaw.BC.periodic

    app = None
    if 'test' in kwargs:
        test = kwargs['test']
        if test == 'homogeneous':
            app = 'test_homogeneous'
        elif test == 'heterogeneous':
            app = 'test_heterogeneous'
        else: raise Exception('Unrecognized test')

    if app == 'test_homogeneous':
        solver.dimensional_split=True
        mx=256; my=4; mz=4
        zr = 1.0  # Impedance in right half
        cr = 1.0  # Sound speed in right half

    if app == 'test_heterogeneous' or app == None:
        solver.dimensional_split=False
        solver.dimensional_split=False
        solver.bc_lower[0]    =pyclaw.BC.wall
        solver.bc_lower[1]    =pyclaw.BC.wall
        solver.bc_lower[2]    =pyclaw.BC.wall
        solver.aux_bc_lower[0]=pyclaw.BC.wall
        solver.aux_bc_lower[1]=pyclaw.BC.wall
        solver.aux_bc_lower[2]=pyclaw.BC.wall
        mx=30; my=30; mz=30
        zr = 2.0  # Impedance in right half
        cr = 2.0  # Sound speed in right half

    solver.limiters = pyclaw.limiters.tvd.MC

    # Initialize domain
    x = pyclaw.Dimension('x',-1.0,1.0,mx)
    y = pyclaw.Dimension('y',-1.0,1.0,my)
    z = pyclaw.Dimension('z',-1.0,1.0,mz)
    domain = pyclaw.Domain([x,y,z])

    num_eqn = 4
    num_aux = 2 # density, sound speed
    state = pyclaw.State(domain,num_eqn,num_aux)

    zl = 1.0  # Impedance in left half
    cl = 1.0  # Sound speed in left half

    grid = state.grid
    grid.compute_c_centers()
    X,Y,Z = grid._c_centers

    state.aux[0,:,:,:] = zl*(X<0.) + zr*(X>=0.) # Impedance
    state.aux[1,:,:,:] = cl*(X<0.) + cr*(X>=0.) # Sound speed

    x0 = -0.5; y0 = 0.; z0 = 0.
    if app == 'test_homogeneous':
        r = np.sqrt((X-x0)**2)
        width=0.2
        state.q[0,:,:,:] = (np.abs(r)<=width)*(1.+np.cos(np.pi*(r)/width))

    elif app == 'test_heterogeneous' or app == None:
        r = np.sqrt((X-x0)**2 + (Y-y0)**2 + (Z-z0)**2)
        width=0.1
        state.q[0,:,:,:] = (np.abs(r-0.3)<=width)*(1.+np.cos(np.pi*(r-0.3)/width))

    else: raise Exception('Unexpected application')
        
    state.q[1,:,:,:] = 0.
    state.q[2,:,:,:] = 0.
    state.q[3,:,:,:] = 0.

    claw = pyclaw.Controller()
    claw.keep_copy = True
    if disable_output:
       claw.output_format = None
    claw.solution = pyclaw.Solution(state,domain)
    claw.solver = solver
    claw.outdir=outdir

    # Solve
    claw.tfinal = 2.0
    return claw
示例#8
0
def shockbubble(use_petsc=False,
                iplot=False,
                htmlplot=False,
                outdir='./_output',
                solver_type='classic',
                amr_type=None):
    """
    Solve the Euler equations of compressible fluid dynamics.
    This example involves a bubble of dense gas that is impacted by a shock.
    """
    from clawpack import riemann

    if use_petsc:
        import clawpack.petclaw as pyclaw
    else:
        from clawpack import pyclaw

    if solver_type == 'sharpclaw':
        solver = pyclaw.SharpClawSolver3D(riemann.euler_3D)
        solver.weno_order = 5
        solver.lim_type = 2
    else:
        solver = pyclaw.ClawSolver3D(riemann.euler_3D)
        solver.dimensional_split = 1
        # solver.transverse_waves = 3
        solver.limiters = 4
        solver.cfl_max = 0.2
        solver.cfl_desired = 0.15
        solver.order = 2
        solver.dt_initial = 1  # 0.000125

    solver.num_waves = 3
    solver.bc_lower[0] = pyclaw.BC.custom
    solver.bc_upper[0] = pyclaw.BC.extrap
    solver.bc_lower[1] = pyclaw.BC.extrap
    solver.bc_upper[1] = pyclaw.BC.extrap
    solver.bc_lower[2] = pyclaw.BC.extrap
    solver.bc_upper[2] = pyclaw.BC.extrap

    # Initialize domain
    factor = 1  #2.0/3.0+1e-10#1.5+1e-10
    mx = int(12 * factor)
    my = int(6 * factor)
    mz = int(6 * factor)

    # number of initial AMR grids in each dimension
    msubgrid = 27

    if amr_type is None:
        # number of Domain grid cells expressed as the product of
        # grid resolution and the number of AMR sub-grids for
        # easy comparison between the two methods
        mx = mx * msubgrid
        my = my * msubgrid
        mz = mz * msubgrid

    x = pyclaw.Dimension('x', 0.0, 2.0, mx)
    y = pyclaw.Dimension('y', -0.5, 0.5, my)
    z = pyclaw.Dimension('z', -0.5, 0.5, mz)
    domain = pyclaw.Domain([x, y, z])
    num_eqn = 5
    state = pyclaw.State(domain, num_eqn)

    state.problem_data['gamma'] = gamma
    state.problem_data['gamma1'] = gamma1

    qinit(state)
    print np.min(state.q[0, ...].reshape(-1))

    solver.user_bc_lower = shockbc

    claw = pyclaw.Controller()
    claw.tfinal = 0.5  #1
    claw.num_output_times = 10  #50
    claw.outdir = outdir
    claw.output_format = None

    if amr_type is not None:
        if amr_type == 'peano':
            import peanoclaw as amrclaw
            claw.solver = amrclaw.Solver(
                solver,
                (x.upper - x.lower) / (mx * msubgrid),
                qinit
                #,refinement_criterion=refinement_criterion_gradient
                ,
                internal_settings=amrclaw.InternalSettings(
                    enable_peano_logging=True,
                    fork_level_increment=1,
                    use_dimensional_splitting_optimization=True))
            claw.solution = amrclaw.Solution(state, domain)
        else:
            raise Exception('unsupported amr_type %s' % amr_type)
    else:
        claw.solver = solver
        claw.solution = pyclaw.Solution(state, domain)

    return claw
def acoustics3D(finalt=1.0,
                use_petsc=True,
                outdir='./_output',
                solver_type='sharpclaw',
                disable_output=True,
                dm=[30, 30, 30],
                **kwargs):
    """
    Python script for scaling test based on 3D acoustics.
    """
    from clawpack import riemann

    if use_petsc:
        import clawpack.petclaw as pyclaw
    else:
        from clawpack import pyclaw

    if solver_type == 'classic':
        solver = pyclaw.ClawSolver3D(riemann.vc_acoustics_3D)
        solver.limiters = pyclaw.limiters.tvd.MC
    elif solver_type == 'sharpclaw':
        solver = pyclaw.SharpClawSolver3D(riemann.vc_acoustics_3D)
    else:
        raise Exception('Unrecognized solver_type.')

    size = PETSc.Comm.getSize(PETSc.COMM_WORLD)
    rank = PETSc.Comm.getRank(PETSc.COMM_WORLD)

    solver.bc_lower[0] = pyclaw.BC.periodic
    solver.bc_upper[0] = pyclaw.BC.periodic
    solver.bc_lower[1] = pyclaw.BC.periodic
    solver.bc_upper[1] = pyclaw.BC.periodic
    solver.bc_lower[2] = pyclaw.BC.periodic
    solver.bc_upper[2] = pyclaw.BC.periodic

    solver.aux_bc_lower[0] = pyclaw.BC.periodic
    solver.aux_bc_upper[0] = pyclaw.BC.periodic
    solver.aux_bc_lower[1] = pyclaw.BC.periodic
    solver.aux_bc_upper[1] = pyclaw.BC.periodic
    solver.aux_bc_lower[2] = pyclaw.BC.periodic
    solver.aux_bc_upper[2] = pyclaw.BC.periodic

    app = None
    # dm = None
    if 'test' in kwargs:
        test = kwargs['test']
        if test == 'homogeneous':
            app = 'test_homogeneous'
        elif test == 'heterogeneous':
            app = 'test_heterogeneous'
        else:
            raise Exception('Unrecognized test')

    if app == 'test_homogeneous':
        if solver_type == 'classic':
            solver.dimensional_split = True
        else:
            solver.lim_type = 1

        solver.limiters = [4]
        # if 'griddm' in kwargs:
        #     dm=kwargs['griddm']
        mx = dm[0]
        my = dm[1]
        mz = dm[2]
        # else:
        #     mx=256; my=4; mz=4

        zr = 1.0  # Impedance in right half
        cr = 1.0  # Sound speed in right half

    if app == 'test_heterogeneous' or app == None:
        if solver_type == 'classic':
            solver.dimensional_split = False

        solver.bc_lower[0] = pyclaw.BC.wall
        solver.bc_lower[1] = pyclaw.BC.wall
        solver.bc_lower[2] = pyclaw.BC.wall
        solver.aux_bc_lower[0] = pyclaw.BC.wall
        solver.aux_bc_lower[1] = pyclaw.BC.wall
        solver.aux_bc_lower[2] = pyclaw.BC.wall
        # if 'griddm' in kwargs:
        #     dm=kwargs['griddm']
        mx = dm[0]
        my = dm[1]
        mz = dm[2]
        # else:
        #     mx=30; my=30; mz=30

        zr = 2.0  # Impedance in right half
        cr = 2.0  # Sound speed in right half

    solver.limiters = pyclaw.limiters.tvd.MC
    solver.cfl_max = 0.5
    solver.cfl_desired = 0.45
    solver.dt_variable = True

    # Initialize domain
    x = pyclaw.Dimension('x', -1.0, 1.0, mx)
    y = pyclaw.Dimension('y', -1.0, 1.0, my)
    z = pyclaw.Dimension('z', -1.0, 1.0, mz)
    domain = pyclaw.Domain([x, y, z])

    num_eqn = 4
    num_aux = 2  # density, sound speed
    state = pyclaw.State(domain, num_eqn, num_aux)

    zl = 1.0  # Impedance in left half
    cl = 1.0  # Sound speed in left half

    grid = state.grid
    grid.compute_c_centers()
    X, Y, Z = grid._c_centers

    state.aux[0, :, :, :] = zl * (X < 0.) + zr * (X >= 0.)  # Impedance
    state.aux[1, :, :, :] = cl * (X < 0.) + cr * (X >= 0.)  # Sound speed

    x0 = -0.5
    y0 = 0.
    z0 = 0.
    if app == 'test_homogeneous':
        r = np.sqrt((X - x0)**2)
        width = 0.2
        state.q[0, :, :, :] = (np.abs(r) <= width) * (1. + np.cos(np.pi *
                                                                  (r) / width))

    elif app == 'test_heterogeneous' or app == None:
        r = np.sqrt((X - x0)**2 + (Y - y0)**2 + (Z - z0)**2)
        width = 0.1
        state.q[0, :, :, :] = (np.abs(r - 0.3) <= width) * (
            1. + np.cos(np.pi * (r - 0.3) / width))

    else:
        raise Exception('Unexpected application')

    state.q[1, :, :, :] = 0.
    state.q[2, :, :, :] = 0.
    state.q[3, :, :, :] = 0.

    dt = np.min(grid.delta) / 2.0 * solver.cfl_desired
    solver.dt = dt
    tic1 = MPI.Wtime()
    claw = pyclaw.Controller()
    claw.keep_copy = False
    if disable_output:
        claw.output_format = None
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver
    claw.output_style = 3
    claw.nstepout = 1
    claw.outdir = outdir + '_' + str(size)

    # Solve
    claw.tfinal = finalt
    claw.num_output_times = 1
    tic2 = MPI.Wtime()
    status = claw.run()
    toc = MPI.Wtime()
    timeVec1.array = toc - tic1
    timeVec2.array = toc - tic2
    t1 = MPI.Wtime()
    duration1 = timeVec1.max()[1]
    duration2 = timeVec2.max()[1]
    t2 = MPI.Wtime()
    log = MPI.File.Open(
        MPI.COMM_WORLD,
        os.path.join(outdir,
                     "results_" + str(size) + '_' + str(ncells) + ".log"),
        MPI.MODE_CREATE | MPI.MODE_WRONLY)

    if rank == 0:
        results = np.empty([7])
        log.Write(solver_type + ' \n')
        log.Write('clawrun + load took ' + str(duration1) +
                  ' seconds, for process ' + str(rank) + '\n')
        log.Write('clawrun took ' + str(duration2) + ' seconds, for process ' +
                  str(rank) + ' in grid ' + str(mx) + '\n')
        log.Write('number of steps: ' +
                  str(claw.solver.status.get('numsteps')) + '\n')
        log.Write('time reduction time ' + str(t2 - t1) + '\n')
        log.Write('tfinal ' + str(claw.tfinal) + ' and dt ' + str(solver.dt))
        print solver_type + ' \n'
        print 'clawrun + load took ' + str(
            duration1) + ' seconds, for process ' + str(rank) + '\n'
        print 'clawrun took ' + str(
            duration2) + ' seconds, for process ' + str(
                rank) + ' in grid ' + str(mx) + '\n'
        print 'number of steps: ' + str(
            claw.solver.status.get('numsteps')) + '\n'
        print 'time reduction time ' + str(t2 - t1) + '\n'
        print 'tfinal ' + str(claw.tfinal) + ' and dt ' + str(solver.dt)
        results[0] = size
        results[1] = mx
        results[2] = np.min(grid.delta)
        results[3] = claw.tfinal
        results[4] = solver.dt
        results[5] = duration1
        results[6] = duration2
        np.save(
            os.path.join(outdir, 'results_' + str(size) + '_' + str(ncells)),
            results)
    return