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 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 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 __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 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 create_volume_datafile(casepath): """Create a volume.csv for a case.""" import numpy casepath = os.path.abspath(casepath) out_path = os.path.join(casepath, "_output") repo_path = os.path.dirname(os.path.abspath(__file__)) claw_path = os.path.join(repo_path, "src", "clawpack-v5.5.0") logger.info("Creating total volume datafile for case %s", casepath) if os.path.isfile(os.path.join(casepath, "volume.csv")): logger.warning("%s exists. Skip.", os.path.join(casepath, "volume.csv")) logger.handlers[0].flush() logger.handlers[1].flush() return # add environment variables os.environ["CLAW"] = claw_path # add clawpack python package search path if claw_path != sys.path[0]: sys.path.insert(0, claw_path) # import utilities from clawpack import pyclaw # get # of frames from setrun.py if casepath != sys.path[0]: sys.path.insert(0, casepath) import setrun # import the setrun.py rundata = setrun.setrun() # get ClawRunData object nframes = rundata.clawdata.num_output_times + 1 nlevels = rundata.amrdata.amr_levels_max del rundata del sys.modules["setrun"] del sys.path[0] data = numpy.zeros((nframes, 1+nlevels), dtype=numpy.float64) for fno in range(0, nframes): # empty solution object soln = pyclaw.Solution() # read soln.read(fno, out_path, file_format="binary", read_aux=False) # calculate total volume at each grid level data[fno, 0] = soln.state.t data[fno, 1:] = get_volumes_single_frame(nlevels, soln) numpy.savetxt(os.path.join(casepath, "volume.csv"), data, delimiter=",") logger.info("Done creating total volume datafile.") logger.handlers[0].flush() logger.handlers[1].flush()
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 read_write_and_compare(file_formats, regression_dir, regression_format, frame_num, aux=False): r"""Test IO file formats: - Reading in an HDF file - Writing files in all formats (for now just ASCII, HDF5) - Reading those files back in - Checking that all the resulting Solution objects are identical """ ref_sol = pyclaw.Solution() ref_sol.read(frame_num, path=regression_dir, file_format=regression_format, read_aux=aux) if aux: assert (ref_sol.state.aux is not None) # Write solution file in each format io_test_dir = os.path.join(thisdir, './io_test') for fmt in file_formats: ref_sol.write(frame_num, path=io_test_dir, file_format=fmt, write_aux=aux) # Read solutions back in s = {} for fmt in file_formats: s[fmt] = pyclaw.Solution() s[fmt].read(frame_num, path=io_test_dir, file_format=fmt, write_aux=aux) # Compare solutions # Probably better to do this by defining __eq__ for each class for fmt, sol in s.iteritems(): check_solutions_are_same(sol, ref_sol)
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 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 __init__(self, solver, global_state, q, qbc, aux, position, size, subdivision_factor, unknowns_per_cell, aux_fields_per_cell, current_time): r""" Initializes this subgrid solver. It get's all information to prepare a domain and state for a single subgrid. :Input: - *solver* - (:class:`pyclaw.Solver`) The PyClaw-solver used for advancing this subgrid in time. - *global_state* - (:class:`pyclaw.State`) The global state. This is not the state used for for the actual solving of the timestep on the subgrid. - *q* - The array storing the current solution. - *qbc* - The array storing the solution of the last timestep including the ghostlayer. - *position* - A d-dimensional tuple holding the position of the grid in the computational domain. This measures the continuous real-world position in floats, not the integer position in terms of cells. - *size* - A d-dimensional tuple holding the size of the grid in the computational domain. This measures the continuous real-world size in floats, not the size in terms of cells. - *subdivision_factor* - The number of cells in one dimension of this subgrid. At the moment only square subgrids are allowed, so the total number of cells in the subgrid (excluding the ghostlayer) is subdivision_factor x subdivision_factor. - *unknowns_per_cell* - The number of equations or unknowns that are stored per cell of the subgrid. """ self.solver = solver number_of_dimensions = get_number_of_dimensions(q) self.domain = create_domain(number_of_dimensions, position, size, subdivision_factor) subgrid_state = create_subgrid_state(global_state, self.domain, q, qbc, aux, unknowns_per_cell, aux_fields_per_cell) subgrid_state.problem_data = global_state.problem_data self.solution = pyclaw.Solution(subgrid_state, self.domain) self.solution.t = current_time self.solver.bc_lower[:] = [pyclaw.BC.custom] * len( self.solver.bc_lower) self.solver.bc_upper[:] = [pyclaw.BC.custom] * len( self.solver.bc_upper) self.qbc = qbc self.solver.user_bc_lower = self.user_bc_lower self.solver.user_bc_upper = self.user_bc_upper self.recover_ghostlayers = False
def plot_depth(data, transform, res, solndir, fno, border=False, level=1, shaded=True, dry_tol=1e-5, vmin=None, vmax=None): """Plot depth on topography.""" from matplotlib import pyplot # a new figure and topo ax fig, ax = plot_topo(data, transform, res, shaded=shaded) # empty solution object soln = pyclaw.Solution() # aux path auxpath = os.path.join(solndir, "fort.a"+"{}".format(fno).zfill(4)) # read soln.read(fno, solndir, file_format="binary", read_aux=os.path.isfile(auxpath)) print("Plotting frame No. {}, T={} secs ({} mins)".format( fno, soln.state.t, int(soln.state.t/60.))) # plot im = plot_at_axes(soln, ax, field=0, border=border, min_level=level, max_level=level, vmin=vmin, vmax=vmax, threshold=dry_tol) # plot colorbar in a new axes for depth cbarax = fig.add_axes([0.875, 0.125, 0.03, 0.75]) if im is None: im = ax.pcolormesh([0, data.shape[1]], [0, data.shape[0]], [[0]]) im.remove() cbar = pyplot.colorbar(im, cax=cbarax, ax=ax) cbar.ax.set_yticklabels([0]*len(cbar.ax.get_yticks())) else: cbar = pyplot.colorbar(im, cax=cbarax, ax=ax) cbar.set_label("Depth (m)") # figure title fig.suptitle("Topography and depth near rupture point, " "T = {} (mins)".format(int(soln.state.t/60.)), x=0.5, y=0.9, fontsize=16, horizontalalignment="center", verticalalignment="bottom") return fig, ax
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_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 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_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 get_bounding_box(solndir, bg, ed, level): """ Get the bounding box of the result at a specific level. Return: [xleft, xright, ybottom, ytop] """ xleft = None xright = None ybottom = None ytop = None for fno in range(bg, ed): # aux path auxpath = os.path.join(solndir, "fort.a"+"{}".format(fno).zfill(4)) # solution soln = pyclaw.Solution() soln.read(fno, solndir, file_format="binary", read_aux=os.path.isfile(auxpath)) # search through AMR grid patched in this solution for state in soln.states: p = state.patch if p.level != level: continue if xleft is None or xleft > p.lower_global[0]: xleft = p.lower_global[0] if ybottom is None or ybottom > p.lower_global[1]: ybottom = p.lower_global[1] if xright is None or xright < p.upper_global[0]: xright = p.upper_global[0] if ytop is None or ytop < p.upper_global[1]: ytop = p.upper_global[1] # finally, return return [xleft, xright, ybottom, ytop]
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