# Using petsc4py.PETSc.SNES directly

**URL:** <https://fenicsproject.discourse.group/t/using-petsc4py-petsc-snes-directly/2368>\
**Category:** Linear Algebra\
**Created:** [February 6, 2020, 2:16am UTC](https://fenicsproject.discourse.group/t/using-petsc4py-petsc-snes-directly/2368 "2020-02-06T02:16:40Z")\
**Posts on this page:** 1\
**Showing post:** 11

<div class="post-metadata">

**Author:** ![niewiarowski](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/niewiarowski/32/620_2.png) [@niewiarowski](https://fenicsproject.discourse.group/u/niewiarowski)\
**Post date:** [February 7, 2020, 4:25pm UTC](https://fenicsproject.discourse.group/t/using-petsc4py-petsc-snes-directly/2368/11 "2020-02-07T16:25:26Z")

</div>

Hi Nate, thanks for offering to help, my MWE is below (top is directly from hyperelasticity demo):

```
from dolfin import *

parameters["form_compiler"]["cpp_optimize"] = True
ffc_options = {"optimize": True, \
               "eliminate_zeros": True, \
               "precompute_basis_const": True, \
               "precompute_ip_const": True}

# Create mesh and define function space
mesh = UnitCubeMesh(24, 16, 16)
V = VectorFunctionSpace(mesh, "Lagrange", 1)

# Mark boundary subdomians
left = CompiledSubDomain("near(x[0], side) && on_boundary", side = 0.0)
right = CompiledSubDomain("near(x[0], side) && on_boundary", side = 1.0)

# Define Dirichlet boundary (x = 0 or x = 1)
c = Expression(("0.0", "0.0", "0.0"), degree=2)
r = Expression(("scale*0.0",
                "scale*(y0 + (x[1] - y0)*cos(theta) - (x[2] - z0)*sin(theta) - x[1])",
                "scale*(z0 + (x[1] - y0)*sin(theta) + (x[2] - z0)*cos(theta) - x[2])"),
                scale = 0.5, y0 = 0.5, z0 = 0.5, theta = pi/3, degree=2)

bcl = DirichletBC(V, c, left)
bcr = DirichletBC(V, r, right)
bcs = [bcl, bcr]

# Define functions
du = TrialFunction(V) # Incremental displacement
v = TestFunction(V) # Test function
u = Function(V) # Displacement from previous iteration
B = Constant((0.0, -0.5, 0.0)) # Body force per unit volume
T = Constant((0.1, 0.0, 0.0)) # Traction force on the boundary

# Kinematics
d = u.geometric_dimension()
I = Identity(d) # Identity tensor
F = I + grad(u) # Deformation gradient
C = F.T*F # Right Cauchy-Green tensor

# Invariants of deformation tensors
Ic = tr(C)
J = det(F)

# Elasticity parameters
E, nu = 10.0, 0.3
mu, lmbda = Constant(E/(2*(1 + nu))), Constant(E*nu/((1 + nu)*(1 - 2*nu)))

# Stored strain energy density (compressible neo-Hookean model)
psi = (mu/2)*(Ic - 3) - mu*ln(J) + (lmbda/2)*(ln(J))**2

# Total potential energy
Pi = psi*dx - dot(B, u)*dx - dot(T, u)*ds

# Compute first variation of Pi (directional derivative about u in the direction of v)
F = derivative(Pi, u, v)

class SNESProblem():
    def __init__ (self, F, u, bcs):
        V = u.function_space()
        du = TrialFunction(V)
        self.L = F
        self.a = derivative(F, u, du)
        self.bcs = bcs
        self.u = u

    def F(self, snes, x, F):
        F = PETScVector()
        assemble(self.L, tensor=F)
        for bc in self.bcs:
            bc.apply(F)                

    def J(self, snes, x, J):
        J = PETScMatrix()
        assemble(J, self.a)
        for bc in self.bcs:
            bc.apply(A)
            
problem = SNESProblem(F, u, bcs)
import petsc4py, sys
petsc4py.init(sys.argv)
from petsc4py import PETSc
    
b = PETScVector() # same as b = PETSc.Vec()
J_mat = PETScMatrix()

snes = PETSc.SNES().create(MPI.comm_world)    
snes.setFunction(problem.F, b.vec())
snes.setJacobian(problem.J, J_mat.mat())
snes.solve(None, problem.u.vector().vec())
```

---

_[View the full topic](https://fenicsproject.discourse.group/t/using-petsc4py-petsc-snes-directly/2368)._
