### Dolfin Implementation: Setup and Parameters
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_sources/demos/elastodynamics/demo_elastodynamics.py.rst
Python code snippet demonstrating the setup of a DOLFIN simulation. It includes importing libraries, configuring compiler options, defining mesh geometry, and setting up boundary conditions for a clamped beam problem.
```python
from dolfin import *
import numpy as np
import matplotlib.pyplot as plt
# Form compiler options
parameters["form_compiler"]["cpp_optimize"] = True
parameters["form_compiler"]["optimize"] = True
# Define mesh
mesh = BoxMesh(Point(0., 0., 0.), Point(1., 0.1, 0.04), 60, 10, 5)
# Sub domain for clamp at left end
def left(x, on_boundary):
return near(x[0], 0.) and on_boundary
# Sub domain for rotation at right end
def right(x, on_boundary):
return near(x[0], 1.) and on_boundary
```
--------------------------------
### Demo and Example Updates
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/ChangeLog
Mentions the addition of new demos or examples to showcase DOLFIN's capabilities.
```APIDOC
Demos:
- Add elastodynamics demo.
- Includes a new demonstration case for elastodynamics simulations.
```
--------------------------------
### Demo Examples
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_sources/ChangeLog.rst
Notes on new demo examples added to showcase specific functionalities.
```APIDOC
Demo Examples:
- Add Stokes demo using the MINI element.
- Add SpatialCoordinates demo.
```
--------------------------------
### Rush-Larsen Scheme Setup (Order 1 & 2)
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_modules/dolfin/multistage/rushlarsenschemes
This snippet demonstrates the setup for the Rush-Larsen time-stepping scheme for different orders (1 and 2). It initializes stage solutions, generates UFL forms for intermediate steps, and converts them to Dolfin forms. It handles the specific calculations for each order, including derivatives and linearizations.
```python
trial = TrialFunction(soln.function_space())
# Stage solutions (3 per order rhs, linearized, and final step)
# If 2nd order the final step for 1 step is a stage
if order == 1:
stage_solutions = []
# Fetch the original step
rl_ufl_form = _rush_larsen_step(rhs_exprs, diff_rhs_exprs,
linear_terms, system_size,
solution, None, dt, time, 1.0,
0.0, v, DX,
time_dep_expressions)
rl_ufl_form = safe_action(derivative(rl_ufl_form, soln, trial), perturbation)
elif order == 2:
# Stage solution for order 2
fn_space = soln.function_space()
stage_solutions = [Function(fn_space, name="y_1/2"),
Function(fn_space, name="y_dot_1/2"),
Function(fn_space, name="y_1")]
y_half_form = _rush_larsen_step(rhs_exprs, diff_rhs_exprs,
linear_terms, system_size,
solution, None, dt, time, 0.5,
0.0, v, DX,
time_dep_expressions)
y_dot_half_form = safe_action(derivative(y_half_form, soln, trial), perturbation)
y_one_form = _rush_larsen_step(rhs_exprs, diff_rhs_exprs,
linear_terms, system_size,
solution, stage_solutions[0],
dt, time, 1.0, 0.5, v, DX,
time_dep_expressions)
rl_ufl_form = safe_action(derivative(y_one_form, soln, trial), perturbation) + \
safe_action(derivative(y_one_form, stage_solutions[0], trial), stage_solutions[1])
ufl_stage_forms.append([y_half_form])
ufl_stage_forms.append([y_dot_half_form])
ufl_stage_forms.append([y_one_form])
dolfin_stage_forms.append([Form(y_half_form)])
dolfin_stage_forms.append([Form(y_dot_half_form)])
dolfin_stage_forms.append([Form(y_one_form)])
# Get last stage form
last_stage = Form(rl_ufl_form)
human_form = "%srush larsen %s" % ("generalized " if generalized else "",
str(order))
return rhs_form, linear_terms, ufl_stage_forms, dolfin_stage_forms, last_stage, \
stage_solutions, dt, dt_stage_offsets, human_form, perturbation
```
--------------------------------
### Setup Rush-Larsen Scheme Components
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_modules/dolfin/multistage/rushlarsenschemes
This Python function orchestrates the setup of a Rush-Larsen time-stepping scheme. It prepares UFL forms, Dolfin forms, and associated data structures based on the order of the scheme and whether the right-hand side is vectorized. It handles the extraction of linear terms and derivatives, returning all necessary components for integration into a solver.
```python
def _rush_larsen_scheme_generator(rhs_form, solution, time, order,
generalized):
"""Generates a list of forms and solutions for the Rush-Larsen scheme
*Arguments*
rhs_form (ufl.Form)
A UFL form representing the rhs for a time differentiated equation
solution (_Function_)
The prognostic variable
time (_Constant_)
A Constant holding the time at the start of the time step
order (int)
The order of the scheme
generalized (bool)
If True generate a generalized Rush Larsen scheme, linearizing all
components.
"""
DX = _check_form(rhs_form)
if DX != ufl.dP:
raise TypeError("Expected a form with a Pointintegral.")
# Create time step
dt = Constant(0.1)
# Get test function
# arguments = rhs_form.arguments()
# coefficients = rhs_form.coefficients()
# Get time dependent expressions
time_dep_expressions = _time_dependent_expressions(rhs_form, time)
# Extract rhs expressions from form
rhs_integrand = rhs_form.integrals()[0].integrand()
rhs_exprs, v = extract_tested_expressions(rhs_integrand)
vector_rhs = len(v.ufl_shape) > 0 and v.ufl_shape[0] > 1
system_size = v.ufl_shape[0] if vector_rhs else 1
# Fix for indexing of v for scalar expressions
v = v if vector_rhs else [v]
# Extract linear terms if not using generalized Rush Larsen
if not generalized:
linear_terms = _find_linear_terms(rhs_exprs, solution)
else:
linear_terms = [True for _ in range(system_size)]
# Wrap the rhs expressions into a ufl vector type
rhs_exprs = ufl.as_vector([rhs_exprs[i] for i in range(system_size)])
rhs_jac = ufl.diff(rhs_exprs, solution)
# Takes time!
if vector_rhs:
diff_rhs_exprs = [expand_indices(expand_derivatives(rhs_jac[ind, ind]))
for ind in range(system_size)]
else:
diff_rhs_exprs = [expand_indices(expand_derivatives(rhs_jac[0]))]
solution = [solution]
ufl_stage_forms = []
dolfin_stage_forms = []
dt_stage_offsets = []
# Stage solutions (3 per order rhs, linearized, and final step)
# If 2nd order the final step for 1 step is a stage
if order == 1:
stage_solutions = []
rl_ufl_form = _rush_larsen_step(rhs_exprs, diff_rhs_exprs, linear_terms,
system_size, solution, None, dt, time, 1.0,
0.0, v, DX, time_dep_expressions)
elif order == 2:
# Stage solution for order 2
if vector_rhs:
stage_solutions = [Function(solution.function_space(), name="y_1/2")]
else:
stage_solutions = [Function(solution[0].function_space(), name="y_1/2")]
stage_form = _rush_larsen_step(rhs_exprs, diff_rhs_exprs,
linear_terms,
system_size, solution, None, dt, time, 0.5,
0.0, v, DX,
time_dep_expressions)
rl_ufl_form = _rush_larsen_step(rhs_exprs, diff_rhs_exprs,
linear_terms, system_size,
solution, stage_solutions[0],
dt, time, 1.0, 0.5, v, DX,
time_dep_expressions)
ufl_stage_forms.append([stage_form])
dolfin_stage_forms.append([Form(stage_form)])
# Get last stage form
last_stage = Form(rl_ufl_form)
human_form = "%srush larsen %s" % ("generalized " if generalized else "",
str(order))
return rhs_form, linear_terms, ufl_stage_forms, dolfin_stage_forms, last_stage, \
stage_solutions, dt, dt_stage_offsets, human_form, None
```
--------------------------------
### Dolfin/PETSc/SLEPc Setup and Checks
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/demos/maxwell-eigenvalues/demo_maxwell-eigenvalues.py
Imports necessary libraries (dolfin, numpy) and verifies that the Dolfin installation is configured with PETSc and SLEPc, which are required for the eigenvalue solver. Exits if dependencies are not met.
```python
from dolfin import *
import numpy as np
if not has_linear_algebra_backend("PETSc"):
print("DOLFIN has not been configured with PETSc. Exiting.")
exit()
if not has_slepc():
print("DOLFIN has not been configured with SLEPc. Exiting.")
exit()
```
--------------------------------
### DOLFIN Mesh Initialization and Setup
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_autogenerated/dolfin.cpp.mesh
Methods for initializing and setting up mesh properties, including cell orientations and global data structures. These are typically used internally or for advanced mesh manipulation.
```APIDOC
dolfin.cpp.mesh.Mesh.init(*args, **kwargs)
Overloaded function for mesh initialization.
- Overloads:
1. init(self: dolfin.cpp.mesh.Mesh) -> None
2. init(self: dolfin.cpp.mesh.Mesh, arg0: int) -> int
3. init(self: dolfin.cpp.mesh.Mesh, arg0: int, arg1: int) -> None
dolfin.cpp.mesh.Mesh.init_cell_orientations(*args, **kwargs)
Overloaded function to initialize cell orientations.
- Overloads:
1. init_cell_orientations(self: dolfin.cpp.mesh.Mesh, arg0: dolfin.cpp.function.Expression) -> None
2. init_cell_orientations(self: dolfin.cpp.mesh.Mesh, arg0: object) -> None
dolfin.cpp.mesh.Mesh.init_global(arg0: int)
Initializes global mesh data.
- Parameters:
- arg0: An integer argument for global initialization.
- Returns: None
```
--------------------------------
### C++ Implementation File Structure Template
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/styleguide_cpp
Shows the standard template for DOLFIN C++ implementation files, including necessary includes, namespace usage, and constructor/destructor definitions.
```cpp
// Copyright (C) 2008 Foo Bar
//
// This file is part of DOLFIN.
//
// DOLFIN is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// DOLFIN is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with DOLFIN. If not, see .
//
// Modified by Bar Foo 2008
#include using namespace dolfin;
//-----------------------------------------------------------------------------
Foo::Foo() : // variable initialization here
{
...
}
//-----------------------------------------------------------------------------
Foo::~Foo()
{
// Do nothing
}
//-----------------------------------------------------------------------------
```
--------------------------------
### DOLFIN Optional Python Dependencies
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/installation
Lists optional Python libraries that can be installed to enhance DOLFIN's functionality, such as Matplotlib for visualization.
```text
Matplotlib (required for plotting)
mpi4py
petsc4py
slepc4py
```
--------------------------------
### Python Demos
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_sources/ChangeLog.rst
Added more Python demos to showcase the library's features and provide examples for users.
```APIDOC
Additional Python Demos:
- Add more Python demos.
Purpose:
- To provide practical examples and usage guides for users.
```
--------------------------------
### Poisson Equation Demo
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/demos/nonlinear-poisson/demo_nonlinear-poisson.py
Demonstrates solving the Poisson equation using DOLFIN. This example typically involves defining a variational problem, boundary conditions, and solving the resulting linear system.
```python
from dolfin import *
# Define mesh and function spaces
mesh = UnitSquareMesh(32, 32)
# Define function spaces
V = FunctionSpace(mesh, 'Lagrange', 1)
# Define boundary conditions
# (Example: Dirichlet boundary condition u=0 on the boundary)
# Define variational problem
# (Example: Find u in V such that a(u,v) = L(v) for all v in V)
# Solve the problem
# (Example: u = Function(V))
# solve(a == L, u, bc)
# Plot the solution (optional)
# plot(u)
# interactive()
```
--------------------------------
### Poisson Equation Demo
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/demos/elastodynamics/demo_elastodynamics.py
Demonstrates solving the Poisson equation using DOLFIN. This example showcases basic finite element discretization and solving techniques.
```python
from dolfin import *
# Define mesh and function spaces
mesh = UnitSquareMesh(32, 32)
V = FunctionSpace(mesh, 'P', 1)
# Define boundary condition
# ... (code omitted for brevity, typically involves boundary definition and DirichletBC)
# Define variational problem
u = TrialFunction(V)
v = TestFunction(V)
f = Constant(-1.0) # Source term
a = dot(grad(u), grad(v))*dx
L = f*v*dx
# Compute solution
u_sol = Function(V)
solve(a == L, u_sol)
# Plot solution (optional)
# plot(u_sol)
# interactive()
```
--------------------------------
### dolfin.cpp.common.Timer Methods
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_autogenerated/dolfin.cpp.common
Provides methods to control and query a timer. The 'start' method initiates timing, and the 'stop' method halts it, returning the elapsed time.
```APIDOC
dolfin.cpp.common.Timer.start(_self: dolfin.cpp.common.Timer) → None
Start timer
dolfin.cpp.common.Timer.stop(_self: dolfin.cpp.common.Timer) → float
Stop timer
```
--------------------------------
### DOLFIN Newton Solver Configuration and Usage
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_sources/demos/cahn-hilliard/demo_cahn-hilliard.py.rst
Demonstrates the setup and execution of the DOLFIN Newton solver. It involves creating a `NonlinearProblem` instance, initializing the `NewtonSolver`, configuring its parameters (linear solver, convergence criterion, tolerance), and then calling the `solve` method within a time-stepping loop.
```python
# Create nonlinear problem and Newton solver
problem = CahnHilliardEquation(a, L)
solver = NewtonSolver()
solver.parameters["linear_solver"] = "lu"
solver.parameters["convergence_criterion"] = "incremental"
solver.parameters["relative_tolerance"] = 1e-6
# Output file
file = File("output.pvd", "compressed")
# Step in time
t = 0.0
T = 50*dt
while (t < T):
t += dt
u0.vector()[:] = u.vector()
solver.solve(problem, u.vector())
file << (u.split()[0], t)
```
--------------------------------
### Poisson Equation Demo in Python
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/demos/auto-adaptive-poisson/demo_auto-adaptive-poisson.py
Demonstrates solving the Poisson equation using DOLFIN. This example typically involves defining a variational problem, boundary conditions, and solving the resulting linear system.
```Python
# This is a placeholder for the actual code from the demo file.
# The actual code would be extracted from:
# https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/demos/poisson/demo_poisson.py.html
from dolfin import *
# Define mesh and function spaces
mesh = UnitSquareMesh(32, 32)
V = FunctionSpace(mesh, 'Lagrange", 1)
# Define boundary condition
# Define variational problem
u = TrialFunction(V)
v = TestFunction(V)
f = Constant(-6.0)
a = dot(grad(u), grad(v))*dx
L = f*v*dx
# Compute solution
uh = Function(V)
solve(a == L, uh)
# Plot solution (optional)
# plot(uh, title="Solution of Poisson equation")
# interactive()
```
--------------------------------
### C++ Constructor Initialization List
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_sources/styleguide_cpp.rst
Demonstrates the use of an initialization list in a C++ constructor for variable initialization, a common practice in C++ for efficiency and correctness, especially for member objects and const members.
```c++
Foo::Foo() : // variable initialization here
{
...
}
```
--------------------------------
### Built-in Meshes Demo
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/demos/elastodynamics/demo_elastodynamics.py
Demonstrates the usage of DOLFIN's built-in mesh generation capabilities. This example shows how to create and utilize standard meshes like UnitSquareMesh.
```python
from dolfin import *
# Create a built-in mesh, e.g., a square mesh
mesh = UnitSquareMesh(8, 8)
# Define a function space on this mesh
V = FunctionSpace(mesh, 'P', 1)
# Perform operations on the mesh and function space
# For example, plotting the mesh or evaluating functions
# plot(mesh)
# interactive()
```
--------------------------------
### Boundary Conditions Setup
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/demos/stokes-iterative/demo_stokes-iterative.py
Defines boundary conditions for the Stokes problem, including no-slip conditions on top/bottom boundaries and an inflow condition on the right boundary for the velocity component. These are implemented using DOLFIN's DirichletBC.
```python
# Boundaries
def right(x, on_boundary): return x[0] > (1.0 - DOLFIN_EPS)
def left(x, on_boundary): return x[0] < DOLFIN_EPS
def top_bottom(x, on_boundary):
return x[1] > 1.0 - DOLFIN_EPS or x[1] < DOLFIN_EPS
# No-slip boundary condition for velocity
noslip = Constant((0.0, 0.0, 0.0))
bc0 = DirichletBC(W.sub(0), noslip, top_bottom)
# Inflow boundary condition for velocity
inflow = Expression(("-sin(x[1]*pi)", "0.0", "0.0"), degree=2)
bc1 = DirichletBC(W.sub(0), inflow, right)
# Collect boundary conditions
bcs = [bc0, bc1]
```
--------------------------------
### C++ Header File Structure Template
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/styleguide_cpp
Demonstrates the standard template for DOLFIN C++ header files, including copyright, licensing, namespace usage, forward declarations, and class definition structure.
```cpp
// Copyright (C) 2008 Foo Bar
//
// This file is part of DOLFIN.
//
// DOLFIN is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// DOLFIN is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with DOLFIN. If not, see .
//
// Modified by Bar Foo 2008
#ifndef __FOO_H
#define __FOO_H
namespace dolfin
{
class Bar; // Forward declarations here
/// Documentation of class
class Foo
{
public:
...
private:
...
};
}
#endif
```
--------------------------------
### Dolfin Adaptive Poisson Solver Setup
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_sources/demos/auto-adaptive-poisson/demo_auto-adaptive-poisson.py.rst
This snippet outlines the core components and concepts used in the Dolfin demo for solving the auto-adaptive Poisson equation. It highlights the use of goal-oriented adaptivity, error control, and the definition of variational forms and goal functionals.
```APIDOC
Dolfin Adaptive Poisson Solver Concepts:
This demo focuses on solving the Poisson equation with automatic adaptive mesh refinement using goal-oriented adaptivity and error control.
Key Concepts:
- Goal-Oriented Adaptivity: Minimizing computational work for a desired accuracy in a specific goal functional.
- Error Control: Applying duality techniques to derive a posteriori error estimates and indicators from the computed solution.
- Goal Functional (M): A functional :math:`\mathcal{M} : V \rightarrow \mathbb{R}` that expresses localized physical properties of the solution. The objective is to minimize error |M(u_h) - u_h| <= TOL.
- Variational Forms:
- Continuous Primal Problem: find :math:`u \in V` such that :math:`a(u, v) = L(v) \quad \forall \ v \in \hat{V}`
- :math:`a(u, v) = \int_{\Omega} \nabla u \cdot \nabla v \, dx` (Bilinear form)
- :math:`L(v) = \int_{\Omega} f v \, dx + \int_{\Gamma_{N}} g v \, ds` (Linear form)
- Discrete Primal Problem: find :math:`u_h \in V_h` such that :math:`a(u_h, v) = L(v) \quad \forall \ v \in \hat{V}_h`
- Weak Residual: :math:`r(v) = L(v) - a(u_h, v)`
- Discrete Dual Variational Problem: find :math:`z_h \in V_h^*` such that :math:`a^*(z_h,v) = \mathcal{M}(v) \quad \forall \ v \in \hat{V}_h^*`
- :math:`a^*(v,w) = a(w,v)` (Adjoint of a)
- Error Estimate Derivation: :math:`\mathcal{M}(u - u_h) = r(z)` where :math:`z` is the solution to the dual problem.
- Mesh Marking: Dorfler marking is used for mesh refinement.
Problem Definition:
- Domain: :math:`\Omega = [0,1] \times [0,1]` (unit square)
- Dirichlet Boundary: :math:`\Gamma_{D} = \{(0, y) \cup (1, y) \subset \partial \Omega\}`
- Neumann Boundary: :math:`\Gamma_{N} = \{(x, 0) \cup (x, 1) \subset \partial \Omega\}`
Dependencies:
- Dolfin library (specifically :py:class:`AdaptiveLinearVariationalSolver `)
```
--------------------------------
### Get Pybind Include Path
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_sources/_autogenerated/dolfin.jit.rst
Retrieves the include path for Pybind11, which is often required for C++ extensions and JIT compilation. This function helps in setting up the necessary build environment for Dolfin's JIT compiler.
```python
from dolfin.jit import get_pybind_include
# Example usage:
include_path = get_pybind_include()
```
--------------------------------
### C++ Destructor Example
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_sources/styleguide_cpp.rst
A simple C++ destructor example, showing a case where the destructor performs no explicit cleanup actions. Destructors are crucial for resource management in C++.
```c++
Foo::~Foo()
{
// Do nothing
}
```
--------------------------------
### Get Pybind Include Path for DOLFIN JIT
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_modules/dolfin/jit
This function retrieves the include path for pybind11, essential for building DOLFIN extensions. It first checks the PYBIND11_DIR environment variable and then falls back to importing the pybind11 module.
```python
import os
def get_pybind_include():
"""Find the pybind11 include path"""
# Look in PYBIND11_DIR
pybind_dir = os.getenv('PYBIND11_DIR', None)
if pybind_dir:
p = os.path.join(pybind_dir, "include")
if (_check_pybind_path(p)):
return [p]
# Extract from pybind11 module
import pybind11
return [pybind11.get_include(True), pybind11.get_include()]
def _check_pybind_path(root):
p = os.path.join(root, "pybind11", "pybind11.h")
if os.path.isfile(p):
return True
else:
return False
```
--------------------------------
### PETSc Build System Configuration Options
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/installation
Provides recommended command-line arguments for configuring the PETSc build system to download and build specific libraries, enhancing DOLFIN's capabilities with parallel processing and advanced solvers.
```shell
--download-parmetis
--download-ptscotch
--download-suitesparse
--download-mumps
--download-hypre
```
--------------------------------
### C++ Class Naming Convention
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_sources/styleguide_cpp.rst
Defines the convention for naming C++ classes. Class names should use camel caps, starting with an uppercase letter and capitalizing the first letter of each subsequent word.
```c++
class FooBar
{
...
};
```
--------------------------------
### C++ Commenting Style
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_sources/styleguide_cpp.rst
Details the preferred style for C++ comments. Use `//` for single-line comments and `///` for documentation comments. Comments should start with a capital letter and generally omit trailing punctuation unless spanning multiple sentences.
```c++
// Check if connectivity has already been computed
if (connectivity.size() > 0)
return;
// Invalidate ordering
mesh._ordered = false;
// Compute entities if they don't exist
if (topology.size(d0) == 0)
compute_entities(mesh, d0);
if (topology.size(d1) == 0)
compute_entities(mesh, d1);
// Check if connectivity still needs to be computed
if (connectivity.size() > 0)
return;
...
```
--------------------------------
### Initialize Time Stepping and Output Files
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_sources/demos/elastodynamics/demo_elastodynamics.py.rst
Details the initialization of variables for time stepping, including time arrays, displacement tracking, energy storage, and setting up an `XDMFFile` for saving simulation results. It configures file writing parameters like `flush_output` and `functions_share_mesh` for efficient I/O.
```python
# Time-stepping
time = np.linspace(0, T, Nsteps+1)
u_tip = np.zeros((Nsteps+1,))
energies = np.zeros((Nsteps+1, 4))
E_damp = 0
E_ext = 0
sig = Function(Vsig, name="sigma")
xdmf_file = XDMFFile("elastodynamics-results.xdmf")
xdmf_file.parameters["flush_output"] = True
xdmf_file.parameters["functions_share_mesh"] = True
xdmf_file.parameters["rewrite_function_mesh"] = False
```
--------------------------------
### Dolfin API: SystemAssembler and Subdomains
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/ChangeLog
Explains the support for subdomains in SystemAssembler, with a note on limitations for interior facet integrals.
```APIDOC
SystemAssembler:
- Support subdomains (not for interior facet integrals).
```
--------------------------------
### XML I/O Transition
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/ChangeLog
Transitioned to a new XML I/O system.
```c++
Transition to new XML io
Migrated the input/output system to a new XML-based format.
```
--------------------------------
### Build and Configuration Options
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/ChangeLog
Details on build system changes and configuration options, including Python version selection and CMake requirements.
```APIDOC
CMake Options:
- DDOLFIN_USE_PYTHON3=on (default): Builds DOLFIN with Python 3 support.
- DDOLFIN_USE_PYTHON3=off: Builds DOLFIN with Python 2 support.
CMake Requirements:
- Require CMake version 3.5 or higher.
```
--------------------------------
### Set Up Boundary Conditions
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/demos/elastodynamics/demo_elastodynamics.py
Marks boundary facets using `MeshFunction` and `AutoSubDomain`, defines a boundary measure `dss` for integrals, and applies Dirichlet boundary conditions (zero displacement) at the left end of the domain.
```Python
# Create mesh function over the cell facets
boundary_subdomains = MeshFunction("size_t", mesh, mesh.topology().dim() - 1)
boundary_subdomains.set_all(0)
force_boundary = AutoSubDomain(right)
force_boundary.mark(boundary_subdomains, 3)
# Define measure for boundary condition integral
dss = ds(subdomain_data=boundary_subdomains)
# Set up boundary condition at left end
zero = Constant((0.0, 0.0, 0.0))
bc = DirichletBC(V, zero, left)
```
--------------------------------
### GoalFunctional Class
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_autogenerated/dolfin.cpp.adaptivity
Represents a goal functional used in adaptive solvers to guide the refinement process based on the functional's value.
```APIDOC
dolfin.cpp.adaptivity.GoalFunctional
Description: Goal functional
```
--------------------------------
### Efficient Linear System Solving with LUSolver
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/demos/elastodynamics/demo_elastodynamics.py
Illustrates how to set up an efficient linear solver for time-dependent problems where the system matrix remains constant. It shows the use of `assemble_system` to obtain the matrix and residual, followed by the initialization of `LUSolver` with parameters like 'symmetric' for optimized factorization reuse, significantly speeding up computations.
```python
# Define solver for reusing factorization
K, res = assemble_system(a_form, L_form, bc)
solver = LUSolver(K, "mumps")
solver.parameters["symmetric"] = True
```
--------------------------------
### dolfin.cpp.common API Documentation
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_autogenerated/dolfin.cpp.common
This section details the functions available in the dolfin.cpp.common module. It covers utilities for managing and retrieving timing information, as well as system-level size information.
```APIDOC
dolfin.cpp.common.list_timings(_arg0: dolfin.cpp.common.TimingClear, arg1: List[dolfin.cpp.common.TimingType]) -> None
- Clears and lists timing information.
- Parameters:
- _arg0: A TimingClear enum value.
- arg1: A list of TimingType enum values.
- Returns: None.
```
```APIDOC
dolfin.cpp.common.sizeof_la_index() -> int
- Returns the size of the linear algebra index.
- Parameters: None.
- Returns: An integer representing the size.
```
```APIDOC
dolfin.cpp.common.timing(_arg0: str, _arg1: dolfin.cpp.common.TimingClear) -> Tuple[int, float, float, float]
- Records timing information for a specific operation.
- Parameters:
- _arg0: A string identifier for the timing event.
- _arg1: A TimingClear enum value.
- Returns: A tuple containing an integer and three float values representing timing data.
```
```APIDOC
dolfin.cpp.common.timings(_arg0: dolfin.cpp.common.TimingClear, arg1: List[dolfin.cpp.common.TimingType]) -> dolfin::Table
- Retrieves timing information as a dolfin::Table.
- Parameters:
- _arg0: A TimingClear enum value.
- arg1: A list of TimingType enum values.
- Returns: A dolfin::Table object containing timing results.
```
--------------------------------
### Hyperelasticity Demo
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/demos/nonlinear-poisson/demo_nonlinear-poisson.py
This example focuses on simulating hyperelastic materials, which exhibit large, nonlinear deformations, using DOLFIN.
```python
from dolfin import *
# Define mesh and function spaces for displacement
mesh = UnitCubeMesh(10, 10, 10)
V = VectorFunctionSpace(mesh, 'Lagrange', 2)
# Define material properties (e.g., strain energy density function)
# (Example: Neo-Hookean, Mooney-Rivlin)
# Define boundary conditions (e.g., fixed boundaries, applied displacements)
# Define variational problem for hyperelasticity
# (This involves nonlinear elasticity, often solved iteratively)
# Solve the nonlinear problem
# (Example: u = Function(V))
# solve(F == 0, u, bc)
```
--------------------------------
### Cahn-Hilliard Equation Demo
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/demos/nonlinear-poisson/demo_nonlinear-poisson.py
This example shows how to implement and solve the Cahn-Hilliard equation, a phase-field model used in materials science.
```python
from dolfin import *
# Define mesh and function spaces
mesh = UnitSquareMesh(64, 64)
# Define function spaces for concentration (phi) and its gradient (grad(phi))
# Often requires mixed elements or specific formulations
# Define time stepping parameters
dt = 0.01
T = 10.0
# Define variational problem for Cahn-Hilliard equation
# (This is a time-dependent PDE, typically solved using implicit time stepping)
# Initialize solution
# (Example: phi = Function(V))
# Time-loop
# for t in arange(0, T, dt):
# # Update solution using a solver
# # solve(F == 0, phi_new, bc)
# # phi = phi_new
# Plotting or saving results...
```
--------------------------------
### Mesh Min/Max Radius Methods
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/genindex
Methods to get the minimum and maximum radii of cells in a mesh. These are important quality indicators for finite element meshes.
```APIDOC
dolfin.cpp.mesh.Mesh.rmax()
Returns the maximum radius of any cell in the mesh.
dolfin.cpp.mesh.Mesh.rmin()
Returns the minimum radius of any cell in the mesh.
```
--------------------------------
### Built-in Meshes: UnitTriangle and UnitTetrahedron
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/ChangeLog
Includes built-in mesh generation for UnitTriangle and UnitTetrahedron. These provide convenient starting points for 2D and 3D simulations.
```APIDOC
from dolfin import UnitTriangle, UnitTetrahedron
tri_mesh = UnitTriangle()
tetra_mesh = UnitTetrahedron()
// Creates standard unit triangle and tetrahedron meshes.
```
--------------------------------
### Initialize PETSc Krylov Solver
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/demos/singular-poisson/demo_singular-poisson.py
Initializes a PETSc Krylov solver with a specified method (e.g., 'cg' for conjugate gradient) and sets the linear operator for the system to be solved. This is the first step in setting up the solver.
```python
solver = PETScKrylovSolver("cg")
solver.set_operator(A)
```
--------------------------------
### Dolfin Timer Class
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_autogenerated/dolfin.cpp.common
A class for measuring elapsed time. It allows starting, stopping, and retrieving timing information, useful for profiling code sections.
```APIDOC
class dolfin.cpp.common.Timer
Timer class
elapsed(self) -> Tuple[float, float, float]
Returns the elapsed time in seconds (real, user, system).
resume(self) -> None
Resumes the timer.
```
--------------------------------
### dolfin.cpp.log Module Functions
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/genindex
Documentation for functions within the dolfin.cpp.log module, specifically the 'begin' function for logging operations.
```APIDOC
dolfin.cpp.log.begin()
Starts logging operations.
```
--------------------------------
### Class names
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/styleguide_cpp
Defines the naming convention for C++ classes within the DOLFIN project, specifying the use of camel caps.
```C++
class FooBar
{
...
};
```
--------------------------------
### Import Necessary Modules
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_sources/demos/auto-adaptive-poisson/demo_auto-adaptive-poisson.py.rst
Imports the required libraries for plotting and the DOLFIN finite element library. These are essential for setting up and solving the Poisson equation.
```python
import matplotlib.pyplot as plt
from dolfin import *
```
--------------------------------
### Interpolating functions in Cahn-Hilliard demo
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/genindex
Example usage of function interpolation within the Cahn-Hilliard demo script. Demonstrates practical application of Dolfin's interpolation capabilities.
```python
# Example from dolfin/demos/cahn-hilliard/demo_cahn-hilliard.py
# ... (code snippet for interpolation would go here if available)
```
--------------------------------
### Configure PETSc LUSolver for Reused Factorization
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_sources/demos/elastodynamics/demo_elastodynamics.py.rst
Shows how to set up and configure PETSc's `LUSolver` for efficient solution of linear systems. It demonstrates assembling the system matrix and residual, creating the solver, and setting solver parameters like `symmetric` to True for performance optimization, enabling factorization reuse across time steps.
```python
# Define solver for reusing factorization
K, res = assemble_system(a_form, L_form, bc)
solver = LUSolver(K, "mumps")
solver.parameters["symmetric"] = True
```
--------------------------------
### Initialize and Solve Eigenproblem
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/demos/eigenvalue/demo_eigenvalue.py
Initializes the SLEPcEigenSolver with the assembled matrix A and calls the solve method to compute eigenvalues. This step can be computationally intensive.
```python
# Create eigensolver
eigensolver = SLEPcEigenSolver(A)
# Compute all eigenvalues of A x = \lambda x
print("Computing eigenvalues. This can take a minute.")
eigensolver.solve()
```
--------------------------------
### Import DOLFIN and Matplotlib
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/demos/built-in-meshes/demo_built-in-meshes.py
Imports necessary modules from the DOLFIN library for mesh operations and Matplotlib for plotting. These are foundational imports for most DOLFIN examples involving mesh visualization.
```python
from dolfin import *
import matplotlib.pyplot as plt
```
--------------------------------
### PETScMatrix and Assembler Options
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_sources/ChangeLog.rst
Introduces new functionalities for PETSc matrices and the `SystemAssembler`. PETSc matrices gain an `apply("flush")` option, and `SystemAssembler` now supports subdomains for certain integral types.
```APIDOC
PETScMatrix:
apply("flush"): Applies a flush operation to the matrix, potentially synchronizing data.
SystemAssembler:
Support for subdomains in SystemAssembler (not for interior facet integrals).
This allows assembling contributions from specific subdomains.
```
--------------------------------
### C++ Indentation Style
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_sources/styleguide_cpp.rst
Specifies the indentation style for C++ code. Indentation should consistently use two spaces, and tabs should not be used.
```c++
// Check if connectivity has already been computed
if (connectivity.size() > 0)
return;
// Invalidate ordering
mesh._ordered = false;
// Compute entities if they don't exist
if (topology.size(d0) == 0)
compute_entities(mesh, d0);
if (topology.size(d1) == 0)
compute_entities(mesh, d1);
// Check if connectivity still needs to be computed
if (connectivity.size() > 0)
return;
...
```
--------------------------------
### Interpolation from Non-matching Mesh Demo
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/demos/nonlinear-poisson/demo_nonlinear-poisson.py
This example shows how to interpolate a function defined on one mesh onto another mesh that does not conform to the first one.
```python
from dolfin import *
# Define a source mesh and function space
mesh1 = UnitSquareMesh(10, 10)
V1 = FunctionSpace(mesh1, 'Lagrange', 1)
# Define a target mesh and function space
mesh2 = UnitSquareMesh(20, 20)
V2 = FunctionSpace(mesh2, 'Lagrange', 1)
# Define a function on the source mesh
# (Example: u1 = Expression('x[0]*x[1]', degree=2))
# Interpolate the function from mesh1 to mesh2
# (Example: u2 = Function(V2))
# u2 = interpolate(u1, V2)
# Or use a projection
# (Example: u2 = project(u1, V2))
```
--------------------------------
### Build HTML documentation
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_sources/contributing.rst
Command to build the HTML version of the DOLFIN documentation locally. This allows contributors to preview how their changes will appear on the web before submitting them.
```Shell
make html
```
--------------------------------
### PointIntegralSolver Newton Solver Reset
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/genindex
Resets the internal state of the Newton solver within the PointIntegralSolver. This is often done to re-initialize the solver for a new iteration or a different problem setup.
```APIDOC
dolfin.cpp.multistage.PointIntegralSolver.reset_newton_solver()
Resets the Newton solver associated with the PointIntegralSolver.
```
--------------------------------
### Dolfin API: Parameter Handling and Solver Methods
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/ChangeLog
Documents new functionalities for managing parameters and listing available solver methods within Dolfin. This includes checking for parameters and listing solver types.
```APIDOC
Parameters:
- has_parameter(name: str): Checks if a parameter exists.
- has_parameter_set(name: str): Checks if a parameter set exists.
Solver Listing Functions:
- list_linear_solver_methods(): Lists available linear solver methods.
- list_lu_solver_methods(): Lists available LU solver methods.
- list_krylov_solver_methods(): Lists available Krylov solver methods.
- list_krylov_solver_preconditioners(): Lists available Krylov solver preconditioners.
```
--------------------------------
### DOLFIN Dependency Check Functions
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/genindex
These functions check for the availability of specific external libraries or functionalities within the DOLFIN installation. They are useful for verifying build configurations and ensuring compatibility.
```APIDOC
dolfin.cpp.common.has_debug()
- Checks if debug support is enabled.
dolfin.cpp.common.has_hdf5()
- Checks if HDF5 support is enabled.
dolfin.cpp.common.has_hdf5_parallel()
- Checks if parallel HDF5 support is enabled.
dolfin.cpp.common.has_mpi()
- Checks if MPI support is enabled.
dolfin.cpp.common.has_mpi4py()
- Checks if mpi4py is available.
dolfin.cpp.common.has_parmetis()
- Checks if Parmetis support is enabled.
dolfin.cpp.common.has_petsc()
- Checks if PETSc support is enabled.
dolfin.cpp.common.has_petsc4py()
- Checks if petsc4py is available.
dolfin.cpp.common.has_scotch()
- Checks if SCOTCH support is enabled.
dolfin.cpp.common.has_slepc()
- Checks if SLEPc support is enabled.
dolfin.cpp.common.has_slepc4py()
- Checks if slepc4py is available.
dolfin.cpp.common.has_sundials()
- Checks if SUNDIALS support is enabled.
```
--------------------------------
### C++ Virtual Function Declaration in Inheritance
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/styleguide_cpp
Demonstrates how to correctly declare inherited virtual functions in subclasses, ensuring clarity and proper polymorphism.
```cpp
class Foo
{
virtual void foo();
virtual void bar() = 0;
};
class Bar : public Foo
{
virtual void foo();
virtual void bar();
};
```
--------------------------------
### dolfin.cpp.mesh.MeshDomains.init()
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/genindex
Initializes the MeshDomains object, which manages domain information for a mesh. This is a C++ method.
```APIDOC
init()
Initializes the mesh domains.
```
--------------------------------
### Check PETSc and SLEPc Availability
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_sources/demos/eigenvalue/demo_eigenvalue.py.rst
Verifies if DOLFIN is configured with the necessary PETSc and SLEPc libraries. Exits the program with a message if either dependency is missing, ensuring the environment is ready for the eigenvalue solver.
```Python
import matplotlib.pyplot as plt
from dolfin import *
# Test for PETSc and SLEPc
if not has_linear_algebra_backend("PETSc"):
print("DOLFIN has not been configured with PETSc. Exiting.")
exit()
if not has_slepc():
print("DOLFIN has not been configured with SLEPc. Exiting.")
exit()
```
--------------------------------
### C++ Variable Naming Conventions
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/styleguide_cpp
Variable names should be in lower-case with underscores separating words. This applies to simple variables and class member variables.
```cpp
Foo foo;
Bar bar;
FooBar foo_bar;
```
--------------------------------
### Initialize and Solve Eigenproblem
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/_sources/demos/eigenvalue/demo_eigenvalue.py.rst
Initializes the SLEPcEigenSolver with the assembled matrix 'A' and solves the standard eigenvalue problem (Ax = \lambda x). The computation of eigenvalues is initiated via the solve() method.
```Python
# Create eigensolver
eigensolver = SLEPcEigenSolver(A)
# Compute all eigenvalues of A x = \lambda x
print("Computing eigenvalues. This can take a minute.")
eigensolver.solve()
```
--------------------------------
### C++ Explicit Constructor Declaration
Source: https://olddocs.fenicsproject.org/dolfin/2019.1.0/python/styleguide_cpp
Illustrates the correct way to declare one-argument constructors as 'explicit' in C++ to prevent unintended type conversions.
```cpp
class Foo
{
explicit Foo(std::size_t i);
};
```