Exemple #1
0
def comparison_plot(f, u, Omega, plotfile='tmp'):
    """Compare f(x,y) and u(x,y) for x,y in Omega in a plot."""
    x, y = sm.symbols('x y')

    f = sm.lambdify([x,y], f, modules="numpy")
    u = sm.lambdify([x,y], u, modules="numpy")
    # When doing symbolics, Omega can easily contain symbolic expressions,
    # assume .evalf() will work in that case to obtain numerical
    # expressions, which then must be converted to float before calling
    # linspace below
    for r in range(2):
        for s in range(2):
            if not isinstance(Omega[r][s], (int,float)):
                Omega[r][s] = float(Omega[r][s].evalf())

    resolution = 41  # no of points in plot
    xcoor = linspace(Omega[0][0], Omega[0][1], resolution)
    ycoor = linspace(Omega[1][0], Omega[1][1], resolution)
    xv, yv = ndgrid(xcoor, ycoor)
    # Vectorized functions expressions does not work with
    # lambdify'ed functions without the modules="numpy"
    exact  = f(xv, yv)
    approx = u(xv, yv)
    figure()
    surfc(xv, yv, exact, title='f(x,y)',
          colorbar=True, colormap=hot(), shading='flat')
    if plotfile:
        savefig('%s_f.pdf' % plotfile, color=True)
        savefig('%s_f.png' % plotfile)
    figure()
    surfc(xv, yv, approx, title='f(x,y)',
          colorbar=True, colormap=hot(), shading='flat')
    if plotfile:
        savefig('%s_u.pdf' % plotfile, color=True)
        savefig('%s_u.png' % plotfile)
Exemple #2
0
    def plot_u(u, x, xv, y, yv, t, n):
        """User action function for plotting."""
        if t[n] == 0:
            time.sleep(2)
        if plot_method == 1:
            # Works well with Gnuplot backend, not with Matplotlib
            st.mesh(x, y, u, title='t=%g' % t[n], zlim=[-1,1],
                    caxis=[-1,1])
        elif plot_method == 2:
            # Works well with Gnuplot backend, not with Matplotlib
            st.surfc(xv, yv, u, title='t=%g' % t[n], zlim=[-1, 1],
                  colorbar=True, colormap=st.hot(), caxis=[-1,1],
                  shading='flat')
        elif plot_method == 3:
            print 'Experimental 3D matplotlib...under development...'
            # Probably too slow
            #plt.clf()
            ax = fig.add_subplot(111, projection='3d')
            u_surf = ax.plot_surface(xv, yv, u, alpha=0.3)
            #ax.contourf(xv, yv, u, zdir='z', offset=-100, cmap=cm.coolwarm)
            #ax.set_zlim(-1, 1)
            # Remove old surface before drawing
            if u_surf is not None:
                ax.collections.remove(u_surf)
            plt.draw()
            time.sleep(1)
        elif plot_method == 4:
	    # Mayavi visualization
            mlab.clf()
            extent1 = (0, 20, 0, 20,-2, 2)
            s = mlab.surf(x , y, u,
                          colormap='Blues',
                          warp_scale=5,extent=extent1)
            mlab.axes(s, color=(.7, .7, .7), extent=extent1,
                      ranges=(0, 10, 0, 10, -1, 1),
                      xlabel='', ylabel='', zlabel='',
                      x_axis_visibility=False,
                      z_axis_visibility=False)
            mlab.outline(s, color=(0.7, .7, .7), extent=extent1)
            mlab.text(6, -2.5, '', z=-4, width=0.14)
            mlab.colorbar(object=None, title=None,
                          orientation='horizontal',
                          nb_labels=None, nb_colors=None,
                          label_fmt=None)
            mlab.title('Gaussian t=%g' % t[n])
            mlab.view(142, -72, 50)
            f = mlab.gcf()
            camera = f.scene.camera
            camera.yaw(0)

        if plot_method > 0:
            time.sleep(0) # pause between frames
            if save_plot:
                filename = 'tmp_%04d.png' % n
		if plot_method == 4:
                    mlab.savefig(filename)  # time consuming!
		elif plot_method in (1,2):
                    st.savefig(filename)  # time consuming!
    def plot_u(u, x, xv, y, yv, t, n):
        """User action function for plotting."""
        if t[n] == 0:
            time.sleep(2)
        if plot_method == 1:
            # Works well with Gnuplot backend, not with Matplotlib
            st.mesh(x, y, u, title='t=%g' % t[n], zlim=[-1, 1], caxis=[-1, 1])
        elif plot_method == 2:
            # Works well with Gnuplot backend, not with Matplotlib
            st.surfc(xv,
                     yv,
                     u,
                     title='t=%g' % t[n],
                     zlim=[-1, 1],
                     colorbar=True,
                     colormap=st.hot(),
                     caxis=[-1, 1],
                     shading='flat')
        elif plot_method == 3:
            print 'Experimental 3D matplotlib...under development...'
            # Probably too slow
            #plt.clf()
            ax = fig.add_subplot(111, projection='3d')
            u_surf = ax.plot_surface(xv, yv, u, alpha=0.3)
            #ax.contourf(xv, yv, u, zdir='z', offset=-100, cmap=cm.coolwarm)
            #ax.set_zlim(-1, 1)
            # Remove old surface before drawing
            if u_surf is not None:
                ax.collections.remove(u_surf)
            plt.draw()
            time.sleep(1)
        elif plot_method == 4:
            # Mayavi visualization
            mlab.clf()
            extent1 = (0, 20, 0, 20, -2, 2)
            s = mlab.surf(x,
                          y,
                          u,
                          colormap='Blues',
                          warp_scale=5,
                          extent=extent1)
            mlab.axes(s,
                      color=(.7, .7, .7),
                      extent=extent1,
                      ranges=(0, 10, 0, 10, -1, 1),
                      xlabel='',
                      ylabel='',
                      zlabel='',
                      x_axis_visibility=False,
                      z_axis_visibility=False)
            mlab.outline(s, color=(0.7, .7, .7), extent=extent1)
            mlab.text(6, -2.5, '', z=-4, width=0.14)
            mlab.colorbar(object=None,
                          title=None,
                          orientation='horizontal',
                          nb_labels=None,
                          nb_colors=None,
                          label_fmt=None)
            mlab.title('Gaussian t=%g' % t[n])
            mlab.view(142, -72, 50)
            f = mlab.gcf()
            camera = f.scene.camera
            camera.yaw(0)

        if plot_method > 0:
            time.sleep(0)  # pause between frames
            if save_plot:
                filename = 'tmp_%04d.png' % n
                if plot_method == 4:
                    mlab.savefig(filename)  # time consuming!
                elif plot_method in (1, 2):
                    st.savefig(filename)  # time consuming!
Exemple #4
0
    def project5f(self):
        '''2D surface plots '''
        dxValues = [0.1]  #, 0.01]
        safetyFacors = [1.04]  #[0.8]
        movieCounter = 0
        dimension = "2D"
        threadNumber = 8
        FontSizeUniversal = 22
        showMovie = True
        for dx in dxValues:
            nx = int(round(1. / dx + 1))
            x = np.linspace(0, 1, nx)
            y = x
            X, Y = np.meshgrid(x, y)
            for safetyFactor in safetyFacors:
                movieCounter += 1
                dt = dx**2 / 4.0 * (1 / safetyFactor)
                alpha = dt / dx**2
                theta = 0.5
                T = .15
                nT = int(round(T / dt + 1))
                outfileName = 'out5f'
                outfileName2 = os.getcwd() + '/results/' + outfileName
                saveEveryNSolution = 10

                self.runCpp(outfileName2, dt, dx, theta, T, dimension,
                            threadNumber)

                # Read data
                scenerios = ['Explicit', 'Analytical']
                xv = x.reshape((x.size, 1))
                yv = y.reshape((1, y.size))
                fileCounter = 1
                st.setp(interactive=False)
                if showMovie:
                    for fileCounter in xrange(1, nT):
                        data = pd.read_csv(
                            outfileName2 +
                            'ImplicitSolutionMatrixUTime%d.txt' % fileCounter,
                            delim_whitespace=True,
                            header=None)
                        st.surfc(xv,
                                 yv,
                                 data,
                                 title='Implicit Time = %.4f' %
                                 ((fileCounter - 1) * dt),
                                 zlim=[-0.1, 1.1],
                                 colorbar=True,
                                 colormap=st.hot(),
                                 caxis=[-0.1, 1.1],
                                 shading='flat',
                                 xlabel='x',
                                 ylabel='y',
                                 zlabel='u')  #
                        st.savefig('movie/tmpImplicit_%04d' % fileCounter +
                                   outfileName + '.png')

                        data2 = pd.read_csv(
                            outfileName2 +
                            'ExplicitSolutionMatrixUTime%d.txt' % fileCounter,
                            delim_whitespace=True,
                            header=None)

                        st.surfc(xv,
                                 yv,
                                 data2,
                                 title='Explicit Time = %.4f' %
                                 ((fileCounter - 1) * dt),
                                 zlim=[-0.1, 1.1],
                                 colorbar=True,
                                 colormap=st.hot(),
                                 caxis=[-0.1, 1.1],
                                 shading='flat',
                                 xlabel='x',
                                 ylabel='y',
                                 zlabel='u')  #
                        st.savefig('movie/tmpExplicit_%04d' % fileCounter +
                                   outfileName + '.png')

                        data3 = pd.read_csv(
                            outfileName2 +
                            'AnalyticalSolutionMatrixU2D%d.txt' % fileCounter,
                            delim_whitespace=True,
                            header=None)
                        st.surfc(xv,
                                 yv,
                                 data3,
                                 title='Analytical Time = %.4f' %
                                 ((fileCounter - 1) * dt),
                                 fontsize=30,
                                 zlim=[-0.1, 1.1],
                                 colorbar=True,
                                 colormap=st.hot(),
                                 caxis=[-0.1, 1.1],
                                 shading='flat',
                                 xlabel='x',
                                 ylabel='y',
                                 zlabel='u')  #
                        st.savefig('movie/tmpAnalytic_%04d' % fileCounter +
                                   outfileName + '.png')

                        data4 = pd.read_csv(
                            outfileName2 +
                            'GaussSeidelSolutionMatrixUTime%d.txt' %
                            fileCounter,
                            delim_whitespace=True,
                            header=None)
                        st.surfc(xv,
                                 yv,
                                 data4,
                                 title='Gauss-Seidel Time = %.4f' %
                                 ((fileCounter - 1) * dt),
                                 fontsize=30,
                                 zlim=[-0.1, 1.1],
                                 colorbar=True,
                                 colormap=st.hot(),
                                 caxis=[-0.1, 1.1],
                                 shading='flat',
                                 xlabel='x',
                                 ylabel='y',
                                 zlabel='u')  #
                        st.savefig('movie/tmpGaussSeidel_%04d' % fileCounter +
                                   outfileName + '.png')

                        st.surfc(xv,
                                 yv, (data / data3 - 1) * 100,
                                 title='Implicit-Analytical time = %.4f' %
                                 ((fileCounter - 1) * dt),
                                 zlim=[-100.1, 100.1],
                                 colorbar=True,
                                 colormap=st.hot(),
                                 caxis=[-100.1, 100.1],
                                 shading='flat',
                                 xlabel='x',
                                 ylabel='y',
                                 zlabel='u')  #
                        st.savefig('movie/tmpErrorImplicit_%04d' %
                                   fileCounter + outfileName + '.png')

                        st.surfc(xv,
                                 yv, (data2 / data3 - 1) * 100,
                                 title='Explicit-Analytical time = %.4f' %
                                 ((fileCounter - 1) * dt),
                                 zlim=[-100.1, 100.1],
                                 colorbar=True,
                                 colormap=st.hot(),
                                 caxis=[-100.1, 100.1],
                                 shading='flat',
                                 xlabel='x',
                                 ylabel='y',
                                 zlabel='u')  #
                        st.savefig('movie/tmpErrorExplicit_%04d' %
                                   fileCounter + outfileName + '.png')

        data = pd.read_csv(outfileName2 + 'Timing.txt', delimiter=',')

        width = 0.35
        fig, ax = plt.subplots()
        rects1 = ax.bar(np.arange(3), [
            np.asscalar(data.implicit.values),
            np.asscalar(data.analytic.values),
            np.asscalar(data.analytic.values) /
            np.asscalar(data.implicit.values)
        ], width)  #, color='r')
        fontSizes = 20
        ax.set_title('Timing Numerical and analytical', fontsize=fontSizes)
        ax.set_xticks(np.arange(3) + width / 10)
        ax.set_xticklabels(
            ('Implicit', 'Analytical', r'$\frac{Analytical}{Numerical}$'))
        #plt.show()
        fig.tight_layout()
        plt.savefig(outfileName2 + 'Timing.png')
        return data