Exemple #1
0
    def __init__(self, domain_config):
        solver = pyclaw.ClawSolver2D(riemann.euler_4wave_2D)
        solver.all_bcs = pyclaw.BC.periodic

        xmin, xmax = domain_config.x_range
        ymin, ymax = domain_config.y_range
        nx, ny = domain_config.num_cells

        domain = pyclaw.Domain([xmin, ymin], [xmax, ymax], [nx, ny])
        solution = pyclaw.Solution(num_eqn, domain)
        solution.problem_data["gamma"] = 2.0
        solver.dimensional_split = False
        solver.transverse_waves = 2
        solver.step_source = q_src

        claw = pyclaw.Controller()
        claw.solution = solution
        claw.solver = solver

        claw.output_format = "ascii"
        claw.outdir = "./_output"

        self._solver = solver
        self._domain = domain
        self._solution = solution
        self._claw = claw
Exemple #2
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
    from clawpack import pyclaw

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

    solver.kernel_language = kernel_language
    from clawpack.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)
Exemple #3
0
def bump_pyclaw(numframes):
    """Returns pyclaw solution of bump initial condition."""
    # Set pyclaw for burgers equation 1D
    claw = pyclaw.Controller()
    claw.tfinal = 5.0  # Set final time
    claw.keep_copy = True  # Keep solution data in memory for plotting
    claw.output_format = None  # Don't write solution data to file
    claw.num_output_times = numframes  # Number of output frames
    claw.solver = pyclaw.ClawSolver1D(
        riemann.acoustics_1D)  # Choose acoustics 1D Riemann solver
    claw.solver.all_bcs = pyclaw.BC.wall  # Choose periodic BCs
    claw.verbosity = False  # Don't print pyclaw output
    domain = pyclaw.Domain((-2., ), (2., ),
                           (800, ))  # Choose domain and mesh resolution
    claw.solution = pyclaw.Solution(claw.solver.num_eqn, domain)
    # Set initial condition
    x = domain.grid.x.centers
    claw.solution.q[0, :] = 4.0 * np.exp(-10 * (x - 1.0)**2)
    claw.solution.q[1, :] = 0.0
    claw.solver.dt_initial = 1.e99
    # Set parameters
    rho = 1.0
    bulk = 1.0
    claw.solution.problem_data['rho'] = rho
    claw.solution.problem_data['bulk'] = bulk
    claw.solution.problem_data['zz'] = np.sqrt(rho * bulk)
    claw.solution.problem_data['cc'] = np.sqrt(bulk / rho)
    # Run pyclaw
    status = claw.run()

    return x, claw.frames
def triplestate_pyclaw(ql, qm, qr, numframes):
    # Set pyclaw for burgers equation 1D
    meshpts = 600
    claw = pyclaw.Controller()
    claw.tfinal = 2.0  # Set final time
    claw.keep_copy = True  # Keep solution data in memory for plotting
    claw.output_format = None  # Don't write solution data to file
    claw.num_output_times = numframes  # Number of output frames
    claw.solver = pyclaw.ClawSolver1D(
        riemann.burgers_1D)  # Choose burgers 1D Riemann solver
    claw.solver.all_bcs = pyclaw.BC.extrap  # Choose periodic BCs
    claw.verbosity = False  # Don't print pyclaw output
    domain = pyclaw.Domain((-3., ), (3., ),
                           (meshpts, ))  # Choose domain and mesh resolution
    claw.solution = pyclaw.Solution(claw.solver.num_eqn, domain)
    # Set initial condition
    x = domain.grid.x.centers
    q0 = 0.0 * x
    xtick1 = int(meshpts / 3)
    xtick2 = int(2 * meshpts / 3)
    q0[0:xtick1] = ql
    q0[xtick1:xtick2] = qm
    q0[xtick2:meshpts] = qr
    claw.solution.q[0, :] = q0
    claw.solver.dt_initial = 1.e99
    # Run pyclaw
    status = claw.run()

    return x, claw.frames
Exemple #5
0
def burgers():
    """
    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

    from clawpack import pyclaw
    from clawpack import riemann

    solver = pyclaw.ClawSolver1D(riemann.burgers_1D)

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

    x = pyclaw.Dimension(-8.0,8.0,1000,name='x')
    domain = pyclaw.Domain(x)
    num_eqn = 1
    state = pyclaw.State(domain,num_eqn)

    xc = domain.grid.x.centers
    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

    claw = pyclaw.Controller()
    claw.tfinal = 6.0
    claw.num_output_times   = 30
    claw.solution = pyclaw.Solution(state,domain)
    claw.solver = solver

    return claw
def advect_1d(u, qfunc, qkws={},
              nx=200, dx=500.,
              t_out=np.arange(0, 3601, 5*60),
              sharp=True):
    """ Run a 1D advection calculation via clawpack. CONSTANT U ONLY.

    """
    rp = riemann.advection_1D

    if sharp:
        solver = pyclaw.SharpClawSolver1D(rp)
        solver.weno_order = 5
    else:
        solver = pyclaw.ClawSolver1D(rp)

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

    x = pyclaw.Dimension(0, dx*nx, nx, name='x')
    domain = pyclaw.Domain(x)

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

    x1d = domain.grid.x.centers
    q = qfunc(x1d, t=0)

    state.q[0, ...] = q

    claw = pyclaw.Controller()
    claw.keep_copy = True
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver

    claw.tfinal = t_out[-1]
    claw.out_times = t_out
    claw.num_output_times = len(t_out) - 1

    claw.run()

    times = claw.out_times
    tracers = [f.q.squeeze() for f in claw.frames]
    tracers = np.asarray(tracers)

    uarr = u*np.ones_like(x1d)

    ds = xr.Dataset(
        {'q': (('time', 'x'), tracers),
         'u': (('x', ), uarr)},
        {'time': times, 'x': x1d}
    )
    ds['time'].attrs.update({'long_name': 'time', 'units': 'seconds since 2000-01-01 0:0:0'})
    ds['x'].attrs.update({'long_name': 'x-coordinate', 'units': 'm'})
    ds['u'].attrs.update({'long_name': 'zonal wind', 'units': 'm/s'})
    ds.attrs.update({
        'Conventions': 'CF-1.7'
    })

    return ds
def setup(outdir='./_output'):



    solver = pyclaw.ClawSolver1D(reactive_euler)
    solver.step_source = step_reaction

    solver.bc_lower[0]=pyclaw.BC.extrap
    solver.bc_upper[0]=pyclaw.BC.extrap

    # Initialize domain
    mx=200;
    x = pyclaw.Dimension('x',0.0,2.0,mx)
    domain = pyclaw.Domain([x])
    num_eqn = 4
    state = pyclaw.State(domain,num_eqn)

    state.problem_data['gamma']= gamma
    state.problem_data['gamma1']= gamma1
    state.problem_data['qheat']= qheat
    state.problem_data['Ea'] = Ea
    state.problem_data['k'] = k
    state.problem_data['T_ign'] = T_ign
    state.problem_data['fspeed'] = fspeed

    rhol =  1.
    rhor = 0.125
    ul = 0.
    ur = 0.
    pl = 1.
    pr = 0.1
    Yl = 1.
    Yr = 1.
    xs1 = 0.75
    xs2 = 1.25

    x =state.grid.x.centers
    state.q[0,:] = (x>xs1)*(x<xs2)*rhol + ~((x>xs1)*(x<xs2))*rhor
    state.q[1,:] = (x>xs1)*(x<xs2)*rhol*ul + ~((x>xs1)*(x<xs2))*rhor*ur
    state.q[2,:] = ((x>xs1)*(x<xs2)*(pl/gamma1 + rhol*ul**2/2) +
                    ~((x>xs1)*(x<xs2))*(pr/gamma1 + rhor*ur**2/2) )
    state.q[3,:] = (x>xs1)*(x<xs2)*(rhol*Yl) + ~((x>xs1)*(x<xs2))*(rhor*Yr)


    claw = pyclaw.Controller()
    claw.tfinal = 0.3
    claw.solution = pyclaw.Solution(state,domain)
    claw.solver = solver
    claw.num_output_times = 10
    claw.outdir = outdir
    claw.setplot = setplot
    claw.keep_copy = True

    #state.mp = 1
    #claw.compute_p = pressure
    #claw.write_aux_always = 'True'

    return claw
Exemple #8
0
def advection_setup(nx=100,
                    solver_type='classic',
                    lim_type=2,
                    weno_order=5,
                    CFL=0.9,
                    time_integrator='SSP104',
                    outdir='./_output'):

    riemann_solver = riemann.advection_1D

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

    solver.kernel_language = 'Fortran'
    solver.cfl_desired = CFL
    solver.cfl_max = CFL * 1.1

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

    x = pyclaw.Dimension(0.0, 1.0, nx, name='x')
    domain = pyclaw.Domain(x)
    state = pyclaw.State(domain, solver.num_eqn)

    state.problem_data['u'] = 1.  # Advection velocity

    # Initial data
    xc = state.grid.x.centers
    beta = 100
    gamma = 0
    x0 = 0.75
    state.q[0, :] = np.exp(-beta * (xc - x0)**2) * np.cos(gamma * (xc - x0))

    claw = pyclaw.Controller()
    claw.keep_copy = True
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver

    if outdir is not None:
        claw.outdir = outdir
    else:
        claw.output_format = None

    claw.tfinal = 1.0

    return claw
Exemple #9
0
def acoustics(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
    from clawpack import pyclaw
    from clawpack import riemann

    solver = pyclaw.ClawSolver1D(riemann.acoustics_variable_1D)

    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(-5.0, 5.0, 500, name='x')
    domain = pyclaw.Domain(x)
    num_eqn = 2
    num_aux = 2
    state = pyclaw.State(domain, 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 = domain.grid.x.centers

    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, domain)
    claw.solver = solver
    claw.tfinal = 5.0
    claw.num_output_times = 10

    # Solve
    return claw
Exemple #10
0
def setup():
    from clawpack import pyclaw
    from clawpack.pyclaw.examples.advection_reaction_2d import advection_2d

    solver = pyclaw.ClawSolver2D(advection_2d)
    # Use dimensional splitting since no transverse solver is defined
    solver.dimensional_split = 1

    solver.all_bcs = pyclaw.BC.extrap
    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

    domain = pyclaw.Domain((0., 0.), (1., 1.), (100, 100))
    solver.num_eqn = 2
    solver.num_waves = 1
    num_aux = 2
    state = pyclaw.State(domain, solver.num_eqn, num_aux)

    Xe, Ye = domain.grid.p_nodes
    Xc, Yc = domain.grid.p_centers
    dx, dy = domain.grid.delta

    # Edge velocities
    # u(x_(i-1/2),y_j)
    state.aux[0, :, :] = -(psi(Xe[:-1, 1:], Ye[:-1, 1:]) -
                           psi(Xe[:-1, :-1], Ye[:-1, :-1])) / dy
    # v(x_i,y_(j-1/2))
    state.aux[1, :, :] = (psi(Xe[1:, :-1], Ye[1:, :-1]) -
                          psi(Xe[:-1, :-1], Ye[:-1, :-1])) / dx

    solver.before_step = set_velocities
    solver.step_source = source_step
    solver.source_split = 1

    state.q[0, :, :] = (Xc <= 0.5)
    state.q[1, :, :] = (Yc <= 0.5)

    claw = pyclaw.Controller()
    claw.tfinal = t_period
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver
    claw.keep_copy = True
    claw.setplot = setplot

    return claw
Exemple #11
0
def burgers(params):
    times = np.linspace(0, time_final, num_out + 1)
    outputs = np.zeros((params.shape[0], num_out + 1))
    for k in range(params.shape[0]):
        # Define domain and mesh
        x = pyclaw.Dimension(0.0, 10.0, 500, name='x')
        domain = pyclaw.Domain(x)
        num_eqn = 1
        state = pyclaw.State(domain, num_eqn)
        xc = state.grid.x.centers
        state.problem_data['efix'] = True

        a = params[k, 0]
        for i in range(state.q.shape[1]):
            if xc[i] <= (3.25 - a):
                state.q[0, i] = fl
            elif xc[i] > (3.25 + a):
                state.q[0, i] = fr
            else:
                state.q[0, i] = 0.5 * \
                    ((fl + fr) - (fl - fr) * (xc[i] - 3.25) / a)

        # Set gauge
        grid = state.grid
        grid.add_gauges([[7.0]])
        state.keep_gauges = True

        # Setup and run
        claw = pyclaw.Controller()
        claw.tfinal = time_final
        claw.num_output_times = num_out
        claw.solution = pyclaw.Solution(state, domain)
        claw.solver = solver
        claw.outdir = './_output'
        claw.run()

        # Process output
        A = np.loadtxt('./_output/_gauges/gauge7.0.txt')
        idx = 0
        vals = []
        for j in range(A.shape[0]):
            if A[j, 0] == times[idx]:
                vals.append(A[j, 1])
                idx += 1
        outputs[k, :] = vals
    return (times, outputs)
Exemple #12
0
def setup(kernel_language='Fortran',
          solver_type='classic',
          use_petsc=False,
          outdir='./_output'):

    solver = pyclaw.ClawSolver2D(riemann.shallow_bathymetry_fwave_2D)
    solver.dimensional_split = 1  # No transverse solver available

    solver.bc_lower[0] = pyclaw.BC.custom
    solver.user_bc_lower = wave_maker_bc
    solver.bc_upper[0] = pyclaw.BC.extrap
    solver.bc_lower[1] = pyclaw.BC.wall
    solver.bc_upper[1] = pyclaw.BC.wall

    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

    my = 20
    mx = 4 * my
    x = pyclaw.Dimension(0., 4., mx, name='x')
    y = pyclaw.Dimension(0, 1, my, name='y')
    domain = pyclaw.Domain([x, y])
    state = pyclaw.State(domain, num_eqn, num_aux=1)

    X, Y = state.p_centers
    state.aux[0, :, :] = bathymetry(X, Y)

    state.q[depth, :, :] = 1. - state.aux[0, :, :]
    state.q[x_momentum, :, :] = 0.
    state.q[y_momentum, :, :] = 0.

    state.problem_data['grav'] = 1.0
    state.problem_data['dry_tolerance'] = 1.e-3
    state.problem_data['sea_level'] = 0.

    claw = pyclaw.Controller()
    claw.tfinal = 10
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver
    claw.num_output_times = 40
    claw.setplot = setplot
    claw.keep_copy = True

    return claw
Exemple #13
0
def acoustics(iplot=False, htmlplot=False, outdir='./_output'):
    """
    This example solves the 1-dimensional acoustics equations in a homogeneous
    medium.
    """
    import numpy as np
    from clawpack import riemann
    from clawpack import pyclaw

    solver = pyclaw.ClawSolver1D(riemann.acoustics_1D)

    solver.bc_lower[0] = pyclaw.BC.wall
    solver.bc_upper[0] = pyclaw.BC.wall

    solver.cfl_desired = 1.0
    solver.cfl_max = 1.0

    x = pyclaw.Dimension(0.0, 1.0, 200, name='x')
    domain = pyclaw.Domain(x)
    num_eqn = 2
    state = pyclaw.State(domain, num_eqn)

    # Set problem-specific variables
    rho = 1.0
    bulk = 1.0
    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 = domain.grid.x.centers
    state.q[0, :] = np.cos(2 * np.pi * xc)
    state.q[1, :] = 0.

    # Set up the controller
    claw = pyclaw.Controller()
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver
    claw.outdir = outdir
    claw.num_output_times = 40
    claw.tfinal = 2.0

    return claw
Exemple #14
0
def fig_61_62_63(solver_order=2, limiters=0):
    """
    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 (1)
    For Figure 6.2(b), set solver.order=2 and solver.limiters = pyclaw.limiters.tvd.superbee (2)
    For Figure 6.2(c), set solver.order=2 and solver.limiters = pyclaw.limiters.tvd.MC (4)

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

    solver = pyclaw.ClawSolver1D(riemann.advection_1D)

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

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

    xc = domain.grid.x.centers
    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, domain)
    claw.solver = solver

    claw.tfinal = 10.0
    return claw
Exemple #15
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

    from clawpack 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)
Exemple #16
0
def fig_31_38(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."""
    from clawpack import pyclaw
    from clawpack import riemann
    import numpy as np

    solver = pyclaw.ClawSolver1D(riemann.acoustics_1D)

    solver.limiters = pyclaw.limiters.tvd.MC
    solver.bc_lower[0] = pyclaw.BC.wall
    solver.bc_upper[0] = pyclaw.BC.extrap

    x = pyclaw.Dimension(-1.0, 1.0, 800, name='x')
    domain = pyclaw.Domain(x)
    num_eqn = 2
    state = pyclaw.State(domain, 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 = domain.grid.x.centers
    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
    claw = pyclaw.Controller()
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver
    claw.outdir = outdir
    claw.tfinal = 3.0
    claw.num_output_times = 30

    return claw
Exemple #17
0
    def __init__(self,
                 domain_config,
                 solver_type="sharpclaw",
                 kernel_language="Python"):
        tau = domain_config["tau"]

        if kernel_language == "Python":
            rs = riemann.euler_1D_py.euler_hllc_1D
        elif kernel_language == "Fortran":
            rs = riemann.euler_with_efix_1D

        if solver_type == "sharpclaw":
            solver = pyclaw.SharpClawSolver1D(rs)
            solver.dq_src = lambda x, y, z: dq_src(x, y, z, tau)
        elif solver_type == "classic":
            solver = pyclaw.ClawSolver1D(rs)
            solver.step_source = lambda x, y, z: q_src(x, y, z, tau)
        solver.kernel_language = kernel_language

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

        nx = domain_config["nx"]
        xmin, xmax = domain_config["xmin"], domain_config["xmax"]
        x = pyclaw.Dimension(xmin, xmax, nx, name="x")
        domain = pyclaw.Domain([x])

        state = pyclaw.State(domain, num_eqn)
        state.problem_data["gamma"] = gamma
        state.problem_data["gamma1"] = gamma - 1.0

        solution = pyclaw.Solution(state, domain)

        claw = pyclaw.Controller()
        claw.solution = solution
        claw.solver = solver

        self._solver = solver
        self._domain = domain
        self._solution = solution
        self._claw = claw
Exemple #18
0
def main():
    # (1) Define the Finite Voluem solver to be used with a Riemann Solver from
    # the library
    solver = pyclaw.ClawSolver1D(riemann.advection_1D)
    solver.bc_lower[0] = pyclaw.BC.periodic
    solver.bc_upper[0] = pyclaw.BC.periodic

    # (2) Define the mesh
    x_dimension = pyclaw.Dimension(0.0, 1.0, 100)
    domain = pyclaw.Domain(x_dimension)

    # (3) Instantiate a solution field on the Mesh
    solution = pyclaw.Solution(
        solver.num_eqn,
        domain,
    )

    # (4) Prescribe an initial state
    state = solution.state
    cell_center_coordinates = state.grid.p_centers[0]
    state.q[0, :] = np.where(
        (cell_center_coordinates > 0.2)
        & (cell_center_coordinates < 0.4),
        1.0,
        0.0,
    )

    # (5) Assign problem-specific parameters ("u" refers to the advection speed)
    state.problem_data["u"] = 1.0

    # (6) The controller takes care of the time integration
    controller = pyclaw.Controller()
    controller.solution = solution
    controller.solver = solver
    controller.tfinal = 1.0

    # (7) Run and visualize
    controller.run()

    pyclaw.plot.interactive_plot()
def bump_pyclaw(numframes):
    # Set pyclaw for burgers equation 1D
    claw = pyclaw.Controller()
    claw.tfinal = 1.5  # Set final time
    claw.keep_copy = True  # Keep solution data in memory for plotting
    claw.output_format = None  # Don't write solution data to file
    claw.num_output_times = numframes  # Number of output frames
    claw.solver = pyclaw.ClawSolver1D(
        riemann.burgers_1D)  # Choose burgers 1D Riemann solver
    claw.solver.all_bcs = pyclaw.BC.periodic  # Choose periodic BCs
    claw.verbosity = False  # Don't print pyclaw output
    domain = pyclaw.Domain((-1., ), (1., ),
                           (500, ))  # Choose domain and mesh resolution
    claw.solution = pyclaw.Solution(claw.solver.num_eqn, domain)
    # Set initial condition
    x = domain.grid.x.centers
    claw.solution.q[0, :] = np.exp(-10 * (x)**2)
    claw.solver.dt_initial = 1.e99
    # Run pyclaw
    status = claw.run()

    return x, claw.frames
Exemple #20
0
def triplestate_pyclaw(ql, qm, qr, numframes):
    """Returns pyclaw solution of triple-state initial condition."""
    # Set pyclaw for burgers equation 1D
    meshpts = 2400  #600
    claw = pyclaw.Controller()
    claw.tfinal = 2.0  # Set final time
    claw.keep_copy = True  # Keep solution data in memory for plotting
    claw.output_format = None  # Don't write solution data to file
    claw.num_output_times = numframes  # Number of output frames
    claw.solver = pyclaw.ClawSolver1D(
        riemann.burgers_1D)  # Choose burgers 1D Riemann solver
    claw.solver.all_bcs = pyclaw.BC.extrap  # Choose periodic BCs
    claw.verbosity = False  # Don't print pyclaw output
    domain = pyclaw.Domain((-12., ), (12., ),
                           (meshpts, ))  # Choose domain and mesh resolution
    claw.solution = pyclaw.Solution(claw.solver.num_eqn, domain)
    # Set initial condition
    x = domain.grid.x.centers
    q0 = 0.0 * x
    xtick1 = 900 + int(meshpts / 12)
    xtick2 = xtick1 + int(meshpts / 12)
    for i in range(xtick1):
        q0[i] = ql + i * 0.0001
    #q0[0:xtick1] = ql
    for i in np.arange(xtick1, xtick2):
        q0[i] = qm + i * 0.0001
    #q0[xtick1:xtick2] = qm
    for i in np.arange(xtick2, meshpts):
        q0[i] = qr + i * 0.0001
    #q0[xtick2:meshpts] = qr
    claw.solution.q[0, :] = q0
    claw.solver.dt_initial = 1.e99
    # Run pyclaw
    status = claw.run()

    return x, claw.frames
Exemple #21
0
def acoustics(problem='Brahmananda'):
    """
    This example solves the 1-dimensional variable-coefficient acoustics
    equations in a medium with a single interface.
    """
    from numpy import sqrt, abs
    from clawpack import pyclaw
    from clawpack import riemann
    import numpy as np
    import math
    import press_ran as pran

    solver = pyclaw.ClawSolver1D(riemann.acoustics_variable_1D)

    solver.bc_lower[0] = pyclaw.BC.periodic
    solver.bc_upper[0] = pyclaw.BC.periodic
    solver.aux_bc_lower[0] = pyclaw.BC.periodic
    solver.aux_bc_upper[0] = pyclaw.BC.periodic

    tFinal = 100
    tFrames = 100
    Nx = 1024
    xmin = 0
    xmax = 10 * math.pi

    sigma = sigma
    mu = mu
    epsilon = epsilon
    k = k

    x = pyclaw.Dimension(xmin, xmax, Nx, name='x')
    domain = pyclaw.Domain(x)
    num_eqn = 2
    num_aux = 2
    state = pyclaw.State(domain, num_eqn, num_aux)

    if problem == 'Brahmananda':
        rho = 1.0
        bulk = epsilon

    xc = domain.grid.x.centers

    for i in range(len(xc)):
        U1 = np.random.rand()
        U2 = np.random.rand()
        GRn = sigma * sqrt(-2 * math.log(U1)) * math.cos(2 * math.pi * U2) + mu
        z = 1 + bulk * GRn
        state.aux[0, i] = rho * z  # Impedance
        state.aux[1, i] = z  # Sound speed

    state.q[0, :] = np.sin(k * xc)
    state.q[1, :] = state.q[0, :] + 0.

    claw = pyclaw.Controller()
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver
    claw.tfinal = tFinal
    claw.num_output_times = tFrames

    # Solve
    return claw
Exemple #22
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."""
    from clawpack 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 clawpack.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)
Exemple #23
0
def setup(use_petsc=False,
          solver_type='classic',
          outdir='./_output',
          disable_output=False):
    if use_petsc:
        raise Exception(
            "petclaw does not currently support mapped grids (go bug Lisandro who promised to implement them)"
        )

    if solver_type != 'classic':
        raise Exception(
            "Only Classic-style solvers (solver_type='classic') are supported on mapped grids"
        )

    solver = pyclaw.ClawSolver2D(riemann.shallow_sphere_2D)
    solver.fmod = classic2

    # Set boundary conditions
    # =======================
    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

    # 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

    # 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 interrupted.
    if (mx % 2 != 0 or my % 2 != 0):
        message = 'Please, use even numbers of cells in both direction. ' \
                  'Only even numbers allow to impose correctly the boundary ' \
                  'conditions!'
        raise ValueError(message)

    x = pyclaw.Dimension(xlower, xupper, mx, name='x')
    y = pyclaw.Dimension(ylower, yupper, my, name='y')
    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_aux = 16  # Number of auxiliary variables
    state = pyclaw.State(domain, solver.num_eqn, num_aux)

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

    # Set auxiliary variables
    # =======================

    # 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=(solver.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
    if disable_output:
        claw.output_format = None
    claw.output_style = 1
    claw.num_output_times = 10
    claw.tfinal = 10
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver
    claw.outdir = outdir

    return claw
Exemple #24
0
def stegoton(rkm, tol, iplot=0, htmlplot=0, outdir='./_output'):
    """
    Stegoton problem.
    Nonlinear elasticity in periodic medium.
    See LeVeque & Yong (2003).

    $$\\epsilon_t - u_x = 0$$
    $$\\rho(x) u_t - \\sigma(\\epsilon,x)_x = 0$$
    """

    from clawpack import pyclaw

    solver = pyclaw.SharpClawSolver1D()
    solver.time_integrator = 'RK'
    solver.A = rkm.A
    solver.b = rkm.b
    solver.b_hat = rkm.bhat
    solver.c = rkm.c
    solver.error_tolerance = tol
    solver.dt_variable = True
    solver.cfl_max = 2.5
    solver.cfl_desired = 1.5
    solver.weno_order = 5

    from clawpack import riemann
    solver.rp = riemann.rp1_nonlinear_elasticity_fwave

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

    #Use the same BCs for the aux array
    solver.aux_bc_lower = solver.bc_lower
    solver.aux_bc_upper = solver.bc_lower

    xlower = 0.0
    xupper = 300.0
    cellsperlayer = 6
    mx = int(round(xupper - xlower)) * cellsperlayer
    x = pyclaw.Dimension('x', xlower, xupper, mx)
    domain = pyclaw.Domain(x)
    num_eqn = 2
    state = pyclaw.State(domain, num_eqn)

    #Set global parameters
    alpha = 0.5
    KA = 1.0
    KB = 4.0
    rhoA = 1.0
    rhoB = 4.0
    state.problem_data = {}
    state.problem_data['t1'] = 10.0
    state.problem_data['tw1'] = 10.0
    state.problem_data['a1'] = 0.0
    state.problem_data['alpha'] = alpha
    state.problem_data['KA'] = KA
    state.problem_data['KB'] = KB
    state.problem_data['rhoA'] = rhoA
    state.problem_data['rhoB'] = rhoB
    state.problem_data['trtime'] = 25000.0
    state.problem_data['trdone'] = False

    #Initialize q and aux
    xc = state.grid.x.centers
    state.aux = setaux(xc,
                       rhoB,
                       KB,
                       rhoA,
                       KA,
                       alpha,
                       xlower=xlower,
                       xupper=xupper)

    a2 = 1.0
    sigma = a2 * np.exp(-((xc - xupper / 2.) / 5.)**2.)
    state.q[0, :] = np.log(sigma + 1.) / state.aux[1, :]
    state.q[1, :] = 0.

    tfinal = 100.
    num_output_times = 10

    solver.max_steps = 5000000
    solver.fwave = True
    solver.num_waves = 2

    solver.lim_type = 2
    solver.char_decomp = 0

    claw = pyclaw.Controller()
    claw.keep_copy = True
    claw.output_style = 1
    claw.num_output_times = num_output_times
    claw.tfinal = tfinal
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver

    # Solve
    status = claw.run()
    print claw.solver.status['totalsteps']

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

    epsilon = claw.frames[-1].q[0, :]
    aux = claw.frames[1].aux
    from clawpack.riemann.rp_nonlinear_elasticity import sigma
    stress = sigma(epsilon, aux[1, :])
    dx = state.grid.delta[0]
    work = solver.status['totalsteps']

    return stress, dx, work
Exemple #25
0
def setup(use_petsc=False,
          kernel_language='Fortran',
          outdir='./_output',
          solver_type='classic'):
    from clawpack import pyclaw

    if Solver == "UNBALANCED":
        import shallow_roe_with_efix_unbalanced
        riemann_solver = shallow_roe_with_efix_unbalanced
    elif Solver == "LEVEQUE":
        import shallow_roe_with_efix_leveque
        riemann_solver = shallow_roe_with_efix_leveque
    elif Solver == "ROGERS":
        import shallow_roe_with_efix_rogers
        riemann_solver = shallow_roe_with_efix_rogers
    elif Solver == "ROGERS_GEO":
        import shallow_roe_with_efix_rogers_geo
        riemann_solver = shallow_roe_with_efix_rogers_geo

    solver = pyclaw.ClawSolver1D(riemann_solver)

    if Solver == "UNBALANCED":
        solver.step_source = step_source
    if Solver == "ROGERS":
        solver.step_source = step_source_rogers
    if Solver == "ROGERS_GEO":
        solver.step_source = step_source_rogers_geo

    solver.limiters = pyclaw.limiters.tvd.vanleer
    solver.num_waves = 3
    solver.num_eqn = 3

    solver.kernel_language = kernel_language

    solver.bc_lower[0] = pyclaw.BC.custom
    solver.bc_upper[0] = pyclaw.BC.custom
    solver.user_bc_lower = qbc_source_split_lower
    solver.user_bc_upper = qbc_source_split_upper

    solver.aux_bc_lower[0] = pyclaw.BC.custom
    solver.aux_bc_upper[0] = pyclaw.BC.custom
    if Solver == 'UNBALANCED':
        solver.aux_bc_lower[0] = pyclaw.BC.extrap
        solver.aux_bc_upper[0] = pyclaw.BC.extrap
    elif Solver == 'LEVEQUE':
        solver.user_aux_bc_lower = auxbc_bathymetry_lower
        solver.user_aux_bc_upper = auxbc_bathymetry_upper
    elif Solver == 'ROGERS':
        solver.user_aux_bc_lower = auxbc_eql_depth_lower
        solver.user_aux_bc_upper = auxbc_eql_depth_upper
    elif Solver == 'ROGERS_GEO':
        solver.user_aux_bc_lower = auxbc_eql_geo_lower
        solver.user_aux_bc_upper = auxbc_eql_geo_upper

    xlower = -0.5
    xupper = 0.5
    mx = Resolution
    num_ghost = 2

    x = pyclaw.Dimension('x', xlower, xupper, mx)
    domain = pyclaw.Domain(x)
    dx = domain.grid.delta[0]

    num_eqn = 3

    num_aux = {
        "UNBALANCED": 1,
        "LEVEQUE": 2,
        "ROGERS": 2,
        "ROGERS_GEO": 3,
    }[Solver]
    state = pyclaw.State(domain, num_eqn, num_aux)

    init_topo(state, xlower, xupper, dx)

    state.problem_data['grav'] = 1.0
    state.problem_data['k'] = K
    state.problem_data['u'] = U
    state.problem_data['dx'] = dx

    qinit(state, xlower, xupper, dx)

    if num_aux > 0:
        auxtmp = np.ndarray(shape=(num_aux, mx + 2 * num_ghost),
                            dtype=float,
                            order='F')
        if Solver == "UNBALANCED":
            setaux_unbalanced(num_ghost, mx, xlower, dx, num_aux, auxtmp)
        elif Solver == "LEVEQUE":
            setaux_bathymetry(num_ghost, mx, xlower, dx, num_aux, auxtmp)
        elif Solver == "ROGERS":
            setaux_eql_depth(num_ghost, mx, xlower, dx, num_aux, auxtmp)
        elif Solver == "ROGERS_GEO":
            setaux_eql_geo(num_ghost, mx, xlower, dx, num_aux, auxtmp)
        state.aux[:, :] = auxtmp[:, num_ghost:-num_ghost]

    claw = pyclaw.Controller()
    claw.keep_copy = True
    claw.output_style = 2
    claw.out_times = np.linspace(T0, T, NPlots + 1)
    claw.write_aux_init = True
    claw.tfinal = T
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver
    claw.outdir = outdir
    claw.setplot = setplot

    return claw
def macro_riemann_plot(which, context='notebook', figsize=(10, 3)):
    """
    Some simulations to show that the Riemann solution describes macroscopic behavior
    in the Cauchy problem.
    """
    from IPython.display import HTML
    from clawpack import pyclaw
    from matplotlib import animation
    from clawpack.riemann import shallow_roe_tracer_1D

    depth = 0
    momentum = 1
    tracer = 2

    solver = pyclaw.ClawSolver1D(shallow_roe_tracer_1D)
    solver.num_eqn = 3
    solver.num_waves = 3
    solver.bc_lower[0] = pyclaw.BC.wall
    solver.bc_upper[0] = pyclaw.BC.wall
    x = pyclaw.Dimension(-1.0, 1.0, 2000, name='x')
    domain = pyclaw.Domain(x)
    state = pyclaw.State(domain, solver.num_eqn)

    state.problem_data['grav'] = 1.0

    grid = state.grid
    xc = grid.p_centers[0]

    hl = 3.
    hr = 1.
    ul = 0.
    ur = 0.

    xs = 0.1

    alpha = (xs - xc) / (2. * xs)
    if which == 'linear':
        state.q[depth, :] = hl * (xc <= -xs) + hr * (xc > xs) + (
            alpha * hl + (1 - alpha) * hr) * (xc > -xs) * (xc <= xs)
        state.q[momentum, :] = hl * ul * (xc <= -xs) + hr * ur * (xc > xs) + (
            alpha * hl * ul + (1 - alpha) * hr * ur) * (xc > -xs) * (xc <= xs)
    elif which == 'oscillatory':
        state.q[depth, :] = hl * (xc <= -xs) + hr * (xc > xs) + (
            alpha * hl + (1 - alpha) * hr +
            0.2 * np.sin(8 * np.pi * xc / xs)) * (xc > -xs) * (xc <= xs)
        state.q[momentum, :] = hl * ul * (xc <= -xs) + hr * ur * (xc > xs) + (
            alpha * hl * ul + (1 - alpha) * hr * ur +
            0.2 * np.cos(8 * np.pi * xc / xs)) * (xc > -xs) * (xc <= xs)

    state.q[tracer, :] = xc

    claw = pyclaw.Controller()
    claw.tfinal = 0.5
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver
    claw.keep_copy = True
    claw.num_output_times = 5
    claw.verbosity = 0

    claw.run()

    fig = plt.figure(figsize=figsize)
    ax_h = fig.add_subplot(121)
    ax_u = fig.add_subplot(122)
    fills = []
    frame = claw.frames[0]
    h = frame.q[0, :]
    u = frame.q[1, :] / h
    b = 0 * h
    surface = h + b
    tracer = frame.q[2, :]

    x, = frame.state.grid.p_centers

    line, = ax_h.plot(x, surface, '-k', linewidth=3)
    line_u, = ax_u.plot(x, u, '-k', linewidth=3)

    fills = {
        'navy': None,
        'blue': None,
        'cornflowerblue': None,
        'deepskyblue': None
    }
    colors = fills.keys()

    def set_stripe_regions(tracer):
        widthl = 0.3 / hl
        widthr = 0.3 / hr
        # Designate areas for each color of stripe
        stripes = {}
        stripes['navy'] = (tracer >= 0)
        stripes['blue'] = (tracer % widthr >= widthr / 2.) * (tracer >= 0)
        stripes['cornflowerblue'] = (tracer <= 0)
        stripes['deepskyblue'] = (tracer % widthl >= widthl / 2.) * (tracer <=
                                                                     0)
        return stripes

    stripes = set_stripe_regions(tracer)

    for color in colors:
        fills[color] = ax_h.fill_between(x,
                                         b,
                                         surface,
                                         facecolor=color,
                                         where=stripes[color],
                                         alpha=0.5)

    ax_h.set_xlabel('$x$')
    ax_u.set_xlabel('$x$')
    ax_h.set_xlim(-1, 1)
    ax_h.set_ylim(0, 3.5)
    ax_u.set_xlim(-1, 1)
    ax_u.set_ylim(-1, 1)
    ax_u.set_title('Velocity')
    ax_h.set_title('Depth')

    def fplot(frame_number):
        fig.suptitle('Solution at time $t=' + str(frame_number / 10.) + '$',
                     fontsize=12)
        # Remove old fill_between plots
        for color in colors:
            fills[color].remove()

        frame = claw.frames[frame_number]
        h = frame.q[0, :]
        u = frame.q[1, :] / h
        b = 0 * h
        tracer = frame.q[2, :]
        surface = h + b
        line.set_data(x, surface)
        line_u.set_data(x, u)
        stripes = set_stripe_regions(tracer)
        for color in colors:
            fills[color] = ax_h.fill_between(x,
                                             b,
                                             surface,
                                             facecolor=color,
                                             where=stripes[color],
                                             alpha=0.5)
        return line,

    if context in ['notebook', 'html']:
        anim = animation.FuncAnimation(fig,
                                       fplot,
                                       frames=len(claw.frames),
                                       interval=200,
                                       repeat=False)
        plt.close()
        return HTML(anim.to_jshtml())
    else:  # PDF output
        fplot(0)
        plt.show()
        fplot(2)
        return fig
Exemple #27
0
solver = pyclaw.ClawSolver2D(riemann.rp2_euler_4wave)
solver.all_bcs = pyclaw.BC.extrap

domain = pyclaw.Domain([0., 0.], [1., 1.], [100, 100])
solution = pyclaw.Solution(solver.num_eqn, domain)
gamma = 1.4
solution.problem_data['gamma'] = gamma

# Set initial data
xx, yy = domain.grid.p_centers
l = xx < 0.5
r = xx >= 0.5
b = yy < 0.5
t = yy >= 0.5
solution.q[0, ...] = 2. * l * t + 1. * l * b + 1. * r * t + 3. * r * b
solution.q[1, ...] = 0.75 * t - 0.75 * b
solution.q[2, ...] = 0.5 * l - 0.5 * r
solution.q[3, ...] = 0.5 * solution.q[0, ...] * (
    solution.q[1, ...]**2 + solution.q[2, ...]**2) + 1. / (gamma - 1.)

#solver.evolve_to_time(solution,tend=0.3)
claw = pyclaw.Controller()
claw.tfinal = 0.3
claw.solution = solution
claw.solver = solver

status = claw.run()

#pyclaw.plot.interactive_plot()
Exemple #28
0
def inclusion():
    from clawpack import pyclaw
    from clawpack import riemann

    solver = pyclaw.ClawSolver2D(riemann.vc_elasticity_2D)
    solver.dimensional_split = False
    solver.transverse_waves = 2
    solver.limiters = pyclaw.limiters.tvd.MC

    mx = 200
    my = 100
    num_aux = 7
    domain = pyclaw.Domain((0., 0.), (2., 1.), (mx, my))
    state = pyclaw.State(domain, solver.num_eqn, num_aux)
    solution = pyclaw.Solution(state, domain)

    solver.bc_lower[0] = pyclaw.BC.custom
    solver.user_bc_lower = moving_wall_bc
    solver.bc_upper[0] = pyclaw.BC.extrap
    solver.bc_lower[1] = pyclaw.BC.periodic  # No stress
    solver.bc_upper[1] = pyclaw.BC.periodic  # No stress

    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

    rho1 = 1.0
    lam1 = 200.
    mu1 = 100.

    rho2 = 1.0
    lam2 = 2.0
    mu2 = 1.0

    # set aux arrays
    #  aux[0,i,j] = density rho in (i,j) cell
    #  aux[1,i,j] = lambda in (i,j) cell
    #  aux[2,i,j] = mu in (i,j) cell
    #  aux[3,i,j] = cp in (i,j) cell
    #  aux[4,i,j] = cs in (i,j) cell
    #  aux[5,i,j] = xdisp in (i,j) cell
    #  aux[6,i,j] = ydisp in (i,j) cell

    xx, yy = domain.grid.p_centers
    inbar = (0.5 < xx) * (xx < 1.5) * (0.4 < yy) * (yy < 0.6)
    outbar = 1 - inbar
    aux = state.aux
    aux[0, :, :] = rho1 * inbar + rho2 * outbar
    aux[1, :, :] = lam1 * inbar + lam2 * outbar
    aux[2, :, :] = mu1 * inbar + mu2 * outbar
    bulk = aux[1, :, :] + 2. * aux[2, :, :]
    aux[3, :, :] = np.sqrt(bulk / aux[0, :, :])
    aux[4, :, :] = np.sqrt(aux[2, :, :] / aux[0, :, :])
    aux[5, :, :] = 0.
    aux[6, :, :] = 0.

    # set initial condition
    state.q[:, :, :] = 0.

    claw = pyclaw.Controller()
    claw.solver = solver
    claw.solution = solution
    claw.num_output_times = 20
    claw.tfinal = 0.5
    claw.setplot = setplot

    return claw
Exemple #29
0
def main_solver_laf_ree(Ea=20,
                        qheat=50,
                        gamma=1.2,
                        T_ign=1.5,
                        mx=1000,
                        xmax=30,
                        tmax=10,
                        dtout=1,
                        outdir='./_output',
                        iplot=1):

    gamma1 = gamma - 1
    # Set up the solver object
    solver = pyclaw.ClawSolver1D(rp_solver)
    solver.step_source = step_reaction
    solver.bc_lower[0] = pyclaw.BC.extrap
    solver.bc_upper[0] = pyclaw.BC.extrap
    # solver.user_bc_upper = custom_bc
    solver.num_waves = 4
    solver.num_eqn = 4

    # Set the domain
    x = pyclaw.Dimension('x', 0.0, xmax, mx)
    domain = pyclaw.Domain([x])

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

    # Set initial condition
    x = state.grid.x.centers
    xs = xmax - 5
    xdet = x[x < xs]
    rhol, Ul, pl, laml, D, k = steadyState.steadyState(qheat, Ea, gamma, xdet)
    ul = Ul + D
    Yl = 1 - laml
    rhor = 1. * np.ones(np.shape(x[x >= xs]))
    ur = 0.0 * np.ones(np.shape(x[x >= xs]))
    pr = 1 * np.ones(np.shape(x[x >= xs]))
    Yr = 1. * np.ones(np.shape(x[x >= xs]))
    rho = np.append(rhol, rhor)
    u = np.append(ul, ur)
    p = np.append(pl, pr)
    Y = np.append(Yl, Yr)

    plt.plot(x, u)

    state.q[0, :] = rho
    state.q[1, :] = rho * u
    state.q[2, :] = p / gamma1 + rho * u**2 / 2 + qheat * rho * Y
    state.q[3, :] = rho * Y
    state.mF = 1

    # Fill dictory of problem data
    state.problem_data['gamma'] = gamma
    state.problem_data['gamma1'] = gamma1
    state.problem_data['qheat'] = qheat
    state.problem_data['Ea'] = Ea
    state.problem_data['T_ign'] = T_ign
    state.problem_data['xfspeed'] = D
    state.problem_data['k'] = k

    # Set up controller

    claw = pyclaw.Controller()
    claw.tfinal = tmax
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver

    #Set up data writting and plotting
    claw.output_style = 1
    nout = np.ceil(tmax / dtout)
    claw.num_output_times = nout
    claw.outdir = outdir
    claw.keep_copy = iplot

    #Run the simulation
    claw.run()

    #Save QOF
    np.save('qof', QOF)

    return QOF
Exemple #30
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

    from clawpack 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)