def burgers(): """ Example from Chapter 11 of LeVeque, Figure 11.8. Shows decay of an initial wave packet to an N-wave with Burgers' equation. """ import numpy as np from clawpack import pyclaw from clawpack import riemann solver = pyclaw.ClawSolver1D(riemann.burgers_1D) solver.limiters = pyclaw.limiters.tvd.MC solver.bc_lower[0] = pyclaw.BC.periodic solver.bc_upper[0] = pyclaw.BC.periodic x = pyclaw.Dimension(-8.0,8.0,1000,name='x') domain = pyclaw.Domain(x) num_eqn = 1 state = pyclaw.State(domain,num_eqn) xc = domain.grid.x.centers state.q[0,:] = (xc>-np.pi)*(xc<np.pi)*(2.*np.sin(3.*xc)+np.cos(2.*xc)+0.2) state.q[0,:] = state.q[0,:]*(np.cos(xc)+1.) state.problem_data['efix']=True claw = pyclaw.Controller() claw.tfinal = 6.0 claw.num_output_times = 30 claw.solution = pyclaw.Solution(state,domain) claw.solver = solver return claw
def 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)
def advect_1d(u, qfunc, qkws={}, nx=200, dx=500., t_out=np.arange(0, 3601, 5*60), sharp=True): """ Run a 1D advection calculation via clawpack. CONSTANT U ONLY. """ rp = riemann.advection_1D if sharp: solver = pyclaw.SharpClawSolver1D(rp) solver.weno_order = 5 else: solver = pyclaw.ClawSolver1D(rp) solver.bc_lower[0] = pyclaw.BC.periodic solver.bc_upper[0] = pyclaw.BC.periodic x = pyclaw.Dimension(0, dx*nx, nx, name='x') domain = pyclaw.Domain(x) state = pyclaw.State(domain, solver.num_eqn) state.problem_data['u'] = u x1d = domain.grid.x.centers q = qfunc(x1d, t=0) state.q[0, ...] = q claw = pyclaw.Controller() claw.keep_copy = True claw.solution = pyclaw.Solution(state, domain) claw.solver = solver claw.tfinal = t_out[-1] claw.out_times = t_out claw.num_output_times = len(t_out) - 1 claw.run() times = claw.out_times tracers = [f.q.squeeze() for f in claw.frames] tracers = np.asarray(tracers) uarr = u*np.ones_like(x1d) ds = xr.Dataset( {'q': (('time', 'x'), tracers), 'u': (('x', ), uarr)}, {'time': times, 'x': x1d} ) ds['time'].attrs.update({'long_name': 'time', 'units': 'seconds since 2000-01-01 0:0:0'}) ds['x'].attrs.update({'long_name': 'x-coordinate', 'units': 'm'}) ds['u'].attrs.update({'long_name': 'zonal wind', 'units': 'm/s'}) ds.attrs.update({ 'Conventions': 'CF-1.7' }) return ds
def setup(outdir='./_output'): solver = pyclaw.ClawSolver1D(reactive_euler) solver.step_source = step_reaction solver.bc_lower[0]=pyclaw.BC.extrap solver.bc_upper[0]=pyclaw.BC.extrap # Initialize domain mx=200; x = pyclaw.Dimension('x',0.0,2.0,mx) domain = pyclaw.Domain([x]) num_eqn = 4 state = pyclaw.State(domain,num_eqn) state.problem_data['gamma']= gamma state.problem_data['gamma1']= gamma1 state.problem_data['qheat']= qheat state.problem_data['Ea'] = Ea state.problem_data['k'] = k state.problem_data['T_ign'] = T_ign state.problem_data['fspeed'] = fspeed rhol = 1. rhor = 0.125 ul = 0. ur = 0. pl = 1. pr = 0.1 Yl = 1. Yr = 1. xs1 = 0.75 xs2 = 1.25 x =state.grid.x.centers state.q[0,:] = (x>xs1)*(x<xs2)*rhol + ~((x>xs1)*(x<xs2))*rhor state.q[1,:] = (x>xs1)*(x<xs2)*rhol*ul + ~((x>xs1)*(x<xs2))*rhor*ur state.q[2,:] = ((x>xs1)*(x<xs2)*(pl/gamma1 + rhol*ul**2/2) + ~((x>xs1)*(x<xs2))*(pr/gamma1 + rhor*ur**2/2) ) state.q[3,:] = (x>xs1)*(x<xs2)*(rhol*Yl) + ~((x>xs1)*(x<xs2))*(rhor*Yr) claw = pyclaw.Controller() claw.tfinal = 0.3 claw.solution = pyclaw.Solution(state,domain) claw.solver = solver claw.num_output_times = 10 claw.outdir = outdir claw.setplot = setplot claw.keep_copy = True #state.mp = 1 #claw.compute_p = pressure #claw.write_aux_always = 'True' return claw
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
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]], ":")
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
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
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
def setup(): from clawpack import pyclaw from clawpack.pyclaw.examples.advection_reaction_2d import advection_2d solver = pyclaw.ClawSolver2D(advection_2d) # Use dimensional splitting since no transverse solver is defined solver.dimensional_split = 1 solver.all_bcs = pyclaw.BC.extrap solver.aux_bc_lower[0] = pyclaw.BC.extrap solver.aux_bc_upper[0] = pyclaw.BC.extrap solver.aux_bc_lower[1] = pyclaw.BC.extrap solver.aux_bc_upper[1] = pyclaw.BC.extrap domain = pyclaw.Domain((0., 0.), (1., 1.), (100, 100)) solver.num_eqn = 2 solver.num_waves = 1 num_aux = 2 state = pyclaw.State(domain, solver.num_eqn, num_aux) Xe, Ye = domain.grid.p_nodes Xc, Yc = domain.grid.p_centers dx, dy = domain.grid.delta # Edge velocities # u(x_(i-1/2),y_j) state.aux[0, :, :] = -(psi(Xe[:-1, 1:], Ye[:-1, 1:]) - psi(Xe[:-1, :-1], Ye[:-1, :-1])) / dy # v(x_i,y_(j-1/2)) state.aux[1, :, :] = (psi(Xe[1:, :-1], Ye[1:, :-1]) - psi(Xe[:-1, :-1], Ye[:-1, :-1])) / dx solver.before_step = set_velocities solver.step_source = source_step solver.source_split = 1 state.q[0, :, :] = (Xc <= 0.5) state.q[1, :, :] = (Yc <= 0.5) claw = pyclaw.Controller() claw.tfinal = t_period claw.solution = pyclaw.Solution(state, domain) claw.solver = solver claw.keep_copy = True claw.setplot = setplot return claw
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 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 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)
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
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)
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
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
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
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)
def setup(use_petsc=False, kernel_language='Fortran', outdir='./_output', solver_type='classic'): from clawpack import pyclaw if Solver == "UNBALANCED": import shallow_roe_with_efix_unbalanced riemann_solver = shallow_roe_with_efix_unbalanced elif Solver == "LEVEQUE": import shallow_roe_with_efix_leveque riemann_solver = shallow_roe_with_efix_leveque elif Solver == "ROGERS": import shallow_roe_with_efix_rogers riemann_solver = shallow_roe_with_efix_rogers elif Solver == "ROGERS_GEO": import shallow_roe_with_efix_rogers_geo riemann_solver = shallow_roe_with_efix_rogers_geo solver = pyclaw.ClawSolver1D(riemann_solver) if Solver == "UNBALANCED": solver.step_source = step_source if Solver == "ROGERS": solver.step_source = step_source_rogers if Solver == "ROGERS_GEO": solver.step_source = step_source_rogers_geo solver.limiters = pyclaw.limiters.tvd.vanleer solver.num_waves = 3 solver.num_eqn = 3 solver.kernel_language = kernel_language solver.bc_lower[0] = pyclaw.BC.custom solver.bc_upper[0] = pyclaw.BC.custom solver.user_bc_lower = qbc_source_split_lower solver.user_bc_upper = qbc_source_split_upper solver.aux_bc_lower[0] = pyclaw.BC.custom solver.aux_bc_upper[0] = pyclaw.BC.custom if Solver == 'UNBALANCED': solver.aux_bc_lower[0] = pyclaw.BC.extrap solver.aux_bc_upper[0] = pyclaw.BC.extrap elif Solver == 'LEVEQUE': solver.user_aux_bc_lower = auxbc_bathymetry_lower solver.user_aux_bc_upper = auxbc_bathymetry_upper elif Solver == 'ROGERS': solver.user_aux_bc_lower = auxbc_eql_depth_lower solver.user_aux_bc_upper = auxbc_eql_depth_upper elif Solver == 'ROGERS_GEO': solver.user_aux_bc_lower = auxbc_eql_geo_lower solver.user_aux_bc_upper = auxbc_eql_geo_upper xlower = -0.5 xupper = 0.5 mx = Resolution num_ghost = 2 x = pyclaw.Dimension('x', xlower, xupper, mx) domain = pyclaw.Domain(x) dx = domain.grid.delta[0] num_eqn = 3 num_aux = { "UNBALANCED": 1, "LEVEQUE": 2, "ROGERS": 2, "ROGERS_GEO": 3, }[Solver] state = pyclaw.State(domain, num_eqn, num_aux) init_topo(state, xlower, xupper, dx) state.problem_data['grav'] = 1.0 state.problem_data['k'] = K state.problem_data['u'] = U state.problem_data['dx'] = dx qinit(state, xlower, xupper, dx) if num_aux > 0: auxtmp = np.ndarray(shape=(num_aux, mx + 2 * num_ghost), dtype=float, order='F') if Solver == "UNBALANCED": setaux_unbalanced(num_ghost, mx, xlower, dx, num_aux, auxtmp) elif Solver == "LEVEQUE": setaux_bathymetry(num_ghost, mx, xlower, dx, num_aux, auxtmp) elif Solver == "ROGERS": setaux_eql_depth(num_ghost, mx, xlower, dx, num_aux, auxtmp) elif Solver == "ROGERS_GEO": setaux_eql_geo(num_ghost, mx, xlower, dx, num_aux, auxtmp) state.aux[:, :] = auxtmp[:, num_ghost:-num_ghost] claw = pyclaw.Controller() claw.keep_copy = True claw.output_style = 2 claw.out_times = np.linspace(T0, T, NPlots + 1) claw.write_aux_init = True claw.tfinal = T claw.solution = pyclaw.Solution(state, domain) claw.solver = solver claw.outdir = outdir claw.setplot = setplot return claw
def 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
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 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
def inclusion(): from clawpack import pyclaw from clawpack import riemann solver = pyclaw.ClawSolver2D(riemann.vc_elasticity_2D) solver.dimensional_split = False solver.transverse_waves = 2 solver.limiters = pyclaw.limiters.tvd.MC mx = 200 my = 100 num_aux = 7 domain = pyclaw.Domain((0., 0.), (2., 1.), (mx, my)) state = pyclaw.State(domain, solver.num_eqn, num_aux) solution = pyclaw.Solution(state, domain) solver.bc_lower[0] = pyclaw.BC.custom solver.user_bc_lower = moving_wall_bc solver.bc_upper[0] = pyclaw.BC.extrap solver.bc_lower[1] = pyclaw.BC.periodic # No stress solver.bc_upper[1] = pyclaw.BC.periodic # No stress solver.aux_bc_lower[0] = pyclaw.BC.extrap solver.aux_bc_upper[0] = pyclaw.BC.extrap solver.aux_bc_lower[1] = pyclaw.BC.extrap solver.aux_bc_upper[1] = pyclaw.BC.extrap rho1 = 1.0 lam1 = 200. mu1 = 100. rho2 = 1.0 lam2 = 2.0 mu2 = 1.0 # set aux arrays # aux[0,i,j] = density rho in (i,j) cell # aux[1,i,j] = lambda in (i,j) cell # aux[2,i,j] = mu in (i,j) cell # aux[3,i,j] = cp in (i,j) cell # aux[4,i,j] = cs in (i,j) cell # aux[5,i,j] = xdisp in (i,j) cell # aux[6,i,j] = ydisp in (i,j) cell xx, yy = domain.grid.p_centers inbar = (0.5 < xx) * (xx < 1.5) * (0.4 < yy) * (yy < 0.6) outbar = 1 - inbar aux = state.aux aux[0, :, :] = rho1 * inbar + rho2 * outbar aux[1, :, :] = lam1 * inbar + lam2 * outbar aux[2, :, :] = mu1 * inbar + mu2 * outbar bulk = aux[1, :, :] + 2. * aux[2, :, :] aux[3, :, :] = np.sqrt(bulk / aux[0, :, :]) aux[4, :, :] = np.sqrt(aux[2, :, :] / aux[0, :, :]) aux[5, :, :] = 0. aux[6, :, :] = 0. # set initial condition state.q[:, :, :] = 0. claw = pyclaw.Controller() claw.solver = solver claw.solution = solution claw.num_output_times = 20 claw.tfinal = 0.5 claw.setplot = setplot return claw
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
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: state.q[0, i] = 0.5 * ((fl + fr) - (fl - fr) * (xc[i] - 0.25 - a) / a) state.problem_data['efix'] = True
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
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)