コード例 #1
0
    def _compute_results(self):
        from pysph.solver.utils import iter_output
        from collections import defaultdict
        data = defaultdict(list)
        for sd, array in iter_output(self.output_files, 'fluid'):
            _t = sd['t']
            data['t'].append(_t)
            m, u, v, x, y = array.get('m', 'u', 'v', 'x', 'y')
            vmag2 = u**2 + v**2
            mom = np.sum(m*np.sqrt(vmag2))
            data['ke'].append(0.5*np.sum(m*vmag2))
            data['xmax'].append(x.max())
            data['ymax'].append(y.max())
            a, A, po, _xe, _ye = exact_solution(_t, n=0)
            data['minor'].append(a)
            data['major'].append(1.0/a)
            data['xe'].append(_xe)
            data['ye'].append(_ye)
            data['y'].append(y)
            data['x'].append(x)
            data['mom'].append(mom)


        for key in data:
            data[key] = np.asarray(data[key])
        fname = os.path.join(self.output_dir, 'results.npz')
        np.savez(fname, **data)
コード例 #2
0
    def post_process(self):
        if len(self.output_files) == 0:
            return

        from pysph.solver.utils import iter_output

        files = self.output_files
        t, amplitude = [], []
        for sd, array in iter_output(files, 'plate'):
            _t = sd['t']
            t.append(_t)
            amplitude.append(array.y[array.amplitude_idx[0]])

        import matplotlib
        import os
        matplotlib.use('Agg')

        from matplotlib import pyplot as plt
        plt.clf()
        plt.plot(t, amplitude)
        plt.xlabel('t')
        plt.ylabel('Amplitude')
        plt.legend()
        fig = os.path.join(self.output_dir, "amplitude.png")
        plt.savefig(fig, dpi=300)
コード例 #3
0
    def post_process(self, info_fname):
        info = self.read_info(info_fname)
        if len(self.output_files) == 0:
            return

        from pysph.solver.utils import iter_output
        t, x_max = [], []
        factor = np.sqrt(2.0 * 9.81 / fluid_column_width)
        files = self.output_files
        for sd, array in iter_output(files, 'fluid'):
            t.append(sd['t'] * factor)
            x = array.get('x')
            x_max.append(x.max())

        t, x_max = list(map(np.asarray, (t, x_max)))
        fname = os.path.join(self.output_dir, 'results.npz')
        np.savez(fname, t=t, x_max=x_max)

        import matplotlib
        matplotlib.use('Agg')
        from matplotlib import pyplot as plt
        from pysph.examples import db_exp_data as dbd
        plt.plot(t, x_max, label='Computed')
        te, xe = dbd.get_koshizuka_oka_data()
        plt.plot(te, xe, 'o', label='Koshizuka & Oka (1996)')
        plt.xlim(0, 0.7 * factor)
        plt.ylim(0, 4.5)
        plt.xlabel('$T$')
        plt.ylabel('$Z/L$')
        plt.legend(loc='upper left')
        plt.savefig(os.path.join(self.output_dir, 'x_vs_t.png'), dpi=300)
        plt.close()
def combined_loghist(file_loc, ax=None, cond=0.0, Bins=20, **plot_kwargs):
    if ax == None:
        ax = plt.gca()

    files = get_files(file_loc)
    df = np.array([])
    cnt = 0
    for solver_data, fluid in iter_output(files, 'fluid'):
        if cnt == 0:
            cnt = 1
        else:
            df = np.concatenate([df, fluid.DRh])
            cnt += 1

    cnt -= 1
    hist, bins = np.histogram(df, bins=Bins)
    hist_norm = hist / cnt

    width = 0.9 * (bins[1] - bins[0])
    center = (bins[:-1] + bins[1:]) / 2

    #ax.bar(center, hist_norm, align='center', width=width, log=True)
    plot_loghist(df, bins=Bins, ax=ax, log=True)

    temp = (df <= cond).sum()
    res = round(temp * 100 / len(df), 3)
    return res
コード例 #5
0
ファイル: dam_break_3d.py プロジェクト: yoojinhwang/pysph
    def post_process(self, info_fname):
        self.read_info(info_fname)
        if len(self.output_files) == 0:
            return

        from pysph.solver.utils import iter_output
        import matplotlib.pyplot as plt
        from pysph.examples import db_exp_data as dbd
        from pysph.tools.interpolator import Interpolator
        import os
        H = self.geom.fluid_column_height
        factor_y = 1 / (ro * 9.81 * H)
        factor_x = np.sqrt(9.81 / H)

        t1, t3, data_p1, data_p3 = dbd.get_kleefsman_data()
        files = self.output_files

        t = []
        p0 = []

        x_probe = self.geom.obstacle_center_x - self.geom.obstacle_length * 0.5
        p_x = np.repeat(x_probe, 2)
        p_y = np.repeat(0, 2)
        p_z = np.array([0.021, 0.101])

        for sd, arrays1, arrays2, arrays3 in iter_output(
                files, "fluid", "obstacle", "boundary"):
            t.append(sd["t"] * factor_x)
            interp = Interpolator([arrays1, arrays2, arrays3],
                                  x=p_x,
                                  y=p_y,
                                  z=p_z,
                                  method="shepard")
            p0.append(interp.interpolate('p') * factor_y)

        fname = os.path.join(self.output_dir, 'results.npz')
        t, p0 = list(map(np.asarray, (t, p0)))
        np.savez(fname, t=t, p0=p0)

        p1 = p0[:, 0]
        p3 = p0[:, 1]

        fig1 = plt.figure()
        plt.plot(t, p1, label="p1 computed", figure=fig1)
        plt.plot(t1, data_p1, label="Kleefsman et al.", figure=fig1)
        plt.legend()
        plt.ylabel(r"$\frac{P}{\rho gH}$")
        plt.xlabel(r"$t \sqrt{\frac{g}{H}} $")
        plt.title("P1")
        plt.savefig(os.path.join(self.output_dir, 'p1_vs_t.png'))

        fig2 = plt.figure()
        plt.plot(t, p3, label="p3 computed", figure=fig2)
        plt.plot(t3, data_p3, label="Kleefsman et al.", figure=fig2)
        plt.legend()
        plt.ylabel(r"$\frac{P}{\rho gH}$")
        plt.xlabel(r"$t \sqrt{\frac{g}{H}} $")
        plt.title("P3")
        plt.savefig(os.path.join(self.output_dir, 'p3_vs_t.png'))
コード例 #6
0
ファイル: pprocess.py プロジェクト: mahgadalla/pysph-1
def get_ke_history(files, array_name):
    t, ke = [], []
    for sd, array in utils.iter_output(files, array_name):
        t.append(sd['t'])
        m, u, v, w = array.get('m', 'u', 'v', 'w')
        _ke = 0.5 * np.sum(m * (u**2 + v**2 + w**2))
        ke.append(_ke)
    return np.asarray(t), np.asarray(ke)
コード例 #7
0
    def post_process(self, info_fname):
        import os
        info = self.read_info(info_fname)
        if len(self.output_files) == 0:
            return

        from pysph.solver.utils import iter_output

        files = self.output_files
        t, xa, ya, r_err = [], [], [], []
        for sd, array in iter_output(files, 'fluid'):
            _t = sd['t']
            t.append(_t)
            x, y = array.get('x', 'y')

            xa.append(x[0])
            ya.append(y[0])

            err = np.abs(np.sqrt(x[0] * x[0] + y[0] * y[0]) - self.R)
            r_err.append(err)

        t = np.array(t)
        xa = np.array(xa)
        ya = np.array(ya)
        r_err = np.array(r_err)

        fname = os.path.join(self.output_dir, 'results.npz')
        np.savez(fname, t=t, x=xa, y=ya, r_err=r_err)

        import matplotlib

        matplotlib.use('Agg')

        if self.INT == "eul":
            tle = "Euler Integrator"
        else:
            tle = "RK-4 Integrator"

        from matplotlib import pyplot as plt
        plt.clf()
        plt.plot(t, xa, label='x')
        plt.plot(t, ya, label='y')
        plt.plot(t, self.R * np.cos(t), label='exact x')
        plt.plot(t, self.R * np.sin(t), label='exact y')
        plt.xlabel('t')
        plt.legend()
        plt.title(tle)
        fig = os.path.join(self.output_dir, "error_position.png")
        plt.savefig(fig, dpi=300)

        plt.clf()
        plt.plot(t, np.sqrt(xa * xa + ya * ya), label='radius')
        plt.plot(t, self.R * np.ones_like(t), label='exact radius')
        plt.xlabel('t')
        plt.legend()
        plt.title(tle)
        fig = os.path.join(self.output_dir, "error_radius.png")
        plt.savefig(fig, dpi=300)
コード例 #8
0
ファイル: st_bouscasse.py プロジェクト: yang7857854/pysph
    def post_process(self, info_fname):
        """
        Comparing wave height 0.05 m to the left of the tank
        """
        self.read_info(info_fname)

        if len(self.output_files) == 0:
            return

        from pysph.solver.utils import iter_output
        import matplotlib.pyplot as plt
        from cyarray.api import UIntArray
        from pysph.base import nnps

        files = self.output_files
        wave_height, t = [], []
        for sd, arrays1, arrays2 in iter_output(files, 'fluid', 'solid'):
            t.append(sd['t'])
            x_left = arrays2.x.min()
            probe_x = x_left + 0.05 + self.dx * (n_layers - 1)
            probe_y = np.linspace(0, arrays1.y.max(), 50)
            probe = get_particle_array(x=probe_x * np.ones_like(probe_y),
                                       y=probe_y)
            pa_list = [arrays1, probe]
            nps = nnps.LinkedListNNPS(dim=2, particles=pa_list, radius_scale=1)
            src_index, dst_index = 0, 1
            nps.set_context(src_index=0, dst_index=1)
            nbrs = UIntArray()
            wh = 0.0
            for i in range(len(probe_y)):
                nps.get_nearest_particles(src_index, dst_index, i, nbrs)
                neighbours = nbrs.get_npy_array()
                for j in range(len(neighbours)):
                    if arrays1.y[neighbours[j]] > wh:
                        wh = arrays1.y[neighbours[j]]

            wave_height.append(wh)

        wave_height = np.array(wave_height)
        wave_height = wave_height - h

        import pysph.examples.st_exp_data as st

        exp_t, exp_H = st.get_bouscasse_data()
        T = 2 * pi / omega
        t = np.array(t) / T
        plt.plot(t, wave_height, label="Computed")
        plt.scatter(exp_t, exp_H, label="Experiment: Bouscasse et al, 2013")
        plt.xlabel("t/T")
        plt.ylabel("Wave Height (m)")
        plt.xlim(8.5, 11)
        plt.legend()
        plt.savefig(os.path.join(self.output_dir, 'H_vs_t.png'))
        plt.show()
コード例 #9
0
ファイル: test_7.py プロジェクト: dineshadepu/mtechReport
 def post_processing(self):
     files = get_files('test_7_output')
     t = []
     y1 = []
     y2 = []
     for solver_data, al, copper in iter_output(files, 'al', 'copper'):
         t.append(solver_data['t'])
         y1.append(-al.wz[0])
         y2.append(-copper.wz[0])
     print("Done")
     print(y1)
     print(y2)
コード例 #10
0
 def post_processing(self):
     files = get_files('big_simulation_output')
     t = []
     y1 = []
     for solver_data, cube in iter_output(files, 'cube'):
         t.append(solver_data['t'])
         y1.append(cube.cm[1])
     print("Done")
     dat = np.array([t, y1])
     dat = dat.T
     print(dat)
     np.savetxt('data.txt', dat, delimiter=',')
コード例 #11
0
ファイル: test_4.py プロジェクト: dineshadepu/mtechReport
 def post_processing(self):
     files = get_files('test_4_output')
     t = []
     y1 = []
     for solver_data, sand, wall in iter_output(files, 'sand', 'wall'):
         t.append(solver_data['t'])
         y1.append(sand.wz[0])
     print("Done")
     target = open('output.txt', 'a+')
     target.write(str(y1[-1]))
     target.close()
     print(y1[-1])
コード例 #12
0
ファイル: db_3d_yeh.py プロジェクト: yang7857854/pysph
    def post_process(self, info_fname):
        self.read_info(info_fname)
        if len(self.output_files) == 0:
            return

        from pysph.solver.utils import iter_output
        import matplotlib.pyplot as plt
        from pysph.examples import db_exp_data as dbd
        from pysph.tools.interpolator import Interpolator
        import os

        exp_vt, exp_v, exp_ft, exp_f = dbd.get_yeh_petroff_data()
        files = self.output_files

        t = []
        u = []

        # Velocity probe location
        vp_x = 0.814
        vp_y = 0.0
        vp_z = 0.026

        for sd, arrays in iter_output(files, "fluid"):
            t.append(sd["t"])
            interp = Interpolator([arrays],
                                  x=vp_x,
                                  y=vp_y,
                                  z=vp_z,
                                  method="shepard")
            u.append(interp.interpolate('u'))

        u = np.array(u)
        fname = os.path.join(self.output_dir, 'results.npz')
        t, u = list(map(np.asarray, (t, u)))
        np.savez(fname, t=t, u=u)

        t = np.array(t) - 0.238
        figure_1 = plt.figure()
        plt.plot(t, u, label="Computed", figure=figure_1)
        plt.scatter(exp_vt,
                    exp_v,
                    label="Experiment, Yeh and Petroff",
                    marker="^",
                    figure=figure_1,
                    color=(0, 0, 0))
        plt.legend()
        plt.ylabel("Horizontal Velocity (m/s)")
        plt.xlabel("Time (s)")
        left, right = plt.xlim()
        plt.xlim(left, 1.4)
        plt.savefig(os.path.join(self.output_dir, 'v_vs_t.png'))
        plt.show()
コード例 #13
0
ファイル: hydrostatic_tank.py プロジェクト: yang7857854/pysph
    def post_process(self, info_fname):
        self.read_info(info_fname)
        if len(self.output_files) == 0:
            return

        from pysph.tools.interpolator import Interpolator
        from pysph.solver.utils import iter_output
        files = self.output_files
        y = np.linspace(0, 0.9, 20)
        x = np.ones_like(y)
        interp = None
        t, p, p_ex = [], [], []
        for sd, arrays in iter_output(files):
            fluid, solid = arrays['fluid'], arrays['solid']
            if interp is None:
                interp = Interpolator([fluid, solid], x=x, y=y)
            else:
                interp.update_particle_arrays([fluid, solid])
            t.append(sd['t'])
            p.append(interp.interpolate('p'))
            g = 1.0 * damping_factor(t[-1], tdamp)
            p_ex.append(abs(rho0 * H * g))

        t, p, p_ex = list(map(np.asarray, (t, p, p_ex)))
        res = os.path.join(self.output_dir, 'results.npz')
        np.savez(res, t=t, p=p, p_ex=p_ex, y=y)

        import matplotlib
        matplotlib.use('Agg')

        pmax = abs(0.9 * rho0 * gy)

        from matplotlib import pyplot as plt
        plt.plot(t, p[:, 0] / pmax, 'o-')
        plt.xlabel(r'$t$')
        plt.ylabel(r'$p$')
        fig = os.path.join(self.output_dir, 'p_bottom.png')
        plt.savefig(fig, dpi=300)

        plt.clf()
        output_at = np.arange(0.25, 2.1, 0.25)
        count = 0
        for i in range(len(t)):
            if abs(t[i] - output_at[count]) < 1e-8:
                plt.plot(y, p[i] / pmax, 'o', label='t=%.2f' % t[i])
                plt.plot(y, p_ex[i] * (H - y) / (H * pmax), 'k-')
                count += 1
        plt.xlabel('$y$')
        plt.ylabel('$p$')
        plt.legend()
        fig = os.path.join(self.output_dir, 'p_vs_y.png')
        plt.savefig(fig, dpi=300)
コード例 #14
0
 def post_processing(self):
     files = get_files('stacked-particles_output')
     t = []
     y1 = []
     y2 = []
     for solver_data, sand, in iter_output(files, 'sand'):
         t.append(solver_data['t'])
         y1.append(sand.y[0])
         y2.append(sand.y[1])
     print("Done")
     plt.plot(t, y1)
     # plt.plot(t, y2)
     plt.show()
コード例 #15
0
ファイル: test_3.py プロジェクト: dineshadepu/mtechReport
 def post_processing(self):
     files = get_files('test_3_output')
     t = []
     y1 = []
     y2 = []
     for solver_data, mg, al in iter_output(files, 'mg', 'al'):
         t.append(solver_data['t'])
         y2.append(-mg.u[0])
         y1.append(-al.u[0])
     print("Done")
     print(y1)
     print(y1[-1] / 3.9)
     print(y2[-1] / 3.9)
コード例 #16
0
 def post_processing(self):
     files = get_files('test_2_output')
     t = []
     y1 = []
     y2 = []
     for solver_data, mg, al in iter_output(files, 'mg', 'al'):
         t.append(solver_data['t'])
         y1.append(-mg.fx[0])
         y2.append(-al.fx[0])
     print("Done")
     plt.plot(t, y1)
     plt.plot(t, y2)
     plt.title("Force in overlap")
     plt.xlabel("time")
     plt.ylabel("Force")
     plt.show()
コード例 #17
0
ファイル: dcdem.py プロジェクト: dineshadepu/mtechReport
 def post_processing(self):
     files = get_files('dcdem_output')
     t = []
     y1 = []
     y2 = []
     for solver_data, glass, lime in iter_output(files, 'glass', 'lime'):
         t.append(solver_data['t'])
         y1.append(-glass.fx[0])
         y2.append(-lime.fx[0])
     print("Done")
     plt.plot(t, y1)
     plt.plot(t, y2)
     plt.title("Force in overlap")
     plt.xlabel("time")
     plt.ylabel("Force")
     plt.show()
コード例 #18
0
    def _plot_force_vs_t(self):
        from pysph.solver.utils import iter_output
        prop = [
            'awhat', 'auhat', 'avhat', 'wg', 'vg', 'ug', 'uf', 'vf', 'wf',
            'wij', 'vmag'
        ]
        # We find the force of the solid on the fluid and the opposite of that
        # is the force on the solid. Note that the assumption is that the solid
        # is far from the inlet and outlet so those are ignored.
        sph_eval = self._get_force_evaluator()

        t, cd, cl = [], [], []
        for sd, arrays in iter_output(self.output_files):
            fluid = arrays['fluid']
            solid = arrays['solid']
            for p in prop:
                solid.add_property(p)
                fluid.add_property(p)
            t.append(sd['t'] * diameter / umax)
            sph_eval.update_particle_arrays([solid, fluid])
            sph_eval.evaluate()
            cd.append(
                np.sum(solid.au * solid.m) / (0.5 * rho * umax**2 * diameter))
            cl.append(
                np.sum(solid.av * solid.m) / (0.5 * rho * umax**2 * diameter))
        t, cd, cl = list(map(np.asarray, (t, cd, cl)))
        # Now plot the results.
        import matplotlib
        matplotlib.use('Agg')
        from matplotlib import pyplot as plt
        plt.figure()
        plt.plot(t, cd, label=r'$C_d$')
        plt.plot(t, cl, label=r'$C_l$')
        plt.xlabel(r'$t$')
        plt.ylabel('$C_d$/$C_l$')
        plt.legend()
        fig = os.path.join(self.output_dir, "lift_drag_vs_t.png")
        plt.savefig(fig, dpi=300)
        plt.close()
        return t, cd, cl
コード例 #19
0
    def post_process(self, info_fname):
        self.read_info(info_fname)
        if len(self.output_files) == 0:
            return

        from pysph.solver.utils import iter_output
        import matplotlib.pyplot as plt
        from pysph.examples import db_exp_data as dbd
        from pysph.tools.interpolator import Interpolator
        H = 1.0
        factor_y = 1 / (ro * g * H)
        factor_x = np.sqrt(g / H)

        data_t, data_p0 = dbd.get_buchner_data()
        files = self.output_files

        t = []
        p0 = []
        for sd, arrays1, arrays2 in iter_output(files, "fluid", "boundary"):
            t.append(sd["t"] * factor_x)
            interp = Interpolator([arrays1, arrays2],
                                  x=[container_width],
                                  y=[H * 0.2],
                                  method=self.interp_method)
            p0.append(interp.interpolate('p') * factor_y)

        plt.plot(t, p0, label="Computed")

        fname = os.path.join(self.output_dir, 'results.npz')
        t, p0 = list(map(np.asarray, (t, p0)))
        np.savez(fname, t=t, p0=p0)

        plt.scatter(data_t,
                    data_p0,
                    color=(0, 0, 0),
                    label="Experiment (Buchner, 2002)")
        plt.legend()
        plt.ylabel(r"$\frac{P}{\rho gH}$")
        plt.xlabel(r"$t \sqrt{\frac{g}{H}}$")
        plt.savefig(os.path.join(self.output_dir, 'p_vs_t.png'))
コード例 #20
0
ファイル: test_6.py プロジェクト: dineshadepu/mtechReport
 def post_processing(self):
     files = get_files('test_6_output')
     t = []
     u1 = []
     v1 = []
     u2 = []
     v2 = []
     for solver_data, al, nylon in iter_output(files, 'al', 'nylon'):
         t.append(solver_data['t'])
         u1.append(-al.u[0])
         v1.append(-al.v[0])
         u2.append(-nylon.u[0])
         v2.append(-nylon.v[0])
     print("Done")
     # aluminium
     print('aluminium')
     print(u1)
     print(v1)
     print(v1[-1] / u1[-1])
     # nylon
     print('nylon')
     print(u2)
     print(v2)
     print(v2[-1] / u2[-1])
コード例 #21
0
    def _plot_cd_vs_t(self):
        from pysph.solver.utils import iter_output, load
        from pysph.tools.sph_evaluator import SPHEvaluator
        from pysph.sph.equation import Group
        from pysph.sph.wc.transport_velocity import (SetWallVelocity,
            MomentumEquationPressureGradient, SolidWallNoSlipBC,
            SolidWallPressureBC, VolumeSummation)

        data = load(self.output_files[0])
        solid = data['arrays']['solid']
        fluid = data['arrays']['fluid']
        x, y = solid.x.copy(), solid.y.copy()
        cx = 0.5 * L; cy = 0.5 * H
        inside = np.sqrt((x-cx)**2 + (y-cy)**2) <= a
        dest = solid.extract_particles(inside.nonzero()[0])
        # We use the same equations for this as the simulation, except that we
        # do not include the acceleration terms as these are externally
        # imposed.  The goal of these is to find the force of the fluid on the
        # cylinder, thus, gx=0.0 is used in the following.
        equations = [
            Group(
                equations=[
                    VolumeSummation(
                        dest='fluid', sources=['fluid', 'solid']
                    ),
                    VolumeSummation(
                        dest='solid', sources=['fluid', 'solid']
                    ),
                    ], real=False),

            Group(
                equations=[
                    SetWallVelocity(dest='solid', sources=['fluid']),
                    ], real=False),

            Group(
                equations=[
                    SolidWallPressureBC(dest='solid', sources=['fluid'],
                                        gx=0.0, b=1.0, rho0=rho0, p0=p0),
                    ], real=False),

            Group(
                equations=[
                    # Pressure gradient terms
                    MomentumEquationPressureGradient(
                        dest='fluid', sources=['solid'], gx=0.0, pb=pb),
                    SolidWallNoSlipBC(
                        dest='fluid', sources=['solid'], nu=nu),
                    ], real=True),
        ]

        sph_eval = SPHEvaluator(
            arrays=[dest, fluid], equations=equations, dim=2,
            kernel=QuinticSpline(dim=2)
        )

        t, cd = [], []
        for sd, fluid in iter_output(self.output_files, 'fluid'):
            fluid.remove_property('vmag2')
            t.append(sd['t'])
            sph_eval.update_particle_arrays([dest, fluid])
            sph_eval.evaluate()
            Fx = np.sum(-fluid.au*fluid.m)
            cd.append(Fx/(nu*rho0*Umax))

        t, cd = list(map(np.asarray, (t, cd)))

        # Now plot the results.
        import matplotlib
        matplotlib.use('Agg')

        from matplotlib import pyplot as plt
        f = plt.figure()
        plt.plot(t, cd)
        plt.xlabel('$t$'); plt.ylabel(r'$C_D$')
        fig = os.path.join(self.output_dir, "cd_vs_t.png")
        plt.savefig(fig, dpi=300)
        plt.close()

        return t, cd
コード例 #22
0
    def post_process(self, info_file_or_dir):
        try:
            import matplotlib as mpl
            mpl.use('pgf')
            from matplotlib import pyplot as plt
        except ImportError:
            print("Post processing requires matplotlib.")
            return
        time = []
        F = []

        for sd, array in iter_output(self.output_files, 'top_wall'):
            t = sd['t']
            time.append(t)
            p, x = array.get('p', 'x')
            xmin = min(x)
            force = 0.0
            for press, pos in zip(p, x):
                if pos < xmin + dx / 4:
                    force += press * dx * dx
            F.append(force)

        csv_file = os.path.join(self.output_dir, "force.csv")
        np.savetxt(csv_file, np.c_[time, F], delimiter=',')

        plt.figure()
        plt.plot(time, F, '-k')
        plt.title("Compression Force")
        plt.xlabel('Time t in s')
        plt.ylabel('Force F in N')
        plt.tight_layout()
        pdf_fig = os.path.join(self.output_dir, "force.pdf")
        plt.savefig(pdf_fig)
        try:
            tex_fig = os.path.join(self.output_dir, "force.tex")
            from matplotlib2tikz import save as tikz_save
            tikz_save(tex_fig)
        except ImportError:
            print("Did not write tikz figure.")

        # plot radius
        time = []
        R = []

        for sd, array in iter_output(self.output_files, 'fluid'):
            t = sd['t']
            time.append(t)
            y, z = array.get('y', 'z')
            R.append(max(np.sqrt(y**2 + z**2)))

        csv_file = os.path.join(self.output_dir, "radius.csv")
        np.savetxt(csv_file, np.c_[time, R], delimiter=',')

        plt.figure()
        plt.plot(time, R, '-k')
        plt.title("Radius (max. radial position of particle)")
        plt.xlabel('Time t in s')
        plt.ylabel('Radius R in m')
        plt.tight_layout()
        pdf_fig = os.path.join(self.output_dir, "radius.pdf")
        plt.savefig(pdf_fig)
        try:
            tex_fig = os.path.join(self.output_dir, "radius.tex")
            from matplotlib2tikz import save as tikz_save
            tikz_save(tex_fig)
        except ImportError:
            print("Did not write tikz figure.")

        # plot pressure at center
        time = []
        press = []

        for sd, array in iter_output(self.output_files, 'fluid'):
            t = sd['t']
            time.append(t)
            p, y, z = array.get('p', 'y', 'z')
            idx = np.where(np.sqrt(y**2 + z**2) < 0.1 * self.D)
            press.append(np.average(p[idx]))

        csv_file = os.path.join(self.output_dir, "pressure.csv")
        np.savetxt(csv_file, np.c_[time, press], delimiter=',')

        plt.figure()
        plt.plot(time, press, '-k')
        plt.title("Pressure at center")
        plt.xlabel('Time t in s')
        plt.ylabel('Pressure p in Pa')
        plt.tight_layout()
        pdf_fig = os.path.join(self.output_dir, "pressure.pdf")
        plt.savefig(pdf_fig)
        try:
            tex_fig = os.path.join(self.output_dir, "pressure.tex")
            from matplotlib2tikz import save as tikz_save
            tikz_save(tex_fig)
        except ImportError:
            print("Did not write tikz figure.")
コード例 #23
0
    def post_process(self, info_fname):
        self.read_info(info_fname)
        if len(self.output_files) == 0:
            return

        from pysph.solver.utils import iter_output
        import matplotlib.pyplot as plt
        from pysph.examples import st_exp_data as st
        from pysph.tools.interpolator import Interpolator

        files = self.output_files

        t = []
        p0 = []
        xc0 = 0.0
        for sd, arrays1, arrays2 in iter_output(files, "fluid", "boundary"):
            t.append(sd["t"])
            xc = arrays2.x.mean()
            if sd["t"] == 0:
                xc0 = xc
            # Point 1: Bottom right corner of the tank
            # Point 2: Top right corner of the tank
            # Point 3: Bottom left corner of the tank
            if xc > xc0:
                z1 = arrays2.z.min()
                x2 = arrays2.x.max()
                x1 = arrays2.x[np.where(arrays2.z == z1)[0][0]]
                z2 = arrays2.x[np.where(arrays2.x == x2)[0][0]]
                angle = np.arctan((z2 - z1) / (x2 - x1))
                x3 = arrays2.x.min()
                z3 = arrays2.z[np.where(arrays2.x == x3)[0][0]]

            if xc <= xc0:
                z2 = arrays2.z.max()
                x1 = arrays2.x.max()
                x2 = arrays2.x[np.where(arrays2.z == z2)[0][0]]
                z1 = arrays2.z[np.where(arrays2.x == x1)[0][0]]
                angle = np.arctan((z2 - z1) / (x2 - x1)) + pi
                z3 = arrays2.z.min()
                x3 = arrays2.x[np.where(arrays2.z == z3)[0][0]]

            if x3 - x1 == 0:
                vec = np.array([-1, 0])
            else:
                vec = np.array([x3 - x1, z3 - z1])
                vec = vec / np.linalg.norm(vec)

            dx = self.dx
            # Probes at 0.17 m above Point 1 and 0.45 m above Point 3
            x_probe = [
                x1 + 0.17 * cos(angle) + 3.25 * dx * vec[0],
                x3 + 0.45 * cos(angle) - 3.25 * dx * vec[0]
            ]
            z_probe = [
                z1 + 0.17 * sin(angle) + 3.25 * dx * vec[1],
                z3 + 0.45 * sin(angle) - 3.25 * dx * vec[1]
            ]
            y_probe = [0, 0]
            interp = Interpolator([arrays1, arrays2],
                                  x=x_probe,
                                  y=y_probe,
                                  z=z_probe,
                                  method=self.interp_method)
            p0.append(interp.interpolate('p'))

        p0 = np.array(p0)
        p2 = p0.T[0] / 1000
        p8 = p0.T[1] / 1000

        p2_avg, p8_avg = p2, p8

        fname = os.path.join(self.output_dir, 'results.npz')
        t, p0 = list(map(np.asarray, (t, p0)))
        np.savez(fname, t=t, p0=p0)

        exp_t2, exp_p2, exp_t8, exp_p8 = st.get_au_pitch_data()

        figure_1 = plt.figure()
        # Probe 2
        plt.plot(t[:-10], p2_avg[:-10], label="Computed", figure=figure_1)
        plt.scatter(exp_t2,
                    exp_p2,
                    color=(0, 0, 0),
                    label="Experiment (Akyildiz and Unal, 2006)",
                    figure=figure_1)
        plt.title("P2 v/s t")
        plt.legend()
        plt.ylabel("Pressue [KPa]")
        plt.xlabel("Time [s]")
        plt.xlim(3, 10)
        plt.savefig(os.path.join(self.output_dir, 'p2_vs_t.png'))
        plt.show()

        figure_2 = plt.figure()
        # Probe 8
        plt.plot(t, p8_avg, label="Computed", figure=figure_2)
        plt.scatter(exp_t8,
                    exp_p8,
                    color=(0, 0, 0),
                    label="Experiment (Akyildiz and Unal, 2006)",
                    figure=figure_2)
        plt.title("P8 v/s t")
        plt.legend()
        plt.ylabel("Pressue [KPa]")
        plt.xlabel("Time [s]")
        plt.xlim(3, 10)
        plt.savefig(os.path.join(self.output_dir, 'p8_vs_t.png'))
        plt.show()
コード例 #24
0
    def post_process(self, info_fname):
        info = self.read_info(info_fname)
        if len(self.output_files) == 0:
            return

        from pysph.solver.utils import iter_output
        decay_rate = -8.0 * np.pi**2 / self.re
        U = self.U

        files = self.output_files
        t, ke, ke_ex, decay, linf, l1, p_l1 = [], [], [], [], [], [], []
        for sd, array in iter_output(files, 'fluid'):
            _t = sd['t']
            t.append(_t)
            x, y, m, u, v, p = self._get_post_process_props(array)
            u_e, v_e, p_e = exact_solution(U, decay_rate, _t, x, y)
            vmag2 = u**2 + v**2
            vmag = np.sqrt(vmag2)
            ke.append(0.5 * np.sum(m * vmag2))
            vmag2_e = u_e**2 + v_e**2
            vmag_e = np.sqrt(vmag2_e)
            ke_ex.append(0.5 * np.sum(m * vmag2_e))

            vmag_max = vmag.max()
            decay.append(vmag_max)
            theoretical_max = U * np.exp(decay_rate * _t)
            linf.append(abs((vmag_max - theoretical_max) / theoretical_max))

            l1_err = np.average(np.abs(vmag - vmag_e))
            avg_vmag_e = np.average(np.abs(vmag_e))
            # scale the error by the maximum velocity.
            l1.append(l1_err / avg_vmag_e)

            p_e_max = np.abs(p_e).max()
            p_error = np.average(np.abs(p - p_e)) / p_e_max
            p_l1.append(p_error)

        t, ke, ke_ex, decay, l1, linf, p_l1 = list(
            map(np.asarray, (t, ke, ke_ex, decay, l1, linf, p_l1)))
        decay_ex = U * np.exp(decay_rate * t)
        fname = os.path.join(self.output_dir, 'results.npz')
        np.savez(fname,
                 t=t,
                 ke=ke,
                 ke_ex=ke_ex,
                 decay=decay,
                 linf=linf,
                 l1=l1,
                 p_l1=p_l1,
                 decay_ex=decay_ex)

        import matplotlib
        matplotlib.use('Agg')

        from matplotlib import pyplot as plt
        plt.clf()
        plt.semilogy(t, decay_ex, label="exact")
        plt.semilogy(t, decay, label="computed")
        plt.xlabel('t')
        plt.ylabel('max velocity')
        plt.legend()
        fig = os.path.join(self.output_dir, "decay.png")
        plt.savefig(fig, dpi=300)

        plt.clf()
        plt.plot(t, linf)
        plt.xlabel('t')
        plt.ylabel(r'$L_\infty$ error')
        fig = os.path.join(self.output_dir, "linf_error.png")
        plt.savefig(fig, dpi=300)

        plt.clf()
        plt.plot(t, l1, label="error")
        plt.xlabel('t')
        plt.ylabel(r'$L_1$ error')
        fig = os.path.join(self.output_dir, "l1_error.png")
        plt.savefig(fig, dpi=300)

        plt.clf()
        plt.plot(t, p_l1, label="error")
        plt.xlabel('t')
        plt.ylabel(r'$L_1$ error for $p$')
        fig = os.path.join(self.output_dir, "p_l1_error.png")
        plt.savefig(fig, dpi=300)
コード例 #25
0
    def _plot_force_vs_t(self):
        from pysph.solver.utils import iter_output, load
        from pysph.tools.sph_evaluator import SPHEvaluator
        from pysph.sph.equation import Group
        from pysph.base.kernels import QuinticSpline
        from pysph.sph.wc.transport_velocity import (
            MomentumEquationPressureGradient, SummationDensity,
            SetWallVelocity)

        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', 'pavg', 'nnbr', 'auf', 'avf', 'awf'
        ]
        for p in prop:
            solid.add_property(p)
            fluid.add_property(p)

        # We find the force of the solid on the fluid and the opposite of that
        # is the force on the solid. Note that the assumption is that the solid
        # is far from the inlet and outlet so those are ignored.
        print(self.nu, p0, self.dc, rho)
        equations = [
            Group(equations=[
                SummationDensity(dest='fluid', sources=['fluid', 'solid']),
                SummationDensity(dest='solid', sources=['fluid', 'solid']),
                SetWallVelocity(dest='solid', sources=['fluid']),
            ],
                  real=False),
            Group(
                equations=[
                    # Pressure gradient terms
                    MomentumEquationPressureGradient(dest='solid',
                                                     sources=['fluid'],
                                                     pb=p0),
                    SolidWallNoSlipBCReverse(dest='solid',
                                             sources=['fluid'],
                                             nu=self.nu),
                ],
                real=True),
        ]
        sph_eval = SPHEvaluator(arrays=[solid, fluid],
                                equations=equations,
                                dim=2,
                                kernel=QuinticSpline(dim=2))
        t, cd, cl = [], [], []
        import gc
        print(self.dc, self.dx, self.nu)
        print('fxf', 'fxp', 'fyf', 'fyp', 'cd', 'cl', 't')
        for sd, arrays in iter_output(self.output_files[:]):
            fluid = arrays['fluid']
            solid = arrays['solid']
            for p in prop:
                solid.add_property(p)
                fluid.add_property(p)
            t.append(sd['t'])
            sph_eval.update_particle_arrays([solid, fluid])
            sph_eval.evaluate()
            fxp = sum(solid.m * solid.au)
            fyp = sum(solid.m * solid.av)
            fxf = sum(solid.m * solid.auf)
            fyf = sum(solid.m * solid.avf)
            fx = fxf + fxp
            fy = fyf + fyp
            cd.append(fx / (0.5 * rho * umax**2 * self.dc))
            cl.append(fy / (0.5 * rho * umax**2 * self.dc))
            print(fxf, fxp, fyf, fyp, cd[-1], cl[-1], t[-1])
            gc.collect()
        t, cd, cl = list(map(np.asarray, (t, cd, cl)))
        # Now plot the results.
        import matplotlib
        matplotlib.use('Agg')
        from matplotlib import pyplot as plt
        plt.figure()
        plt.plot(t, cd, label=r'$C_d$')
        plt.plot(t, cl, label=r'$C_l$')
        plt.xlabel(r'$t$')
        plt.ylabel('cd/cl')
        plt.legend()
        plt.grid()
        fig = os.path.join(self.output_dir, "force_vs_t.png")
        plt.savefig(fig, dpi=300)
        plt.close()
        return t, cd, cl