Ejemplo n.º 1
0
 def geneFunctionSpace(self):
     P2 = fe.FiniteElement('P', fe.triangle, 2)
     element = fe.MixedElement([P2, P2])
     if self.domain.haveMesh == False:
         self.domain.geneMesh()
     self.V = fe.FunctionSpace(self.domain.mesh, element)
     self.haveFunctionSpace = True
Ejemplo n.º 2
0
    def initWeakFormulation():
        """Define function spaces etc. to initialize weak formulation."""
        P = fe.FiniteElement('P', mesh.ufl_cell(), 1)
        V = fe.FunctionSpace(mesh, 'P', 1)
        auxP = []
        for k in range(nEvenMoments):
            auxP.append(P)
        VVec = fe.FunctionSpace(mesh, fe.MixedElement(auxP))
        auxV = []
        for k in range(nEvenMoments):
            auxV.append(V)
        assigner = fe.FunctionAssigner(auxV, VVec)

        v = fe.TestFunctions(VVec)
        u = fe.TrialFunctions(VVec)
        uSol = fe.Function(VVec)

        uSolComponents = []
        for k in range(nEvenMoments):
            uSolComponents.append(fe.Function(V))

        # FEniCS work-around
        if N_PN == 1:
            solAssignMod = lambda uSolComponents, uSol: [
                assigner.assign(uSolComponents[0], uSol)
            ]
        else:
            solAssignMod = lambda uSolComponents, uSol: assigner.assign(
                uSolComponents, uSol)

        return u, v, V, uSol, uSolComponents, solAssignMod
Ejemplo n.º 3
0
def _create_function_spaces(t, T, a, b, fineness_t, fineness_x):
    """Here we create the function spaces involved (and also the
    mesh as well).
    """
    
    nx = round((b - a) / fineness_x)  # number of space steps

    ### Define periodic boundary
    class PeriodicBoundary(fc.SubDomain):

        def inside(self, x, on_boundary):
            return bool(x[0] < fc.DOLFIN_EPS and 
                        x[0] > -fc.DOLFIN_EPS and 
                        on_boundary)

        # Map right boundary to left boundary
        def map(self, x, y):
            y[0] = x[0] - (b - a)

    ### Create mesh and define function spaces
    mesh = fc.IntervalMesh(nx, a, b)
    F_ele = fc.FiniteElement("CG", mesh.ufl_cell(), 1)
    V = fc.FunctionSpace(mesh, F_ele, 
                         constrained_domain=PeriodicBoundary())
    W = fc.FunctionSpace(mesh, fc.MixedElement([F_ele, F_ele]), 
                         constrained_domain=PeriodicBoundary())
    
    return V, W, mesh
Ejemplo n.º 4
0
    def __init__(self,
                 mesh: fe.Mesh,
                 density: fe.Expression,
                 constitutive_model: ConstitutiveModelBase,
                 bf: fe.Expression = fe.Expression('0', degree=0)):

        self._mesh = mesh
        self._density = density
        self._constitutive_model = constitutive_model
        self.bf = bf

        element_v = fe.VectorElement("P", mesh.ufl_cell(), 1)
        element_s = fe.FiniteElement("P", mesh.ufl_cell(), 1)
        mixed_element = fe.MixedElement([element_v, element_v, element_s])
        W = fe.FunctionSpace(mesh, mixed_element)

        # Unknowns, values at previous step and test functions
        w = fe.Function(W)
        self.u, self.v, self.p = fe.split(w)

        w0 = fe.Function(W)
        self.u0, self.v0, self.p0 = fe.split(w0)
        self.a0 = fe.Function(fe.FunctionSpace(mesh, element_v))

        self.ut, self.vt, self.pt = fe.TestFunctions(W)

        self.F = kin.def_grad(self.u)
        self.F0 = kin.def_grad(self.u0)
Ejemplo n.º 5
0
def dynamic_solver_func(ncells=10,  # количество узлов на заданном итервале
                        init_time=0,  # начальный момент времени
                        end_time=10,  # конечный момент времени
                        dxdphi=1,  # производная от потенциала по х
                        dydphi=1,  # производня от потенциала по у
                        x0=0,  # начальное положение по оси х
                        vx0=1,  # проекция начальной скорости на ось х
                        y0=0,  # начальное положение по оси у
                        vy0=1):  # проекция начальной скорости на ось у
    """ Функция на вход которой подается производная от потенциала
        гравитационного поля, возвращающая координаты смещенных
        материальных точек (частиц).
    """
    # генерация сетки на заданном интервале времени
    mesh = fen.IntervalMesh(ncells, 0, end_time-init_time)

    welm = fen.MixedElement([fen.FiniteElement('Lagrange', fen.interval, 2),
                             fen.FiniteElement('Lagrange', fen.interval, 2),
                             fen.FiniteElement('Lagrange', fen.interval, 2),
                             fen.FiniteElement('Lagrange', fen.interval, 2)])

    # генерация функционального рростаанства
    W = fen.FunctionSpace(mesh, welm)

    # постановка начальных условий задачи
    bcsys = [fen.DirichletBC(W.sub(0), fen.Constant(x0), 'near(x[0], 0)'),
             fen.DirichletBC(W.sub(1), fen.Constant(vx0), 'near(x[0], 0)'),
             fen.DirichletBC(W.sub(2), fen.Constant(y0), 'near(x[0], 0)'),
             fen.DirichletBC(W.sub(3), fen.Constant(vy0), 'near(x[0], 0)')]

    # опееделение тестовых функций для решения задачи
    up = fen.Function(W)
    x_cor, v_x, y_cor, v_y = fen.split(up)
    v1, v2, v3, v4 = fen.split(fen.TestFunction(W))

    # постановка задачи drdt = v; dvdt = - grad(phi) в проекциях на оси системы координат
    weak_form = (x_cor.dx(0) - v_x) * v1 * fen.dx + (v_x.dx(0) + dxdphi) * v2 * fen.dx \
                + (y_cor.dx(0) - v_y) * v3 * fen.dx + (v_y.dx(0) + dydphi) * v4 * fen.dx

    # решние поставленной задачи
    fen.solve(weak_form == 0, up, bcs=bcsys)

    # определение момента времени
    time = fen.Point(end_time - init_time)

    # расчет координат и скоростей
    x_end_time = up(time.x())[0]
    vx_end_time = up(time.x())[1]
    y_end_time = up(time.x())[2]
    vy_end_time = up(time.x())[3]

    return x_end_time, y_end_time, vx_end_time, vy_end_time
Ejemplo n.º 6
0
    def setup_element(self):
        """ Implement the mixed element per @cite{danaila2014newton}. """
        pressure_element = fenics.FiniteElement(
            "P", self.mesh.ufl_cell(), self.temperature_element_degree)

        velocity_element = fenics.VectorElement(
            "P", self.mesh.ufl_cell(), self.temperature_element_degree + 1)

        temperature_element = fenics.FiniteElement(
            "P", self.mesh.ufl_cell(), self.temperature_element_degree)

        self.element = fenics.MixedElement(
            [pressure_element, velocity_element, temperature_element])
Ejemplo n.º 7
0
def make_mixed_fe(cell):
    """ Define the mixed finite element.
    MixedFunctionSpace used to be available but is now deprecated. 
    To create the mixed space, I'm using the approach from https://fenicsproject.org/qa/11983/mixedfunctionspace-in-2016-2-0
    """
    velocity_degree = pressure_degree + 1

    velocity_element = fenics.VectorElement("P", cell, velocity_degree)

    pressure_element = fenics.FiniteElement("P", cell, pressure_degree)

    temperature_element = fenics.FiniteElement("P", cell, temperature_degree)

    mixed_element = fenics.MixedElement(
        [velocity_element, pressure_element, temperature_element])

    return mixed_element
Ejemplo n.º 8
0
    def __init__(self,
                 mesh: fe.Mesh,
                 constitutive_model: ConstitutiveModelBase,
                 u_order=1,
                 p_order=0):

        # TODO a lot here...

        element_v = fe.VectorElement("P", mesh.ufl_cell(), u_order)
        element_s = fe.FiniteElement("DG", mesh.ufl_cell(), p_order)
        # mixed_element = fe.MixedElement([element_v, element_v, element_s])
        mixed_element = fe.MixedElement([element_v, element_s])

        self.W = fe.FunctionSpace(mesh, mixed_element)

        self.V, self.Q = self.W.split()

        self.w = fe.Function(self.W)
        self.u, self.p = fe.split(self.w)
        w0 = fe.Function(self.W)
        self.u0, self.p0 = fe.split(w0)
        self.ut, self.pt = fe.TestFunctions(self.W)

        self.F = kin.def_grad(self.u)
        self.F0 = kin.def_grad(self.u0)

        S_iso = constitutive_model.iso_stress(self.u)
        mod_p = constitutive_model.p(self.u)
        J = fe.det(self.F)
        F_inv = fe.inv(self.F)

        if mod_p is None:
            mod_p = J**2 - 1.
        else:
            mod_p -= self.p

        S = S_iso + J * self.p * F_inv * F_inv.T

        self.d_LHS = fe.inner(fe.grad(self.ut), self.F * S) * fe.dx \
                     + fe.inner(mod_p, self.pt) * fe.dx
        # + fe.inner(mod_p, fe.tr(fe.nabla_grad(self.ut)*fe.inv(self.F))) * fe.dx

        self.d_RHS = (fe.inner(fe.Constant((0., 0., 0.)), self.ut) * fe.dx)
Ejemplo n.º 9
0
# Create mesh and define function space
size = width, height = 1.0, 0.75

mesh = fn.RectangleMesh(fn.Point(-width / 2, 0.0), fn.Point(width / 2, height),
                        52, 39)  # 52 * 0.75 = 39, elements are square
nn = fn.FacetNormal(mesh)

# Defintion of function spaces
Vh = fn.VectorElement("CG", mesh.ufl_cell(), 2)
Zh = fn.FiniteElement("CG", mesh.ufl_cell(), 1)
Qh = fn.FiniteElement("CG", mesh.ufl_cell(), 2)

# spaces for displacement and total pressure should be compatible
# whereas the space for fluid pressure can be "anything". In particular the one for total pressure

Hh = fn.FunctionSpace(mesh, fn.MixedElement([Vh, Zh, Qh]))

(u, phi, p) = fn.TrialFunctions(Hh)
(v, psi, q) = fn.TestFunctions(Hh)

fileU = fn.File(mesh.mpi_comm(), "Output/2_5_1_Footing_wall_removed/u.pvd")
filePHI = fn.File(mesh.mpi_comm(), "Output/2_5_1_Footing_wall_removed/phi.pvd")
fileP = fn.File(mesh.mpi_comm(), "Output/2_5_1_Footing_wall_removed/p.pvd")

# ******** Model constants ********** #
E = 3.0e4
nu = 0.4995
lmbda = E * nu / ((1. + nu) * (1. - 2. * nu))
mu = E / (2. * (1. + nu))

c0 = 1.0e-3
Ejemplo n.º 10
0
mesh = fe.Mesh('step.xml')

# Control pannel
MODEL = False  # flag to use SA model
b = fe.Expression(('0', '0'), degree=DEG)  # forcing
nu = fe.Constant(2e-6)
rho = fe.Constant(1)
RE = 0.01
lmx = 1  # mixing length
dt = 0.1
# Re = 10 / 1e-4 = 1e5

V = fe.VectorElement("Lagrange", mesh.ufl_cell(), 2)
P = fe.FiniteElement("Lagrange", mesh.ufl_cell(), 1)
NU = fe.FiniteElement("Lagrange", mesh.ufl_cell(), 1)
if MODEL: M = fe.MixedElement([V, P, NU])
else: M = fe.MixedElement([V, P])
W = fe.FunctionSpace(mesh, M)

W0 = fe.Function(W)
We = fe.Function(W)
u0, p0 = fe.split(We)
#u0 = fe.Function((W0[0], W0[1]), 'Velocity000023.vtu')
#p0 = fe.Function(W0[2])
v, q = fe.TestFunctions(W)
#u, p = fe.split(W0)
u, p = (fe.as_vector((W0[0], W0[1])), W0[2])

#-------------------------------------------------------
# Defining essential/Dirichlet boundary conditions
# Step 1: Identify all boundary segments forming Gamma_d
Ejemplo n.º 11
0
fn.parameters["form_compiler"]["cpp_optimize"] = True

# file outputs
fileE = fn.File("Output/1_4_Karma/E.pvd")
filen = fn.File("Output/1_4_Karma/n.pvd")
t = 0.0; dt = 0.3; Tfinal = 600.0; frequency = 100;

# mesh
L = 6.72; nps = 64;
mesh = fn.RectangleMesh(fn.Point(0, 0), fn.Point(L, L),
			            nps, nps, "crossed")

# element and function spaces
Mhe = fn.FiniteElement("CG", mesh.ufl_cell(), 1)
Mh  = fn.FunctionSpace(mesh, Mhe)
Nh  = fn.FunctionSpace(mesh, fn.MixedElement([Mhe,Mhe]))

# trial and test functions
v, n   = fn.TrialFunctions(Nh)
w, m   = fn.TestFunctions(Nh)

# solution
Ksol   = fn.Function(Nh)

# model constants
diffScale = fn.Constant(1e-3)
D0 = 1.1 * diffScale
tauv  = fn.Constant(2.5)
taun  = fn.Constant(250.0)
Re    = fn.Constant(1.0)
M     = fn.Constant(5.0)
Ejemplo n.º 12
0
def navierStokes(projectId, mesh, faceSets, boundarySets, config):

    log("Navier Stokes Analysis has started")

    # this is the default directory, when user request for download all files in this directory is being compressed and sent to the user
    resultDir = "./Results/"

    if len(config["steps"]) > 1:
        return "more than 1 step is not supported yet"

    # config is a dictionary containing all the user inputs for solver configurations
    t_init = 0.0
    t_final = float(config['steps'][0]["finalTime"])
    t_num = int(config['steps'][0]["iterationNo"])
    dt = ((t_final - t_init) / t_num)
    t = t_init

    #
    #  Viscosity coefficient.
    #
    nu = float(config['materials'][0]["viscosity"])
    rho = float(config['materials'][0]["density"])

    #
    #  Declare Finite Element Spaces
    # do not use triangle directly
    P2 = fn.VectorElement("P", mesh.ufl_cell(), 2)
    P1 = fn.FiniteElement("P", mesh.ufl_cell(), 1)
    TH = fn.MixedElement([P2, P1])
    V = fn.VectorFunctionSpace(mesh, "P", 2)
    Q = fn.FunctionSpace(mesh, "P", 1)
    W = fn.FunctionSpace(mesh, TH)

    #
    #  Declare Finite Element Functions
    #
    (u, p) = fn.TrialFunctions(W)
    (v, q) = fn.TestFunctions(W)
    w = fn.Function(W)
    u0 = fn.Function(V)
    p0 = fn.Function(Q)

    #
    # Macros needed for weak formulation.
    #
    def contract(u, v):
        return fn.inner(fn.nabla_grad(u), fn.nabla_grad(v))

    def b(u, v, w):
        return 0.5 * (fn.inner(fn.dot(u, fn.nabla_grad(v)), w) -
                      fn.inner(fn.dot(u, fn.nabla_grad(w)), v))

    # Define boundaries
    bcs = []
    for BC in config['BCs']:
        if BC["boundaryType"] == "wall":
            for edge in json.loads(BC["edges"]):
                bcs.append(
                    fn.DirichletBC(W.sub(0),
                                   fn.Constant((0.0, 0.0, 0.0)),
                                   boundarySets,
                                   int(edge),
                                   method='topological'))
        if BC["boundaryType"] == "inlet":
            vel = json.loads(BC['value'])
            for edge in json.loads(BC["edges"]):
                bcs.append(
                    fn.DirichletBC(W.sub(0),
                                   fn.Expression(
                                       (str(vel[0]), str(vel[1]), str(vel[2])),
                                       degree=2),
                                   boundarySets,
                                   int(edge),
                                   method='topological'))
        if BC["boundaryType"] == "outlet":
            for edge in json.loads(BC["edges"]):
                bcs.append(
                    fn.DirichletBC(W.sub(1),
                                   fn.Constant(float(BC['value'])),
                                   boundarySets,
                                   int(edge),
                                   method='topological'))

    f = fn.Constant((0.0, 0.0, 0.0))

    #  weak form NSE
    NSE = (1.0/dt)*fn.inner(u, v)*fn.dx + b(u0, u, v)*fn.dx + nu * \
        contract(u, v)*fn.dx - fn.div(v)*p*fn.dx + q*fn.div(u)*fn.dx
    LNSE = fn.inner(f, v) * fn.dx + (1. / dt) * fn.inner(u0, v) * fn.dx

    velocity_file = fn.XDMFFile(resultDir + "/vel.xdmf")
    pressure_file = fn.XDMFFile(resultDir + "/pressure.xdmf")
    velocity_file.parameters["flush_output"] = True
    velocity_file.parameters["functions_share_mesh"] = True
    pressure_file.parameters["flush_output"] = True
    pressure_file.parameters["functions_share_mesh"] = True
    #
    # code for projecting a boundary condition into a file for visualization
    #
    # for bc in bcs:
    #     bc.apply(w.vector())
    # fn.File("para_plotting/bc.pvd") << w.sub(0)

    for jj in range(0, t_num):
        t = t + dt
        # print('t = ' + str(t))
        A, b = fn.assemble_system(NSE, LNSE, bcs)
        fn.solve(A, w.vector(), b)
        # fn.solve(NSE==LNSE,w,bcs)
        fn.assign(u0, w.sub(0))
        fn.assign(p0, w.sub(1))
        # Save Solutions to Paraview File
        if (jj % 20 == 0):
            velocity_file.write(u0, t)
            pressure_file.write(p0, t)
            sendFile(projectId, resultDir + "vel.xdmf")
            sendFile(projectId, resultDir + "vel.h5")
            sendFile(projectId, resultDir + "pressure.xdmf")
            sendFile(projectId, resultDir + "pressure.h5")
            statusUpdate(projectId, "STARTED", {"progress": jj / t_num * 100})
Ejemplo n.º 13
0
import fenics
import matplotlib

N = 4

mesh = fenics.UnitSquareMesh(N, N)

P2 = fenics.VectorElement('P', mesh.ufl_cell(), 2)

P1 = fenics.FiniteElement('P', mesh.ufl_cell(), 1)

P2P1 = fenics.MixedElement([P2, P1])

W = fenics.FunctionSpace(mesh, P2P1)

psi_u, psi_p = fenics.TestFunctions(W)

w = fenics.Function(W)

u, p = fenics.split(w)

dynamic_viscosity = 0.01

mu = fenics.Constant(dynamic_viscosity)

inner, dot, grad, div, sym = fenics.inner, fenics.dot, fenics.grad, fenics.div, fenics.sym

momentum = dot(psi_u, dot(grad(u), u)) - div(psi_u) * p + 2. * mu * inner(
    sym(grad(psi_u)), sym(grad(u)))

mass = -psi_p * div(u)
Ejemplo n.º 14
0
    def xest_implement_2d_myosin(self):
        #Parameters
        total_time = 1.0
        number_of_time_steps = 100
        delta_t = total_time / number_of_time_steps
        nx = ny = 100
        domain_size = 1.0
        lambda_ = 5.0
        mu = 2.0
        gamma = 1.0
        eta_b = 0.0
        eta_s = 1.0
        k_b = 1.0
        k_u = 1.0
        #         zeta_1 = -0.5
        zeta_1 = 0.0
        zeta_2 = 1.0
        mu_a = 1.0
        K_0 = 1.0
        K_1 = 0.0
        K_2 = 0.0
        K_3 = 0.0
        D = 0.25
        alpha = 3
        c = 0.1

        # Sub domain for Periodic boundary condition
        class PeriodicBoundary(fenics.SubDomain):
            # Left boundary is "target domain" G
            def inside(self, x, on_boundary):
                # return True if on left or bottom boundary AND NOT on one of the two corners (0, 1) and (1, 0)
                return bool(
                    (fenics.near(x[0], 0) or fenics.near(x[1], 0)) and
                    (not ((fenics.near(x[0], 0) and fenics.near(x[1], 1)) or
                          (fenics.near(x[0], 1) and fenics.near(x[1], 0))))
                    and on_boundary)

            def map(self, x, y):
                if fenics.near(x[0], 1) and fenics.near(x[1], 1):
                    y[0] = x[0] - 1.
                    y[1] = x[1] - 1.
                elif fenics.near(x[0], 1):
                    y[0] = x[0] - 1.
                    y[1] = x[1]
                else:  # near(x[1], 1)
                    y[0] = x[0]
                    y[1] = x[1] - 1.

        periodic_boundary_condition = PeriodicBoundary()

        #Set up finite elements
        mesh = fenics.RectangleMesh(fenics.Point(0, 0),
                                    fenics.Point(domain_size, domain_size), nx,
                                    ny)
        vector_element = fenics.VectorElement('P', fenics.triangle, 2, dim=2)
        single_element = fenics.FiniteElement('P', fenics.triangle, 2)
        mixed_element = fenics.MixedElement(vector_element, single_element)
        V = fenics.FunctionSpace(
            mesh,
            mixed_element,
            constrained_domain=periodic_boundary_condition)
        v, r = fenics.TestFunctions(V)
        full_trial_function = fenics.Function(V)
        u, rho = fenics.split(full_trial_function)
        full_trial_function_n = fenics.Function(V)
        u_n, rho_n = fenics.split(full_trial_function_n)

        #Define non-linear weak formulation
        def epsilon(u):
            return 0.5 * (fenics.nabla_grad(u) + fenics.nabla_grad(u).T
                          )  #return sym(nabla_grad(u))

        def sigma_e(u):
            return lambda_ * ufl.nabla_div(u) * fenics.Identity(
                2) + 2 * mu * epsilon(u)

        def sigma_d(u):
            return eta_b * ufl.nabla_div(u) * fenics.Identity(
                2) + 2 * eta_s * epsilon(u)
#         def sigma_a(u,rho):
#             return ( -zeta_1*rho/(1+zeta_2*rho)*mu_a*fenics.Identity(2)*(K_0+K_1*ufl.nabla_div(u)+
#                                                                          K_2*ufl.nabla_div(u)*ufl.nabla_div(u)+K_3*ufl.nabla_div(u)*ufl.nabla_div(u)*ufl.nabla_div(u)))

        def sigma_a(u, rho):
            return -zeta_1 * rho / (
                1 + zeta_2 * rho) * mu_a * fenics.Identity(2) * (K_0)

        F = (gamma * fenics.dot(u, v) * fenics.dx -
             gamma * fenics.dot(u_n, v) * fenics.dx +
             fenics.inner(sigma_d(u), fenics.nabla_grad(v)) * fenics.dx -
             fenics.inner(sigma_d(u_n), fenics.nabla_grad(v)) * fenics.dx -
             delta_t *
             fenics.inner(sigma_e(u) + sigma_a(u, rho), fenics.nabla_grad(v)) *
             fenics.dx + rho * r * fenics.dx - rho_n * r * fenics.dx +
             ufl.nabla_div(rho * u) * r * fenics.dx -
             ufl.nabla_div(rho * u_n) * r * fenics.dx - D * delta_t *
             fenics.dot(fenics.nabla_grad(rho), fenics.nabla_grad(r)) *
             fenics.dx + delta_t *
             (-k_u * rho * fenics.exp(alpha * ufl.nabla_div(u)) + k_b *
              (1 - c * ufl.nabla_div(u))) * r * fenics.dx)

        #         F = ( gamma*fenics.dot(u,v)*fenics.dx - gamma*fenics.dot(u_n,v)*fenics.dx + fenics.inner(sigma_d(u),fenics.nabla_grad(v))*fenics.dx -
        #               fenics.inner(sigma_d(u_n),fenics.nabla_grad(v))*fenics.dx - delta_t*fenics.inner(sigma_e(u)+sigma_a(u,rho),fenics.nabla_grad(v))*fenics.dx
        #               +rho*r*fenics.dx-rho_n*r*fenics.dx + ufl.nabla_div(rho*u)*r*fenics.dx - ufl.nabla_div(rho*u_n)*r*fenics.dx -
        #               D*delta_t*fenics.dot(fenics.nabla_grad(rho),fenics.nabla_grad(r))*fenics.dx +delta_t*(-k_u*rho*fenics.exp(alpha*ufl.nabla_div(u))+k_b*(1-c*ufl.nabla_div(u))))

        vtkfile_rho = fenics.File(
            os.path.join(os.path.dirname(__file__), 'output', 'myosin_2d',
                         'solution_rho.pvd'))
        vtkfile_u = fenics.File(
            os.path.join(os.path.dirname(__file__), 'output', 'myosin_2d',
                         'solution_u.pvd'))

        #         rho_0 = fenics.Expression(((('0.0'),('0.0'),('0.0')),('sin(x[0])')), degree=1 )
        #         full_trial_function_n = fenics.project(rho_0, V)
        time = 0.0
        for time_index in range(number_of_time_steps):
            # Update current time
            time += delta_t
            # Compute solution
            fenics.solve(F == 0, full_trial_function)
            # Save to file and plot solution
            vis_u, vis_rho = full_trial_function.split()
            vtkfile_rho << (vis_rho, time)
            vtkfile_u << (vis_u, time)
            full_trial_function_n.assign(full_trial_function)
Ejemplo n.º 15
0
    def __init__(self, L, ne, r0, Q0, E, h0, theta, dt, degA=1, degQ=1):

        # -- Setup domain
        self.L = L
        self.ne = ne
        self.dt = dt
        self.mesh = fe.IntervalMesh(ne, 0, L)
        QE = fe.FiniteElement("Lagrange",
                              cell=self.mesh.ufl_cell(),
                              degree=degQ)
        AE = fe.FiniteElement("Lagrange",
                              cell=self.mesh.ufl_cell(),
                              degree=degA)
        ME = fe.MixedElement([AE, QE])

        # -- Setup functionspaces
        self.V = fe.FunctionSpace(self.mesh, ME)
        self.V_A = self.V.sub(0)
        self.V_Q = self.V.sub(1)
        (self.v1, self.v2) = fe.TestFunctions(self.V)
        self.dv1 = fe.grad(self.v1)[0]
        self.dv2 = fe.grad(self.v2)[0]
        self.E = E
        self.h0 = h0
        self.beta = E * h0 * np.sqrt(np.pi)
        self.A0 = np.pi * r0**2
        self.Q0 = Q0
        self.U0 = fe.Function(self.V)
        self.Un = fe.Function(self.V)

        # -- Setup initial conditions
        self.U0.assign(fe.Expression(('A0', 'Q0'), A0=self.A0, Q0=Q0,
                                     degree=1))
        self.Un.assign(fe.Expression(('A0', 'Q0'), A0=self.A0, Q0=Q0,
                                     degree=1))
        (self.u01, self.u02) = fe.split(self.U0)
        (self.un1, self.un2) = fe.split(self.Un)
        self.du01 = fe.grad(self.u01)[0]
        self.du02 = fe.grad(self.u02)[0]
        self.dun1 = fe.grad(self.un1)[0]
        self.dun2 = fe.grad(self.un2)[0]
        (self.W1_initial,
         self.W2_initial) = self.getCharacteristics(self.A0, self.Q0)

        # -- Setup weakform terms
        B0 = self.getB(self.u01, self.u02)
        Bn = self.getB(self.un1, self.un2)
        H0 = self.getH(self.u01, self.u02)
        Hn = self.getH(self.un1, self.un2)
        HdUdz0 = matMult(H0, [self.du01, self.du02])
        HdUdzn = matMult(Hn, [self.dun1, self.dun2])

        # -- Setup weakform
        wf = -self.un1 * self.v1 - self.un2 * self.v2
        wf += self.u01 * self.v1 + self.u02 * self.v2
        wf += -dt * theta * (HdUdzn[0] + Bn[0]) * self.v1 - dt * theta * (
            HdUdzn[1] + Bn[1]) * self.v2
        wf += -dt * (1 - theta) * (HdUdz0[0] + B0[0]) * self.v1 - dt * (
            1 - theta) * (HdUdz0[1] + B0[1]) * self.v2
        wf = wf * fe.dx
        self.wf = wf
        self.J = fe.derivative(wf, self.Un, fe.TrialFunction(self.V))
Ejemplo n.º 16
0
    def discretize(self):
        """Builds function space, call again after introducing constraints"""
        # FEniCS interface
        self.mesh = fn.IntervalMesh(self.N, self.x0_scaled, self.x1_scaled)

        # http://www.femtable.org/
        # Argyris*                          ARG
        # Arnold-Winther*                   AW
        # Brezzi-Douglas-Fortin-Marini*     BDFM
        # Brezzi-Douglas-Marini             BDM
        # Bubble                            B
        # Crouzeix-Raviart                  CR
        # Discontinuous Lagrange            DG
        # Discontinuous Raviart-Thomas      DRT
        # Hermite*                          HER
        # Lagrange                          CG
        # Mardal-Tai-Winther*               MTW
        # Morley*                           MOR
        # Nedelec 1st kind H(curl)          N1curl
        # Nedelec 2nd kind H(curl)          N2curl
        # Quadrature                        Q
        # Raviart-Thomas                    RT
        # Real                              R

        # construct test and trial function space from elements
        # spanned by Lagrange polynomials for the pyhsical variables of
        # potential and concentration and global elements with a single degree
        # of freedom ('Real') for constraints.
        # For an example of this approach, refer to
        #     https://fenicsproject.org/docs/dolfin/latest/python/demos/neumann-poisson/demo_neumann-poisson.py.html
        # For another example on how to construct and split function spaces
        # for solving coupled equations, refer to
        #     https://fenicsproject.org/docs/dolfin/latest/python/demos/mixed-poisson/demo_mixed-poisson.py.html

        P = fn.FiniteElement('Lagrange', fn.interval, 3)
        R = fn.FiniteElement('Real', fn.interval, 0)
        elements = [P] * (1 + self.M) + [R] * self.K

        H = fn.MixedElement(elements)
        self.W = fn.FunctionSpace(self.mesh, H)

        # solution functions
        self.w = fn.Function(self.W)

        # set initial values if available
        P = fn.FunctionSpace(self.mesh, 'P', 1)
        dof2vtx = fn.vertex_to_dof_map(P)
        if self.ui0 is not None:
            x = np.linspace(self.x0_scaled, self.x1_scaled, self.ui0.shape[0])
            ui0 = scipy.interpolate.interp1d(x, self.ui0)
            # use linear interpolation on mesh
            self.u0_func = fn.Function(P)
            self.u0_func.vector()[:] = ui0(self.X)[dof2vtx]
            fn.assign(self.w.sub(0),
                      fn.interpolate(self.u0_func,
                                     self.W.sub(0).collapse()))

        if self.ni0 is not None:
            x = np.linspace(self.x0_scaled, self.x1_scaled, self.ni0.shape[1])
            ni0 = scipy.interpolate.interp1d(x, self.ni0)
            self.p0_func = [fn.Function(P)] * self.ni0.shape[0]
            for k in range(self.ni0.shape[0]):
                self.p0_func[k].vector()[:] = ni0(self.X)[k, :][dof2vtx]
                fn.assign(
                    self.w.sub(1 + k),
                    fn.interpolate(self.p0_func[k],
                                   self.W.sub(k + 1).collapse()))

        # u represents voltage , p concentrations
        uplam = fn.split(self.w)
        self.u, self.p, self.lam = (uplam[0], [*uplam[1:(self.M + 1)]],
                                    [*uplam[(self.M + 1):]])

        # v, q and mu represent respective test functions
        vqmu = fn.TestFunctions(self.W)
        self.v, self.q, self.mu = (vqmu[0], [*vqmu[1:(self.M + 1)]],
                                   [*vqmu[(self.M + 1):]])
Ejemplo n.º 17
0
    def xest_implement_1d_myosin(self):
        #Parameters
        total_time = 10.0
        number_of_time_steps = 1000
        #         delta_t = fenics.Constant(total_time/number_of_time_steps)
        delta_t = total_time / number_of_time_steps
        nx = 1000
        domain_size = 1.0
        b = fenics.Constant(6.0)
        k = fenics.Constant(0.5)
        z_1 = fenics.Constant(-10.5)  #always negative
        #         z_1 = fenics.Constant(0.0) #always negative
        z_2 = 0.1  # always positive
        xi_0 = fenics.Constant(1.0)  #always positive
        xi_1 = fenics.Constant(1.0)  #always positive
        xi_2 = 0.001  #always positive
        xi_3 = 0.0001  #always negative
        d = fenics.Constant(0.15)
        alpha = fenics.Constant(1.0)
        c = fenics.Constant(0.1)

        # Sub domain for Periodic boundary condition
        class PeriodicBoundary(fenics.SubDomain):
            # Left boundary is "target domain" G
            def inside(self, x, on_boundary):
                return bool(-fenics.DOLFIN_EPS < x[0] < fenics.DOLFIN_EPS
                            and on_boundary)

            def map(self, x, y):
                y[0] = x[0] - 1

        periodic_boundary_condition = PeriodicBoundary()

        #Set up finite elements
        mesh = fenics.IntervalMesh(nx, 0.0, 1.0)
        vector_element = fenics.FiniteElement('P', fenics.interval, 1)
        single_element = fenics.FiniteElement('P', fenics.interval, 1)
        mixed_element = fenics.MixedElement(vector_element, single_element)
        V = fenics.FunctionSpace(
            mesh,
            mixed_element,
            constrained_domain=periodic_boundary_condition)
        #         V = fenics.FunctionSpace(mesh, mixed_element)
        v, r = fenics.TestFunctions(V)
        full_trial_function = fenics.Function(V)
        u, rho = fenics.split(full_trial_function)
        full_trial_function_n = fenics.Function(V)
        u_n, rho_n = fenics.split(full_trial_function_n)
        u_initial = fenics.Constant(0.0)
        #         rho_initial = fenics.Expression('1.0*sin(pi*x[0])*sin(pi*x[0])+1.0/k0', degree=2,k0 = k)
        rho_initial = fenics.Expression('1/k0', degree=2, k0=k)
        u_n = fenics.interpolate(u_initial, V.sub(0).collapse())
        rho_n = fenics.interpolate(rho_initial, V.sub(1).collapse())
        #         perturbation = np.zeros(rho_n.vector().size())
        #         perturbation[:int(perturbation.shape[0]/2)] = 1.0
        rho_n.vector().set_local(
            np.array(rho_n.vector()) + 1.0 *
            (0.5 - np.random.random(rho_n.vector().size())))
        #         u_n.vector().set_local(np.array(u_n.vector())+4.0*(0.5-np.random.random(u_n.vector().size())))
        fenics.assign(full_trial_function_n, [u_n, rho_n])
        u_n, rho_n = fenics.split(full_trial_function_n)

        F = (u * v * fenics.dx - u_n * v * fenics.dx + delta_t *
             (b + (z_1 * rho) /
              (1 + z_2 * rho) * c * xi_1) * u.dx(0) * v.dx(0) * fenics.dx -
             delta_t * (z_1 * rho) / (1 + z_2 * rho) * c * c * xi_2 / 2.0 *
             u.dx(0) * u.dx(0) * v.dx(0) * fenics.dx + delta_t * (z_1 * rho) /
             (1 + z_2 * rho) * c * c * c * xi_3 / 6.0 * u.dx(0) * u.dx(0) *
             u.dx(0) * v.dx(0) * fenics.dx - delta_t * z_1 * rho /
             (1 + z_2 * rho) * xi_0 * v.dx(0) * fenics.dx +
             u.dx(0) * v.dx(0) * fenics.dx - u_n.dx(0) * v.dx(0) * fenics.dx +
             rho * r * fenics.dx - rho_n * r * fenics.dx -
             rho * u * r.dx(0) * fenics.dx + rho * u_n * r.dx(0) * fenics.dx +
             delta_t * d * rho.dx(0) * r.dx(0) * fenics.dx +
             delta_t * k * fenics.exp(alpha * u.dx(0)) * rho * r * fenics.dx -
             delta_t * r * fenics.dx + delta_t * c * u.dx(0) * r * fenics.dx)

        vtkfile_rho = fenics.File(
            os.path.join(os.path.dirname(__file__), 'output', 'myosin_2d',
                         'solution_rho.pvd'))
        vtkfile_u = fenics.File(
            os.path.join(os.path.dirname(__file__), 'output', 'myosin_2d',
                         'solution_u.pvd'))

        #         rho_0 = fenics.Expression(((('0.0'),('0.0'),('0.0')),('sin(x[0])')), degree=1 )
        #         full_trial_function_n = fenics.project(rho_0, V)
        #         print('initial u and rho')
        #         print(u_n.vector())
        #         print(rho_n.vector())

        time = 0.0
        not_initialised = True
        plt.figure()
        for time_index in range(number_of_time_steps):
            # Update current time
            time += delta_t
            # Compute solution
            fenics.solve(F == 0, full_trial_function)
            # Save to file and plot solution
            vis_u, vis_rho = full_trial_function.split()
            plt.subplot(311)
            fenics.plot(vis_u, color='blue')
            plt.ylim(-0.5, 0.5)
            plt.subplot(312)
            fenics.plot(-vis_u.dx(0), color='blue')
            plt.ylim(-2, 2)
            plt.title('actin density change')
            plt.subplot(313)
            fenics.plot(vis_rho, color='blue')
            plt.title('myosin density')
            plt.ylim(0, 7)
            plt.tight_layout()
            if not_initialised:
                animation_camera = celluloid.Camera(plt.gcf())
                not_initialised = False
            animation_camera.snap()
            print('time is')
            print(time)
            #             plt.savefig(os.path.join(os.path.dirname(__file__),'output','this_output_at_time_' + '{:04d}'.format(time_index) + '.png'))
            #             print('this u and rho')
            #             print(np.array(vis_u.vector()))
            #             print(np.array(vis_rho.vector()))
            #             vtkfile_rho << (vis_rho, time)
            #             vtkfile_u << (vis_u, time)
            full_trial_function_n.assign(full_trial_function)

        animation = animation_camera.animate()
        animation.save(
            os.path.join(os.path.dirname(__file__), 'output', 'myosin_1D.mp4'))
Ejemplo n.º 18
0
    def demo64(self, permeability, obs_case=1):
        mesh = UnitSquareMesh(63, 63)
        ak_values = permeability
        flux_order = 3
        s = scenarios.darcy_problem_1()
        DRT = fenics.FiniteElement("DRT", mesh.ufl_cell(), flux_order)
        # Lagrange
        CG = fenics.FiniteElement("CG", mesh.ufl_cell(), flux_order + 1)
        if s.integral_constraint:
            # From https://fenicsproject.org/qa/14184/how-to-solve-linear-system-with-constaint
            R = fenics.FiniteElement("R", mesh.ufl_cell(), 0)
            W = fenics.FunctionSpace(mesh, fenics.MixedElement([DRT, CG, R]))
            # Define trial and test functions
            (sigma, u, r) = fenics.TrialFunctions(W)
            (tau, v, r_) = fenics.TestFunctions(W)
        else:
            W = fenics.FunctionSpace(mesh, DRT * CG)
            # Define trial and test functions
            (sigma, u) = fenics.TrialFunctions(W)
            (tau, v) = fenics.TestFunctions(W)
        f = s.source_function
        g = s.g

        # Define property field function
        W_CG = fenics.FunctionSpace(mesh, "Lagrange", 1)
        if s.ak is None:
            ak = property_field.get_conductivity(W_CG, ak_values)
        else:
            ak = s.ak

        # Define variational form
        a = (fenics.dot(sigma, tau) + fenics.dot(ak * fenics.grad(u), tau) +
             fenics.dot(sigma, fenics.grad(v))) * fenics.dx
        L = -f * v * fenics.dx + g * v * fenics.ds
        # L = 0
        if s.integral_constraint:
            # Lagrange multiplier?  See above link.
            a += r_ * u * fenics.dx + v * r * fenics.dx
        # Define Dirichlet BC
        bc = fenics.DirichletBC(W.sub(1), s.dirichlet_bc, s.gamma_dirichlet)
        # Compute solution

        w = fenics.Function(W)
        fenics.solve(a == L, w, bc)
        # fenics.solve(a == L, w)
        if s.integral_constraint:
            (sigma, u, r) = w.split()
        else:
            (sigma, u) = w.split()
        x = u.compute_vertex_values(mesh)
        x2 = sigma.compute_vertex_values(mesh)
        p = x
        pre = p.reshape((64, 64))
        vx = x2[:4096].reshape((64, 64))
        vy = x2[4096:].reshape((64, 64))

        if obs_case == 1:
            dd = np.zeros([8, 8])
            pos = np.full((8 * 8, 2), 0)
            col = [4, 12, 20, 28, 36, 44, 52, 60]
            position = [4, 12, 20, 28, 36, 44, 52, 60]
            for i in range(8):
                for j in range(8):
                    row = position
                    pos[8 * i + j, :] = [col[i], row[j]]
                    dd[i, j] = pre[col[i], row[j]]
            like = dd.reshape(8 * 8, )
        return like, pre, vx, vy, ak_values, pos
Ejemplo n.º 19
0
for cycle in range(initial_hot_wall_refinement_cycles):

    edge_markers = fenics.MeshFunction("bool", mesh, 1, False)

    hot_wall.mark(edge_markers, True)

    fenics.adapt(mesh, edge_markers)

    mesh = mesh.child()

P1 = fenics.FiniteElement('P', mesh.ufl_cell(), 1)

P2 = fenics.VectorElement('P', mesh.ufl_cell(), 2)

mixed_element = fenics.MixedElement([P1, P2, P1])

W = fenics.FunctionSpace(mesh, mixed_element)

psi_p, psi_u, psi_T = fenics.TestFunctions(W)

w = fenics.Function(W)

p, u, T = fenics.split(w)

prandtl_number = 56.2

Pr = fenics.Constant(prandtl_number)

rayleigh_number = 3.27e5
Ejemplo n.º 20
0
time = np.linspace(0,(T/2+(0.25-0.165)),int(nt))
dt = time[1]-time[0]
time = np.array(time)
Pin = 2e4*np.sin(2*np.pi*time/T) * np.heaviside(T/2-time,1)
Ain = (Pin*A0/beta+np.sqrt(A0))**2;


# -- Spatial domain
ne = 2**7
L = 15
mesh = fe.IntervalMesh(int(ne),0,L)
degQ = 1 
degA = 1
QE     = fe.FiniteElement("Lagrange", cell=mesh.ufl_cell(), degree=degQ)
AE     = fe.FiniteElement("Lagrange", cell=mesh.ufl_cell(), degree=degA)
ME     = fe.MixedElement([AE,QE])
V      = fe.FunctionSpace(mesh,ME)
V_A = V.sub(0)
V_Q = V.sub(1)
(v1,v2) = fe.TestFunctions(V)
dv1 = fe.grad(v1)[0]
dv2 = fe.grad(v2)[0]
(u1,u2) = fe.TrialFunctions(V)
U0 = fe.Function(V)
U0.assign( fe.Expression( ( 'A0', 'Q0' ) , A0=A0, Q0=Q0, degree=1 ) )
Un = fe.Function(V)
Un.assign( fe.Expression( ( 'A0', 'Q0' ) , A0=A0, Q0=Q0, degree=1 ) )
(u01,u02) = fe.split(U0)
(un1,un2) = fe.split(Un)
du01 = fe.grad(u01)[0] ; du02 = fe.grad(u02)[0]
dun1 = fe.grad(un1)[0] ; dun2 = fe.grad(un2)[0]
Ejemplo n.º 21
0
mesh, dx, ds, boundaries = load_2d_muscle_geo()
cell = mesh.ufl_cell()
dim = 2

# Notation
#  u: displacement field
#  p: lagrange multiplier, pressure
#  v: velocity field

element_u = fe.VectorElement('CG', cell, 2)
element_p = fe.FiniteElement('CG', cell, 1)
element_v = fe.VectorElement('CG', cell, 2)

# define mixed elements
mix_up = fe.MixedElement([element_u, element_p])
mix_uv = fe.MixedElement([element_u, element_v])
mix_pv = fe.MixedElement([element_p, element_v])
mix_upv = fe.MixedElement([element_u, element_p, element_v])

# define function spaces
V_u = fe.FunctionSpace(mesh, element_u)
V_p = fe.FunctionSpace(mesh, element_p)
V_v = fe.FunctionSpace(mesh, element_v)
V_up = fe.FunctionSpace(mesh, mix_up)
V_uv = fe.FunctionSpace(mesh, mix_uv)
V_pv = fe.FunctionSpace(mesh, mix_pv)
V_upv = fe.FunctionSpace(mesh, mix_upv)

# Material constants
c_10 = fe.Constant(1e4)
Ejemplo n.º 22
0
    def demo16(self, permeability, obs_case=1):
        """This demo program solves the mixed formulation of Poisson's
        equation:

            sigma + grad(u) = 0    in Omega
                div(sigma) = f    in Omega
                    du/dn = g    on Gamma_N
                        u = u_D  on Gamma_D
        
        The corresponding weak (variational problem)
        
            <sigma, tau> + <grad(u), tau>   = 0
                                                    for all tau
                        - <sigma, grad(v)> = <f, v> + <g, v>
                                                    for all v
        
        is solved using DRT (Discontinuous Raviart-Thomas) elements
        of degree k for (sigma, tau) and CG (Lagrange) elements
        of degree k + 1 for (u, v) for k >= 1.
        """

        mesh = UnitSquareMesh(15, 15)
        ak_values = permeability
        flux_order = 3
        s = scenarios.darcy_problem_1()
        DRT = fenics.FiniteElement("DRT", mesh.ufl_cell(), flux_order)
        # Lagrange
        CG = fenics.FiniteElement("CG", mesh.ufl_cell(), flux_order + 1)
        if s.integral_constraint:
            # From https://fenicsproject.org/qa/14184/how-to-solve-linear-system-with-constaint
            R = fenics.FiniteElement("R", mesh.ufl_cell(), 0)
            W = fenics.FunctionSpace(mesh, fenics.MixedElement([DRT, CG, R]))
            # Define trial and test functions
            (sigma, u, r) = fenics.TrialFunctions(W)
            (tau, v, r_) = fenics.TestFunctions(W)
        else:
            W = fenics.FunctionSpace(mesh, DRT * CG)
            # Define trial and test functions
            (sigma, u) = fenics.TrialFunctions(W)
            (tau, v) = fenics.TestFunctions(W)
        f = s.source_function
        g = s.g

        # Define property field function
        W_CG = fenics.FunctionSpace(mesh, "Lagrange", 1)
        if s.ak is None:
            ak = property_field.get_conductivity(W_CG, ak_values)
        else:
            ak = s.ak

        # Define variational form
        a = (fenics.dot(sigma, tau) + fenics.dot(ak * fenics.grad(u), tau) +
             fenics.dot(sigma, fenics.grad(v))) * fenics.dx
        L = -f * v * fenics.dx + g * v * fenics.ds
        # L = 0
        if s.integral_constraint:
            # Lagrange multiplier?  See above link.
            a += r_ * u * fenics.dx + v * r * fenics.dx
        # Define Dirichlet BC
        bc = fenics.DirichletBC(W.sub(1), s.dirichlet_bc, s.gamma_dirichlet)
        # Compute solution
        w = fenics.Function(W)
        fenics.solve(a == L, w, bc)
        # fenics.solve(a == L, w)
        if s.integral_constraint:
            (sigma, u, r) = w.split()
        else:
            (sigma, u) = w.split()
        x = u.compute_vertex_values(mesh)
        x2 = sigma.compute_vertex_values(mesh)
        p = x
        pre = p.reshape((16, 16))
        vx = x2[:256].reshape((16, 16))
        vy = x2[256:].reshape((16, 16))

        if obs_case == 1:
            dd = np.zeros([8, 8])
            pos = np.full((8 * 8, 2), 0)
            col = [1, 3, 5, 7, 9, 11, 13, 15]
            position = [1, 3, 5, 7, 9, 11, 13, 15]
            for i in range(8):
                for j in range(8):
                    row = position
                    pos[8 * i + j, :] = [col[i], row[j]]
                    dd[i, j] = pre[col[i], row[j]]
            like = dd.reshape(8 * 8, )
        return like, pre, vx, vy, ak_values, pos
Ejemplo n.º 23
0
import fenics as fn
# set parameters
fn.parameters["form_compiler"]["representation"] = "uflacs"
fn.parameters["form_compiler"]["cpp_optimize"] = True

# mesh setup
nps = 64  # number of points
mesh = fn.UnitSquareMesh(nps, nps)
fileu = fn.File(mesh.mpi_comm(), "Output/1_3_Schnackenberg/u.pvd")
filev = fn.File(mesh.mpi_comm(), "Output/1_3_Schnackenberg/v.pvd")

# function spaces
P1 = fn.FiniteElement("Lagrange", mesh.ufl_cell(), 1)
Mh = fn.FunctionSpace(mesh, "Lagrange", 1)
Nh = fn.FunctionSpace(mesh, fn.MixedElement([P1, P1]))
Sol = fn.Function(Nh)

# trial and test functions
u, v = fn.TrialFunctions(Nh)
uT, vT = fn.TestFunctions(Nh)

# model constants
a = fn.Constant(0.1305)
b = fn.Constant(0.7695)
c1 = fn.Constant(0.05)
c2 = fn.Constant(1.0)
d = fn.Constant(170.0)

# initial value
uinit = fn.Expression('a + b + 0.001 * exp(-100.0 * (pow(x[0] - 1.0/3, 2)' +
                      ' + pow(x[1] - 0.5, 2)))',
Ejemplo n.º 24
0
with fn.XDMFFile("meshing/Dmesh.xdmf") as infile:
    infile.read(mesh)
mvc = fn.MeshValueCollection("size_t", mesh, 2)
with fn.XDMFFile("meshing/Dmf.xdmf") as infile:
    infile.read(mvc, "name_to_read")
mf = fn.cpp.mesh.MeshFunctionSizet(mesh, mvc)

# %%
M = 2  #species

Poly = fn.FiniteElement('Lagrange', mesh.ufl_cell(), 2)
Multi = fn.FiniteElement('Real', mesh.ufl_cell(), 0)
ElemP = [Poly] * (M + 1)
ElemR = [Multi] * (M)
Elem = [ElemP + ElemR][0]
Mixed = fn.MixedElement(Elem)
V = fn.FunctionSpace(mesh, Mixed)

# %%
# define potentials and concentrations
u_GND = fn.Expression('0', degree=2)  #Ground
u_DD = fn.Expression('0.5', degree=2)  #pontential
c_avg = fn.Expression('0.0001', degree=2)  #average concentration

# set boundary conditions
bcs = []
bcs += [fn.DirichletBC(V.sub(0), u_DD, mf, 3)]
bcs += [fn.DirichletBC(V.sub(0), u_GND, mf, 1)]

# define problem
UC = fn.Function(V)
Ejemplo n.º 25
0
    def compute_conv_diff_reac_video(self, initial_condition=None, video_ref=None, video_size=None):

        names = {'Cl', 'K'}


        P1 = FiniteElement('P', fe.triangle, 1)
        element = fe.MixedElement([P1, P1])
        V_single = FunctionSpace(self.mesh, P1)
        V = FunctionSpace(self.mesh, element)
        self.V_conc = V

        # load video
        video = VideoData(element=P1)
        video.load_video(self.video_filename)

        if( video_ref is not None and video_size is not None):
            video.set_reference_frame(video_ref, video_size)


        print(video)

        dt = 0.05
        t = 0.
        t_end = 20.

        u_init = Function(V)
        (u_cl, u_k) = TrialFunction(V)
        (v_cl, v_k) = TestFunction(V)

        #u_na = video


        if initial_condition is None:
            #initial_condition = Expression(("f*exp(-0.5*((x[0]-a)*(x[0]-a)+(x[1]-b)*(x[1]-b))/var)/(sqrt(2*pi)*var)",
            #                                "0."), a = 80, b= 55, var=10, f=10, pi=fe.pi, element=element)

            initial_condition = Expression(("f",
                                            "0."), a=80, b=55, var=0.1, f=0.1, pi=fe.pi, element=element)

        u_init = fe.interpolate(initial_condition, V)
        u_init_cl = u_init[0]

        u_init_k = u_init[1]
        u_init_na : VideoData= video

        assert (self.flow is not None)

        n = fe.FacetNormal(self.mesh)

        dx, ds = self.dx, self.ds
        flow = 5. * self.flow
        f_in = fe.Constant(0.00)
        f_in_cl = fe.Constant(-0.05)
        D = fe.Constant(0.1)

        C_na = fe.Constant(0.1)
        k1 = fe.Constant(0.2)
        k_1 = fe.Constant(0.00001)
        # explicit
        F = (
                (u_cl - u_init_cl) * v_cl * dx
                + dt * D * inner(grad(u_cl), grad(v_cl)) * dx
                + dt * inner(flow, grad(u_cl)) * v_cl * dx
                #+ (u_na - u_init_na) * v_na * dx
                #+ dt * D * inner(grad(u_na), grad(v_na)) * dx
                #+ dt * inner(flow, grad(u_na)) * v_na * dx
                + (u_k - u_init_k) * v_k * dx
                + dt * D * inner(grad(u_k), grad(v_k)) * dx
                + dt * inner(flow, grad(u_k)) * v_k * dx
                + f_in_cl * v_cl * dx
                #+ f_in * v_na * dx
                + f_in * v_k * dx
                + dt * k1 * u_init_cl * C_na * u_init_na * v_cl * dx
                #+ dt * k1 * u_init_cl * u_init_na * v_na * dx
                - dt * k1 * u_init_cl * C_na * u_init_na * v_k * dx
                - dt * k_1 * u_init_k * v_cl * dx
                #- dt * k_1 * u_init_k * v_na * dx
                + dt * k_1 * u_init_k * v_k * dx
        )
        # implicit
        F = (
                (u_cl - u_init_cl) * v_cl * dx
                + dt * D * inner(grad(u_cl), grad(v_cl)) * dx
                + dt * inner(flow, grad(u_cl)) * v_cl * dx
                # + (u_na - u_init_na) * v_na * dx
                # + dt * D * inner(grad(u_na), grad(v_na)) * dx
                # + dt * inner(flow, grad(u_na)) * v_na * dx
                + (u_k - u_init_k) * v_k * dx
                + dt * D * inner(grad(u_k), grad(v_k)) * dx
                + dt * inner(flow, grad(u_k)) * v_k * dx
                + f_in_cl * v_cl * dx
                # + f_in * v_na * dx
                + f_in * v_k * dx
                + dt * k1 * u_cl * C_na * u_init_na * v_cl * dx
                # + dt * k1 * u_init_cl * u_init_na * v_na * dx
                - dt * k1 * u_cl * C_na * u_init_na * v_k * dx
                - dt * k_1 * u_k * v_cl * dx
                # - dt * k_1 * u_init_k * v_na * dx
                + dt * k_1 * u_k * v_k * dx
        )

        self.F = F

        a, L = fe.lhs(F), fe.rhs(F)
        a_mat = fe.assemble(a)
        L_vec = fe.assemble(L)

        output1 = fe.File('/tmp/cl_dyn.pvd')
        output2 = fe.File('/tmp/na_dyn.pvd')
        output3 = fe.File('/tmp/k_dyn.pvd')
        output4 = fe.File('/tmp/all_dyn.pvd')
        # solve

        self.sol = []

        u_na = Function(V_single)
        u_na = fe.interpolate(u_init_na,V_single)

        na_inflow = 0

        t_plot = 0.5
        t_last_plot = 0

        while t < t_end:
            t = t + dt
            t_last_plot += dt
            print(t)

            u = Function(V)

            u_init_na.set_time(5*t)

            a_mat = fe.assemble(a)
            L_vec = fe.assemble(L)
            fe.solve(a_mat, u.vector(), L_vec)
            # NonlinearVariationalProblem(F,u)
            u_init.assign(u)

            u_cl, u_k = u.split()

            # u_init_cl.assign(u_cl)
            # u_init_na.assign(u_na)
            # u_init_k.assign(u_k)

            u_na = fe.interpolate(u_init_na, V_single)

            u_cl.rename("cl", "cl")
            u_na.rename("na", "na")
            u_k.rename("k", "k")
            output1 << u_cl, t
            output2 << u_na, t
            output3 << u_k, t
            self.sol.append((u_cl, u_na, u_k))

            print( fe.assemble(u_cl*self.dx))

            if t_last_plot > t_plot:
                t_last_plot = 0
                plt.figure(figsize=(8,16))
                plt.subplot(211)
                fe.plot(u_cl)
                plt.subplot(212)
                fe.plot(u_k)
                plt.show()



        self.u_cl = u_cl
        #self.u_na = u_na
        self.u_k = u_k