示例#1
0
    def run(self):
        domain = self._create_domain()
        mesh = generate_mesh(domain, MESH_PTS)
        
        # fe.plot(mesh)
        # plt.show()

        self._create_boundary_expression()
        
        Omega = fe.FiniteElement("Lagrange", mesh.ufl_cell(), 1)
        R = fe.FiniteElement("Real", mesh.ufl_cell(), 0)
        W = fe.FunctionSpace(mesh, Omega*R)
        Theta, c = fe.TrialFunction(W)
        v, d = fe.TestFunctions(W)
        sigma = self.conductivity
        
        LHS = (sigma * fe.inner(fe.grad(Theta), fe.grad(v)) + c*v + Theta*d) * fe.dx
        RHS = self.boundary_exp * v * fe.ds

        w = fe.Function(W)
        fe.solve(LHS == RHS, w)
        Theta, c = w.split()
        print(c(0, 0))

        # fe.plot(Theta, "solution", mode='color', vmin=-3, vmax=3)
        # plt.show()

        plot(fe.interpolate(Theta, fe.FunctionSpace(mesh, Omega)), mode='color')
        plt.show()
示例#2
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
示例#3
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])
示例#4
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
示例#5
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
示例#6
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
示例#7
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)
示例#8
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
示例#9
0
    def run(self):
        e_domain = self._create_e_domain()
        mesh = generate_mesh(e_domain, MESH_PTS)

        self._create_boundary_expression()

        Omega_e = fe.FiniteElement("Lagrange", mesh.ufl_cell(), 1)
        Omega_i = fe.FiniteElement("Lagrange",
                                   self.passive_seg.mesh.ufl_cell(), 1)
        Omega = fe.FunctionSpace(mesh, Omega_e * Omega_i)
        Theta_e, Theta_i = fe.TrialFunction(Omega)
        v_e, v_i = fe.TestFunctions(Omega)
        sigma_e, sigma_i = 0.3, 0.4

        LHS = sigma_e * fe.inner(fe.grad(Theta_e),
                                 fe.grad(v_e)) * fe.dx  # poisson
        LHS += sigma_i * fe.inner(fe.grad(Theta_i),
                                  fe.grad(v_i)) * fe.dx  # poisson
        LHS -= sigma_e * fe.grad(Theta_e) * v_e * fe.ds  # current
        LHS += sigma_i * fe.grad(Theta_i) * v_i * fe.ds  # current
        RHS = self.boundary_exp * v_e * fe.ds  # source term

        # TODO: solve Poisson in extracellular space
        w = fe.Function(Omega)
        fe.solve(LHS == RHS, w)
        Theta_e, Theta_i = w.split()

        plot(fe.interpolate(Theta, fe.FunctionSpace(mesh, Omega)),
             mode='color')
        plt.show()

        # Set the potential just inside the membrane to Ve (just computed)
        # minus V_m (from prev timestep)
        self.passive_seg.set_v(Theta, self.passive_seg_vm)

        # Solve for the potential and current inside the passive cell
        self.passive_seg.run()

        # Use Im to compute a new Vm for the next timestep, eq (8)
        self.passive_seg_vm = self.passive_seg_vm + self.dt / self.cm * (
            self.passive_seg_im - self.passive_seg_vm / self.rm)
示例#10
0
def Vufl(soln, t):
    "Make a UFL object for plotting V"
    split = fe.split(soln.function)
    irho = split[0]
    iUs = split[1:]
    soln.ksdg.set_time(t)
    V = (soln.V(iUs, irho, params=soln.ksdg.iparams) /
         (soln.ksdg.iparams['sigma']**2 / 2))
    fs = soln.function.function_space()
    cell = fs.ufl_cell()
    CE = fe.FiniteElement('CG', cell, soln.degree)
    CS = fe.FunctionSpace(fs.mesh(), CE)
    pV = fe.project(V, CS, solver_type='petsc')
    return pV
示例#11
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)
    return alphabar + (alphaunderbar - alphabar) * rho * (1 + q) / (rho + q)


N = 20
delta = 1.5  # The aspect ratio of the domain, 1 high and \delta wide
V = (
    fenics_adjoint.Constant(1.0 / 3) * delta
)  # want the fluid to occupy 1/3 of the domain

mesh = fenics_adjoint.Mesh(
    fenics.RectangleMesh(fenics.Point(0.0, 0.0), fenics.Point(delta, 1.0), N, N)
)
A = fenics.FunctionSpace(mesh, "CG", 1)  # control function space

U_h = fenics.VectorElement("CG", mesh.ufl_cell(), 2)
P_h = fenics.FiniteElement("CG", mesh.ufl_cell(), 1)
W = fenics.FunctionSpace(mesh, U_h * P_h)  # mixed Taylor-Hood function space

# Define the boundary condition on velocity
(x, y) = ufl.SpatialCoordinate(mesh)
l = 1.0 / 6.0  # noqa: E741
gbar = 1.0
cond1 = ufl.And(ufl.gt(y, (1.0 / 4 - l / 2)), ufl.lt(y, (1.0 / 4 + l / 2)))
val1 = gbar * (1 - (2 * (y - 0.25) / l) ** 2)
cond2 = ufl.And(ufl.gt(y, (3.0 / 4 - l / 2)), ufl.lt(y, (3.0 / 4 + l / 2)))
val2 = gbar * (1 - (2 * (y - 0.75) / l) ** 2)
inflow_outflow = ufl.conditional(cond1, val1, ufl.conditional(cond2, val2, 0))
inflow_outflow_bc = fenics_adjoint.project(inflow_outflow, W.sub(0).sub(0).collapse())

solve_templates = (fenics_adjoint.Function(A),)
assemble_templates = (fenics_adjoint.Function(W), fenics_adjoint.Function(A))
示例#13
0
import fenics as fn
fn.parameters["form_compiler"]["representation"] = "uflacs"
fn.parameters["form_compiler"]["cpp_optimize"] = True

# 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
示例#14
0
# -------------Create DOLPHIN mesh and define function space----------
ae = 1.0
edge = 2 * ae  # размер области
G = 1.0
m_sun = 1.0
rad_sun = 0.05
ncells = 256

tol = 1E-14

domain = mshr.Rectangle(fen.Point(-edge, -edge), fen.Point(edge, edge))

# generate mesh and determination of the Function Space
mesh = mshr.generate_mesh(domain, ncells)

P1 = fen.FiniteElement('CG', fen.triangle, 1)

V = fen.FunctionSpace(mesh, P1)
Q = fen.FunctionSpace(mesh, 'DG', 0)

# -------------Define boundary condition------------
phi_L = fen.Expression('-G*m_sun/pow(pow(x[1], 2) + pow(edge, 2),0.5)',
                       degree=2,
                       G=G,
                       m_sun=m_sun,
                       edge=edge)
phi_R = fen.Expression('-G*m_sun/pow(pow(x[1], 2) + pow(edge, 2),0.5)',
                       degree=2,
                       G=G,
                       m_sun=m_sun,
                       edge=edge)
示例#15
0
    def monolithic_solve(self):
        self.U = fe.VectorElement('CG', self.mesh.ufl_cell(), 1)
        self.W = fe.FiniteElement("CG", self.mesh.ufl_cell(), 1)
        self.M = fe.FunctionSpace(self.mesh, self.U * self.W)

        self.WW = fe.FunctionSpace(self.mesh, 'DG', 0)

        m_test = fe.TestFunctions(self.M)
        m_delta = fe.TrialFunctions(self.M)
        m_new = fe.Function(self.M)

        self.eta, self.zeta = m_test
        self.x_new, self.d_new = fe.split(m_new)

        self.H_old = fe.Function(self.WW)

        vtkfile_u = fe.File('data/pvd/{}/u.pvd'.format(self.case_name))
        vtkfile_d = fe.File('data/pvd/{}/d.pvd'.format(self.case_name))

        self.build_weak_form_monolithic()
        dG = fe.derivative(self.G, m_new)

        self.set_bcs_monolithic()
        p = fe.NonlinearVariationalProblem(self.G, m_new, self.BC, dG)
        solver = fe.NonlinearVariationalSolver(p)

        for i, (disp, rp) in enumerate(
                zip(self.displacements, self.relaxation_parameters)):

            print('\n')
            print(
                '================================================================================='
            )
            print('>> Step {}, disp boundary condition = {} [mm]'.format(
                i, disp))
            print(
                '================================================================================='
            )

            self.H_old.assign(
                fe.project(
                    history(self.H_old, self.psi(strain(fe.grad(self.x_new))),
                            self.psi_cr), self.WW))

            self.presLoad.t = disp

            newton_prm = solver.parameters['newton_solver']
            newton_prm['maximum_iterations'] = 100
            newton_prm['absolute_tolerance'] = 1e-4
            newton_prm['relaxation_parameter'] = rp

            solver.solve()

            self.x_plot, self.d_plot = m_new.split()
            self.x_plot.rename("u", "u")
            self.d_plot.rename("d", "d")

            vtkfile_u << self.x_plot
            vtkfile_d << self.d_plot

            force_upper = float(fe.assemble(self.sigma[1, 1] * self.ds(1)))
            print("Force upper {}".format(force_upper))
            self.delta_u_recorded.append(disp)
            self.sigma_recorded.append(force_upper)

            print(
                '================================================================================='
            )
示例#16
0
# %%

# %%
mesh = fn.Mesh()
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 = []
示例#17
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
示例#18
0
# fenics parameters
fn.parameters["form_compiler"]["representation"] = "uflacs"
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)
示例#19
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):]])
示例#20
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))
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)))',
示例#22
0
from load_meshes import load_2d_muscle_geo, load_2d_muscle_bc

from plotting_tools import *

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)
示例#23
0
DEG = 2

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])

#-------------------------------------------------------
示例#24
0
#
#
#                                      Writing it in weak form, here v is the test function
#
#                                              (𝑣,𝜕𝑡ℎ)=−𝑑𝑇/𝑑ℎ(𝑘/𝜌)(∇𝑣,∇ℎ)
#
#                                      Since it is a non-linear problem,
#
#                                       F= (𝑣,𝜕𝑡ℎ)+𝑑𝑇/𝑑ℎ (𝑘/𝜌)(∇𝑣,∇ℎ)=0
#
#                                      is solved by newton's method.
#

#The one dimensional mesg spanned by piecewise polynomial
mesh = fe.UnitIntervalMesh(Mesh_size)  #One Dimensional mesh
P1 = fe.FiniteElement('P', mesh.ufl_cell(), 1)
V = fe.FunctionSpace(
    mesh, P1)  #Function space spanned by piecewise linear polynomials
v = fe.TestFunction(V)  #Test function
h = fe.Function(V)  #Enthalpy-Trial function
fe.plot(mesh)
plt.show()

#Temperature is assumed to be a function of the third power of enthalpy as a guess.


def Temp(h):  #Temperature as a function of enthalpy
    return (
        (h)**3
    )  # Approximating the fuction to be cubic such that it closely resemble the physics of the problem
示例#25
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)
示例#26
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'))
示例#27
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
示例#28
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})
示例#29
0
import numpy as np

#import matplotlib.pyplot as plt

# some fenics settings
fe.parameters['form_compiler']['cpp_optimize'] = True
fe.parameters['form_compiler']['optimize'] = True
#fe.parameters["form_compiler"]["quadrature_degree"] = 5

# Create mesh and define function space
n = 20
mesh = fe.UnitCubeMesh(n, n, n)

# Init function spaces
element_3 = fe.VectorElement("P", mesh.ufl_cell(), 1)
element = fe.FiniteElement("P", mesh.ufl_cell(), 2)

# Mixed function space
TH = element_3 * element
V = fe.FunctionSpace(mesh, TH)

# Define Boundaries
left = fe.CompiledSubDomain("near(x[0], side) && on_boundary", side=0.0)
right = fe.CompiledSubDomain("near(x[0], side) && on_boundary", side=1.0)

# Define Dirichlet boundary (x = 0 or x = 1)
u_left = fe.Expression(("0.0", "0.0", "0.0"), element=element_3)
u_right = fe.Expression(("0.0", "0.0", "0.0"), element=element_3)
p_left = fe.Constant(0.)

# Define acting force
示例#30
0
T = 2*0.165
nt = 1e3
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)