Ejemplo n.º 1
0
 def get_A_GaNi(self, N, primaldual='primal', tensor=True):
     """
     Returns stiffness matrix for a scheme with trapezoidal quadrature rule.
     """
     coord = Grid.get_coordinates(N, self.Y)
     A = self.evaluate(coord, tensor=tensor)
     if primaldual is 'dual':
         A = A.inv()
     return A.shift()
Ejemplo n.º 2
0
 def get_A_GaNi(self, N, primaldual='primal', tensor=True):
     """
     Returns stiffness matrix for a scheme with trapezoidal quadrature rule.
     """
     coord = Grid.get_coordinates(N, self.Y)
     A = self.evaluate(coord, tensor=tensor)
     if primaldual is 'dual':
         A = A.inv()
     return A.shift()
Ejemplo n.º 3
0
 def savefig(self, fname='material.pdf', N=50*np.ones(2)):
     import pylab as pl
     pl.figure(num=None, figsize=(3,3), dpi=1000)
     coord = Grid.get_coordinates(N, self.Y)
     vals = self.evaluate(coord)[0, 0]
     pl.pcolor(coord[0], coord[1], -vals)
     pl.xlim([-self.Y[0]/2, self.Y[0]/2])
     pl.ylim([-self.Y[1]/2, self.Y[1]/2])
     pl.xlabel(r'coordinate $x_1$')
     pl.ylabel(r'coordinate $x_2$')
     pl.savefig(fname, pad_inches=0.02, bbox_inches='tight')
     pl.close()
Ejemplo n.º 4
0
 def savefig(self, fname='material.pdf', N=50 * np.ones(2)):
     import pylab as pl
     pl.figure(num=None, figsize=(3, 3), dpi=1000)
     coord = Grid.get_coordinates(N, self.Y)
     vals = self.evaluate(coord)[0, 0]
     pl.pcolor(coord[0], coord[1], -vals)
     pl.xlim([-self.Y[0] / 2, self.Y[0] / 2])
     pl.ylim([-self.Y[1] / 2, self.Y[1] / 2])
     pl.xlabel(r'coordinate $x_1$')
     pl.ylabel(r'coordinate $x_2$')
     pl.savefig(fname, pad_inches=0.02, bbox_inches='tight')
     pl.close()
Ejemplo n.º 5
0
    def plot(self, ind=slice(None), N=None, filen=None, ptype='imshow'):
        if N is None:
            N = self.N

        from mpl_toolkits.mplot3d import axes3d
        import matplotlib.pyplot as plt
        from ffthompy.trigpol import Grid

        coord = Grid.get_coordinates(N, self.Y)

        Z = self.project(N)
        Z = Z.val[ind]
        if self.Fourier:
            Z = np.abs(Z)

        if Z.ndim != 2:
            raise ValueError("The plotting is suited only for dim=2!")

        fig = plt.figure()
        if ptype in ['wireframe']:
            ax = fig.add_subplot(111, projection='3d')
            ax.plot_wireframe(coord[-2], coord[-1], Z)
        elif ptype in ['surface']:
            from matplotlib import cm
            ax = fig.gca(projection='3d')
            surf = ax.plot_surface(coord[-2],
                                   coord[-1],
                                   Z,
                                   rstride=1,
                                   cstride=1,
                                   cmap=cm.coolwarm,
                                   linewidth=0,
                                   antialiased=False)

            fig.colorbar(surf, shrink=0.5, aspect=5)
        elif ptype in ['imshow']:
            ax = plt.imshow(Z)
            plt.colorbar(ax)

        if filen is None:
            plt.show()
        else:
            plt.savefig(filen)
Ejemplo n.º 6
0
    def plot(self, ind=slice(None), N=None, filen=None, ptype='imshow'):
        assert(not self.Fourier)
        if N is None:
            N = self.N

        from mpl_toolkits.mplot3d import axes3d
        import matplotlib.pyplot as plt
        from ffthompy.trigpol import Grid

        coord=Grid.get_coordinates(N, self.Y)

        Z=self.project(N)
        Z = Z.val[ind]

        if Z.ndim != 2:
            raise ValueError("The plotting is suited only for dim=2!")

        fig = plt.figure()
        if ptype in ['wireframe']:
            ax = fig.add_subplot(111, projection='3d')
            ax.plot_wireframe(coord[-2], coord[-1], Z)
        elif ptype in ['surface']:
            from matplotlib import cm
            ax = fig.gca(projection='3d')
            surf = ax.plot_surface(coord[-2], coord[-1], Z,
                                   rstride=1, cstride=1, cmap=cm.coolwarm,
                                   linewidth=0, antialiased=False)

            fig.colorbar(surf, shrink=0.5, aspect=5)
        elif ptype in ['imshow']:
            ax = plt.imshow(Z)
            plt.colorbar(ax)

        if filen is None:
            plt.show()
        else:
            plt.savefig(filen)
Ejemplo n.º 7
0
    def plot(self, ind=0, N=None, filen=None, Y=None, ptype='surface'):
        dim=self.N.size
        if dim!=2:
            raise ValueError("The plotting is suited only for dim=2!")
        if Y is None:
            Y=np.ones(dim)
        if N is None:
            N=self.N

        from mpl_toolkits.mplot3d import axes3d
        import matplotlib.pyplot as plt
        from ffthompy.trigpol import Grid
        fig=plt.figure()
        coord=Grid.get_coordinates(N, Y)
        if np.all(np.greater(N, self.N)):
            Z=DFT.ifftnc(enlarge(DFT.fftnc(self.val[ind], self.N), N), N).real
        elif np.all(np.less(N, self.N)):
            Z=DFT.ifftnc(decrease(DFT.fftnc(self.val[ind], self.N), N), N).real
        elif np.allclose(N, self.N):
            Z=self.val[ind]

        if ptype in ['wireframe']:
            ax=fig.add_subplot(111, projection='3d')
            ax.plot_wireframe(coord[0], coord[1], Z)
        elif ptype in ['surface']:
            from matplotlib import cm
            ax=fig.gca(projection='3d')
            surf=ax.plot_surface(coord[0], coord[1], Z,
                                   rstride=1, cstride=1, cmap=cm.coolwarm,
                                   linewidth=0, antialiased=False)
            fig.colorbar(surf, shrink=0.5, aspect=5)

        if filen is None:
            plt.show()
        else:
            plt.savefig(filen)
Ejemplo n.º 8
0
    def plot(self, ind=0, N=None, filen=None, Y=None, ptype='surface'):
        dim=self.N.size
        if dim!=2:
            raise ValueError("The plotting is suited only for dim=2!")
        if Y is None:
            Y=np.ones(dim)
        if N is None:
            N=self.N

        from mpl_toolkits.mplot3d import axes3d
        import matplotlib.pyplot as plt
        from ffthompy.trigpol import Grid
        fig=plt.figure()
        coord=Grid.get_coordinates(N, Y)
        if np.all(np.greater(N, self.N)):
            Z=DFT.ifftnc(enlarge(DFT.fftnc(self.val[ind], self.N), N), N).real
        elif np.all(np.less(N, self.N)):
            Z=DFT.ifftnc(decrease(DFT.fftnc(self.val[ind], self.N), N), N).real
        elif np.allclose(N, self.N):
            Z=self.val[ind]

        if ptype in ['wireframe']:
            ax=fig.add_subplot(111, projection='3d')
            ax.plot_wireframe(coord[0], coord[1], Z)
        elif ptype in ['surface']:
            from matplotlib import cm
            ax=fig.gca(projection='3d')
            surf=ax.plot_surface(coord[0], coord[1], Z,
                                   rstride=1, cstride=1, cmap=cm.coolwarm,
                                   linewidth=0, antialiased=False)
            fig.colorbar(surf, shrink=0.5, aspect=5)

        if filen is None:
            plt.show()
        else:
            plt.savefig(filen)
Ejemplo n.º 9
0
phi_fine = phi.project(M)
print(phi_fine)
print("""The procedure is provided by VecTri.enlarge(M) function, which consists of
a calculation of Fourier coefficients, putting zeros to Fourier coefficients
with high frequencies, and inverse FFT that evaluates the polynomial on
a fine grid.
""")


print("""In order to plot this polynomial, we also set a size of a cell
Y =""")
Y = np.ones(d) # size of a cell
print(Y)
print(""" and evaluate the coordinates of grid points, which are stored in
numpy.ndarray of following shape:
coord.shape =""")
coord = Grid.get_coordinates(M, Y)
print(coord.shape)

if __name__ == "__main__":
    print("""
    Now, the plot of fundamental trigonometric polynomial is shown:""")
    from mpl_toolkits.mplot3d import axes3d
    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.plot_wireframe(coord[0], coord[1], phi_fine.val)
    plt.show()

print('END')
Ejemplo n.º 10
0
    def get_A_Ga(self, Nbar, primaldual='primal', order=-1, P=None):
        """
        Returns stiffness matrix for scheme with exact integration.
        """
        if order == -1:
            if 'order' in self.conf:
                order = self.conf['order']
            else:
                raise ValueError('The material order is undefined!')
        elif order not in [None, 'exact', 0, 1]:
            raise ValueError('Wrong material order (%s)!' % str(order))

        if order in [None, 'exact']: # inclusion-based composite
            shape_funs = self.get_shape_functions(Nbar)
            val = np.zeros(self.conf['vals'][0].shape + shape_funs[0].shape)
            for ii in range(len(self.conf['inclusions'])):
                if primaldual is 'primal':
                    Aincl = self.conf['vals'][ii]
                elif primaldual is 'dual':
                    Aincl = np.linalg.inv(self.conf['vals'][ii])
                val += np.einsum('ij...,k...->ijk...', Aincl, shape_funs[ii])
            name = 'A_Ga'

        else: # grid-based composite
            if P is None and 'P' in self.conf:
                P = self.conf['P']
            coord = Grid.get_coordinates(P, self.Y)
            vals = self.evaluate(coord)

            if primaldual is 'dual':
                vals = vals.inv()

            h = self.Y/P
            if order in [0, 'constant']:
                Wraw = get_weights_con(h, Nbar, self.Y)
            elif order in [1, 'bilinear']:
                Wraw = get_weights_lin(h, Nbar, self.Y)

            val = np.zeros(vals.shape+tuple(Nbar))
            for m,n in itertools.product(*(range(d) for d in vals.shape)):
                hAM0 = np.prod(P)*cfftnc(vals[m, n], P)
                if np.allclose(P, Nbar):
                    hAM = hAM0
                elif np.all(np.greater_equal(P, Nbar)):
                    hAM = decrease(hAM0, Nbar)
                elif np.all(np.less(P, Nbar)):
                    factor = np.ceil(np.array(Nbar, dtype=np.float64) / P)
                    hAM0per = np.tile(hAM0,
                                      2*np.array(factor, dtype=np.int)-1)
                    hAM = decrease(hAM0per, Nbar)
                else:
                    msg = """This combination of double N (%s) and P (%s) "
                        implemented.""" % (str(Nbar), str(P))
                    raise NotImplementedError(msg)

                val[m, n] = np.real(icfftnc(Wraw*hAM, Nbar))

            name = 'A_Ga_o{0}_P{1}'.format(order, np.array(P).max())

        return Tensor(name=name, val=val, N=Nbar, order=2, Y=self.Y, multype=21,
                      Fourier=False, origin='c').shift()
Ejemplo n.º 11
0
    def get_A_Ga(self, Nbar, primaldual='primal', order=-1, P=None):
        """
        Returns stiffness matrix for scheme with exact integration.
        """
        if order == -1:
            if 'order' in self.conf:
                order = self.conf['order']
            else:
                raise ValueError('The material order is undefined!')
        elif order not in [None, 'exact', 0, 1]:
            raise ValueError('Wrong material order (%s)!' % str(order))

        if order in [None, 'exact']:  # inclusion-based composite
            shape_funs = self.get_shape_functions(Nbar)
            val = np.zeros(self.conf['vals'][0].shape + shape_funs[0].shape)
            for ii in range(len(self.conf['inclusions'])):
                if primaldual is 'primal':
                    Aincl = self.conf['vals'][ii]
                elif primaldual is 'dual':
                    Aincl = np.linalg.inv(self.conf['vals'][ii])
                val += np.einsum('ij...,k...->ijk...', Aincl, shape_funs[ii])
            name = 'A_Ga'

        else:  # grid-based composite
            if P is None and 'P' in self.conf:
                P = self.conf['P']
            coord = Grid.get_coordinates(P, self.Y)
            vals = self.evaluate(coord)

            if primaldual is 'dual':
                vals = vals.inv()

            h = self.Y / P
            if order in [0, 'constant']:
                Wraw = get_weights_con(h, Nbar, self.Y)
            elif order in [1, 'bilinear']:
                Wraw = get_weights_lin(h, Nbar, self.Y)

            val = np.zeros(vals.shape + tuple(Nbar))
            for m, n in itertools.product(*(list(range(d))
                                            for d in vals.shape)):
                hAM0 = np.prod(P) * cfftnc(vals[m, n], P)
                if np.allclose(P, Nbar):
                    hAM = hAM0
                elif np.all(np.greater_equal(P, Nbar)):
                    hAM = decrease(hAM0, Nbar)
                elif np.all(np.less(P, Nbar)):
                    factor = np.ceil(np.array(Nbar, dtype=np.float64) / 2 / P)
                    hAM0per = np.tile(hAM0,
                                      2 * np.array(factor, dtype=np.int) + 1)
                    hAM = decrease(hAM0per, Nbar)
                else:
                    msg = """This combination of double N (%s) and P (%s) "
                        implemented.""" % (str(Nbar), str(P))
                    raise NotImplementedError(msg)

                val[m, n] = np.real(icfftnc(Wraw * hAM, Nbar))

            name = 'A_Ga_o{0}_P{1}'.format(order, np.array(P).max())

        return Tensor(name=name,
                      val=val,
                      N=Nbar,
                      order=2,
                      Y=self.Y,
                      multype=21,
                      Fourier=False,
                      origin='c').shift()
Ejemplo n.º 12
0
phi_fine = phi.project(M)
print(phi_fine)
print(
    """The procedure is provided by VecTri.enlarge(M) function, which consists of
a calculation of Fourier coefficients, putting zeros to Fourier coefficients
with high frequencies, and inverse FFT that evaluates the polynomial on
a fine grid.
""")

print("""In order to plot this polynomial, we also set a size of a cell
Y =""")
Y = np.ones(d)  # size of a cell
print(Y)
print(""" and evaluate the coordinates of grid points, which are stored in
numpy.ndarray of following shape:
coord.shape =""")
coord = Grid.get_coordinates(M, Y)
print(coord.shape)

if __name__ == "__main__":
    print("""
    Now, the plot of fundamental trigonometric polynomial is shown:""")
    from mpl_toolkits.mplot3d import axes3d
    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.plot_wireframe(coord[0], coord[1], phi_fine.val)
    plt.show()

print('END')