Пример #1
0
def fig_61_62_63(kernel_language='Python',
                 iplot=False,
                 htmlplot=False,
                 solver_type='classic',
                 outdir='./_output'):
    """
    Compare several methods for advecting a Gaussian and square wave.

    The settings coded here are for Figure 6.1(a).
    For Figure 6.1(b), set solver.order=2.
    For Figure 6.2(a), set solver.order=2 and solver.limiters = pyclaw.limiters.tvd.minmod
    For Figure 6.2(b), set solver.order=2 and solver.limiters = pyclaw.limiters.tvd.superbee
    For Figure 6.2(c), set solver.order=2 and solver.limiters = pyclaw.limiters.tvd.MC

    For Figure 6.3, set IC='wavepacket' and other options as appropriate.
    """
    import numpy as np
    import pyclaw

    if solver_type == 'sharpclaw':
        solver = pyclaw.SharpClawSolver1D()
    else:
        solver = pyclaw.ClawSolver1D()

    solver.kernel_language = kernel_language
    from riemann import rp_advection
    solver.num_waves = rp_advection.num_waves
    if solver.kernel_language == 'Python':
        solver.rp = rp_advection.rp_advection_1d

    solver.bc_lower[0] = 2
    solver.bc_upper[0] = 2
    solver.limiters = 0
    solver.order = 1
    solver.cfl_desired = 0.8

    x = pyclaw.Dimension('x', 0.0, 1.0, mx)
    grid = pyclaw.Grid(x)
    num_eqn = 1
    state = pyclaw.State(grid, num_eqn)
    state.problem_data['u'] = 1.

    xc = grid.x.center
    if IC == 'gauss_square':
        state.q[0, :] = np.exp(-beta * (xc - x0)**2) + (xc > 0.6) * (xc < 0.8)
    elif IC == 'wavepacket':
        state.q[0, :] = np.exp(-beta * (xc - x0)**2) * np.sin(80. * xc)
    else:
        raise Exception('Unrecognized initial condition specification.')

    claw = pyclaw.Controller()
    claw.solution = pyclaw.Solution(state)
    claw.solver = solver
    claw.outdir = outdir

    claw.tfinal = 10.0
    status = claw.run()

    if htmlplot: pyclaw.plot.html_plot(outdir=outdir)
    if iplot: pyclaw.plot.interactive_plot(outdir=outdir)
Пример #2
0
def burgers(iplot=1, htmlplot=0, outdir='./_output'):
    """
    Example from Chapter 11 of LeVeque, Figure 11.8.
    Shows decay of an initial wave packet to an N-wave with Burgers' equation.
    """
    import numpy as np

    import pyclaw

    solver = pyclaw.ClawSolver1D()

    solver.num_waves = 1
    solver.limiters = pyclaw.limiters.tvd.MC
    solver.bc_lower[0] = pyclaw.BC.periodic
    solver.bc_upper[0] = pyclaw.BC.periodic

    #===========================================================================
    # Initialize grids and then initialize the solution associated to the grid
    #===========================================================================
    x = pyclaw.Dimension('x', -8.0, 8.0, 1000)
    grid = pyclaw.Grid(x)
    num_eqn = 1
    state = pyclaw.State(grid, num_eqn)

    xc = grid.x.center
    state.q[0, :] = (xc > -np.pi) * (xc < np.pi) * (2. * np.sin(3. * xc) +
                                                    np.cos(2. * xc) + 0.2)
    state.q[0, :] = state.q[0, :] * (np.cos(xc) + 1.)
    state.problem_data['efix'] = True

    #===========================================================================
    # Setup controller and controller parameters. Then solve the problem
    #===========================================================================
    claw = pyclaw.Controller()
    claw.tfinal = 6.0
    claw.num_output_times = 30
    claw.solution = pyclaw.Solution(state)
    claw.solver = solver
    claw.outdir = outdir

    status = claw.run()

    if htmlplot: pyclaw.plot.html_plot(outdir=outdir)
    if iplot: pyclaw.plot.interactive_plot(outdir=outdir)
def shallow_4_Rossby_Haurwitz(iplot=0,htmlplot=False,outdir='./_output'):

    # Import pyclaw module
    import pyclaw

    #===========================================================================
    # Set up solver and solver parameters
    #===========================================================================
    solver = pyclaw.ClawSolver2D()
    import riemann
    solver.rp = riemann.rp2_shallow_sphere
    import classic2
    solver.fmod = classic2

    # Set boundary conditions
    # =======================

    # Conserved variables
    solver.bc_lower[0] = pyclaw.BC.periodic
    solver.bc_upper[0] = pyclaw.BC.periodic
    solver.bc_lower[1] = pyclaw.BC.custom  # Custom BC for sphere
    solver.bc_upper[1] = pyclaw.BC.custom  # Custom BC for sphere

    solver.user_bc_lower = qbc_lower_y
    solver.user_bc_upper = qbc_upper_y

    # Auxiliary array
    solver.aux_bc_lower[0] = pyclaw.BC.periodic
    solver.aux_bc_upper[0] = pyclaw.BC.periodic
    solver.aux_bc_lower[1] = pyclaw.BC.custom  # Custom BC for sphere
    solver.aux_bc_upper[1] = pyclaw.BC.custom  # Custom BC for sphere

    solver.user_aux_bc_lower = auxbc_lower_y
    solver.user_aux_bc_upper = auxbc_upper_y


    # Dimensional splitting ?
    # =======================
    solver.dimensional_split = 0
 
    # Transverse increment waves and transverse correction waves are computed 
    # and propagated.
    # =======================================================================
    solver.transverse_waves = 2
    
    # Number of waves in each Riemann solution
    # ========================================
    solver.num_waves = 3

    # Use source splitting method
    # ===========================
    solver.source_split = 2

    # Set source function
    # ===================
    solver.step_source = fortran_src_wrapper

    # Set the limiter for the waves
    # =============================
    solver.limiters = pyclaw.limiters.tvd.MC


    #===========================================================================
    # Initialize domain and state, then initialize the solution associated to the 
    # state and finally initialize aux array
    #===========================================================================
    # Domain:
    # ====
    xlower = -3.0
    xupper = 1.0
    mx = 100

    ylower = -1.0
    yupper = 1.0
    my = 50

    # Check whether or not the even number of cells are used in in both 
    # directions. If odd numbers are used a message is print at screen and the 
    # simulation is interrputed.
    if(mx % 2 != 0 or my % 2 != 0):
        import sys
        message = 'Please, use even numbers of cells in both direction. ' \
                  'Only even numbers allow to impose correctly the boundary ' \
                  'conditions!'
        print message
        sys.exit(0)


    x = pyclaw.Dimension('x',xlower,xupper,mx)
    y = pyclaw.Dimension('y',ylower,yupper,my)
    domain = pyclaw.Domain([x,y])
    dx = domain.grid.delta[0]
    dy = domain.grid.delta[1]

    # Define some parameters used in Fortran common blocks 
    solver.fmod.comxyt.dxcom = dx
    solver.fmod.comxyt.dycom = dy
    solver.fmod.sw.g = 11489.57219  
    solver.rp.comxyt.dxcom = dx
    solver.rp.comxyt.dycom = dy
    solver.rp.sw.g = 11489.57219  

    # Define state object
    # ===================
    num_eqn = 4  # Number of equations
    num_aux = 16 # Number of auxiliary variables
    state = pyclaw.State(domain,num_eqn,num_aux)

    # Override default mapc2p function
    # ================================
    state.grid.mapc2p = mapc2p_sphere_vectorized
        

    # Set auxiliary variables
    # =======================
    import problem
    
    # Get lower left corner coordinates 
    xlower,ylower = state.grid.lower[0],state.grid.lower[1]

    num_ghost = 2
    auxtmp = np.ndarray(shape=(num_aux,mx+2*num_ghost,my+2*num_ghost), dtype=float, order='F')
    auxtmp = problem.setaux(mx,my,num_ghost,mx,my,xlower,ylower,dx,dy,auxtmp,Rsphere)
    state.aux[:,:,:] = auxtmp[:,num_ghost:-num_ghost,num_ghost:-num_ghost]

    # Set index for capa
    state.index_capa = 0

    # Set initial conditions
    # ====================== 
    # 1) Call fortran function
    qtmp = np.ndarray(shape=(num_eqn,mx+2*num_ghost,my+2*num_ghost), dtype=float, order='F')
    qtmp = problem.qinit(mx,my,num_ghost,mx,my,xlower,ylower,dx,dy,qtmp,auxtmp,Rsphere)
    state.q[:,:,:] = qtmp[:,num_ghost:-num_ghost,num_ghost:-num_ghost]

    # 2) call python function define above
    #qinit(state,mx,my)


    #===========================================================================
    # Set up controller and controller parameters
    #===========================================================================
    claw = pyclaw.Controller()
    claw.keep_copy = False
    claw.output_style = 1
    claw.num_output_times = 10
    claw.tfinal = 10
    claw.solution = pyclaw.Solution(state,domain)
    claw.solver = solver
    claw.outdir = outdir

    #===========================================================================
    # Solve the problem
    #===========================================================================
    status = claw.run()

    #===========================================================================
    # Plot results
    #===========================================================================
    if htmlplot:  pyclaw.plot.html_plot(outdir=outdir)
    if iplot:     pyclaw.plot.interactive_plot(outdir=outdir)
Пример #4
0
def test_3x3_grid():
    r"""This test simply solves a 3x3 grid, once with PyClaw and once as one patch 
    with PeanoClaw. In the end it checks if the resulting qbcs match.
    """
    #===========================================================================
    # Import libraries
    #===========================================================================
    import numpy as np
    import pyclaw
    import peanoclaw

    #===========================================================================
    # Setup solver and solver parameters for PyClaw run
    #===========================================================================
    pyclaw_solver = setup_solver()
    
    #===========================================================================
    # Setup solver and solver parameters for PeanoClaw run
    #===========================================================================
    peanoclaw_solver = setup_solver()
    peano_solver = peanoclaw.Solver(peanoclaw_solver, 1.0)

    #===========================================================================
    # Initialize domain and state, then initialize the solution associated to the 
    # state and finally initialize aux array
    #===========================================================================

    # Domain:
    xlower = 0.0
    xupper = 1.0
    mx = 3
    ylower = 0.0
    yupper = 1.0
    my = 3
    x = pyclaw.Dimension(xlower,xupper,mx,name='x')
    y = pyclaw.Dimension(ylower,yupper,my,name='y')
    domain = pyclaw.Domain([x,y])

    num_eqn = 3  # Number of equations
    pyclaw_state = pyclaw.State(domain,num_eqn)
    peanoclaw_state = pyclaw.State(domain, num_eqn)

    grav = 1.0 # Parameter (global auxiliary variable)
    pyclaw_state.problem_data['grav'] = grav
    peanoclaw_state.problem_data['grav'] = grav

    # Initial solution
    # ================
    # Riemann states of the dam break problem
    damRadius = 0.2
    hl = 2.
    ul = 0.
    vl = 0.
    hr = 1.
    ur = 0.
    vr = 0.
    
    qinit(pyclaw_state,hl,ul,vl,hr,ur,vl,damRadius) # This function is defined above
    qinit(peanoclaw_state,hl,ul,vl,hr,ur,vl,damRadius) # This function is defined above

    tfinal = 1.0
    #===========================================================================
    # Set up controller and controller parameters for PyClaw run
    #===========================================================================
    pyclaw_controller = pyclaw.Controller()
    pyclaw_controller.tfinal = tfinal
    pyclaw_controller.solution = pyclaw.Solution(pyclaw_state,domain)
    pyclaw_controller.solver = pyclaw_solver
    pyclaw_controller.num_output_times = 1
    
    pyclaw_controller.run()
    
    #===========================================================================
    # Set up controller and controller parameters for PyClaw run
    #===========================================================================
    peanoclaw_controller = pyclaw.Controller()
    peanoclaw_controller.tfinal = tfinal
    peanoclaw_controller.solution = pyclaw.Solution(peanoclaw_state,domain)
    peanoclaw_controller.solver = peano_solver
    peanoclaw_controller.num_output_times = 1
    
    peanoclaw_controller.run()
    
    assert(np.max(np.abs(pyclaw_solver.qbc - peanoclaw_solver.qbc)) < 1e-9)
Пример #5
0
def acoustics(solver_type='classic',iplot=True,htmlplot=False,outdir='./_output',problem='figure 9.4'):
    """
    This example solves the 1-dimensional variable-coefficient acoustics
    equations in a medium with a single interface.
    """
    from numpy import sqrt, abs

    import pyclaw

    if solver_type=='classic':
        solver = pyclaw.ClawSolver1D()
    elif solver_type=='sharpclaw':
        solver = pyclaw.SharpClawSolver1D()
    else: raise Exception('Unrecognized value of solver_type.')

    solver.num_waves=2
    solver.limiters = pyclaw.limiters.tvd.MC
    solver.bc_lower[0] = pyclaw.BC.extrap
    solver.bc_upper[0] = pyclaw.BC.extrap
    solver.aux_bc_lower[0] = pyclaw.BC.extrap
    solver.aux_bc_upper[0] = pyclaw.BC.extrap

    x = pyclaw.Dimension('x',-5.0,5.0,500)
    grid = pyclaw.Grid(x)
    num_eqn = 2
    num_aux = 2
    state = pyclaw.State(grid,num_eqn,num_aux)

    if problem == 'figure 9.4':
        rhol = 1.0
        cl   = 1.0
        rhor = 2.0
        cr   = 0.5
    elif problem == 'figure 9.5':
        rhol = 1.0
        cl   = 1.0
        rhor = 4.0
        cr   = 0.5
    zl = rhol*cl
    zr = rhor*cr
    xc = grid.x.center

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

    # initial condition: half-ellipse
    state.q[0,:] = sqrt(abs(1.-(xc+3.)**2))*(xc>-4.)*(xc<-2.)
    state.q[1,:] = state.q[0,:] + 0.

    claw = pyclaw.Controller()
    claw.solution = pyclaw.Solution(state)
    claw.solver = solver
    claw.tfinal = 5.0
    claw.num_output_times   = 10

    # Solve
    status = claw.run()

    # Plot results
    if htmlplot:  pyclaw.plot.html_plot(outdir=outdir)
    if iplot:     pyclaw.plot.interactive_plot(outdir=outdir)
Пример #6
0
def contourLineSphere(fileName='fort.q0000', path='./_output'):
    """
    This function plot the contour lines on a spherical surface for the shallow
    water equations solved on a sphere.
    """

    # Open file
    # =========

    # Concatenate path and file name
    pathFileName = path + "/" + fileName

    try:
        f = file(pathFileName, "r")
    except IOError as e:
        print("({})".format(e))
        sys.exit()

    # Read file header
    # ================
    # The information contained in the first two lines are not used.
    unsed = f.readline()  # patch_number
    unused = f.readline()  # AMR_level

    # Read mx, my, xlow, ylow, dx and dy
    line = f.readline()
    sline = line.split()
    mx = int(sline[0])

    line = f.readline()
    sline = line.split()
    my = int(sline[0])

    line = f.readline()
    sline = line.split()
    xlower = float(sline[0])

    line = f.readline()
    sline = line.split()
    ylower = float(sline[0])

    line = f.readline()
    sline = line.split()
    dx = float(sline[0])

    line = f.readline()
    sline = line.split()
    dy = float(sline[0])

    # Patch:
    # ====
    xupper = xlower + mx * dx
    yupper = ylower + my * dy

    x = pyclaw.Dimension('x', xlower, xupper, mx)
    y = pyclaw.Dimension('y', ylower, yupper, my)
    patch = pyclaw.Patch([x, y])

    # Override default mapc2p function
    # ================================
    patch.mapc2p = rh.mapc2p_sphere_vectorized

    # Compute the physical coordinates of each cell's centers
    # ======================================================
    patch.compute_p_centers(recompute=True)
    xp = patch._p_centers[0]
    yp = patch._p_centers[1]
    zp = patch._p_centers[2]

    patch.compute_c_centers(recompute=True)
    xc = patch._c_centers[0]
    yc = patch._c_centers[1]

    # Define arrays of conserved variables
    h = np.zeros((mx, my))
    hu = np.zeros((mx, my))
    hv = np.zeros((mx, my))
    hw = np.zeros((mx, my))

    # Read solution
    for j in range(my):
        tmp = np.fromfile(f, dtype='float', sep=" ", count=4 * mx)
        tmp = tmp.reshape((mx, 4))
        h[:, j] = tmp[:, 0]
        hu[:, j] = tmp[:, 1]
        hv[:, j] = tmp[:, 2]
        hw[:, j] = tmp[:, 3]

    # Plot solution in the computational domain
    # =========================================

    # Fluid height
    plt.figure()
    CS = plt.contour(xc, yc, h)
    plt.title('Fluid height (computational domain)')
    plt.xlabel('xc')
    plt.ylabel('yc')
    plt.clabel(CS, inline=1, fontsize=10)
    plt.show()
Пример #7
0
def fig_31_38(kernel_language='Fortran',solver_type='classic',iplot=False,htmlplot=False,outdir='./_output'):
    r"""Produces the output shown in Figures 3.1 and 3.8 of the FVM book.
    These involve simple waves in the acoustics system."""
    import pyclaw
    import numpy as np

    #=================================================================
    # Import the appropriate solver type, depending on the options passed
    #=================================================================
    if solver_type=='classic':
        solver = pyclaw.ClawSolver1D()
    elif solver_type=='sharpclaw':
        solver = pyclaw.SharpClawSolver1D()
    else: raise Exception('Unrecognized value of solver_type.')

    #========================================================================
    # Instantiate the solver and define the system of equations to be solved
    #========================================================================
    solver.kernel_language=kernel_language
    from riemann import rp_acoustics
    solver.num_waves=rp_acoustics.num_waves
    if kernel_language=='Python': 
        solver.rp = rp_acoustics.rp_acoustics_1d
 
    solver.limiters = pyclaw.limiters.tvd.MC
    solver.bc_lower[0] = pyclaw.BC.wall
    solver.bc_upper[0] = pyclaw.BC.extrap

    #========================================================================
    # Instantiate the grid and set the boundary conditions
    #========================================================================
    x = pyclaw.Dimension('x',-1.0,1.0,800)
    grid = pyclaw.Grid(x)
    num_eqn = 2
    state = pyclaw.State(grid,num_eqn)

    #========================================================================
    # Set problem-specific variables
    #========================================================================
    rho = 1.0
    bulk = 0.25
    state.problem_data['rho']=rho
    state.problem_data['bulk']=bulk
    state.problem_data['zz']=np.sqrt(rho*bulk)
    state.problem_data['cc']=np.sqrt(bulk/rho)

    #========================================================================
    # Set the initial condition
    #========================================================================
    xc=grid.x.center
    beta=100; gamma=0; x0=0.75
    state.q[0,:] = 0.5*np.exp(-80 * xc**2) + 0.5*(np.abs(xc+0.2)<0.1)
    state.q[1,:] = 0.
    
    #========================================================================
    # Set up the controller object
    #========================================================================
    claw = pyclaw.Controller()
    claw.solution = pyclaw.Solution(state)
    claw.solver = solver
    claw.outdir = outdir
    claw.tfinal = 3.0
    claw.num_output_times   = 30

    # Solve
    status = claw.run()

    # Plot results
    if htmlplot:  pyclaw.plot.html_plot(outdir=outdir)
    if iplot:     pyclaw.plot.interactive_plot(outdir=outdir)
def shallow_4_Rossby_Haurwitz(iplot=0, htmlplot=False, outdir='./_output'):

    # Import pyclaw module
    import pyclaw

    #===========================================================================
    # Set up solver and solver parameters
    #===========================================================================
    solver = pyclaw.ClawSolver2D()

    # Set boundary conditions
    # =======================

    # Conserved variables
    solver.bc_lower[0] = pyclaw.BC.periodic
    solver.bc_upper[0] = pyclaw.BC.periodic
    solver.bc_lower[1] = pyclaw.BC.custom  # Custom BC for sphere
    solver.bc_upper[1] = pyclaw.BC.custom  # Custom BC for sphere

    solver.user_bc_lower = qbc_lower_y
    solver.user_bc_upper = qbc_upper_y

    # Auxiliary array
    solver.aux_bc_lower[0] = pyclaw.BC.periodic
    solver.aux_bc_upper[0] = pyclaw.BC.periodic
    solver.aux_bc_lower[1] = pyclaw.BC.custom  # Custom BC for sphere
    solver.aux_bc_upper[1] = pyclaw.BC.custom  # Custom BC for sphere

    solver.user_aux_bc_lower = auxbc_lower_y
    solver.user_aux_bc_upper = auxbc_upper_y

    # Dimensional splitting ?
    # =======================
    solver.dimensional_split = 0

    # Transverse increment waves and transverse correction waves are computed
    # and propagated.
    # =======================================================================
    solver.transverse_waves = 2

    # Number of waves in each Riemann solution
    # ========================================
    solver.num_waves = 3

    # Use source splitting method
    # ===========================
    solver.source_split = 2

    # Set source function
    # ===================
    solver.step_source = fortran_src_wrapper

    # Set the limiter for the waves
    # =============================
    solver.limiters = pyclaw.limiters.tvd.MC

    #===========================================================================
    # Initialize domain and state, then initialize the solution associated to the
    # state and finally initialize aux array
    #===========================================================================
    # Domain:
    # ====
    xlower = -3.0
    xupper = 1.0
    mx = 40

    ylower = -1.0
    yupper = 1.0
    my = 20

    x = pyclaw.Dimension('x', xlower, xupper, mx)
    y = pyclaw.Dimension('y', ylower, yupper, my)
    domain = pyclaw.Domain([x, y])
    dx = domain.delta[0]
    dy = domain.delta[1]

    # Define some parameters used in classic2
    import classic2
    classic2.comxyt.dxcom = dx
    classic2.comxyt.dycom = dy
    classic2.sw.g = 11489.57219

    # Override default mapc2p function
    # ================================
    grid = domain.grid
    grid.mapc2p = mapc2p_sphere_vectorized

    # Define state object
    # ===================
    num_eqn = 4  # Number of equations
    num_aux = 16  # Number of auxiliary variables
    state = pyclaw.State(domain, num_eqn, num_aux)

    # Set auxiliary variables
    # =======================
    import problem

    # Get lower left corner coordinates
    xlower, ylower = grid.lower[0], grid.lower[1]

    num_ghost = 2
    auxtmp = np.ndarray(shape=(num_aux, mx + 2 * num_ghost,
                               my + 2 * num_ghost),
                        dtype=float,
                        order='F')
    auxtmp = problem.setaux(mx, my, num_ghost, mx, my, xlower, ylower, dx, dy,
                            auxtmp, Rsphere)
    state.aux[:, :, :] = auxtmp[:, num_ghost:-num_ghost, num_ghost:-num_ghost]

    # Set index for capa
    state.index_capa = 0

    # Set initial conditions
    # ======================
    # 1) Call fortran function
    qtmp = np.ndarray(shape=(num_eqn, mx + 2 * num_ghost, my + 2 * num_ghost),
                      dtype=float,
                      order='F')
    qtmp = problem.qinit(mx, my, num_ghost, mx, my, xlower, ylower, dx, dy,
                         qtmp, auxtmp, Rsphere)
    state.q[:, :, :] = qtmp[:, num_ghost:-num_ghost, num_ghost:-num_ghost]

    # 2) call python function define above
    #qinit(state,mx,my)

    #===========================================================================
    # Set up controller and controller parameters
    #===========================================================================
    claw = pyclaw.Controller()
    claw.keep_copy = True
    claw.output_style = 1
    claw.num_output_times = 10
    claw.tfinal = 10
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver
    claw.outdir = outdir

    #===========================================================================
    # Solve the problem
    #===========================================================================
    status = claw.run()

    #===========================================================================
    # Plot results
    #===========================================================================
    if htmlplot: pyclaw.plot.html_plot(outdir=outdir)
    if iplot: pyclaw.plot.interactive_plot(outdir=outdir)

    # Define variable usedto verify the correctness of the regression test
    # ====================================================================
    height = claw.frames[claw.num_output_times].state.q[0, :, :]
    return height