def test_write_hdf5(self): """Test the method to write the mesh in HDF5 format.""" grid = petibmpy.CartesianGrid(config=self.config) filepath = pathlib.Path('grid.h5') grid.write_hdf5(filepath) coords = petibmpy.read_grid_hdf5(filepath, 'vertex') for x, x2 in zip(grid.get_gridlines(), coords): self.assertTrue(numpy.allclose(x, x2)) filepath.unlink()
def test_read_write_grid_hdf5(self): """Test I/O functions for HDF5 format.""" filepath = pathlib.Path('grid.h5') for dim in [2, 3]: coords = [self.x, self.y, self.z][:dim] petibmpy.write_grid_hdf5(filepath, 'name', *coords) coords2 = petibmpy.read_grid_hdf5(filepath, 'name') self.assertEqual(len(coords2), len(coords)) for i in range(dim): self.assertTrue(numpy.allclose(coords2[i], coords[i])) filepath.unlink()
def load_field_3d(datadir, config, time, name): # Set parameters. time *= config.T # convert to dimensional time timestep = int(time / config.dt) # time-step index # Load gridline coordinates from file. filepath = datadir / 'grid.h5' x, y, z = petibmpy.read_grid_hdf5(filepath, name) # Shift z locations to match figures of Li & Dong (2016). z -= config.S / 2 # Load 3D field solution from file. filepath = datadir / f'{timestep:0>7}.h5' field = petibmpy.read_field_hdf5(filepath, name) # Return grid and streamwise vorticity. return (x, y, z), field
def petibm_load_grid_and_field(datadir, timestep, name): """Load the gridlines and values of a field at a given time step. Parameters ---------- datadir : pathlib.Path Directory with the data to load. timestep : int Time-step index. name : str Name of the field to read, e.g. 'u', 'v', or 'p'. Returns ------- tuple Gridline locations in each direction as a tuple of 1D arrays of floats. numpy.ndarray Field values at given time step. """ grid = petibmpy.read_grid_hdf5(datadir / 'grid.h5', name) field = petibmpy.read_field_hdf5(datadir / f'{timestep:0>7}.h5', name) return grid, field
# Set number of levels for the contours. contourf_levels = numpy.linspace(-5.0, 5.0, num=50) contour_levels = numpy.linspace(-5.0, 5.0, num=10) # Create data type to store information about annotation. Annotation = collections.namedtuple('Annotation', ['text', 'xytext', 'xyarrow']) # ---------------------------------------------------------------------------- # Plot the 2D slice of the streamwise vorticity in the y/z plane at x/c = 0.3. # ---------------------------------------------------------------------------- # Load the gridline coordinates from file. filepath = datadir / 'grid.h5' x, y, z = petibmpy.read_grid_hdf5(filepath, 'wx') # Load the field solution from file. filepath = datadir / '{:0>7}.h5'.format(timestep) wx = petibmpy.read_field_hdf5(filepath, 'wx') # Interpolate the vorticity component in the y/z plane in the near wake. xloc = 0.3 # location along the x direction (near wake) wx_tmp = numpy.swapaxes(wx, -1, 0) wx_xloc = petibmpy.linear_interpolation(wx_tmp, x, xloc) # Create the Matplotlib figure. fig, ax = pyplot.subplots(figsize=(4.0, 4.0)) ax.set_xlabel('z/c') ax.set_ylabel('y/c')
import pathlib import petibmpy name = 'wz' # name of the vorticity variable timestep = 20000 # final time-step index show_figure = True # if True, display the figure # Set the simulation and data directories. simudir = pathlib.Path(__file__).absolute().parents[1] datadir = simudir / 'output' # Load the gridlines from file. filepath = datadir / 'grid.h5' x, y = petibmpy.read_grid_hdf5(filepath, name) # Load the vorticity field from file. filepath = datadir / f'{timestep:0>7}.h5' wz = petibmpy.read_field_hdf5(filepath, name) # Load the boundary coordinates from file. filepath = simudir / 'cylinder.body' xb, yb = petibmpy.read_body(filepath, skiprows=1) # Plot the contours of the vorticity field. pyplot.rc('font', family='serif', size=16) fig, ax = pyplot.subplots(figsize=(6.0, 6.0)) ax.set_xlabel('x / D') ax.set_ylabel('y / D') levels = numpy.arange(-3.0, 3.0 + 0.4 / 2, 0.4) ax.contour(x, y, wz, levels=levels, colors='black') ax.plot(xb, yb, color='red')
"""Plot the final time step vorticity field.""" from matplotlib import pyplot import numpy import pathlib import petibmpy show_figure = True # display the Matplotlib figure save_figure = True # save the Matplotlib figure simudir = pathlib.Path(__file__).absolute().parents[1] datadir = simudir / 'output' # Load the grid lines from file. filepath = datadir / 'grid.h5' x, y = petibmpy.read_grid_hdf5(filepath, 'wz') # Load the vorticity field from file. timestep = 25000 filepath = datadir / f'{timestep:0>7}.h5' wz = petibmpy.read_field_hdf5(filepath, 'wz') # Plot the contours of the vorticity. pyplot.rc('font', family='serif', size=14) fig, ax = pyplot.subplots(figsize=(6.0, 6.0)) ax.set_xlabel('x') ax.set_ylabel('y') levels = numpy.linspace(-5.0, 5.0, num=21) ax.contourf(x, y, wz, levels=levels, extend='both') ax.contour(x, y, wz, levels=levels, colors='black') ax.axis('scaled', adjust='box')
# Set the wing kinematics. config = rodney.WingKinematics(nt_period=2000) c = config.c # chord length S = config.S # spanwise length A_phi = config.A_phi # rolling amplitude (radians) n_periods = config.n_periods # number of flapping cycles nt_period = config.nt_period # number of time steps per cycle dt = config.dt # time-step size probes = [] # will store info about the probes # Set probe information for the x- and y- components of the velocity. fields = ['u', 'v'] for field in fields: filepath = datadir / 'grid.h5' grid = petibmpy.read_grid_hdf5(filepath, field) xlocs = [1.0, 2.0, 3.0, 4.0, 5.0] for i, xloc in enumerate(xlocs): name = f'probe{i + 1}-{field}' box = ((xloc, xloc), (-3.0, 3.0), (S / 2, S / 2)) probe = petibmpy.ProbeVolume(name, field, box=box, adjust_box=True, grid=grid, n_sum=nt_period, path=f'{name}.h5') probes.append(probe) # Set probe information for the z-component of the velocity. fields = ['w']
ax1.set_xlabel('y') ax1.set_ylabel('u') ax2.set_xlabel('x') ax2.set_ylabel('v') for Re, timestep in zip(Res, timesteps): # Load data from Ghia et al. (1982). adir = rootdir / 'data' filepath = adir / 'ghia_et_al_1982_lid_driven_cavity.dat' yu_g, uc_g, xv_g, vc_g = load_data_ghia_et_al_1982(filepath, str(Re)) # Load gridlines and velocity fields. simudir = maindir / f'liddrivencavity2dRe{Re}' datadir = simudir / 'output' filepath = datadir / 'grid.h5' xu, yu = petibmpy.read_grid_hdf5(filepath, 'u') xv, yv = petibmpy.read_grid_hdf5(filepath, 'v') filepath = datadir / f'{timestep:0>7}.h5' u = petibmpy.read_field_hdf5(filepath, 'u') v = petibmpy.read_field_hdf5(filepath, 'v') # Interpolate solution at centerlines of the cavity. uc = petibmpy.linear_interpolation(u.T, xu, 0.5) vc = petibmpy.linear_interpolation(v, yv, 0.5) # Plot the velocity profiles. ax1.plot(yu, uc, label=f'Re = {Re}') label = ('Ghia et al. (1982)' if Re == Res[-1] else None) ax1.plot(yu_g, uc_g, label=label,
"""Compute the cell-centered x-component of the vorticity.""" import pathlib import petibmpy name = 'wx_cc' simudir = pathlib.Path(__file__).absolute().parents[1] datadir = simudir / 'output' gridpath = datadir / 'grid.h5' outdir = datadir / 'postprocessing' / name outdir.mkdir(parents=True, exist_ok=True) # Read the cell-centered grid. x, y, z = petibmpy.read_grid_hdf5(gridpath, 'p') # Read the grid of the x-component of the vorticity. grid_wx = petibmpy.read_grid_hdf5(gridpath, 'wx') # Save the grid on which is defined the Q-criterion. gridpath = outdir / 'grid.h5' petibmpy.write_grid_hdf5(gridpath, name, x, y, z) # List of time-step indices to process. timesteps = [7750, 7875, 8000, 8250, 8375, 8500, 8625, 8750, 8875] interp_args = dict(bounds_error=False, method='linear', fill_value=None) for timestep in timesteps: print('[time step {}] Computing the cell-centered x-vorticity ...' .format(timestep)) filepath = datadir / '{:0>7}.h5'.format(timestep)
def subset_gridline(x, xs, xe): """Return subset of gridline points given a target start and end.""" mask, = numpy.where((x >= xs) & (x <= xe)) x = x[mask] xlim = (min(x), max(x)) return x, xlim args = rodney.parse_command_line() maindir = pathlib.Path(__file__).parents[1] datadir = maindir / 'output' # Load gridline coordinates from file. filepath = datadir / 'grid.h5' x, y, z = petibmpy.read_grid_hdf5(filepath, 'vertex') # Subset gridline coordinates. x, xlim = subset_gridline(x, -5.0, 5.0) y, ylim = subset_gridline(y, -5.0, 5.0) z, zlim = subset_gridline(z, -5.0, 5.0) # Load body coordinates from file. filepath = maindir / 'wing.body' wing = rodney.WingKinematics() wing.load_body(filepath, skiprows=1) # Keep only points on the contour of the wing. x0, _, z0 = wing.get_coordinates(org=True) points = numpy.array([x0, z0]).T hull = ConvexHull(points)
# Read the body file to add body location on the axes. filepath = simudir / 'data' / 'snake2d.body' with open(filepath, 'r') as infile: xb, _ = numpy.loadtxt(infile, skiprows=1, unpack=True) xb_min, xb_max = numpy.min(xb), numpy.max(xb) # Plot the filled contours of the velocity components in the x/z plane. timestep = 100000 # time-step index y_target = -0.2 # y-location where to interpolate names = ['u', 'v'] # name of the velocity components to plot pyplot.rc('font', family='serif', size=16) fig, ax = pyplot.subplots(figsize=(8.0, 4.0), nrows=len(names), sharex=True) for i, name in enumerate(names): # Read the grid coordinates on which the velocity is located. gridpath = simudir / 'output' / 'grid.h5' x, y, z = petibmpy.read_grid_hdf5(gridpath, name) x_min, x_max = numpy.min(x), numpy.max(x) z_min, z_max = numpy.min(z), numpy.max(z) # Read the velocity data at prescribed time step. filepath = datadir / 'solution' / '{:0>7}.h5'.format(timestep) data = petibmpy.read_field_hdf5(filepath, name) # Perform linear interpolation. data_target = interp_xzplane(y, data, y_target=y_target) # Plot the filled contour, the 0-contour, and the body. ax[i].set_ylabel('z') levels = numpy.linspace(-1.0, 1.0, num=52) ax[i].contourf(*numpy.meshgrid(x, z), data_target,
import pathlib import yaml import petibmpy name = 'qcrit' simudir = pathlib.Path(__file__).absolute().parents[1] datadir = simudir / 'output' gridpath = datadir / 'grid.h5' outdir = datadir / 'postprocessing' / name outdir.mkdir(parents=True, exist_ok=True) # Read the cell-centered grid. x, y, z = petibmpy.read_grid_hdf5(gridpath, 'p') # Read the grid of the velocity components. grid_u = petibmpy.read_grid_hdf5(gridpath, 'u') grid_v = petibmpy.read_grid_hdf5(gridpath, 'v') grid_w = petibmpy.read_grid_hdf5(gridpath, 'w') # Save the grid on which is defined the Q-criterion. gridpath = outdir / 'grid.h5' petibmpy.write_grid_hdf5(gridpath, name, x, y, z) # Get temporal parameters. filepath = simudir / 'config.yaml' with open(filepath, 'r') as infile: config = yaml.load(infile, Loader=yaml.FullLoader)['parameters'] nstart, nt, nsave = config['startStep'], config['nt'], config['nsave'] timesteps = list(range(nstart, nstart + nt + 1, nsave))
# Set parameters. rootdir = pathlib.Path(__file__).absolute().parents[1] timestep = 500 # solution time-step index field_names = ['p', 'u', 'v'] # name of the fields ncells = [30, 90, 270, 810] # number of cells in each direction ratio = 3 # refinement ratio between two consecutive grids # Load the grid and field from files. data = {} for name in field_names: subdata = {'grids': [], 'fields': []} for n in ncells: simudir = rootdir / str(n) datadir = simudir / 'output' grid = petibmpy.read_grid_hdf5(datadir / 'grid.h5', name) filepath = datadir / f'{timestep:0>7}.h5' field = petibmpy.read_field_hdf5(filepath, name) subdata['grids'].append(grid) subdata['fields'].append(field) data[name] = subdata # Compute the observed orders of convergence. alphas = {} for name in field_names: grids, fields = data[name]['grids'], data[name]['fields'] # Compute order of convergence using the three coarsest grids. # Fields are interpolated on the first grid. alpha1 = observed_order_convergence(fields[:3], grids[:3], grids[0], ratio) # Compute order of convergence using the three finest grids. # Fields are interpolated on the first grid.