def callback_initialization(
                q, qbc, aux, subdivision_factor_x0, subdivision_factor_x1,
                subdivision_factor_x2, unknowns_per_subcell,
                aux_fields_per_subcell, size_x, size_y, size_z, position_x,
                position_y, position_z, skip_q_initialization):
            import clawpack.pyclaw as pyclaw

            dim = get_number_of_dimensions(q)
            if dim is 2:
                self.dim_x = pyclaw.Dimension('x', position_x,
                                              position_x + size_x,
                                              subdivision_factor_x0)
                self.dim_y = pyclaw.Dimension('y', position_y,
                                              position_y + size_y,
                                              subdivision_factor_x1)
                domain = pyclaw.Domain([self.dim_x, self.dim_y])

            elif dim is 3:
                self.dim_x = pyclaw.Dimension('x', position_x,
                                              position_x + size_x,
                                              subdivision_factor_x0)
                self.dim_y = pyclaw.Dimension('y', position_y,
                                              position_y + size_y,
                                              subdivision_factor_x1)
                self.dim_z = pyclaw.Dimension('z', position_z,
                                              position_z + size_z,
                                              subdivision_factor_x2)
                domain = pyclaw.Domain([self.dim_x, self.dim_y, self.dim_z])

            subgrid_state = pyclaw.State(domain, unknowns_per_subcell,
                                         aux_fields_per_subcell)
            subgrid_state.q = q
            if (aux_fields_per_subcell > 0):
                subgrid_state.aux = aux
            subgrid_state.problem_data = self.solver.solution.state.problem_data

            if not skip_q_initialization:
                self.q_initialization(subgrid_state)

            if (self.aux_initialization != None
                    and aux_fields_per_subcell > 0):
                self.aux_initialization(subgrid_state)

            #Steer refinement
            if self.refinement_criterion != None:
                return self.refinement_criterion(subgrid_state)
            else:
                return self.initial_minimal_mesh_width
Beispiel #2
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
Beispiel #3
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)
Beispiel #4
0
    def __init__(self, cparams, dtype_u, dtype_f):
        """
        Initialization routine

        Args:
            cparams: custom parameters for the example
            dtype_u: particle data type (will be passed parent class)
            dtype_f: acceleration data type (will be passed parent class)
        """

        # these parameters will be used later, so assert their existence
        assert 'nvars' in cparams

        # add parameters as attributes for further reference
        for k, v in cparams.items():
            setattr(self, k, v)

        # invoke super init, passing number of dofs, dtype_u and dtype_f
        super(advection_2d_explicit, self).__init__(self.nvars, dtype_u,
                                                    dtype_f)

        riemann_solver = riemann.advection_2D  # NOTE: This uses the FORTRAN kernels of clawpack
        self.solver = pyclaw.SharpClawSolver2D(riemann.advection_2D)
        self.solver.weno_order = 5
        self.solver.time_integrator = 'Euler'  # Remove later
        self.solver.kernel_language = 'Fortran'
        self.solver.bc_lower[0] = pyclaw.BC.periodic
        self.solver.bc_upper[0] = pyclaw.BC.periodic
        self.solver.bc_lower[1] = pyclaw.BC.periodic
        self.solver.bc_upper[1] = pyclaw.BC.periodic
        self.solver.cfl_max = 1.0
        assert self.solver.is_valid()

        x = pyclaw.Dimension(-1.0, 1.0, self.nvars[1], name='x')
        y = pyclaw.Dimension(0.0, 1.0, self.nvars[2], name='y')
        self.domain = pyclaw.Domain([x, y])

        self.state = pyclaw.State(self.domain, self.solver.num_eqn)
        # self.dx = self.state.grid.x.centers[1] - self.state.grid.x.centers[0]

        self.state.problem_data['u'] = 1.0
        self.state.problem_data['v'] = 0.0

        solution = pyclaw.Solution(self.state, self.domain)
        self.solver.setup(solution)

        self.xc, self.yc = self.state.grid.p_centers
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
Beispiel #6
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
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
    def momentum2(current_data):
        x = pyclaw.Dimension(xlower, xupper, cells_number, name='x')
        domain = pyclaw.Domain(x)
        state = pyclaw.State(domain, 2, 2)

        xc = state.grid.x.centers
        x_wall = nw_edge_p
        axis = plt.gca()
        axis.plot(xc, hu1[current_data.frameno, :], 'r:')
        axis.plot([x_wall, x_wall],
                  [-1.1 * current_data.q[1, nw], 1.1 * current_data.q[1, nw]],
                  ":")
Beispiel #9
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
Beispiel #10
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
Beispiel #11
0
        def callback_add_to_solution(q, qbc, ghostlayer_width, size_x, size_y,
                                     size_z, position_x, position_y,
                                     position_z, currentTime):
            dim = get_number_of_dimensions(q)

            # Set up grid information for current patch
            if dim is 2:
                subdivision_factor_x = q.shape[1]
                subdivision_factor_y = q.shape[2]
                unknowns_per_subcell = q.shape[0]
                dim_x = pyclaw.Dimension('x', position_x, position_x + size_x,
                                         subdivision_factor_x)
                dim_y = pyclaw.Dimension('y', position_y, position_y + size_y,
                                         subdivision_factor_y)

                patch = pyclaw.geometry.Patch((dim_x, dim_y))

            elif dim is 3:
                subdivision_factor_x = q.shape[1]
                subdivision_factor_y = q.shape[2]
                subdivision_factor_z = q.shape[3]
                unknowns_per_subcell = q.shape[0]
                dim_x = pyclaw.Dimension('x', position_x, position_x + size_x,
                                         subdivision_factor_x)
                dim_y = pyclaw.Dimension('y', position_y, position_y + size_y,
                                         subdivision_factor_y)
                dim_z = pyclaw.Dimension('z', position_z, position_z + size_z,
                                         subdivision_factor_z)

                patch = pyclaw.geometry.Patch((dim_x, dim_y, dim_z))

            state = pyclaw.State(patch, unknowns_per_subcell)
            state.q[:] = q[:]
            state.t = currentTime

            self.gathered_patches.append(patch)
            self.gathered_states.append(state)
Beispiel #12
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)
    def height2(current_data):
        x = pyclaw.Dimension(xlower, xupper, cells_number, name='x')
        domain = pyclaw.Domain(x)
        state = pyclaw.State(domain, 2, 2)

        xc = state.grid.x.centers
        print(len(xc))
        print(len(h1[current_data.frameno, :]))
        axis = plt.gca()
        jump = numpy.zeros(len(xc))
        jump[nw] = 0.1  #wall height
        axis.plot(xc, h1[current_data.frameno, :] + bathy(current_data) + jump,
                  'r:')

        x_wall = nw_edge_p
        y1 = current_data.aux[0, nw - 1]
        y2 = y1 + wall_height
        axis.plot([x_wall, x_wall], [y1, y2], 'g', linewidth=2.5)
Beispiel #14
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
Beispiel #15
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
Beispiel #16
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)
Beispiel #17
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
Beispiel #18
0
def read_patch_header(f, num_dim):
    r"""Read header describing the next patch
    
    :Input:
     - *f* - (file) Handle to open file
     - *num_dim* - (int) Number of dimensions
     
    :Output:
     - *patch* - (clawpack.pyclaw.geometry.Patch) Initialized patch represented
       by the header data.
    
    """

    n = np.zeros((num_dim), dtype=int)
    d = np.zeros((num_dim))
    lower = np.zeros((num_dim))
    patch_index = read_data_line(f, data_type=int)
    level = read_data_line(f, data_type=int)
    for i in range(num_dim):
        n[i] = read_data_line(f, data_type=int)
    for i in range(num_dim):
        lower[i] = read_data_line(f)
    for i in range(num_dim):
        d[i] = read_data_line(f)

    blank = f.readline()

    # Construct the patch
    # Since we do not have names here, we will construct each patch with
    # dimension names x,y,z
    names = ['x', 'y', 'z']
    dimensions = [
        pyclaw.Dimension(lower[i], lower[i] + n[i] * d[i], n[i], name=names[i])
        for i in range(num_dim)
    ]
    patch = pyclaw.geometry.Patch(dimensions)

    # Add AMR attributes:
    patch.patch_index = patch_index
    patch.level = level

    return patch
Beispiel #19
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
Beispiel #20
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()
Beispiel #21
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
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
Beispiel #23
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
Beispiel #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
Beispiel #25
0
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
#state.q[0, :] = 0.01 * np.cos(np.pi * 2 * xc) + 0.50
#beta = 10; gamma = 0; x0 = 0.5
#state.q[0,:] = 0.01 * np.exp(-beta * (xc-x0)**2) * np.cos(gamma * (xc - x0))
a = 3.0
for i in range(state.q.shape[1]):
    if xc[i] <= 0.25:
        state.q[0, i] = fl
    elif xc[i] > (0.25 + 2.0 * a):
        state.q[0, i] = fr
    else:
Beispiel #26
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
Beispiel #27
0
    def contourLineSphere(fileName='fort.q0000', path='./_output'):
        """
        This function plots the contour lines on a spherical surface for the shallow
        water equations solved on a sphere.
        """

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

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

        f = open(pathFileName, "r")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        # Fluid height
        plt.figure()
        CS = plt.contour(xc, yc, h)
        plt.title('Fluid height (computational domain)')
        plt.xlabel('xc')
        plt.ylabel('yc')
        plt.clabel(CS, inline=1, fontsize=10)
        plt.show()
Beispiel #28
0
def read(solution,
         frame,
         path='./',
         file_prefix='fort',
         read_aux=False,
         options={}):
    r"""
    Read in a frame of ascii formatted files, and enter the data into the
    solution object.
    
    This routine reads the ascii formatted files corresponding to the classic
    clawpack format 'fort.txxxx', 'fort.qxxxx', and 'fort.axxxx' or 'fort.aux'
    Note that the fort prefix can be changed.
    
    :Input:
     - *solution* - (:class:`~pyclaw.solution.Solution`) Solution object to 
       read the data into.
     - *frame* - (int) Frame number to be read in
     - *path* - (string) Path to the current directory of the file
     - *file_prefix* - (string) Prefix of the files to be read in.  
       ``default = 'fort'``
     - *read_aux* (bool) Whether or not an auxillary file will try to be read 
       in.  ``default = False``
     - *options* - (dict) Dictionary of optional arguments dependent on 
       the format being read in.  ``default = {}``
    """

    pickle_filename = os.path.join(
        path, '%s.pkl' % file_prefix) + str(frame).zfill(4)
    problem_data = None
    mapc2p = None
    try:
        if os.path.exists(pickle_filename):
            with open(pickle_filename, 'rb') as pickle_file:
                value_dict = pickle.load(pickle_file)
            problem_data = value_dict.get('problem_data', None)
            mapc2p = value_dict.get('mapc2p', None)
    except IOError:
        logger.info("Unable to open pickle file %s" % (pickle_filename))

    # Construct path names
    base_path = os.path.join(path, )
    q_fname = os.path.join(base_path,
                           '%s.q' % file_prefix) + str(frame).zfill(4)

    # Read in values from fort.t file:
    [t, num_eqn, nstates, num_aux, num_dim] = read_t(frame, path, file_prefix)

    patches = []
    n = np.zeros((num_dim), dtype=int)
    d = np.zeros((num_dim))
    lower = np.zeros((num_dim))
    # Since we do not have names here, we will construct each patch with
    # dimension names x,y,z
    names = ['x', 'y', 'z']

    # Read in values from fort.q file:
    with open(q_fname, 'r') as f:
        # Loop through every patch setting the appropriate information
        for m in xrange(nstates):
            # Read header for this patch
            patch_index = read_data_line(f, data_type=int)
            level = read_data_line(f, data_type=int)
            for i in xrange(num_dim):
                n[i] = read_data_line(f, data_type=int)
            for i in xrange(num_dim):
                lower[i] = read_data_line(f)
            for i in xrange(num_dim):
                d[i] = read_data_line(f)

            blank = f.readline()

            # Construct the patch
            dimensions = [pyclaw.Dimension(lower[i],lower[i]+n[i]*d[i],\
                          n[i],name=names[i]) for i in xrange(num_dim)]
            patch = pyclaw.geometry.Patch(dimensions)
            state = pyclaw.state.State(patch, num_eqn, num_aux)
            state.t = t
            state.problem_data = problem_data
            if mapc2p is not None:
                # If no mapc2p the default identity map in grid will be used
                state.grid.mapc2p = mapc2p

            if num_aux > 0:
                # Write NaNs for now to indicate this is uninitialized
                state.aux[:] = np.nan

            # Fill in q values
            state.q = read_array(f, state, num_eqn)

            # Add AMR attributes:
            patch.patch_index = patch_index
            patch.level = level

            # Add new patch to solution
            solution.states.append(state)
            patches.append(state.patch)

    solution.domain = pyclaw.geometry.Domain(patches)

    # Read auxillary file if available and requested
    # Matching dimension parameter tolerances
    ABS_TOL = 1e-8
    REL_TOL = 1e-15
    if solution.states[0].num_aux > 0 and read_aux:
        # Check for aux file
        fname1 = os.path.join(base_path,
                              '%s.a' % file_prefix) + str(frame).zfill(4)
        fname2 = os.path.join(base_path,
                              '%s.a' % file_prefix) + str(0).zfill(4)
        if os.path.exists(fname1):
            # aux file specific to this frame:
            fname = fname1
        elif os.path.exists(fname2):
            # Assume that aux data from initial time is valid for all frames:
            fname = fname2
            # Note that this is generally not true when AMR is used.
        else:
            logger.debug("Unable to open auxillary file %s or %s" %
                         (fname1, fname2))
            return

        # Read in fort.auxxxxx file
        with open(fname, 'r') as f:
            for state in solution.states:
                patch = state.patch
                patch_index = read_data_line(f, data_type=int)

                # Read patch header and check that it matches that from fort.qxxxx
                assert patch.level == read_data_line(f,data_type=int), \
                        "Patch level in aux file header did not match patch no %s." % patch.patch_index
                for dim in patch.dimensions:
                    num_cells = read_data_line(f, data_type=int)
                    assert dim.num_cells == num_cells, \
                        "Dimension %s's num_cells in aux file header did not match patch no %s." % (dim.name,patch.patch_index)
                for dim in patch.dimensions:
                    lower = read_data_line(f, data_type=float)
                    assert np.abs(lower - dim.lower) <= ABS_TOL + REL_TOL * np.abs(dim.lower), \
                            'Value of lower in aux file does not match.'
                for dim in patch.dimensions:
                    delta = read_data_line(f, data_type=float)
                    assert np.abs(delta - dim.delta) <= ABS_TOL + REL_TOL * np.abs(dim.delta), \
                            'Value of delta in aux file does not match.'

                blank = f.readline()
                state.aux = read_array(f, state, num_aux)
Beispiel #29
0
    
    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)

state.q[density ,:] = 1.
state.q[momentum,:] = 0.
state.q[energy  ,:] = pressure / (state.q[density,:]*(gamma - 1.))

grid = state.grid
grid.add_gauges([ [9.0] ])
Beispiel #30
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