Reference.py 7.78 KB
Newer Older
Antoine MARTIN's avatar
Antoine MARTIN committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209



from dolfin import *
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter



def local_project(v,V):
    dv = TrialFunction(V)
    v_ = TestFunction(V)
    a_proj = inner(dv,v_)*dx
    b_proj = inner(v,v_)*dx
    solver = LocalSolver(a_proj,b_proj)
    solver.factorize()
    u = Function(V)
    solver.solve_local_rhs(u)
    return u

#cf 'Contenu des fichiers' à propos de 'reference'
def reference(tabC,res1,c,ec,fr):
    #res=256
    k,ll,mm,nn=tabC.shape
    mesh = UnitSquareMesh(res1, res1, "left/right")

    class LocalC(UserExpression):
        def __init__(self, Cij, mesh):
            self.Cij = Cij
            self.Nx, self.Ny, a, b = Cij.shape
            assert a==3 and b==3, "Wrong shape"
            self.mesh = mesh
            UserExpression.__init__(self)
        def eval_cell(self, value, x, ufc_cell):
            p = Cell(mesh, ufc_cell.index).midpoint()
            i, j = int(p[0]*(self.Nx)), int(p[1]*(self.Ny))
            value[:] = self.Cij[j, i,:,:].flatten()

        def value_shape(self):
            return (3, 3)


#Ici on crée, à partir du tableau des tenseurs d'élasticité correspondant au domaine dont on veut calculer le Chom, un tableau Cv représentant le même Cn mais adapté à une résolution plus fine 'res'
    # Cv = np.array([[np.zeros((3,3)) for i in range(res)] for j in range(res)])
    # for i0 in range(k):
    #     for j0 in range(k):
    #         for i in range(int(i0*res/k),int((i0+1)*res/k)):
    #             for j in range (int(j0*res/k),int((j0+1)*res/k)):
    #                 Cv[i,j]=tabC[i0,j0]

    # plt.imshow(tabC[:,:,0,0])
    # plt.show()
    # plt.close()
    # plt.imshow(Cv[:,:,0,0])
    # plt.show()
    # plt.close()

#Cvar est la transformation du tableau Cv en une fonction définie sur 'mesh'
    Cvar= LocalC(tabC,mesh)
    #Avar= LocalC(tA,mesh)

    # class used to define the periodic boundary map
    class PeriodicBoundary(SubDomain):
        def __init__(self, vertices, tolerance=DOLFIN_EPS):
            """ vertices stores the coordinates of the 4 unit cell corners"""
            SubDomain.__init__(self, tolerance)
            self.tol = tolerance
            self.vv = vertices
            self.a1 = self.vv[1,:]-self.vv[0,:] # first vector generating periodicity
            self.a2 = self.vv[3,:]-self.vv[0,:] # second vector generating periodicity
            # check if UC vertices form indeed a parallelogram
            assert np.linalg.norm(self.vv[2, :]-self.vv[3, :] - self.a1) <= self.tol
            assert np.linalg.norm(self.vv[2, :]-self.vv[1, :] - self.a2) <= self.tol

        def inside(self, x, on_boundary):
            # return True if on left or bottom boundary AND NOT on one of the
            # bottom-right or top-left vertices
            return bool((near(x[0], self.vv[0,0] + x[1]*self.a2[0]/self.vv[3,1], self.tol) or
                        near(x[1], self.vv[0,1] + x[0]*self.a1[1]/self.vv[1,0], self.tol)) and
                        (not ((near(x[0], self.vv[1,0], self.tol) and near(x[1], self.vv[1,1], self.tol)) or
                        (near(x[0], self.vv[3,0], self.tol) and near(x[1], self.vv[3,1], self.tol)))) and on_boundary)

        def map(self, x, y):
            if near(x[0], self.vv[2,0], self.tol) and near(x[1], self.vv[2,1], self.tol): # if on top-right corner
                y[0] = x[0] - (self.a1[0]+self.a2[0])
                y[1] = x[1] - (self.a1[1]+self.a2[1])
            elif near(x[0], self.vv[1,0] + x[1]*self.a2[0]/self.vv[2,1], self.tol): # if on right boundary
                y[0] = x[0] - self.a1[0]
                y[1] = x[1] - self.a1[1]
            else:   # should be on top boundary
                y[0] = x[0] - self.a2[0]
                y[1] = x[1] - self.a2[1]



#la fonction reference_problem prend en argument C, donnant le tenseur d'élasticité en un point de 'mesh', et renvoie le Chom du domaine. k étant le nombre de phases différentes sur le domaine, qui correspond à la taille du tableau Cn pris en argument par la fonction 'reference'
    def reference_problem(C, mesh,k):

        def eps(v):
            return as_vector([v[0].dx(0),
                            v[1].dx(1),
                            (v[0].dx(1)+v[1].dx(0))/sqrt(2)])

        def sigma(v, Eps):
            return dot(C, eps(v)+Eps)

        #def sigma_HH(Eps):
        #    return dot(C,dot(A,Eps))

        Ve = VectorElement("CG", mesh.ufl_cell(), 2)
        Re = VectorElement("R", mesh.ufl_cell(), 0)
        vertices = np.array([[0, 0], [1, 0], [1, 1], [0, 1]])
        W = FunctionSpace(mesh, MixedElement([Ve, Re]), constrained_domain=PeriodicBoundary(vertices, tolerance=1e-10))
        V = VectorFunctionSpace(mesh,'DG',degree=1,dim=3)

        v_,lamb_ = TestFunctions(W)
        dv, dlamb = TrialFunctions(W)
        w = Function(W)

        Eps = Constant((0,)*3)
        F = inner(sigma(dv, Eps), eps(v_))*dx
        a, L = lhs(F), rhs(F)
        a += dot(lamb_,dv)*dx + dot(dlamb,v_)*dx

        Chom = np.zeros((3, 3))
        
        for (j, case) in enumerate(["Exx", "Eyy", "Exy"]):
            ffile = XDMFFile('c='+str(c)+'/ech='+str(ec)+'/frac='+str(fr)+'/Strain_EF_{}.xdmf'.format(case))

            ee = np.zeros((3,))
            ee[j] = 1
            Eps.assign(Constant(ee))
            solve(a == L, w)#, solver_parameters={"linear_solver": "mumps"})#, solver_parameters={"linear_solver": "bicgstab", "preconditioner":"ilu"})
            (v, lamb) = split(w)
            
            vf = Function(V, name='Strain-'+case)
            vf.assign(local_project(eps(v), V))
            ffile.write_checkpoint(vf, case, 0.)

           
            #sEF=sigma(v,Eps)
            #sHH=sigma_HH(Eps)
            #diff_sig=sEF-sHH
            #plt.figure(figsize=(80.,50.))
            #pp=plot(diff_sig[0],cmap='hot')
            #co=plt.colorbar(pp,shrink=1.)
            #co.ax.tick_params(labelsize=100.)
            #plt.savefig('c='+str(c)+'/ech='+str(ec)+'/frac='+str(fr)+'/diff_sig_11'+case+'.jpg')
            #plt.show()
            #plt.close()
            #plt.figure(figsize=(80.,50.))
            #pp=plot(sEF[0],cmap='hot')
            #co=plt.colorbar(pp,shrink=1.)
            #co.ax.tick_params(labelsize=100.)
            #plt.savefig('c='+str(c)+'/ech='+str(ec)+'/frac='+str(fr)+'/sigEF_11'+case+'.jpg')
            #plt.close()
            #plt.figure(figsize=(80.,50.))
            #pp=plot(sEF[0]-diff_sig[0],cmap='hot')
            #co=plt.colorbar(pp,shrink=1.)
            #co.ax.tick_params(labelsize=100.)
            #plt.savefig('c='+str(c)+'/ech='+str(ec)+'/frac='+str(fr)+'/sigHH_11'+case+'.jpg')
            #plt.close()
            #plt.figure(figsize=(80.,50.))
            #pp=plot(diff_sig[1],cmap='hot')
            #co=plt.colorbar(pp,shrink=1.)
            #co.ax.tick_params(labelsize=100.)
            #plt.savefig('c='+str(c)+'/ech='+str(ec)+'/frac='+str(fr)+'/diff_sig_22'+case+'.jpg')
            #plt.show()
            #plt.close()
            #plt.figure(figsize=(80.,50.))
            #pp=plot(diff_sig[2],cmap='hot')
            #co=plt.colorbar(pp,shrink=1.)
            #co.ax.tick_params(labelsize=100.)
            #plt.savefig('c='+str(c)+'/ech='+str(ec)+'/frac='+str(fr)+'/diff_sig_12'+case+'.jpg')
            #plt.show()
            #plt.close()


            Sigma = np.zeros((3,))
            for kk in range(3):
                Sigma[kk] = assemble(sigma(v, Eps)[kk]*dx)
            Chom[j, :] = Sigma

            ffile.close()
        return Chom

    Chom = reference_problem(Cvar, mesh,k)
    CVoigt = np.array([[0., 0., 0.],
                [0., 0., 0.],
                [0., 0., 0.]])
    for i in range(k):
        for j in range(k):
            CVoigt=CVoigt+tabC[i,j]

    CVoigt=CVoigt/k/k

    print(Chom)
    return Chom,CVoigt