def main(): comm = mpi.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() root = mkdtemp() filename = join(root, 'test.npz') x = np.ones(5, dtype=float)*rank pa = ParticleArray(name='fluid', constants={'c1': 0.0, 'c2': [0.0, 0.0]}, x=x) try: dump(filename, [pa], {}, mpi_comm=comm) if rank == 0: data = load(filename) pa1 = data["arrays"]["fluid"] assert_lists_same(pa.properties.keys(), pa1.properties.keys()) assert_lists_same(pa.constants.keys(), pa1.constants.keys()) expect = np.ones(5*size) for i in range(size): expect[5*i:5*(i+1)] = i assert np.allclose(pa1.x, expect, atol=1e-14), \ "Expected %s, got %s" % (expect, pa1.x) finally: shutil.rmtree(root)
def test_dump_and_load_with_constants(self): x = np.linspace(0, 1.0, 10) y = x * 2.0 pa = get_particle_array_wcsph(name='fluid', x=x, y=y, constants={ 'c1': 1.0, 'c2': [2.0, 3.0] }) pa.add_property('A', data=2.0, stride=2) pa.set_output_arrays(['x', 'y', 'A']) fname = self._get_filename('simple') dump(fname, [pa], solver_data={}) data = load(fname) arrays = data['arrays'] pa1 = arrays['fluid'] self.assertListEqual(list(sorted(pa.properties.keys())), list(sorted(pa1.properties.keys()))) self.assertListEqual(list(sorted(pa.constants.keys())), list(sorted(pa1.constants.keys()))) self.assertTrue(np.allclose(pa.x, pa1.x, atol=1e-14)) self.assertTrue(np.allclose(pa.y, pa1.y, atol=1e-14)) self.assertTrue(np.allclose(pa.A, pa1.A, atol=1e-14)) self.assertTrue(np.allclose(pa.c1, pa1.c1, atol=1e-14)) self.assertTrue(np.allclose(pa.c2, pa1.c2, atol=1e-14))
def post_process(self): import matplotlib.pyplot as plt from pysph.solver.utils import load files = self.output_files t = [] centerx = [] centery = [] for f in files: data = load(f) pa = data['arrays']['liquid'] t.append(data['solver_data']['t']) x = pa.x y = pa.y length = len(x) cx = 0 cy = 0 count = 0 for i in range(length): if x[i] > 0 and y[i] > 0: cx += x[i] cy += y[i] count += 1 else: continue # As the masses are all the same in this case centerx.append(cx / count) centery.append(cy / count) fname = os.path.join(self.output_dir, 'results.npz') np.savez(fname, t=t, centerx=centerx, centery=centery) plt.plot(t, centerx, 'o', label='x position') plt.plot(t, centery, '*', label='y position') plt.legend() fig1 = os.path.join(self.output_dir, 'centerofmassposvst') plt.savefig(fig1) plt.close()
def post_process(self): import matplotlib.pyplot as plt from pysph.solver.utils import load files = self.output_files t = [] centerx = [] centery = [] velx = [] vely = [] for f in files: data = load(f) pa = data['arrays']['fluid'] t.append(data['solver_data']['t']) x = pa.x y = pa.y u = pa.u v = pa.v color = pa.color length = len(color) cx = 0 cy = 0 vx = 0 vy = 0 count = 0 for i in range(length): if color[i] == 1: if x[i] > 0 and y[i] > 0: cx += x[i] cy += y[i] vx += u[i] vy += v[i] count += 1 else: continue else: continue # As the masses are all the same in this case centerx.append(cx / count) centery.append(cy / count) velx.append(vx / count) vely.append(vy / count) fname = os.path.join(self.output_dir, 'results.npz') np.savez(fname, t=t, centerx=centerx, centery=centery, velx=velx, vely=vely) plt.plot(t, centerx, label='x position') plt.plot(t, centery, label='y position') plt.legend() fig1 = os.path.join(self.output_dir, 'centerofmassposvst') plt.savefig(fig1) plt.close() plt.plot(t, velx, label='x velocity') plt.plot(t, vely, label='y velocity') plt.legend() fig2 = os.path.join(self.output_dir, 'centerofmassvelvst') plt.savefig(fig2) plt.close()
def custom_plot3(sph_schm, sph_schm_legend, bins = 20, sz=(19.2,14.4), save=False): fig, axs = plt.subplots(2, 2, figsize=sz) i = 0 for schm in sph_schm: file_loc = file_base + '/Outputs/' + schm leg = sph_schm_legend[schm] files = get_files(file_loc) data = load(files[-1])['arrays']['fluid'] x, y, lmda, DRh = data.get('x', 'y', 'lmda', 'DRh') if i <= 1: plot_loghist(DRh, ax=axs[0,i%2], bins = bins) axs[0,i%2].set_title(leg, fontsize=20) else: plot_loghist(DRh, ax=axs[1,i%2], bins = bins) axs[1,i%2].set_title(leg, fontsize=20) i += 1 fig.suptitle(figTitle3, fontsize=24) fig.tight_layout() fig.subplots_adjust(top=0.9) if save == True: tle = file_base + '/TGV_DRH_plot' + savefig_additional + '.png' fig.savefig(tle, dpi=400)
def _plot_u_vs_y(self): files = self.output_files # take the last solution data fname = files[-1] data = load(fname) tf = data['solver_data']['t'] fluid = data['arrays']['fluid'] u = fluid.u.copy() y = fluid.y.copy() # exact parabolic profile for the u-velocity d = self.d fx = self.fx nu = self.nu ye = np.linspace(0, self.Ly, 100) ue = 0.5 * fx / nu * ye * (self.Ly - ye) from matplotlib import pyplot as plt plt.clf() plt.plot(ye, ue, label="exact") plt.plot(y, u, 'ko', fillstyle='none', label="computed") plt.xlabel('y') plt.ylabel('u') plt.legend() plt.title('Velocity profile at %s' % tf) fig = os.path.join(self.output_dir, "comparison.png") plt.savefig(fig, dpi=300) return ye, ue, y, u
def post_process(self): import os from pysph.solver.utils import load if len(self.output_files) < 1: return outfile = self.output_files[-1] data = load(outfile) pa = data['arrays']['fluid'] x_c = pa.x u = self.c_0 * self.delta_rho * numpy.sin(self.k * x_c) /\ self.rho_0 u_c = pa.u l_inf = numpy.max(numpy.abs(u_c - u)) l_1 = (numpy.sum(numpy.abs(u_c - u)) / self.n_particles) print("L_inf norm of velocity for the problem: %s" % (l_inf)) print("L_1 norm of velocity for the problem: %s" % (l_1)) rho = self.rho_0 + self.delta_rho *\ numpy.sin(self.k * x_c) rho_c = pa.rho l1 = numpy.sum(numpy.abs(rho - rho_c)) l1 = l1 / self.n_particles print("l_1 norm of density for the problem: %s" % (l1)) fname = os.path.join(self.output_dir, 'norms.npz') numpy.savez(fname, linf_vel=l_inf, l1_vel=l_1, l1_rho=l1)
def get_results(self, array="fluid"): files = self.files nfiles = self.nfiles # compute the kinetic energy history for the array self.get_ke_history(array) # interpolate the u-velocity profile along the centerline y = np.linspace(0,1,101) x = np.ones_like(y) * 0.2 h = np.ones_like(y) * 1.5 * 0.01 dst = gpa('test', x=x, y=y, h=h) # take the last solution data fname = self.files[-1] data = utils.load(fname) self.pa = src = data['arrays'][array] interp = utils.SPHInterpolate(dim=2, dst=dst, src=src) self.ui = ui = interp.interpolate(src.u) self.y = y # exact parabolic profile for the u-velocity self.ye = y self.ue = self.Vmax*y/self.L
def post_process(self): try: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt except ImportError: print("Post processing requires Matplotlib") return from pysph.solver.utils import load files = self.output_files ke = [] t = [] for f in files: data = load(f) pa = data['arrays']['fluid'] t.append(data['solver_data']['t']) m = pa.m u = pa.u v = pa.v length = len(m) ke.append(np.log10(sum(0.5 * m * (u**2 + v**2) / length))) fname = os.path.join(self.output_dir, 'results.npz') np.savez(fname, t=t, ke=ke) plt.plot(t, ke, 'o') fig = os.path.join(self.output_dir, "KEvst.png") plt.savefig(fig) plt.close()
def get_results(self, array="fluid"): files = self.files nfiles = self.nfiles # compute the kinetic energy history for the array self.get_ke_history(array) # interpolated velocities dx = 0.01 self._x = _x = np.linspace(0,1,101) xx, yy = np.meshgrid(_x, _x) xgrid = xx.ravel(); ygrid = yy.ravel() hgrid = np.ones_like(xgrid) * 1.3 * dx self.grid = grid = gpa('grid', x=xgrid, y=ygrid, h=hgrid) self.xx = xx; self.yy = yy # take the last solution data fname = self.files[-1] data = utils.load(fname) self.pa = src = data['arrays'][array] interp = utils.SPHInterpolate(dim=2, dst=grid, src=src) self.ui = ui = interp.interpolate(src.u) self.vi = vi = interp.interpolate(src.v) ui.shape = 101,101 vi.shape = 101,101 # velocity magnitude self.vmag = vmag = np.sqrt( ui**2 + vi**2 )
def _plot_u_vs_y(self): files = self.output_files # take the last solution data fname = files[-1] data = load(fname) tf = data["solver_data"]["t"] fluid = data["arrays"]["fluid"] yp = fluid.y.copy() up = fluid.u.copy() # exact parabolic profile for the u-velocity ye = np.linspace(0, 1, 101) ue = Vmax * ye / Ly from matplotlib import pyplot as plt plt.clf() plt.plot(ye, ue, label="exact") plt.plot(yp, up, "ko", fillstyle="none", label="computed") plt.xlabel("y") plt.ylabel("u") plt.legend() plt.title("Velocity profile at %s" % tf) fig = os.path.join(self.output_dir, "comparison.png") plt.savefig(fig, dpi=300) return ye, ue, yp, up
def _file_count_changed(self, value): fname = self.files[value] self.current_file = os.path.basename(fname) # Code to read the file, create particle array and setup the helper. data = load(fname) solver_data = data["solver_data"] arrays = data["arrays"] self.current_time = t = float(solver_data["t"]) self.time_step = float(solver_data["dt"]) self.iteration = int(solver_data["count"]) names = arrays.keys() pa_names = self.pa_names if len(pa_names) == 0: self.pa_names = names pas = [] for name in names: pa = arrays[name] pah = ParticleArrayHelper(scene=self.scene, name=name) # Must set this after setting the scene. pah.set(particle_array=pa, time=t) pas.append(pah) # Turn on the legend for the first particle array. if len(pas) > 0: pas[0].set(show_legend=True, show_time=True) self.particle_arrays = pas else: for idx, name in enumerate(pa_names): pa = arrays[name] pah = self.particle_arrays[idx] pah.set(particle_array=pa, time=t) if self.record: self._do_snap()
def post_process(self): import matplotlib.pyplot as plt from pysph.solver.utils import load files = self.output_files amat = [] t = [] for f in files: data = load(f) pa = data['arrays']['fluid'] t.append(data['solver_data']['t']) x = pa.x color = pa.color length = len(color) min_x = 0.0 max_x = 0.0 for i in range(length): if color[i] == 1: if x[i] < min_x: min_x = x[i] if x[i] > max_x: max_x = x[i] else: continue else: continue amat.append(0.5*(max_x - min_x)) fname = os.path.join(self.output_dir, 'results.npz') np.savez(fname, t=t, semimajor=amat) plt.plot(t, amat) fig = os.path.join(self.output_dir, 'semimajorvst.png') plt.savefig(fig) plt.close()
def _make_final_plot(self): try: import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt except ImportError: print("Post processing requires matplotlib.") return last_output = self.output_files[-1] from pysph.solver.utils import load data = load(last_output) pa = data['arrays']['fluid'] tf = data['solver_data']['t'] a, A, po, xe, ye = exact_solution(tf) print("At tf=%s" % tf) print("Semi-major axis length (exact, computed) = %s, %s" % (1.0/a, max(pa.y))) plt.plot(xe, ye, 'k--', label='exact') plt.scatter(pa.x, pa.y, marker='.', label='particles') plt.ylim(-2, 2) plt.xlim(plt.ylim()) plt.title("Particles at %s secs" % tf) plt.xlabel('x') plt.ylabel('y') plt.legend() fig = os.path.join(self.output_dir, "comparison.png") plt.savefig(fig, dpi=300) print("Figure written to %s." % fig)
def post_process(self): try: import matplotlib matplotlib.use('Agg') from matplotlib import pyplot except ImportError: print("Post processing requires matplotlib.") return if self.rank > 0 or len(self.output_files) == 0: return import os from pysph.solver.utils import load outfile = self.output_files[-1] data = load(outfile) pa = data['arrays']['fluid'] x = pa.x y = pa.y rho = pa.rho p = pa.p r = numpy.sqrt(x**2 + y**2) # exact solutions vs = 1.0 / 3.0 # shock radial velocity rs = vs * tf # position of shock ri = numpy.linspace(0, rs, 10) ro = numpy.linspace(rs, xmax, 100) re = numpy.concatenate((ri, ro)) rho_e1 = numpy.ones_like(ri) * ((gamma + 1) / (gamma - 1))**dim rho_e2 = rho0 * (1 + tf / ro)**(dim - 1) rho_e = numpy.concatenate((rho_e1, rho_e2)) p_e1 = vs * rho_e1 p_e2 = numpy.zeros_like(ro) p_e = numpy.concatenate((p_e1, p_e2)) pyplot.scatter(r, p, s=1) pyplot.xlabel('r') pyplot.ylabel('P') pyplot.plot(re, p_e, color='r', lw=1) pyplot.legend(['exact', self.options.scheme]) fname = os.path.join(self.output_dir, 'pressure.png') pyplot.savefig(fname, dpi=300) pyplot.close('all') pyplot.scatter(r, rho, s=1) pyplot.xlabel('r') pyplot.ylabel(r'$\rho$') pyplot.plot(re, rho_e, color='r', lw=1) pyplot.legend(['exact', self.options.scheme]) fname = os.path.join(self.output_dir, 'density.png') pyplot.savefig(fname, dpi=300) pyplot.close('all')
def create_particles(self): # create the particles dx = self.dx _x = np.arange( dx/2, L, dx ) x, y = np.meshgrid(_x, _x); x = x.ravel(); y = y.ravel() if self.options.init is not None: fname = self.options.init from pysph.solver.utils import load data = load(fname) _f = data['arrays']['fluid'] x, y = _f.x.copy(), _f.y.copy() if self.options.perturb > 0: np.random.seed(1) factor = dx*self.options.perturb x += np.random.random(x.shape)*factor y += np.random.random(x.shape)*factor h = np.ones_like(x) * dx # create the arrays fluid = get_particle_array(name='fluid', x=x, y=y, h=h) self.scheme.setup_properties([fluid]) # add the requisite arrays fluid.add_property('color') fluid.add_output_arrays(['color']) print("Taylor green vortex problem :: nfluid = %d, dt = %g"%( fluid.get_number_of_particles(), self.dt)) # setup the particle properties pi = np.pi; cos = np.cos; sin=np.sin # color fluid.color[:] = cos(2*pi*x) * cos(4*pi*y) # velocities fluid.u[:] = -U * cos(2*pi*x) * sin(2*pi*y) fluid.v[:] = +U * sin(2*pi*x) * cos(2*pi*y) fluid.p[:] = -U*U*(np.cos(4*np.pi*x) + np.cos(4*np.pi*y))*0.25 # mass is set to get the reference density of each phase fluid.rho[:] = rho0 fluid.m[:] = self.volume * fluid.rho # volume is set as dx^2 if self.options.scheme == 'tvf': fluid.V[:] = 1./self.volume # smoothing lengths fluid.h[:] = self.hdx * dx # return the particle list return [fluid]
def get_com(file): data = load(file) t = data['solver_data']['t'] pa = data['arrays']['cylinders'] total_mass = np.sum(pa.m) moment_x = np.sum(pa.m * pa.x) moment_y = np.sum(pa.m * pa.y) x_com = moment_x / total_mass y_com = moment_y / total_mass return t, x_com / (26 * 1e-2), y_com / (26 * 1e-2)
def post_process(self): if len(self.output_files) < 1 or self.rank > 0: return try: import matplotlib matplotlib.use('Agg') from matplotlib import pyplot except ImportError: print("Post processing requires matplotlib.") return from pysph.solver.utils import load import os plot_exact = False plot_legends = ['pysph'] try: import h5py plot_exact = True plot_legends.append('exact') except ImportError: print("h5py not found, exact data will not be plotted") fname = os.path.join(os.path.dirname(__file__), 'wc_exact.hdf5') props = ["rho", "u", "p", "e"] props_h5 = ["'" + pr + "'" for pr in props] if plot_exact: h5file = h5py.File(fname) dataset = h5file['data_0'] outfile = self.output_files[-1] data = load(outfile) pa = data['arrays']['fluid'] x = pa.x u = pa.u e = pa.e p = pa.p rho = pa.rho prop_vals = [rho, u, p, e] for _i, prop in enumerate(props): pyplot.plot(x, prop_vals[_i]) if plot_exact: pyplot.scatter( dataset.get( props_h5[_i])['data_0'].get("'x'")['data_0'][:], dataset.get( props_h5[_i])['data_0'].get("'data'")['data_0'][:], c='k', s=4) pyplot.xlabel('x') pyplot.ylabel(props[_i]) pyplot.legend(plot_legends) fig = os.path.join(self.output_dir, props[_i] + ".png") pyplot.savefig(fig, dpi=300) pyplot.close('all')
def _plot_velocity(self): from pysph.tools.interpolator import Interpolator from pysph.solver.utils import load # Find the u profile for comparison. y = np.linspace(0.0, H, 100) x = np.ones_like(y) * L / 2 fname = self.output_files[-1] data = load(fname) dm = self.create_domain() interp = Interpolator(list(data['arrays'].values()), x=x, y=y, domain_manager=dm) ui_lby2 = interp.interpolate('u') x = np.ones_like(y) * L interp.set_interpolation_points(x=x, y=y) ui_l = interp.interpolate('u') import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt y /= H y -= 0.5 f = plt.figure() plt.plot(y, ui_lby2, 'k-', label='x=L/2') plt.plot(y, ui_l, 'k-', label='x=L') plt.xlabel('y/H') plt.ylabel('u') plt.legend() fig = os.path.join(self.output_dir, 'u_profile.png') plt.savefig(fig, dpi=300) plt.close() # Plot the contours of vmag. xx, yy = np.mgrid[0:L:100j, 0:H:100j] interp.set_interpolation_points(x=xx, y=yy) u = interp.interpolate('u') v = interp.interpolate('v') xx /= L yy /= H vmag = np.sqrt(u * u + v * v) f = plt.figure() plt.contourf(xx, yy, vmag) plt.xlabel('x/L') plt.ylabel('y/H') plt.colorbar() fig = os.path.join(self.output_dir, 'vmag_contour.png') plt.savefig(fig, dpi=300) plt.close() return y, ui_lby2, ui_l, xx, yy, vmag
def get_frame(self, frame): '''Return particle arrays for a given frame number with caching. Parameters ---------- frame : int Returns ------- A dictionary. Examples -------- >>> sample = Viewer2D('/home/deep/pysph/trivial_inlet_outlet_output/') >>> sample.get_frame(12) { 'arrays': { 'fluid': <pysph.base.particle_array.ParticleArray at 0x7f3f7d144d60>, 'inlet': <pysph.base.particle_array.ParticleArray at 0x7f3f7d144b98>, 'outlet': <pysph.base.particle_array.ParticleArray at 0x7f3f7d144c30> }, 'solver_data': {'count': 240, 'dt': 0.01, 't': 2.399999999999993} } ''' if self.cache is not None: if frame in self.cache: temp_data = self.cache[frame] else: self.cache[frame] = temp_data = load(self.paths_list[frame]) else: temp_data = load(self.paths_list[frame]) return temp_data
def load_output(self, count): """Load particle data from dumped output file. Parameters ---------- count : str The iteration time from which to load the data. If time is '?' then list of available data files is returned else the latest available data file is used Notes ----- Data is loaded from the :py:attr:`output_directory` using the same format as stored by the :py:meth:`dump_output` method. Proper functioning required that all the relevant properties of arrays be dumped. """ # get the list of available files available_files = [ i.rsplit('_', 1)[1][:-4] for i in os.listdir(self.output_directory) if i.startswith(self.fname) and i.endswith('.npz') ] if count == '?': return sorted(set(available_files), key=int) else: if count not in available_files: msg = "File with iteration count `%s` does not exist" % (count) msg += "\nValid iteration counts are %s" % (sorted( set(available_files), key=int)) raise IOError(msg) array_names = [pa.name for pa in self.particles] # load the output file data = load( os.path.join(self.output_directory, self.fname + '_' + str(count) + '.npz')) arrays = [data["arrays"][i] for i in array_names] # set the Particle's arrays self.particles = arrays solver_data = data['solver_data'] self.t = float(solver_data['t']) self.dt = float(solver_data['dt']) self.count = int(solver_data['count'])
def test_load_works_with_dump_version1(self): x = np.linspace(0, 1.0, 10) y = x*2.0 pa = get_particle_array(name='fluid', x=x, y=y) fname = self._get_filename('simple') dump_v1(fname, [pa], solver_data={}) data = load(fname) arrays = data['arrays'] pa1 = arrays['fluid'] self.assertListEqual(list(sorted(pa.properties.keys())), list(sorted(pa1.properties.keys()))) self.assertTrue(np.allclose(pa.x, pa1.x, atol=1e-14)) self.assertTrue(np.allclose(pa.y, pa1.y, atol=1e-14))
def create_particles(self): """Create or load particle arrays.""" if self.options.continuation: data = load(self.options.continuation) fluid = data["arrays"]["fluid"] fibers = data["arrays"]["fibers"] fibers.phifrac[:] = 2.0 fibers.phi0[:] = np.pi self.solver.t = data["solver_data"]["t"] self.solver.count = data["solver_data"]["count"] return [fluid, fibers] else: return self.create_suspension_particles()
def write_vtk(self, array_name, props): if not TVTK: return # create a list of props if type(props) != list: props = [props] # create an output folder for the vtk files dirname = path.join(self.dirname, "vtk") utils.mkdir(dirname) nfiles = self.nfiles for i in range(self.start, nfiles): f = self.files[i] data = utils.load(f) array = data["arrays"][array_name] num_particles = array.num_real_particles # save the points points = np.zeros(shape=(num_particles, 3)) points[:, 0] = array.z points[:, 1] = array.y points[:, 2] = array.x mesh = tvtk.PolyData(points=points) # add the scalar props for prop in props: if prop == "vmag": u, v, w = array.get("u", "v", "w") numpy_array = np.sqrt(u ** 2 + v ** 2 + w ** 2) else: numpy_array = array.get(prop) vtkarray = array2vtk(numpy_array) vtkarray.SetName(prop) # add the array as point data mesh.point_data.add_array(vtkarray) # set the last prop as the active scalar mesh.point_data.set_active_scalars(props[-1]) # spit it out fileno = data["solver_data"]["count"] _fname = self.fname + "_%s_%s" % (array_name, fileno) self._write_vtk_snapshot(mesh, dirname, _fname)
def post_process(self): from pysph.solver.utils import load if len(self.output_files) < 1: return outfile = self.output_files[-1] data = load(outfile) pa = data['arrays']['fluid'] x_c = pa.x u = self.c_0 * self.delta_rho * numpy.sin(self.k * x_c) /\ self.rho_0 u_c = pa.u l_inf = numpy.max(numpy.abs(u_c - u)) print("L_inf norm for the problem: %s" % (l_inf))
def test_dump_and_load_with_partial_data_dump(self): x = np.linspace(0, 1.0, 10) y = x*2.0 pa = get_particle_array_wcsph(name='fluid', x=x, y=y) pa.set_output_arrays(['x', 'y']) fname = self._get_filename('simple') dump(fname, [pa], solver_data={}) data = load(fname) arrays = data['arrays'] pa1 = arrays['fluid'] self.assertListEqual(list(sorted(pa.properties.keys())), list(sorted(pa1.properties.keys()))) self.assertTrue(np.allclose(pa.x, pa1.x, atol=1e-14)) self.assertTrue(np.allclose(pa.y, pa1.y, atol=1e-14))
def write_vtk(self, array_name, props): if not TVTK: return # create a list of props if type(props) != list: props = [props] # create an output folder for the vtk files dirname = path.join(self.dirname, 'vtk') utils.mkdir(dirname) nfiles = self.nfiles for i in range(self.start, nfiles): f = self.files[i] data = utils.load(f) array = data['arrays'][array_name] num_particles = array.num_real_particles # save the points points = np.zeros(shape=(num_particles, 3)) points[:, 0] = array.z points[:, 1] = array.y points[:, 2] = array.x mesh = tvtk.PolyData(points=points) # add the scalar props for prop in props: if prop == 'vmag': u, v, w = array.get('u', 'v', 'w') numpy_array = np.sqrt(u**2 + v**2 + w**2) else: numpy_array = array.get(prop) vtkarray = array2vtk(numpy_array) vtkarray.SetName(prop) # add the array as point data mesh.point_data.add_array(vtkarray) # set the last prop as the active scalar mesh.point_data.set_active_scalars(props[-1]) # spit it out fileno = data['solver_data']['count'] _fname = self.fname + '_%s_%s' % (array_name, fileno) self._write_vtk_snapshot(mesh, dirname, _fname)
def post_process(self): from pysph.solver.utils import load if len(self.output_files) < 1: return outfile = self.output_files[-1] data = load(outfile) pa = data['arrays']['fluid'] x_c = pa.x y_c = pa.y rho_c = pa.rho rho_e = 1 + 0.2 * numpy.sin(numpy.pi * (x_c + y_c)) num_particles = rho_c.size l1_norm = numpy.sum(numpy.abs(rho_c - rho_e)) / num_particles print(l1_norm)
def get_ke_history(self, array_name): nfiles = self.nfiles self.ke = ke = np.zeros(nfiles, dtype=np.float64) self.t = t = np.zeros(nfiles, dtype=np.float64) for i in range(nfiles): data = utils.load(self.files[i]) # save the time array t[i] = data["solver_data"]["t"] array = data["arrays"][array_name] m, u, v, w = array.get("m", "u", "v", "w") ke[i] = 0.5 * np.sum(m * (u ** 2 + v ** 2))
def __init__(self, file, file_count): self.temp_data = load(file)['arrays'] self.frame = widgets.IntSlider( min=0, max=file_count, step=1, value=0, description='frame', layout=widgets.Layout(width='600px'), ) self.particles = {} for array_name in self.temp_data.keys(): self.particles[array_name] = ParticleArrayWidgets3D( self.temp_data[array_name], )
def test_dump_and_load_works_by_default(self): x = np.linspace(0, 1.0, 10) y = x*2.0 dt = 1.0 pa = get_particle_array(name='fluid', x=x, y=y) fname = self._get_filename('simple') dump(fname, [pa], solver_data={'dt': dt}) data = load(fname) solver_data = data['solver_data'] arrays = data['arrays'] pa1 = arrays['fluid'] self.assertListEqual(list(solver_data.keys()), ['dt']) self.assertListEqual(list(sorted(pa.properties.keys())), list(sorted(pa1.properties.keys()))) self.assertTrue(np.allclose(pa.x, pa1.x, atol=1e-14)) self.assertTrue(np.allclose(pa.y, pa1.y, atol=1e-14))
def __init__(self, file, file_count): self.temp_data = load(file)['arrays'] self.frame = widgets.IntSlider( min=0, max=file_count, step=1, value=0, description='frame', layout=widgets.Layout(width='500px'), continuous_update=False, ) self.play_button = widgets.Play( min=0, max=file_count, step=1, disabled=False, ) self.link = widgets.jslink( (self.frame, 'value'), (self.play_button, 'value'), ) self.delay_box = widgets.FloatText( value=0.2, description='Delay', disabled=False, layout=widgets.Layout(width='240px', display='flex'), ) self.save_figure = widgets.Text( value='', placeholder='example.pdf', description='Save figure', disabled=False, layout=widgets.Layout(width='240px', display='flex'), ) self.save_all_plots = widgets.ToggleButton( value=False, description='Save all plots!', disabled=False, tooltip='Saves the corresponding plots for all the' + ' frames in the presently set styling.', icon='', ) self.particles = {} for array_name in self.temp_data.keys(): self.particles[array_name] = ParticleArrayWidgets( self.temp_data[array_name], )
def _get_force_evaluator(self): from pysph.solver.utils import load from pysph.base.kernels import QuinticSpline from pysph.tools.sph_evaluator import SPHEvaluator from pysph.sph.equation import Group from pysph.sph.wc.transport_velocity import ( SetWallVelocity, MomentumEquationPressureGradient, SolidWallNoSlipBC, VolumeSummation, MomentumEquationViscosity) data = load(self.output_files[0]) solid = data['arrays']['solid'] fluid = data['arrays']['fluid'] prop = [ 'awhat', 'auhat', 'avhat', 'wg', 'vg', 'ug', 'V', 'uf', 'vf', 'wf', 'wij', 'vmag' ] for p in prop: solid.add_property(p) fluid.add_property(p) equations = [ Group(equations=[ SetWallVelocity(dest='fluid', sources=['solid']), VolumeSummation(dest='fluid', sources=['fluid', 'solid']), VolumeSummation(dest='solid', sources=['fluid', 'solid']), ], real=False), Group( equations=[ # Pressure gradient terms MomentumEquationPressureGradient( dest='solid', sources=['fluid', 'solid'], pb=p0), MomentumEquationViscosity(dest='solid', sources=['fluid', 'solid'], nu=self.nu), SolidWallNoSlipBC(dest='solid', sources=['fluid'], nu=self.nu), ], real=True), ] sph_eval = SPHEvaluator(arrays=[solid, fluid], equations=equations, dim=2, kernel=QuinticSpline(dim=2)) return sph_eval
def test_that_output_array_information_is_saved(self): # Given x = np.linspace(0, 1.0, 10) y = x*2.0 pa = get_particle_array(name='fluid', x=x, y=y, u=3*x) # When output_arrays = ['x', 'y', 'u'] pa.set_output_arrays(output_arrays) fname = self._get_filename('simple') dump(fname, [pa], solver_data={}) data = load(fname) pa1 = data['arrays']['fluid'] # Then. self.assertEqual(set(pa.output_property_arrays), set(output_arrays)) self.assertEqual(set(pa1.output_property_arrays), set(output_arrays))
def post_process(self): try: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt except ImportError: print("Post processing requires Matplotlib") return from pysph.solver.utils import load files = self.output_files dp = [] t = [] for f in files: data = load(f) pa = data['arrays']['fluid'] t.append(data['solver_data']['t']) m = pa.m x = pa.x y = pa.y N = pa.N p = pa.p n = len(m) count_in = 0 count_out = 0 p_in = 0 p_out = 0 for i in range(n): r = radius(x[i], y[i]) if N[i] < 1: if radius(x[i], y[i]) < 0.0625: p_in += p[i] count_in += 1 else: p_out += p[i] count_out += 1 else: continue dp.append((p_in / count_in) - (p_out / count_out)) fname = os.path.join(self.output_dir, 'results.npz') np.savez(fname, t=t, dp=dp) plt.plot(t, dp) fig = os.path.join(self.output_dir, "dpvst.png") plt.savefig(fig) plt.close()
def main(fname, prop, npoint): from pysph.solver.utils import load print "Loading", fname data = load(fname) arrays = data['arrays'].values() interp = Interpolator(arrays, num_points=npoint) print interp.shape print "Interpolating" prop = interp.interpolate(prop) print "Visualizing" from mayavi import mlab src = mlab.pipeline.scalar_field(interp.x, interp.y, interp.z, prop) if interp.dim == 3: mlab.pipeline.scalar_cut_plane(src) else: mlab.pipeline.surface(src) mlab.pipeline.outline(src) mlab.show()
def comute_stats(self, array="fluid"): files = self.files nfiles = self.nfiles # compute the kinetic energy history for the array self.get_ke_history(array) decay = np.zeros( nfiles ) linf = np.zeros( nfiles ) for i in range(nfiles): data = utils.load(files[i]) pa = data['arrays'][array] vmag = np.sqrt( pa.vmag2 ) t = data['solver_data']['t'] decay[i] = vmag.max() # compute the error norm theoretical_max = self.U * np.exp(self.decay_rate_constant * t) linf[i] = abs( (vmag.max() - theoretical_max)/theoretical_max ) self.decay = decay self.linf = linf
def _file_name_changed(self, fname): if os.path.exists(fname): data = load(fname) self.particle_array = data['arrays']['fluid']