예제 #1
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
예제 #2
0
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
예제 #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
예제 #4
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)
예제 #5
0
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
예제 #6
0
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
예제 #7
0
파일: demo.py 프로젝트: ketch/polo
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
예제 #8
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
예제 #9
0
def iniSourceVolume():

    xMin = -0.5
    xMax = 10.0
    Nx = 5000
    Gamma = 1.
    f0 = 1.

    Glob = Globals()

    Glob.domain = pyclaw.Domain([xMin], [xMax], [Nx])
    Glob.solver = pyclaw.ClawSolver1D(riemann.acoustics_variable_1D)
    Glob.state = pyclaw.State(Glob.domain, 2, 2)
    Glob.solution = pyclaw.Solution(Glob.state, Glob.domain)

    Glob.x = Glob.domain.grid.p_centers[0]
    Glob.dx = Glob.domain.grid.delta[0]
    Glob.inRange = lambda (a, b): np.logical_and(Glob.x <= b, Glob.x >= a)

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

    layers = {
        0: ((-0.50, 10.00), (0.343, 0.01, 0.000)),  # surrounding "air" 
        1: ((0.000, 5.500), (2.77, 1.7, 0.000)),  # PMMA layer
        2: ((4.980, 5.020), (2.50, 1.00, 0.000)),  # Glue layer
        3: ((4.995, 5.005), (2.25, 1.78, 0.000)),  # PVDF
        4: ((5.500, 5.550), (1.80, 1.00, 100.0)),  # Ink
        5: ((5.550, 9.550), (5.60, 2.63, 0.000))  # Glass
    }

    Glob.mua = np.zeros(Glob.x.size)
    for no, (zR, (c, rho, mu)) in sorted(layers.iteritems()):
        Glob.solution.state.aux[0, Glob.inRange(zR)] = rho
        Glob.solution.state.aux[1, Glob.inRange(zR)] = c
        Glob.mua[Glob.inRange(zR)] = mu

    Glob.solver.dt_initial = Glob.dx * 0.3 / max(Glob.solution.state.aux[1, :])

    Glob.state.q[
        0, :] = Gamma * f0 * Glob.mua * np.exp(-np.cumsum(Glob.mua * Glob.dx))
    #p0 = Gamma*f0*Glob.mua*np.exp(-np.cumsum(Glob.mua*Glob.dx))
    #Glob.state.q[0,:] = convolveIniStressGauss(Glob.x,p0,0.03)
    Glob.state.q[1, :] = 0.

    xDMin, xDMax = 4.995, 5.005
    Det = Detector(Glob.inRange((xDMin, xDMax)), xDMax - xDMin)

    return Glob, Det
예제 #10
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)
예제 #11
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
예제 #12
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
예제 #13
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
예제 #14
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
예제 #15
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()
예제 #16
0
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
예제 #17
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
예제 #18
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
예제 #19
0
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
예제 #20
0
def setup(use_petsc=False, outdir='./_output', solver_type='classic'):

    from clawpack import pyclaw
    import reactive_euler_roe_1D
    import reactive_euler_efix_roe_1D

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

    #solver = pyclaw.ClawSolver1D(reactive_euler_roe_1D)
    solver = pyclaw.ClawSolver1D(reactive_euler_efix_roe_1D)

    solver.bc_lower[0] = pyclaw.BC.extrap
    solver.bc_upper[0] = pyclaw.BC.extrap
    solver.order = 2
    solver.limiters = 1
    solver.num_waves = 4
    solver.num_eqn = 4

    # Initialize domain
    mx = 400
    x = pyclaw.Dimension('x', 0.0, 4.0, mx)
    domain = pyclaw.Domain([x])
    state = pyclaw.State(domain, solver.num_eqn)

    state.problem_data['gamma'] = gamma
    state.problem_data['gamma1'] = gamma1
    state.problem_data['qheat'] = 1
    state.problem_data['Ea'] = 0
    state.problem_data['k'] = 0
    state.problem_data['T_ign'] = 0
    state.problem_data['xfspeed'] = 0

    rhol = 1.
    rhor = 0.125
    ul = 0.5
    ur = 0.5
    pl = 1.
    pr = 0.1
    xs1 = -1.
    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, :] = 0.2

    #    rhol =  1.
    #    rhor = 0.125
    #    ul = 0.
    #    ur = 0.
    #    pl = 1.
    #    pr = 0.1
    #    xs = 0.5
    #
    #    x =state.grid.x.centers
    #    state.q[0,:] = (x<xs)*rhol + (x>=xs)*rhor
    #    state.q[1,:] = (x<xs)*rhol*ul + (x>=xs)*rhor*ur
    #    state.q[2,:] = (x<xs)*(pl/gamma1 + rhol*ul**2/2) + (x>=xs)*(pr/gamma1 + rhor*ur**2/2)
    ##
    claw = pyclaw.Controller()
    claw.tfinal = 10
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver
    claw.num_output_times = 100
    claw.outdir = outdir
    claw.setplot = setplot
    claw.keep_copy = True

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

    return claw
예제 #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
예제 #22
0
    # Compute the second spatial derivative:
    qx = np.gradient(uuu, dx)
    qxx = np.gradient(qx, dx)

    # We only want the middle portion:
    l = len(u)

    return qxx[l:2 * l]


"""
Nucleation
"""
## Specify Riemann Solver and instantiate solver object:
solver = pyclaw.ClawSolver1D(riemann.burgers_1D_py.burgers_1D)
solver.limiters = pyclaw.limiters.tvd.vanleer
solver.kernel_language = 'Python'

# Set up boundary conditions and CFL:
solver.step_source = step_Euler
solver.bc_lower[0] = pyclaw.BC.periodic
solver.bc_upper[0] = pyclaw.BC.periodic
solver.aux_bc_lower[0] = pyclaw.BC.extrap
solver.aux_bc_upper[0] = pyclaw.BC.extrap
solver.max_steps = 100000
solver.cfl_desired = 0.1

# Specify domain and fields, and initial conditions:
L = 2.0 * np.pi
mx = 1000
예제 #23
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)
def main_solver_saf_ree(Ea=1.65,
                        qheat=1.7,
                        gamma=1.4,
                        T_ign=1.1,
                        mx=300,
                        xmax=30,
                        tmax=10,
                        dtout=1,
                        outdir='./_output',
                        iplot=1,
                        animation=0):

    gamma1 = gamma - 1
    # Set up the solver object
    solver = pyclaw.ClawSolver1D(reactive_euler)
    solver.step_source = step_reaction
    solver.before_step = b4step
    solver.bc_lower[0] = pyclaw.BC.extrap
    solver.bc_upper[0] = pyclaw.BC.custom
    solver.user_bc_upper = custom_bc

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

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

    # Set initial condition
    x = state.grid.x.centers
    #    xs = xmax-5
    xs = np.inf
    xdet = x[x < xs]
    rhol, Ul, pl, laml, D0, k = steadyState.steadyState(qheat, Ea, gamma, xdet)
    ul = Ul + D0
    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)

    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

    # Set initial condition
    #    x =state.grid.x.centers
    #    rho, U, p, lam, D, k = steadyState.steadyState(qheat, Ea, gamma, x)
    #    u = U + D
    #    Y = 1-lam
    #
    #    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['fspeed'] = D0
    state.problem_data['k'] = k
    state.problem_data['animation'] = animation

    #    plt.plot(x, u)
    #    plt.show()

    # Set up controller

    claw = pyclaw.Controller()
    claw.compute_F = total_variation
    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.setplot = setplot
    claw.outdir = outdir
    claw.keep_copy = iplot

    #Run the simulation
    claw.run()

    claw.plot()

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

    return QOF
예제 #25
0
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.DEBUG)
    root_logger.propagate = True


def disable_loggers():
    """
    Disable all loggers (quiet runs)
    """

    root_logger = logging.getLogger()
    root_logger.disabled = True

from clawpack.riemann import advection_1D
fsolver_1D = pyclaw.ClawSolver1D(advection_1D)
fsolver_1D.kernel_language = 'Fortran'

from clawpack.riemann import advection_1D_py
pysolver_1D = pyclaw.ClawSolver1D(advection_1D_py.advection_1D)
pysolver_1D.kernel_language = 'Python'

from clawpack.riemann import shallow_roe_with_efix_2D
fsolver_2D = pyclaw.ClawSolver2D(shallow_roe_with_efix_2D)
fsolver_2D.kernel_language = 'Fortran'

solvers_1D = {
    'current_fortran' : fsolver_1D,
    'current_python'  : pysolver_1D
}
예제 #26
0
model for fluid dynamics.

The initial condition is sinusoidal, but after a short time a shock forms
(due to the nonlinearity).
"""
from __future__ import absolute_import
import matplotlib.pyplot as plt
import numpy as np
import scipy.io as sio
from clawpack import riemann

from clawpack import pyclaw

riemann_solver = riemann.burgers_1D_py.burgers_1D

solver = pyclaw.ClawSolver1D(riemann_solver)
solver.limiters = pyclaw.limiters.tvd.vanleer

solver.kernel_language = 'Python'

fl = 1.5
fr = 1.0
solver.bc_lower[0] = pyclaw.BC.extrap  # pyclaw.BC.periodic
solver.bc_upper[0] = pyclaw.BC.extrap  # pyclaw.BC.periodic

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
예제 #27
0
def setup(use_petsc=False, outdir='./_output', solver_type='classic'):

    from clawpack import pyclaw
    import euler_roe_1D
    import euler_efix_roe_1D


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

    if solver_type=='sharpclaw':
        solver = pyclaw.SharpClawSolver1D(riemann.euler_with_efix_1D)
        solver.weno_order = 5

        #solver.lim_type = 2
        solver.char_decomp = 1
        solver.time_integrator = 'SSP104'
    else:
        #solver = pyclaw.ClawSolver1D(euler_roe_1D)
        solver = pyclaw.ClawSolver1D(euler_efix_roe_1D)


    solver.bc_lower[0]=pyclaw.BC.extrap
    solver.bc_upper[0]=pyclaw.BC.extrap
    solver.order = 1
    solver.limiters = 1
    solver.num_waves = 3
    solver.num_eqn = 3


    # Initialize domain
    mx=400;
    x = pyclaw.Dimension('x',0.0,4.0,mx)
    domain = pyclaw.Domain([x])
    num_eqn = 3
    state = pyclaw.State(domain,num_eqn)

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


    rhol =  1.
    rhor = 0.125
    ul = 0.5
    ur = 0.5
    pl = 1.
    pr = 0.1
    xs1 = -1.
    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) )

#    rhol =  1.
#    rhor = 0.125
#    ul = 0.
#    ur = 0.
#    pl = 1.
#    pr = 0.1
#    xs = 0.5
#
#    x =state.grid.x.centers
#    state.q[0,:] = (x<xs)*rhol + (x>=xs)*rhor
#    state.q[1,:] = (x<xs)*rhol*ul + (x>=xs)*rhor*ur
#    state.q[2,:] = (x<xs)*(pl/gamma1 + rhol*ul**2/2) + (x>=xs)*(pr/gamma1 + rhor*ur**2/2)
##
    claw = pyclaw.Controller()
    claw.tfinal = 2.
    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
예제 #28
0
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.axescmd = 'subplot(212)'
    plotaxes.title = 'Energy'

    plotitem = plotaxes.new_plotitem(plot_type='1d')
    plotitem.plot_var = energy
    plotitem.kwargs = {'linewidth':3}
    
    return plotdata


from clawpack import pyclaw

rs = riemann.euler_with_efix_1D

solver = pyclaw.ClawSolver1D(rs)
solver.kernel_language = 'Fortran'

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

mx = 800;
x = pyclaw.Dimension('x',0.0,10.0,mx)
domain = pyclaw.Domain([x])
state = pyclaw.State(domain,num_eqn)

state.problem_data['gamma'] = gamma
xc = state.grid.x.centers

pressure = 1. + (xc>1)*(xc<2)* 1000.  # Modify this line
# You can change anything except the velocity in the interval (3,8)
예제 #29
0
파일: 1D_SWE.py 프로젝트: m-ender/PHASM201
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
예제 #30
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)