def _get_rtmass(self,output_petsc=True):
     """
     Get the square root of assembled mass matrix M using lumping.
     --credit to: Umberto Villa
     """
     test = df.TestFunction(self.V)
     V_deg = self.V.ufl_element().degree()
     try:
         V_q_fe = df.FiniteElement('Quadrature',self.V.mesh().ufl_cell(),2*V_deg,quad_scheme='default')
         V_q = df.FunctionSpace(self.V.mesh(),V_q_fe)
     except:
         print('Use FiniteElement in specifying FunctionSpace after version 1.6.0!')
         V_q = df.FunctionSpace(self.V.mesh(), 'Quadrature', 2*self.V._FunctionSpace___degree)
     trial_q = df.TrialFunction(V_q)
     test_q = df.TestFunction(V_q)
     M_q = df.PETScMatrix()
     df.assemble(trial_q*test_q*df.dx,tensor=M_q,form_compiler_parameters={'quadrature_degree': 2*V_deg})
     ones = df.interpolate(df.Constant(1.), V_q).vector()
     dM_q = M_q*ones
     M_q.zero()
     dM_q_2fill = ones.array() / np.sqrt(dM_q.array() )
     dM_q.set_local( dM_q_2fill )
     M_q.set_diagonal(dM_q)
     mixedM = df.PETScMatrix()
     df.assemble(trial_q*test*df.dx,tensor=mixedM,form_compiler_parameters={'quadrature_degree': 2*V_deg})
     if output_petsc and df.has_petsc4py():
         rtM = df.PETScMatrix(df.as_backend_type(mixedM).mat().matMult(df.as_backend_type(M_q).mat()))
     else:
         rtM = sps.csr_matrix(mixedM.array()*dM_q_2fill)
         csr_trim0(rtM,1e-12)
     return rtM
 def _get_cov(self,output_petsc=True):
     """
     Get the covariance matrix C with C = K M.
     """
     if output_petsc and df.has_petsc4py():
         from petsc4py import PETSc
         C_f=os.path.join(os.getcwd(),'C_petsc.dat')
         try:
             viewer = PETSc.Viewer().createBinary(C_f, 'r')
             C_petsc=df.PETScMatrix(PETSc.Mat().load(viewer))
             print('Read the covariance successfully!')
         except:
             C_petsc= df.PETScMatrix(df.as_backend_type(self.K).mat().matMult(df.as_backend_type(self.M).mat()))
             viewer = PETSc.Viewer().createBinary(C_f, 'w')
             viewer(df.as_backend_type(C_petsc).mat())
         return C_petsc
     else:
         import cPickle
         C_f=os.path.join(os.getcwd(),'C_sps.dat')
         try:
             f = open(C_f, 'rb')
             C_sps = cPickle.load(f)
             f.close()
             print('Read the covariance successfully!')
         except:
             C_sps=sps.csr_matrix(self.K.dot(self.M.array()))
             csr_trim0(C_sps)
             f = open(C_f, 'wb')
             cPickle.dump(C_sps,f,-1)
             f.close()
         return C_sps
    def soln_adj2(self, obj):
        """
        Solve the 2nd order adjoint equation.
        < adj_dFdstates, states_adj2 > = < d2Jdstates, states_fwd2 >
        """
        self.states_adj2 = df.Function(self.W)  # 2nd forward states
        # Solve 2nd adjoint PDE < adj_dFdstates, states_adj2 > = < d2Jdstates, states_fwd2 >
        #         df.solve(self.adj_dFdstates == df.action(self.d2Jdstates, self.states_fwd2), self.states_adj2, self.adj_bcs)
        #         A,b = df.assemble_system(self.adj_dFdstates, df.action(self.d2Jdstates, self.states_fwd2), self.adj_bcs)
        #         df.solve(A, self.states_adj2.vector(), b)

        #         rhs_adj2 = df.PETScVector()
        #         df.assemble(df.action(self.d2Jdstates, self.states_fwd2), tensor=rhs_adj2)

        u_fwd2, _ = df.split(self.states_fwd2)
        if not df.has_petsc4py():
            warnings.warn('Configure dolfin with petsc4py to run faster!')
            self.dirac_2 = obj.ptsrc(u_fwd2, ord=2)
            rhs_adj2 = df.Vector(self.mpi_comm, self.W.dim())
            [delta.apply(rhs_adj2) for delta in self.dirac_2]
        else:
            rhs_adj2 = df.PETScVector(self.mpi_comm, self.W.dim())
            val_dirac_2, idx_dirac_2 = obj.dirac(u_fwd2, ord=2)
            rhs_adj2.vec()[idx_dirac_2] = val_dirac_2
#             np.allclose(rhs_adj2.array(),rhs_adj12.vec())

        [bc.apply(rhs_adj2) for bc in self.adj_bcs]

        df.solve(self.adj_dFdstates_assemb, self.states_adj2.vector(),
                 rhs_adj2)
        self.soln_count[3] += 1
        u_adj2, l_adj2 = df.split(self.states_adj2)
        return u_adj2, l_adj2
Beispiel #4
0
def create_PETScMatrix(shape,
                       mpi_comm=None,
                       rows=None,
                       cols=None,
                       values=None):
    """
    Create and set up PETScMatrix of arbitrary size using petsc4py.
    """
    if df.has_petsc4py():
        from petsc4py import PETSc
    else:
        print(
            'Dolfin is not compiled with petsc4py! Cannot create PETScMatrix of arbitrary size.'
        )
        exit()
    if mpi_comm is None:
        mpi_comm = df.mpi_comm_world()
    mat = PETSc.Mat()
    mat.create(mpi_comm)
    mat.setSizes(shape)
    mat.setType('aij')
    mat.setUp()
    mat.setValues(rows, cols, values)
    mat.assemble()
    return mat
    def soln_adj(self, obj):
        """
        Solve the adjoint equation.
        < adj_dFdstates, states_adj > = dJdstates
        """
        self.states_adj = df.Function(self.W)  # adjoint states
        # Solve adjoint PDE < adj_dFdstates, states_adj > = dJdstates
        #         df.solve(self.adj_dFdstates == self.dJdstates , self.states_adj, self.adj_bcs)
        #         A,b = df.assemble_system(self.adj_dFdstates, self.dJdstates, self.adj_bcs)
        #         df.solve(A, self.states_adj.vector(), b)
        #         error: assemble (solve) point integral (J) has supported underlying FunctionSpace no more than CG1; have to use PointSource? Yuk!

        u_fwd, _ = df.split(self.states_fwd)
        if not df.has_petsc4py():
            warnings.warn('Configure dolfin with petsc4py to run faster!')
            self.dirac_1 = obj.ptsrc(u_fwd, ord=1)
            rhs_adj = df.Vector(self.mpi_comm, self.W.dim())
            [delta.apply(rhs_adj) for delta in self.dirac_1]
        else:
            rhs_adj = df.PETScVector(self.mpi_comm, self.W.dim())
            val_dirac_1, idx_dirac_1 = obj.dirac(u_fwd, ord=1)
            rhs_adj.vec()[idx_dirac_1] = val_dirac_1
#             np.allclose(rhs_adj.array(),rhs_adj1.vec())

        [bc.apply(self.adj_dFdstates_assemb, rhs_adj) for bc in self.adj_bcs]

        df.solve(self.adj_dFdstates_assemb, self.states_adj.vector(), rhs_adj)
        self.soln_count[1] += 1
        u_adj, l_adj = df.split(self.states_adj)
        return u_adj, l_adj
Beispiel #6
0
 def _get_ker(self, output_petsc=True):
     """
     Get the kernel matrix K with K_ij = k(x_i,x_j).
     """
     load_success = False
     if output_petsc and df.has_petsc4py():
         from petsc4py import PETSc
         K_f = os.path.join(os.getcwd(),
                            'K_petsc_dim' + str(self.dim) + '.dat')
         try:
             viewer = PETSc.Viewer().createBinary(K_f, 'r')
             K = df.PETScMatrix(PETSc.Mat().load(viewer))
             load_success = True
         except:
             pass
     else:
         import cPickle
         K_f = os.path.join(os.getcwd(),
                            'K_sps_dim' + str(self.dim) + '.dat')
         try:
             f = open(K_f, 'rb')
             K = cPickle.load(f)
             f.close()
             load_success = True
         except:
             pass
     if load_success:
         print('Read the kernel successfully!')
         return K
     else:
         import scipy.spatial.distance
         K_sps = sps.csr_matrix(
             self.sigma**2 * np.exp(-sp.spatial.distance.squareform(
                 sp.spatial.distance.pdist(self.dof_coords)) /
                                    (2 * self.s)))
         csr_trim0(K_sps, 1e-10)
         if output_petsc and df.has_petsc4py():
             K_petsc = df.PETScMatrix(csr2petscmat(K_sps))
             viewer = PETSc.Viewer().createBinary(K_f, 'w')
             viewer(df.as_backend_type(K_petsc).mat())
             return K_petsc
         else:
             f = open(K_f, 'wb')
             cPickle.dump(K_sps, f, -1)
             f.close()
             return K_sps
Beispiel #7
0
    def _as_petscmat(self):
        if df.has_petsc4py():
            from petsc4py import PETSc
            mat = PETSc.Mat().createPython(df.as_backend_type(self.prior.M).mat().getSizes(), comm = self.prior.mpi_comm)
#             mat = PETSc.Mat().createPython(self.dim, comm = self.prior.mpi_comm)
            mat.setPythonContext(self)
            return df.PETScMatrix(mat)
        else:
            df.warning('Petsc4py not installed: cannot generate PETScMatrix with specified size!')
            pass
Beispiel #8
0
def _get_sqrtm(A, m_name='K', output_petsc=True, SAVE=True):
    """
    Get the root of matrix A.
    """
    if output_petsc and df.has_petsc4py():
        from petsc4py import PETSc
        rtA_f = os.path.join(
            os.getcwd(),
            'rt' + m_name + '_petsc_dim' + str(A.size(0)) + '.dat')
        try:
            viewer = PETSc.Viewer().createBinary(rtA_f, 'r')
            rtA_petsc = df.PETScMatrix(PETSc.Mat().load(viewer))
            print('Read the root of ' + {
                'K': 'kernel',
                'C': 'covariance'
            }[m_name] + ' successfully!')
        except:
            import scipy.linalg as spla
            rtA_sps = sps.csr_matrix(spla.sqrtm(A.array()).real)
            csr_trim0(rtA_sps, 1e-10)
            rtA_petsc = df.PETScMatrix(csr2petscmat(rtA_sps))
            if SAVE:
                viewer = PETSc.Viewer().createBinary(rtA_f, 'w')
                viewer(df.as_backend_type(rtA_petsc).mat())
        return rtA_petsc
    else:
        import cPickle
        rtA_f = os.path.join(
            os.getcwd(), 'rt' + m_name + '_sps_dim' + str(A.shape[0]) + '.dat')
        try:
            f = open(rtA_f, 'rb')
            rtA_sps = cPickle.load(f)
            f.close()
            print('Read the root of ' + {
                'K': 'kernel',
                'C': 'covariance'
            }[m_name] + ' successfully!')
        except:
            import scipy.linalg as spla
            rtA_sps = sps.csr_matrix(spla.sqrtm(A.toarray()).real)
            csr_trim0(rtA_sps, 1e-10)
            if SAVE:
                f = open(rtA_f, 'wb')
                cPickle.dump(rtA_sps, f, -1)
                f.close()
        return rtA_sps
Beispiel #9
0
# -*- coding: utf-8 -*-
"""
Checks that this version of FEniCS/DOLFIN was compiled with parallel HDF5 and
a few extra preconditoners and solvers.
"""

import dolfin as df

assert df.has_hdf5_parallel()

assert df.has_krylov_solver_preconditioner('hypre_amg')
assert df.has_krylov_solver_preconditioner('hypre_euclid')
assert df.has_krylov_solver_preconditioner('hypre_parasails')

assert df.has_lu_solver_method('mumps')

assert df.has_petsc()
assert df.has_petsc4py()