def gatherStates(self): r""" Writes gathered solution to file. """ if (self.peano == None or self.libpeano == None): raise Exception( "self.peano and self.libpeano have to be initialized with the reference to the Peano grid by peanoclaw.Solver.setup(...)" ) #Gather patches and states self.gathered_patches = [] self.gathered_states = [] self.libpeano.pyclaw_peano_gatherSolution.argtypes = [c_void_p] self.libpeano.pyclaw_peano_gatherSolution(self.peano) if (len(self.gathered_patches) > 0): #Assemble solution and write file self.domain = pyclaw.Domain(self.gathered_patches) self.solution = pyclaw.Solution(self.gathered_states, self.domain) else: self.domain = pyclaw.Domain(self.patch) self.solution = pyclaw.Solution(self.state, self.domain) self.t = self.solution.t
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 bump_pyclaw(numframes): """Returns pyclaw solution of bump initial condition.""" # Set pyclaw for burgers equation 1D claw = pyclaw.Controller() claw.tfinal = 5.0 # Set final time claw.keep_copy = True # Keep solution data in memory for plotting claw.output_format = None # Don't write solution data to file claw.num_output_times = numframes # Number of output frames claw.solver = pyclaw.ClawSolver1D( riemann.acoustics_1D) # Choose acoustics 1D Riemann solver claw.solver.all_bcs = pyclaw.BC.wall # Choose periodic BCs claw.verbosity = False # Don't print pyclaw output domain = pyclaw.Domain((-2., ), (2., ), (800, )) # Choose domain and mesh resolution claw.solution = pyclaw.Solution(claw.solver.num_eqn, domain) # Set initial condition x = domain.grid.x.centers claw.solution.q[0, :] = 4.0 * np.exp(-10 * (x - 1.0)**2) claw.solution.q[1, :] = 0.0 claw.solver.dt_initial = 1.e99 # Set parameters rho = 1.0 bulk = 1.0 claw.solution.problem_data['rho'] = rho claw.solution.problem_data['bulk'] = bulk claw.solution.problem_data['zz'] = np.sqrt(rho * bulk) claw.solution.problem_data['cc'] = np.sqrt(bulk / rho) # Run pyclaw status = claw.run() return x, claw.frames
def 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 triplestate_pyclaw(ql, qm, qr, numframes): # Set pyclaw for burgers equation 1D meshpts = 600 claw = pyclaw.Controller() claw.tfinal = 2.0 # Set final time claw.keep_copy = True # Keep solution data in memory for plotting claw.output_format = None # Don't write solution data to file claw.num_output_times = numframes # Number of output frames claw.solver = pyclaw.ClawSolver1D( riemann.burgers_1D) # Choose burgers 1D Riemann solver claw.solver.all_bcs = pyclaw.BC.extrap # Choose periodic BCs claw.verbosity = False # Don't print pyclaw output domain = pyclaw.Domain((-3., ), (3., ), (meshpts, )) # Choose domain and mesh resolution claw.solution = pyclaw.Solution(claw.solver.num_eqn, domain) # Set initial condition x = domain.grid.x.centers q0 = 0.0 * x xtick1 = int(meshpts / 3) xtick2 = int(2 * meshpts / 3) q0[0:xtick1] = ql q0[xtick1:xtick2] = qm q0[xtick2:meshpts] = qr claw.solution.q[0, :] = q0 claw.solver.dt_initial = 1.e99 # Run pyclaw status = claw.run() return x, claw.frames
def __init__(self, domain_config): solver = pyclaw.ClawSolver2D(riemann.euler_4wave_2D) solver.all_bcs = pyclaw.BC.periodic xmin, xmax = domain_config.x_range ymin, ymax = domain_config.y_range nx, ny = domain_config.num_cells domain = pyclaw.Domain([xmin, ymin], [xmax, ymax], [nx, ny]) solution = pyclaw.Solution(num_eqn, domain) solution.problem_data["gamma"] = 2.0 solver.dimensional_split = False solver.transverse_waves = 2 solver.step_source = q_src claw = pyclaw.Controller() claw.solution = solution claw.solver = solver claw.output_format = "ascii" claw.outdir = "./_output" self._solver = solver self._domain = domain self._solution = solution self._claw = claw
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 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 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 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 __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(): 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 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 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 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 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 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 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 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 from clawpack import riemann solver = pyclaw.ClawSolver1D(riemann.burgers_1D) 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) 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 #=========================================================================== # 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, domain) claw.solver = solver claw.outdir = outdir 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 main(): # (1) Define the Finite Voluem solver to be used with a Riemann Solver from # the library solver = pyclaw.ClawSolver1D(riemann.advection_1D) solver.bc_lower[0] = pyclaw.BC.periodic solver.bc_upper[0] = pyclaw.BC.periodic # (2) Define the mesh x_dimension = pyclaw.Dimension(0.0, 1.0, 100) domain = pyclaw.Domain(x_dimension) # (3) Instantiate a solution field on the Mesh solution = pyclaw.Solution( solver.num_eqn, domain, ) # (4) Prescribe an initial state state = solution.state cell_center_coordinates = state.grid.p_centers[0] state.q[0, :] = np.where( (cell_center_coordinates > 0.2) & (cell_center_coordinates < 0.4), 1.0, 0.0, ) # (5) Assign problem-specific parameters ("u" refers to the advection speed) state.problem_data["u"] = 1.0 # (6) The controller takes care of the time integration controller = pyclaw.Controller() controller.solution = solution controller.solver = solver controller.tfinal = 1.0 # (7) Run and visualize controller.run() pyclaw.plot.interactive_plot()
def bump_pyclaw(numframes): # Set pyclaw for burgers equation 1D claw = pyclaw.Controller() claw.tfinal = 1.5 # Set final time claw.keep_copy = True # Keep solution data in memory for plotting claw.output_format = None # Don't write solution data to file claw.num_output_times = numframes # Number of output frames claw.solver = pyclaw.ClawSolver1D( riemann.burgers_1D) # Choose burgers 1D Riemann solver claw.solver.all_bcs = pyclaw.BC.periodic # Choose periodic BCs claw.verbosity = False # Don't print pyclaw output domain = pyclaw.Domain((-1., ), (1., ), (500, )) # Choose domain and mesh resolution claw.solution = pyclaw.Solution(claw.solver.num_eqn, domain) # Set initial condition x = domain.grid.x.centers claw.solution.q[0, :] = np.exp(-10 * (x)**2) claw.solver.dt_initial = 1.e99 # Run pyclaw status = claw.run() return x, claw.frames
def triplestate_pyclaw(ql, qm, qr, numframes): """Returns pyclaw solution of triple-state initial condition.""" # Set pyclaw for burgers equation 1D meshpts = 2400 #600 claw = pyclaw.Controller() claw.tfinal = 2.0 # Set final time claw.keep_copy = True # Keep solution data in memory for plotting claw.output_format = None # Don't write solution data to file claw.num_output_times = numframes # Number of output frames claw.solver = pyclaw.ClawSolver1D( riemann.burgers_1D) # Choose burgers 1D Riemann solver claw.solver.all_bcs = pyclaw.BC.extrap # Choose periodic BCs claw.verbosity = False # Don't print pyclaw output domain = pyclaw.Domain((-12., ), (12., ), (meshpts, )) # Choose domain and mesh resolution claw.solution = pyclaw.Solution(claw.solver.num_eqn, domain) # Set initial condition x = domain.grid.x.centers q0 = 0.0 * x xtick1 = 900 + int(meshpts / 12) xtick2 = xtick1 + int(meshpts / 12) for i in range(xtick1): q0[i] = ql + i * 0.0001 #q0[0:xtick1] = ql for i in np.arange(xtick1, xtick2): q0[i] = qm + i * 0.0001 #q0[xtick1:xtick2] = qm for i in np.arange(xtick2, meshpts): q0[i] = qr + i * 0.0001 #q0[xtick2:meshpts] = qr claw.solution.q[0, :] = q0 claw.solver.dt_initial = 1.e99 # Run pyclaw status = claw.run() return x, claw.frames
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
#!/usr/bin/env python # encoding: utf-8 """ Solve the Euler equations of compressible fluid dynamics. """ from clawpack import pyclaw from clawpack import riemann solver = pyclaw.ClawSolver2D(riemann.rp2_euler_4wave) solver.all_bcs = pyclaw.BC.extrap domain = pyclaw.Domain([0., 0.], [1., 1.], [100, 100]) solution = pyclaw.Solution(solver.num_eqn, domain) gamma = 1.4 solution.problem_data['gamma'] = gamma # Set initial data xx, yy = domain.grid.p_centers l = xx < 0.5 r = xx >= 0.5 b = yy < 0.5 t = yy >= 0.5 solution.q[0, ...] = 2. * l * t + 1. * l * b + 1. * r * t + 3. * r * b solution.q[1, ...] = 0.75 * t - 0.75 * b solution.q[2, ...] = 0.5 * l - 0.5 * r solution.q[3, ...] = 0.5 * solution.q[0, ...] * ( solution.q[1, ...]**2 + solution.q[2, ...]**2) + 1. / (gamma - 1.) #solver.evolve_to_time(solution,tend=0.3) claw = pyclaw.Controller() claw.tfinal = 0.3
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(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
import matplotlib.pyplot as plt q = frame.q x, y = frame.state.grid.c_centers plt.pcolormesh(x, y, q[density, ...]) def plot_results(): from clawpack.visclaw import iplot ip = iplot.Iplot(load_frame, plot_frame) ip.plotloop() solver = pyclaw.ClawSolver2D(riemann.euler_4wave_2D) solver.all_bcs = pyclaw.BC.extrap domain = pyclaw.Domain([0., 0.], [1., 1.], [200, 200]) solution = pyclaw.Solution(num_eqn, domain) gamma = 1.4 solution.problem_data['gamma'] = gamma # Set initial data xx, yy = domain.grid.p_centers l = xx < 0.5 r = xx >= 0.5 b = yy < 0.5 t = yy >= 0.5 solution.q[density, ...] = 2. * l * t + 1. * l * b + 1. * r * t + 3. * r * b solution.q[x_momentum, ...] = 0.75 * t - 0.75 * b solution.q[y_momentum, ...] = 0.5 * l - 0.5 * r solution.q[energy, ...] = 0.5 * solution.q[density, ...] * (solution.q[ x_momentum, ...]**2 + solution.q[y_momentum, ...]**2) + 1. / (gamma - 1.)