def run(options): for fname in options.inputfile: if os.path.isdir(fname): files = [os.path.join(fname, file) for file in os.listdir(fname) if file.endswith(output_formats)] files = remove_irrelevant_files(files) options.inputfile.extend(files) continue data = load(fname) particles = [] for ptype, pdata in data['arrays'].items(): particles.append(pdata) filename = os.path.splitext(fname)[0] if options.outdir is not None: filename = options.outdir + os.path.split(filename)[1] dump_vtk(filename, particles, scalars=options.scalars, velocity=['u', 'v', 'w'])
def sort_file_list(files): """Given a list of input files, sort them in serial order, in-place. """ files[:] = remove_irrelevant_files(files) files.sort(key=_sort_key) return files
def _plots(self): """Create plots. It is employing a iteration over all time steps. """ from matplotlib import pyplot as plt # empty list for time and orientation angle t = [] angle = [] N = 0 # iteration over all output files output_files = remove_irrelevant_files(self.output_files) for i, fname in enumerate(output_files): data = load(fname) # extracting time and fiber data t.append(data['solver_data']['t']) fiber = data['arrays']['fiber'] # computation of orientation angle dxx = fiber.x[0] - fiber.x[-1] dyy = fiber.y[0] - fiber.y[-1] a = np.arctan(dxx / (dyy + 0.01 * self.h0)) + N * np.pi if len(angle) > 0 and a - angle[-1] > 3: N -= 1 a -= np.pi elif len(angle) > 0 and a - angle[-1] < -3: N += 1 a += np.pi angle.append(a) # Integrate Jeffery's solution print("Solving Jeffery's ODE") t = np.array(t) phi0 = angle[0] ar_zhang = get_zhang_aspect_ratio(self.ar) angle_jeffery_zhang = odeint(jeffery_ode, phi0, t, atol=1E-15, args=(ar_zhang, self.options.G)) # open new plot plt.figure() # plot computed angle and Jeffery's solution plt.plot(t * self.options.G, angle, '-k') plt.plot(t * self.options.G, angle_jeffery_zhang, '--k', color='grey') # labels plt.xlabel('Strains $tG$') plt.ylabel('Rotation angle $\phi$') plt.legend(['SPH Simulation', 'Jeffery (Zhang)']) plt.grid() x1, x2, y1, y2 = plt.axis() plt.axis((0, x2, 0, y2)) ax = plt.gca() ax.set_yticks([0, 0.5 * np.pi, np.pi, 1.5 * np.pi]) ax.set_yticklabels(['0', r'$\pi/2$', r'$\pi$', r'$3/2\pi$']) plt.tight_layout() # save figure angfig = os.path.join(self.output_dir, 'angleplot.pdf') plt.savefig(angfig, dpi=300, bbox_inches='tight') try: tex_fig = os.path.join(self.output_dir, "angleplot.tex") from tikzplotlib import save as tikz_save tikz_save(tex_fig) except ImportError: print("Did not write tikz figure.") print("Angleplot written to %s." % angfig)
def post_process(self, info_fname): """Save fiber orientation tensor to csv file.""" if len(self.output_files) == 0: return from pysph.tools.pprocess import get_ke_history from matplotlib import pyplot as plt t, ke = get_ke_history(self.output_files, "fluid") plt.clf() plt.plot(t, ke) plt.xlabel("t") plt.ylabel("Kinetic energy") fig = os.path.join(self.output_dir, "ke_history.png") plt.savefig(fig, dpi=300) # empty list for time t = [] # empty lists for fiber orientation tensors A = [] # iteration over all output files output_files = remove_irrelevant_files(self.output_files) for fname in output_files: data = load(fname) # extracting time t.append(data["solver_data"]["t"]) if self.n > 0: # extrating all arrays. directions = [] fiber = data["arrays"]["fibers"] startpoints = [i * (self.options.lf - 1) for i in range(0, self.n)] endpoints = [ i * (self.options.lf - 1) - 1 for i in range(1, self.n + 1) ] for start, end in zip(startpoints, endpoints): px = np.mean(fiber.rxnext[start:end]) py = np.mean(fiber.rynext[start:end]) pz = np.mean(fiber.rznext[start:end]) n = np.array([px, py, pz]) norm = np.linalg.norm(n) if norm == 0: p = np.array([1, 0, 0]) else: p = n / norm directions.append(p) N = len(directions) a = np.zeros([3, 3]) for p in directions: for i in range(3): for j in range(3): a[i, j] += 1.0 / N * (p[i] * p[j]) A.append(a.ravel()) csv_file = os.path.join(self.output_dir, "A.csv") data = np.hstack((np.matrix(t).T, np.vstack(A))) np.savetxt(csv_file, data, delimiter=",") # plot results data = np.loadtxt(csv_file, delimiter=',') t = data[:, 0] plt.figure(figsize=(12, 3)) for j, i in enumerate([0, 4, 8, 1]): plt.subplot("14"+str(j+1)) p = plt.plot(self.options.G*t, data[:, i+1]) plt.xlabel("Strains") plt.ylabel("Component %d" % j) if i % 2 == 0: plt.ylim([0, 1]) else: plt.ylim([-1, 1]) plt.tight_layout() plt.savefig(csv_file.replace('.csv', '.pdf')) try: from matplotlib2tikz import save as tikz_save tikz_save(csv_file.replace('.csv', '.tex')) except ImportError: print("Did not write tikz figure.")
def post_process(self, info_fname): """Plot ellispoid angle and compare it to Jeffery's ODE.""" try: import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt from matplotlib import rc rc('font', **{ 'family': 'serif', 'serif': ['Computer Modern'], 'size': 18 }) rc('text', usetex=True) except ImportError: print("Post processing requires matplotlib.") return t = [] phi = [] output_files = remove_irrelevant_files(self.output_files) # Going through output files for i, fname in enumerate(output_files): data = load(fname) # Extract time t.append(data['solver_data']['t']) # extract relative positions of ellipsoid particles ellipsoid = data['arrays']['ellipsoid'] x = ellipsoid.x - np.mean(ellipsoid.x) y = ellipsoid.y - np.mean(ellipsoid.y) # compute orienation as covariance matrix coords = np.vstack([x, y]) cov = np.cov(coords) evals, evecs = np.linalg.eig(cov) sort_indices = np.argsort(evals)[::-1] dx, dy = evecs[:, sort_indices[0]] if abs(dx) < 1E-15: phi.append(0.0) else: phi.append(np.pi / 2.0 - np.arctan(dy / dx)) # reference solution t = np.array(t) phi0 = 0.0 angle_jeffery = odeint(jeffery_ode, phi0, t, atol=1E-15, args=(3.0, 1.0)) # open new plot plt.figure() # plot computed angle and Jeffery's solution plt.plot(t, phi, '-k') plt.plot(t, angle_jeffery, '--k') # labels plt.xlabel('Time $t$ in s') plt.ylabel('Rotation angle $\phi$') plt.legend(['SPH Simulation', 'Jeffery']) plt.grid() x1, x2, y1, y2 = plt.axis() plt.axis((0, x2, 0, y2)) ax = plt.gca() ax.set_yticks([0, 0.5 * np.pi, np.pi, 1.5 * np.pi]) ax.set_yticklabels(['0', '$\pi/2$', '$\pi$', '$3/2\pi$']) plt.tight_layout() plt.savefig("test.pdf", bbox_inches='tight')