def compare_pressure(self): """ Compares the pressure field node by node with a reference. """ time_step = ioPetIBM.get_time_steps(directory=self.directory)[-1] grid = ioPetIBM.read_grid(directory=self.directory) pressure = ioPetIBM.read_pressure(time_step, grid, directory=self.directory) grid = ioPetIBM.read_grid(directory=self.reference) pressure_reference = ioPetIBM.read_pressure(time_step, grid, directory=self.reference) self.compare_arrays(pressure.x, pressure_reference.x, tag='pressure: x-nodes') self.compare_arrays(pressure.y, pressure_reference.y, tag='pressure: y-nodes') try: self.compare_arrays(pressure.z, pressure_reference.z, tag='pressure: z-nodes') except: pass self.compare_arrays(pressure.values, pressure_reference.values, tag='pressure: values')
def compare_grid(self): """Compares the mesh-grid with a reference one.""" grid = ioPetIBM.read_grid(self.directory) grid_reference = ioPetIBM.read_grid(self.reference) for i, direction in enumerate(grid): self.compare_arrays(direction, grid_reference[i], tag='grid[{}]'.format(i))
def compare_velocity(self): """Compares the velocity field node by node with a reference.""" time_step = ioPetIBM.get_time_steps(self.directory)[-1] grid = ioPetIBM.read_grid(self.directory) velocity = ioPetIBM.read_velocity(self.directory, time_step, grid, periodic=self.periodic) grid = ioPetIBM.read_grid(self.reference) velocity_reference = ioPetIBM.read_velocity(self.reference, time_step, grid, periodic=self.periodic) for i, component in enumerate(velocity): self.compare_arrays(component.x, velocity_reference[i].x, tag='velocity[{}]: x-nodes'.format(i)) self.compare_arrays(component.y, velocity_reference[i].y, tag='velocity[{}]: y-nodes'.format(i)) try: self.compare_arrays(component.z, velocity_reference[i].z, tag='velocity[{}]: z-nodes'.format(i)) except: pass self.compare_arrays(component.values, velocity_reference[i].values, tag='velocity[{}]: values'.format(i))
def main(): """Interpolates the solution from a grid to another.""" args = read_inputs() # reference solution reference = {} if not args.time_step: args.time_step = sorted(int(folder) for folder in os.listdir(args.reference_directory) if folder[0]=='0')[-1] reference['input'] = '{}/{:0>7}'.format(args.reference_directory, args.time_step) # new simulation case = {} case['output'] = '{}/0000000'.format(args.case_directory) if args.same_grid: print('Same grid, data are simply copied ...') if os.path.isdir(case['output']): shutil.rmtree(case['output']) shutil.copytree(reference['input'], case['output']) return # read reference solution reference['grid'] = ioPetIBM.read_grid(args.reference_directory) reference['u'], reference['v'], reference['w'] = ioPetIBM.read_velocity(args.reference_directory, args.time_step, reference['grid'], periodic=args.periodic) reference['p'] = ioPetIBM.read_pressure(args.reference_directory, args.time_step, reference['grid'])
def main(): """Converts PETSc output to .vtk format.""" # parse command-line args = read_inputs() print('[case-directory] {}'.format(args.case_directory)) print('[variables] {}'.format(args.variables)) # list of time-steps to post-process time_steps = ioPetIBM.get_time_steps(args.case_directory, args.time_steps) # read mesh grid grid = ioPetIBM.read_grid(args.case_directory) for time_step in time_steps: if 'velocity' in args.variables: velocity = ioPetIBM.read_velocity(args.case_directory, time_step, grid, periodic=args.periodic) # need to get velocity at cell-centers, not staggered arrangement velocity = interpolate_cell_centers(velocity) ioPetIBM.write_vtk(velocity, args.case_directory, time_step, name='velocity', view=[args.bottom_left, args.top_right], stride=args.stride) if 'pressure' in args.variables: pressure = ioPetIBM.read_pressure(args.case_directory, time_step, grid) ioPetIBM.write_vtk(pressure, args.case_directory, time_step, name='pressure', view=[args.bottom_left, args.top_right], stride=args.stride)
def main(args): """ Generates .vtk files out of the saved PETSc solutions. Parameters ---------- args: namespace Databased with arguments parsed from the command-line. """ print('[directory] {}'.format(args.directory)) print('[variables] {}'.format(args.variables)) # list of time-steps to post-process time_steps = ioPetIBM.get_time_steps(args.directory, args.time_steps) # read mesh grid grid = ioPetIBM.read_grid(args.directory) for time_step in time_steps: if 'velocity' in args.variables: velocity = ioPetIBM.read_velocity(args.directory, time_step, grid, periodic=args.periodic) # need to get velocity at cell-centers, not staggered arrangement velocity = interpolate_cell_centers(velocity) ioPetIBM.write_vtk(velocity, args.directory, time_step, name='velocity', view=[args.bottom_left, args.top_right], stride=args.stride) if 'pressure' in args.variables: pressure = ioPetIBM.read_pressure(args.directory, time_step, grid) ioPetIBM.write_vtk(pressure, args.directory, time_step, name='pressure', view=[args.bottom_left, args.top_right], stride=args.stride)
def main(): """Plots the the velocity, pressure and vorticity fields at saved time-steps for a two-dimensional simulation. """ # parse command-line args = read_inputs() print('[case directory] {}'.format(args.case_directory)) time_steps = ioPetIBM.get_time_steps(args.case_directory, args.time_steps) # create directory where images will be saved images_directory = '{}/images'.format(args.case_directory) print('[images directory] {}'.format(images_directory)) if not os.path.isdir(images_directory): os.makedirs(images_directory) # read the grid nodes coords = ioPetIBM.read_grid(args.case_directory) # load default style of matplotlib figures pyplot.style.use('{}/scripts/python/style/' 'style_PetIBM.mplstyle'.format(os.environ['PETIBM_DIR'])) for time_step in time_steps: if args.velocity or args.vorticity: # get velocity fields u, v = ioPetIBM.read_velocity(args.case_directory, time_step, coords, periodic=args.periodic) if args.velocity: # plot u-velocity field u.label = 'u-velocity' image_path = '{}/uVelocity{:0>7}.png'.format(images_directory, time_step) plot_contour(u, args.u_range, image_path, view=args.bottom_left+args.top_right, size=args.size, dpi=args.dpi) # plot v-velocity field v.label = 'v-velocity' image_path = '{}/vVelocity{:0>7}.png'.format(images_directory, time_step) plot_contour(v, args.v_range, image_path, view=args.bottom_left+args.top_right, size=args.size, dpi=args.dpi) if args.vorticity: # compute vorticity field w = vorticity(u, v) # plot vorticity field w.label = 'vorticity' image_path = '{}/vorticity{:0>7}.png'.format(images_directory, time_step) plot_contour(w, args.vorticity_range, image_path, view=args.bottom_left+args.top_right, size=args.size, dpi=args.dpi) if args.pressure: # get pressure field p = ioPetIBM.read_pressure(args.case_directory, time_step, coords) # plot pressure field p.label = 'pressure' image_path = '{}/pressure{:0>7}.png'.format(images_directory, time_step) plot_contour(p, args.pressure_range, image_path, view=args.bottom_left+args.top_right, size=args.size, dpi=args.dpi)
def compare_pressure(self): """Compares the pressure field node by node with a reference.""" time_step = ioPetIBM.get_time_steps(self.directory)[-1] grid = ioPetIBM.read_grid(self.directory) pressure = ioPetIBM.read_pressure(self.directory, time_step, grid) grid = ioPetIBM.read_grid(self.reference) pressure_reference = ioPetIBM.read_pressure(self.reference, time_step, grid) self.compare_arrays(pressure.x, pressure_reference.x, tag='pressure: x-nodes') self.compare_arrays(pressure.y, pressure_reference.y, tag='pressure: y-nodes') try: self.compare_arrays(pressure.z, pressure_reference.z, tag='pressure: z-nodes') except: pass self.compare_arrays(pressure.values, pressure_reference.values, tag='pressure: values')
def main(): """Plots and writes the velocity components at the centerline of the cavity and compares with experimental results form Ghia et al. (1982). """ # column indices in file with experimental results cols = {'100': {'u': 1, 'v': 7}, '1000': {'u':2, 'v': 8}, '3200': {'u':3, 'v': 9}, '5000': {'u':4, 'v': 10}, '10000': {'u': 5, 'v': 11}} experimental_file = ('{}/validation_data/' 'cavity-GGS82.txt'.format(os.environ['PETIBM_DIR'])) # parse command-line args = read_inputs() print('[case directory] {}'.format(args.case_directory)) Re = args.Re if not args.time_step: args.time_step = ioPetIBM.get_time_steps(args.case_directory)[-1] # read mesh grid grid = ioPetIBM.read_grid(args.case_directory) nx, ny = grid[0].size-1, grid[1].size-1 # create directory where images will be saved images_directory = '{}/images'.format(args.case_directory) print('[images directory] {}'.format(images_directory)) if not os.path.isdir(images_directory): os.makedirs(images_directory) # create directory where data will be saved data_directory = '{}/data'.format(args.case_directory) print('[data directory] {}'.format(data_directory)) if not os.path.isdir(data_directory): os.makedirs(data_directory) # get velocity field u, v = ioPetIBM.read_velocity(args.case_directory, args.time_step, grid) # load default style for figures pyplot.style.use('{}/scripts/python/style/' 'style_PetIBM.mplstyle'.format(os.environ['PETIBM_DIR'])) # plot and write u-velocity along y-centerline print('\nPlot u-velocity along vertical centerline ...') pyplot.xlabel('y',) pyplot.ylabel('u-velocity along vertical centerline') if nx%2 == 0: u_centerline = u.values[:, nx/2-1] else: u_centerline = 0.5*(u.values[:, nx/2-1]+u.values[:, nx/2]) pyplot.plot(u.y, u_centerline, label='PetIBM', color='k', linestyle='-', linewidth=1) if Re in list(cols.keys()): print('\nComparison with Ghia et al. (1982)') with open(experimental_file, 'r') as infile: y_exp, u_exp = numpy.loadtxt(infile, dtype=float, usecols= (0, cols[Re]['u']), unpack=True) pyplot.plot(y_exp, u_exp, label='Ghia et al. (1982)', linewidth=0, marker='o') pyplot.legend() pyplot.title('Lid-driven cavity flow at Re={} (mesh: {}x{})'.format(Re, nx, ny)) pyplot.savefig('{}/uVelocityCenterlineRe{}_{}x{}.png'.format(images_directory, Re, nx, ny)) pyplot.close() print('\nWrite u-velocity along vertical centerline ...') data_path = '{}/uVelocityCenterlineRe{}_{}x{}.txt'.format(data_directory, Re, nx, ny) with open(data_path, 'w') as outfile: numpy.savetxt(outfile, numpy.c_[u.y, u_centerline], fmt='%.6f', delimiter='\t', header='u-velocity along vertical centerline\n' 'Re={}, mesh: {}x{}\n[y]\t[u]'.format(Re, nx, ny)) # plot and write v-velocity along x-centerline print('\nPlot v-velocity along horizontal centerline ...') pyplot.xlabel('x') pyplot.ylabel('v-velocity along horizontal centerline') if ny%2 == 0: v_centerline = v.values[ny/2-1, :] else: v_centerline = 0.5*(v.values[ny/2-1, :]+v.values[ny/2, :]) pyplot.plot(v.x, v_centerline, label='PetIBM', color='k', linestyle='-', linewidth=1) if Re in list(cols.keys()): print('Comparison with Ghia et al. (1982)') with open(experimental_file, 'r') as infile: x_exp, u_exp = numpy.loadtxt(infile, dtype=float, usecols= (6, cols[Re]['v']), unpack=True) pyplot.plot(x_exp, u_exp, label='Ghia et al. (1982)', linewidth=0, marker='o') pyplot.legend() pyplot.title('Lid-driven cavity flow at Re={} (mesh: {}x{})'.format(Re, nx, ny)) pyplot.savefig('{}/vVelocityCenterlineRe{}_{}x{}.png'.format(images_directory, Re, nx, ny)) pyplot.close() print('\nwrite v-velocity along horizontal centerline ...') data_path = '{}/vVelocityCenterlineRe{}_{}x{}.txt'.format(data_directory, Re, nx, ny) with open(data_path, 'w') as outfile: numpy.savetxt(outfile, numpy.c_[v.x, v_centerline], fmt='%.6f', delimiter='\t', header='v-velocity along horizontal centerline\n' 'Re={}, mesh: {}x{}\n[x]\t[v]'.format(Re, nx, ny))
def main(): """Plots the the velocity, pressure and vorticity fields at saved time-steps for a two-dimensional simulation. """ # parse command-line args = read_inputs() print('[case directory] {}'.format(args.case_directory)) time_steps = ioPetIBM.get_time_steps(args.case_directory, args.time_steps) # create directory where images will be saved images_directory = '{}/images'.format(args.case_directory) print('[images directory] {}'.format(images_directory)) if not os.path.isdir(images_directory): os.makedirs(images_directory) # read the grid nodes coords = ioPetIBM.read_grid(args.case_directory) # load default style of matplotlib figures pyplot.style.use('{}/scripts/python/style/' 'style_PetIBM.mplstyle'.format(os.environ['PETIBM_DIR'])) for time_step in time_steps: if args.velocity or args.vorticity: # get velocity fields u, v = ioPetIBM.read_velocity(args.case_directory, time_step, coords, periodic=args.periodic) if args.velocity: # plot u-velocity field u.label = 'u-velocity' image_path = '{}/uVelocity{:0>7}.png'.format( images_directory, time_step) plot_contour(u, args.u_range, image_path, view=args.bottom_left + args.top_right, size=args.size, dpi=args.dpi) # plot v-velocity field v.label = 'v-velocity' image_path = '{}/vVelocity{:0>7}.png'.format( images_directory, time_step) plot_contour(v, args.v_range, image_path, view=args.bottom_left + args.top_right, size=args.size, dpi=args.dpi) if args.vorticity: # compute vorticity field w = vorticity(u, v) # plot vorticity field w.label = 'vorticity' image_path = '{}/vorticity{:0>7}.png'.format( images_directory, time_step) plot_contour(w, args.vorticity_range, image_path, view=args.bottom_left + args.top_right, size=args.size, dpi=args.dpi) if args.pressure: # get pressure field p = ioPetIBM.read_pressure(args.case_directory, time_step, coords) # plot pressure field p.label = 'pressure' image_path = '{}/pressure{:0>7}.png'.format( images_directory, time_step) plot_contour(p, args.pressure_range, image_path, view=args.bottom_left + args.top_right, size=args.size, dpi=args.dpi)
def main(args): """ Plots the the velocity, pressure and vorticity fields at saved time-steps for a two-dimensional simulation. Parameters ---------- args: namespace Database with arguments parsed from the command-line. """ print('[case directory] {}'.format(args.directory)) time_steps = ioPetIBM.get_time_steps(args.time_steps, directory=args.directory) # create directory where images will be saved images_directory = os.path.join(args.directory, 'images') print('[images directory] {}'.format(images_directory)) if not os.path.isdir(images_directory): os.makedirs(images_directory) # read the grid nodes coords = ioPetIBM.read_grid(directory=args.directory) # load default style of matplotlib figures pyplot.style.use( os.path.join(os.environ['PETIBM_DIR'], 'scripts', 'python', 'style', 'style_PetIBM.mplstyle')) for time_step in time_steps: if args.velocity or args.vorticity: # get velocity fields u, v = ioPetIBM.read_velocity(time_step, coords, directory=args.directory, periodic=args.periodic) if args.velocity: # plot u-velocity field u.label = 'u-velocity' image_path = os.path.join( images_directory, 'uVelocity{:0>7}.png'.format(time_step)) plot_contour(u, args.u_range, image_path, view=args.bottom_left + args.top_right, size=args.size, dpi=args.dpi) # plot v-velocity field v.label = 'v-velocity' image_path = os.path.join( images_directory, 'vVelocity{:0>7}.png'.format(time_step)) plot_contour(v, args.v_range, image_path, view=args.bottom_left + args.top_right, size=args.size, dpi=args.dpi) if args.vorticity: # compute vorticity field w = vorticity(u, v) # plot vorticity field w.label = 'vorticity' image_path = os.path.join( images_directory, 'vorticity{:0>7}.png'.format(time_step)) plot_contour(w, args.vorticity_range, image_path, view=args.bottom_left + args.top_right, size=args.size, dpi=args.dpi) if args.pressure: # get pressure field p = ioPetIBM.read_pressure(time_step, coords, directory=args.directory) # plot pressure field p.label = 'pressure' image_path = os.path.join(images_directory, 'pressure{:0>7}.png'.format(time_step)) plot_contour(p, args.pressure_range, image_path, view=args.bottom_left + args.top_right, size=args.size, dpi=args.dpi)
def main(): """Plots the grid convergence for the Taylor-Green vortex case.""" # parse command-line args = read_inputs() # initialization simulations = sorted(int(directory) for directory in os.listdir(args.directory) if os.path.isdir('/'.join([args.directory, directory]))) cases = numpy.empty(len(simulations), dtype=dict) for i, case in enumerate(cases): cases[i] = {'directory': '{}/{}'.format(args.directory, simulations[i]), 'grid-size': '{0}x{0}'.format(simulations[i])} for i, case in enumerate(cases): print('\n[case] grid-size: {}'.format(case['grid-size'])) # read mesh grid x, y = ioPetIBM.read_grid(case['directory']) cases[i]['grid-spacing'] = (x[-1]-x[0])/(x.size-1) # read velocity and pressure fields cases[i]['u'], cases[i]['v'] = ioPetIBM.read_velocity(case['directory'], args.time_step, [x, y], periodic=['x', 'y']) cases[i]['p'] = ioPetIBM.read_pressure(case['directory'], args.time_step, [x, y]) # compute analytical solution cases[i]['u'].exact, _, _, _ = taylor_green_vortex(case['u'].x, case['u'].y, V=args.amplitude, time=args.time_step*args.dt, Re=args.Re) _, cases[i]['v'].exact, _, _ = taylor_green_vortex(case['v'].x, case['v'].y, V=args.amplitude, time=args.time_step*args.dt, Re=args.Re) _, _, cases[i]['p'].exact, _ = taylor_green_vortex(case['p'].x, case['p'].y, V=args.amplitude, time=args.time_step*args.dt, Re=args.Re) # compute L2-norm error for field in ['u', 'v', 'p']: cases[i][field].error = (l2_norm(case[field].values-case[field].exact) / l2_norm(case[field].exact)) if args.plot: print('\nPlot the field difference between numerical and analytical ...') # create directory where images will be saved images_directory = '{}/images/differences'.format(case['directory']) if not os.path.isdir(images_directory): os.makedirs(images_directory) # load default style pyplot.style.use('{}/scripts/python/style/' 'style_PetIBM.mplstyle'.format(os.environ['PETIBM_DIR'])) # set parameters of the plots cases[i]['u'].label = 'u-velocity' cases[i]['u'].file_name = 'uVelocity' cases[i]['v'].label = 'v-velocity' cases[i]['v'].file_name = 'vVelocity' cases[i]['p'].label = 'pressure' cases[i]['p'].file_name = 'pressure' # plot velocity fields and pressure field for field in ['u', 'v', 'p']: image_path = '{}/{}{:0>7}_numerical.png'.format(images_directory, case[field].file_name, args.time_step) plot_field(case[field].x, case[field].y, case[field].values, case[field].label, image_path) image_path = '{}/{}{:0>7}_analytical.png'.format(images_directory, case[field].file_name, args.time_step) plot_field(case[field].x, case[field].y, case[field].exact, case[field].label, image_path) image_path = '{}/{}{:0>7}_difference.png'.format(images_directory, case[field].file_name, args.time_step) plot_field(case[field].x, case[field].y, case[field].values-case[field].exact, case[field].label, image_path) print('\nObserved order of convergence:') last_three = True coarse, medium, fine = cases[-3:] if last_three else cases[:3] ratio = coarse['grid-spacing']/medium['grid-spacing'] alpha = {'u': compute_order(ratio, coarse['u'].values, restriction(medium['u'], coarse['u']).values, restriction(fine['u'], coarse['u']).values), 'v': compute_order(ratio, coarse['v'].values, restriction(medium['v'], coarse['v']).values, restriction(fine['v'], coarse['v']).values), 'p': compute_order(ratio, coarse['p'].values, restriction(medium['p'], coarse['p']).values, restriction(fine['p'], coarse['p']).values)} print('\tu: {}'.format(alpha['u'])) print('\tv: {}'.format(alpha['v'])) print('\tp: {}'.format(alpha['p'])) # write orders of convergence into file file_path = '{}/orders_of_convergence.dat'.format(args.directory) with open(file_path, 'w') as outfile: outfile.write('u: {}\n'.format(alpha['u'])) outfile.write('v: {}\n'.format(alpha['v'])) outfile.write('p: {}\n'.format(alpha['p'])) if args.save or args.show: print('\nPlot the grid convergence ...') pyplot.style.use('{}/scripts/python/style/' 'style_PetIBM.mplstyle'.format(os.environ['PETIBM_DIR'])) pyplot.xlabel('grid-spacing') pyplot.ylabel('$L_2$-norm error') # plot errors in u-velocity pyplot.plot([case['grid-spacing'] for case in cases], [case['u'].error for case in cases], label='u-velocity', marker='o') # plot errors in v-velocity pyplot.plot([case['grid-spacing'] for case in cases], [case['v'].error for case in cases], label='v-velocity', marker='o') # plot errors in pressure pyplot.plot([case['grid-spacing'] for case in cases], [case['p'].error for case in cases], label='pressure', marker='o') # plot convergence-gauge for 1st- and 2nd- orders h = numpy.linspace(cases[0]['grid-spacing'], cases[-1]['grid-spacing'], 101) pyplot.plot(h, h, label='$1^{st}$-order convergence', color='k') pyplot.plot(h, h**2, label='$2^{nd}$-order convergence', color='k', linestyle='--') pyplot.legend() pyplot.xscale('log') pyplot.yscale('log') if args.save: pyplot.savefig('{}/{}.png'.format(args.directory, args.output)) if args.show: pyplot.show()
args.time_step = sorted( int(folder) for folder in os.listdir(args.reference_directory) if folder[0] == '0')[-1] reference['input'] = '{}/{:0>7}'.format(args.reference_directory, args.time_step) # new simulation case = {} case['output'] = '{}/0000000'.format(args.case_directory) if args.same_grid: print('Same grid, data are simply copied ...') if os.path.isdir(case['output']): shutil.rmtree(case['output']) shutil.copytree(reference['input'], case['output']) return # read reference solution reference['grid'] = ioPetIBM.read_grid(args.reference_directory) reference['u'], reference['v'], reference['w'] = ioPetIBM.read_velocity( args.reference_directory, args.time_step, reference['grid'], periodic=args.periodic) reference['p'] = ioPetIBM.read_pressure(args.reference_directory, args.time_step, reference['grid']) if __name__ == '__main__': print('\n[{}] START\n'.format(os.path.basename(__file__))) main() print('\n[{}] END\n'.format(os.path.basename(__file__)))
def main(args): """ Plots the grid convergence for the lid-driven cavity case. Parameters ---------- args: namespace Database with arguments parsed from the command-line. """ # initialization simulations = sorted( int(directory) for directory in os.listdir(args.directory) if os.path.isdir('/'.join([args.directory, directory]))) cases = numpy.empty(len(simulations), dtype=dict) for i, case in enumerate(cases): cases[i] = { 'directory': '{}/{}'.format(args.directory, simulations[i]), 'grid-size': '{0}x{0}'.format(simulations[i]) } for i, case in enumerate(cases): directory = case['directory'] print('\n[case] grid-size: {}'.format(case['grid-size'])) # read mesh grid grid = ioPetIBM.read_grid(directory=directory) cases[i]['grid-spacing'] = (grid[0][-1] - grid[0][0]) / (grid[0].size - 1) # read velocity components cases[i]['u'], cases[i]['v'] = ioPetIBM.read_velocity( args.time_step, grid, directory=directory) # pressure cases[i]['p'] = ioPetIBM.read_pressure(args.time_step, grid, directory=directory) print('\nObserved order of convergence:') last_three = True coarse, medium, fine = cases[-3:] if last_three else cases[:3] ratio = coarse['grid-spacing'] / medium['grid-spacing'] alpha = { 'u': compute_order(ratio, coarse['u'].values, restriction(medium['u'], coarse['u']).values, restriction(fine['u'], coarse['u']).values), 'v': compute_order(ratio, coarse['v'].values, restriction(medium['v'], coarse['v']).values, restriction(fine['v'], coarse['v']).values), 'p': compute_order(ratio, coarse['p'].values, restriction(medium['p'], coarse['p']).values, restriction(fine['p'], coarse['p']).values) } print('\tu: {}'.format(alpha['u'])) print('\tv: {}'.format(alpha['v'])) print('\tp: {}'.format(alpha['p'])) # write orders of convergence into file file_path = '{}/orders_of_convergence.dat'.format(args.directory) with open(file_path, 'w') as outfile: outfile.write('u: {}\n'.format(alpha['u'])) outfile.write('v: {}\n'.format(alpha['v'])) outfile.write('p: {}\n'.format(alpha['p'])) # grid convergence, comparison with finest grid fine = cases[-1] for i, case in enumerate(cases[:-1]): u_fine = restriction(fine['u'], case['u']) cases[i]['u'].error = (l2_norm(case['u'].values - u_fine.values) / l2_norm(u_fine.values)) v_fine = restriction(fine['v'], case['v']) cases[i]['v'].error = (l2_norm(case['v'].values - v_fine.values) / l2_norm(v_fine.values)) p_fine = restriction(fine['p'], case['p']) cases[i]['p'].error = (l2_norm(case['p'].values - p_fine.values) / l2_norm(p_fine.values)) if args.save or args.show: print('\nPlot the grid convergence ...') pyplot.style.use( os.path.join(os.environ['PETIBM_DIR'], 'scripts', 'python', 'style', 'style_PetIBM.mplstyle')) pyplot.xlabel('grid-spacing') pyplot.ylabel('$L_2$-norm error') # plot errors in u-velocity pyplot.plot([case['grid-spacing'] for case in cases[:-1]], [case['u'].error for case in cases[:-1]], label='u-velocity', marker='o') # plot errors in v-velocity pyplot.plot([case['grid-spacing'] for case in cases[:-1]], [case['v'].error for case in cases[:-1]], label='v-velocity', marker='o') # plot errors in pressure pyplot.plot([case['grid-spacing'] for case in cases[:-1]], [case['p'].error for case in cases[:-1]], label='pressure', marker='o') h = numpy.linspace(cases[0]['grid-spacing'], cases[-1]['grid-spacing'], 101) # plot convergence-gauge for 1st- and 2nd- order pyplot.plot(h, h, label='$1^{st}$-order convergence', color='k') pyplot.plot(h, h**2, label='$2^{nd}$-order convergence', color='k', linestyle='--') pyplot.legend() pyplot.xscale('log') pyplot.yscale('log') if args.save: pyplot.savefig(os.path.join(args.directory, args.output)) if args.show: pyplot.show()
def main(args): """ Plots the grid convergence for the Taylor-Green vortex case. Parameters ---------- args: namespace Database with arguments parsed from the command-line. """ # initialization simulations = sorted( int(directory) for directory in os.listdir(args.directory) if os.path.isdir('/'.join([args.directory, directory]))) cases = numpy.empty(len(simulations), dtype=dict) for i, case in enumerate(cases): cases[i] = { 'directory': '{}/{}'.format(args.directory, simulations[i]), 'grid-size': '{0}x{0}'.format(simulations[i]) } for i, case in enumerate(cases): directory = case['directory'] print('\n[case] grid-size: {}'.format(case['grid-size'])) # read mesh grid x, y = ioPetIBM.read_grid(directory=directory) cases[i]['grid-spacing'] = (x[-1] - x[0]) / (x.size - 1) # read velocity and pressure fields cases[i]['u'], cases[i]['v'] = ioPetIBM.read_velocity( args.time_step, [x, y], periodic=['x', 'y'], directory=directory) cases[i]['p'] = ioPetIBM.read_pressure(args.time_step, [x, y], directory=directory) # compute analytical solution cases[i]['u'].exact, _, _, _ = taylor_green_vortex( case['u'].x, case['u'].y, V=args.amplitude, time=(args.time_step * args.dt), Re=args.Re) _, cases[i]['v'].exact, _, _ = taylor_green_vortex( case['v'].x, case['v'].y, V=args.amplitude, time=(args.time_step * args.dt), Re=args.Re) _, _, cases[i]['p'].exact, _ = taylor_green_vortex( case['p'].x, case['p'].y, V=args.amplitude, time=(args.time_step * args.dt), Re=args.Re) # compute L2-norm error for field in ['u', 'v', 'p']: cases[i][field].error = ( l2_norm(case[field].values - case[field].exact) / l2_norm(case[field].exact)) if args.plot: print( '\nPlot the field difference between numerical and analytical ...' ) # create directory where images will be saved images_directory = os.path.join(case['directory'], 'images', 'differences') if not os.path.isdir(images_directory): os.makedirs(images_directory) # load default style pyplot.style.use( os.path.join(os.environ['PETIBM_DIR'], 'scripts', 'python', 'style', 'style_PetIBM.mplstyle')) # set parameters of the plots cases[i]['u'].label = 'u-velocity' cases[i]['u'].file_name = 'uVelocity' cases[i]['v'].label = 'v-velocity' cases[i]['v'].file_name = 'vVelocity' cases[i]['p'].label = 'pressure' cases[i]['p'].file_name = 'pressure' # plot velocity fields and pressure field for field in ['u', 'v', 'p']: image_path = os.path.join( images_directory, '{}{:0>7}_numerical.png'.format(case[field].file_name, args.time_step)) plot_field(case[field].x, case[field].y, case[field].values, case[field].label, image_path) image_path = os.path.join( images_directory, '{}{:0>7}_analytical.png'.format(case[field].file_name, args.time_step)) plot_field(case[field].x, case[field].y, case[field].exact, case[field].label, image_path) image_path = os.path.join( images_directory, '{}{:0>7}_difference.png'.format(case[field].file_name, args.time_step)) plot_field(case[field].x, case[field].y, case[field].values - case[field].exact, case[field].label, image_path) print('\nObserved order of convergence:') last_three = True coarse, medium, fine = cases[-3:] if last_three else cases[:3] ratio = coarse['grid-spacing'] / medium['grid-spacing'] alpha = { 'u': compute_order(ratio, coarse['u'].values, restriction(medium['u'], coarse['u']).values, restriction(fine['u'], coarse['u']).values), 'v': compute_order(ratio, coarse['v'].values, restriction(medium['v'], coarse['v']).values, restriction(fine['v'], coarse['v']).values), 'p': compute_order(ratio, coarse['p'].values, restriction(medium['p'], coarse['p']).values, restriction(fine['p'], coarse['p']).values) } print('\tu: {}'.format(alpha['u'])) print('\tv: {}'.format(alpha['v'])) print('\tp: {}'.format(alpha['p'])) # write orders of convergence into file file_path = os.path.join(args.directory, 'orders_of_convergence.dat') with open(file_path, 'w') as outfile: outfile.write('u: {}\n'.format(alpha['u'])) outfile.write('v: {}\n'.format(alpha['v'])) outfile.write('p: {}\n'.format(alpha['p'])) if args.save or args.show: print('\nPlot the grid convergence ...') pyplot.style.use( os.path.join(os.environ['PETIBM_DIR'], 'scripts', 'python', 'style', 'style_PetIBM.mplstyle')) pyplot.xlabel('grid-spacing') pyplot.ylabel('$L_2$-norm error') # plot errors in u-velocity pyplot.plot([case['grid-spacing'] for case in cases], [case['u'].error for case in cases], label='u-velocity', marker='o') # plot errors in v-velocity pyplot.plot([case['grid-spacing'] for case in cases], [case['v'].error for case in cases], label='v-velocity', marker='o') # plot errors in pressure pyplot.plot([case['grid-spacing'] for case in cases], [case['p'].error for case in cases], label='pressure', marker='o') # plot convergence-gauge for 1st- and 2nd- orders h = numpy.linspace(cases[0]['grid-spacing'], cases[-1]['grid-spacing'], 101) pyplot.plot(h, h, label='$1^{st}$-order convergence', color='k') pyplot.plot(h, h**2, label='$2^{nd}$-order convergence', color='k', linestyle='--') pyplot.legend() pyplot.xscale('log') pyplot.yscale('log') if args.save: pyplot.savefig(os.path.join(args.directory, args.output + '.png')) if args.show: pyplot.show()
def main(args): """ Plots and writes the velocity components at the centerline of the cavity and compares with experimental results form Ghia et al. (1982). Parameters ---------- args: namespace Database with arguments parsed from the command-line. """ # column indices in file with experimental results cols = { '100': { 'u': 1, 'v': 7 }, '1000': { 'u': 2, 'v': 8 }, '3200': { 'u': 3, 'v': 9 }, '5000': { 'u': 4, 'v': 10 }, '10000': { 'u': 5, 'v': 11 } } experimental_file = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'data', 'cavity-GGS82.txt') print('[case directory] {}'.format(args.directory)) Re = args.Re if not args.time_step: args.time_step = ioPetIBM.get_time_steps(directory=args.directory)[-1] # read mesh grid grid = ioPetIBM.read_grid(directory=args.directory) nx, ny = grid[0].size - 1, grid[1].size - 1 # create directory where images will be saved images_directory = os.path.join(args.directory, 'images') print('[images directory] {}'.format(images_directory)) if not os.path.isdir(images_directory): os.makedirs(images_directory) # create directory where data will be saved data_directory = os.path.join(args.directory, 'data') print('[data directory] {}'.format(data_directory)) if not os.path.isdir(data_directory): os.makedirs(data_directory) # get velocity field u, v = ioPetIBM.read_velocity(args.time_step, grid, directory=args.directory) # load default style for figures pyplot.style.use( os.path.join(os.environ['PETIBM_DIR'], 'scripts', 'python', 'style', 'style_PetIBM.mplstyle')) # plot and write u-velocity along y-centerline print('\nPlot u-velocity along vertical centerline ...') pyplot.grid(True) pyplot.xlabel('y', ) pyplot.ylabel('u-velocity along vertical centerline') if nx % 2 == 0: u_centerline = u.values[:, nx / 2 - 1] else: u_centerline = 0.5 * (u.values[:, nx / 2 - 1] + u.values[:, nx / 2]) pyplot.plot(u.y, u_centerline, label='PetIBM', color='k', linestyle='-', linewidth=1) if Re in list(cols.keys()): print('\nComparison with Ghia et al. (1982)') with open(experimental_file, 'r') as infile: y_exp, u_exp = numpy.loadtxt(infile, dtype=float, usecols=(0, cols[Re]['u']), unpack=True) pyplot.plot(y_exp, u_exp, label='Ghia et al. (1982)', linewidth=0, marker='o') pyplot.legend() pyplot.title('Lid-driven cavity flow at Re={} (mesh: {}x{})' ''.format(Re, nx, ny)) pyplot.savefig( os.path.join(images_directory, 'uVelocityCenterlineRe{}_{}x{}.png'.format(Re, nx, ny))) pyplot.close() print('\nWrite u-velocity along vertical centerline ...') data_path = os.path.join( data_directory, 'uVelocityCenterlineRe{}_{}x{}.txt'.format(Re, nx, ny)) with open(data_path, 'w') as outfile: numpy.savetxt(outfile, numpy.c_[u.y, u_centerline], fmt='%.6f', delimiter='\t', header='u-velocity along vertical centerline\n' 'Re={}, mesh: {}x{}\n[y]\t[u]'.format(Re, nx, ny)) # plot and write v-velocity along x-centerline print('\nPlot v-velocity along horizontal centerline ...') pyplot.grid(True) pyplot.xlabel('x') pyplot.ylabel('v-velocity along horizontal centerline') if ny % 2 == 0: v_centerline = v.values[ny / 2 - 1, :] else: v_centerline = 0.5 * (v.values[ny / 2 - 1, :] + v.values[ny / 2, :]) pyplot.plot(v.x, v_centerline, label='PetIBM', color='k', linestyle='-', linewidth=1) if Re in list(cols.keys()): print('Comparison with Ghia et al. (1982)') with open(experimental_file, 'r') as infile: x_exp, u_exp = numpy.loadtxt(infile, dtype=float, usecols=(6, cols[Re]['v']), unpack=True) pyplot.plot(x_exp, u_exp, label='Ghia et al. (1982)', linewidth=0, marker='o') pyplot.legend() pyplot.title('Lid-driven cavity flow at Re={} (mesh: {}x{})' ''.format(Re, nx, ny)) pyplot.savefig( os.path.join(images_directory, 'vVelocityCenterlineRe{}_{}x{}.png'.format(Re, nx, ny))) pyplot.close() print('\nwrite v-velocity along horizontal centerline ...') data_path = os.path.join( data_directory, 'vVelocityCenterlineRe{}_{}x{}.txt'.format(Re, nx, ny)) with open(data_path, 'w') as outfile: numpy.savetxt(outfile, numpy.c_[v.x, v_centerline], fmt='%.6f', delimiter='\t', header='v-velocity along horizontal centerline\n' 'Re={}, mesh: {}x{}\n[x]\t[v]'.format(Re, nx, ny))
def main(): """Plots the grid convergence for the lid-driven cavity case.""" # parse command-line args = read_inputs() # initialization simulations = sorted(int(directory) for directory in os.listdir(args.directory) if os.path.isdir('/'.join([args.directory, directory]))) cases = numpy.empty(len(simulations), dtype=dict) for i, case in enumerate(cases): cases[i] = {'directory': '{}/{}'.format(args.directory, simulations[i]), 'grid-size': '{0}x{0}'.format(simulations[i])} for i, case in enumerate(cases): print('\n[case] grid-size: {}'.format(case['grid-size'])) # read mesh grid grid = ioPetIBM.read_grid(case['directory']) cases[i]['grid-spacing'] = (grid[0][-1]-grid[0][0])/(grid[0].size-1) # read velocity components cases[i]['u'], cases[i]['v'] = ioPetIBM.read_velocity(case['directory'], args.time_step, grid) # pressure cases[i]['p'] = ioPetIBM.read_pressure(case['directory'], args.time_step, grid) print('\nObserved order of convergence:') last_three = True coarse, medium, fine = cases[-3:] if last_three else cases[:3] ratio = coarse['grid-spacing']/medium['grid-spacing'] alpha = {'u': compute_order(ratio, coarse['u'].values, restriction(medium['u'], coarse['u']).values, restriction(fine['u'], coarse['u']).values), 'v': compute_order(ratio, coarse['v'].values, restriction(medium['v'], coarse['v']).values, restriction(fine['v'], coarse['v']).values), 'p': compute_order(ratio, coarse['p'].values, restriction(medium['p'], coarse['p']).values, restriction(fine['p'], coarse['p']).values)} print('\tu: {}'.format(alpha['u'])) print('\tv: {}'.format(alpha['v'])) print('\tp: {}'.format(alpha['p'])) # write orders of convergence into file file_path = '{}/orders_of_convergence.dat'.format(args.directory) with open(file_path, 'w') as outfile: outfile.write('u: {}\n'.format(alpha['u'])) outfile.write('v: {}\n'.format(alpha['v'])) outfile.write('p: {}\n'.format(alpha['p'])) # grid convergence, comparison with finest grid fine = cases[-1] for i, case in enumerate(cases[:-1]): u_fine = restriction(fine['u'], case['u']) cases[i]['u'].error = (l2_norm(case['u'].values-u_fine.values) / l2_norm(u_fine.values)) v_fine = restriction(fine['v'], case['v']) cases[i]['v'].error = (l2_norm(case['v'].values-v_fine.values) / l2_norm(v_fine.values)) p_fine = restriction(fine['p'], case['p']) cases[i]['p'].error = (l2_norm(case['p'].values-p_fine.values) / l2_norm(p_fine.values)) if args.save or args.show: print('\nPlot the grid convergence ...') pyplot.style.use('{}/scripts/python/style/' 'style_PetIBM.mplstyle'.format(os.environ['PETIBM_DIR'])) pyplot.xlabel('grid-spacing') pyplot.ylabel('$L_2$-norm error') # plot errors in u-velocity pyplot.plot([case['grid-spacing'] for case in cases[:-1]], [case['u'].error for case in cases[:-1]], label='u-velocity', marker='o') # plot errors in v-velocity pyplot.plot([case['grid-spacing'] for case in cases[:-1]], [case['v'].error for case in cases[:-1]], label='v-velocity', marker='o') # plot errors in pressure pyplot.plot([case['grid-spacing'] for case in cases[:-1]], [case['p'].error for case in cases[:-1]], label='pressure', marker='o') h = numpy.linspace(cases[0]['grid-spacing'], cases[-1]['grid-spacing'], 101) # plot convergence-gauge for 1st- and 2nd- order pyplot.plot(h, h, label='$1^{st}$-order convergence', color='k') pyplot.plot(h, h**2, label='$2^{nd}$-order convergence', color='k', linestyle='--') pyplot.legend() pyplot.xscale('log') pyplot.yscale('log') if args.save: pyplot.savefig('{}/{}.png'.format(args.directory, args.output)) if args.show: pyplot.show()