Giter Club home page Giter Club logo

dolfinx-tutorial's Introduction

The DOLFINx tutorial

Test, build and publish Test release branch against DOLFINx nightly build

Author: Jørgen S. Dokken

This is the source code for the dolfinx-tutorial webpage. If you have any comments, corrections or questions, please submit an issue in the issue tracker.

Contributing

If you want to contribute to this tutorial, please make a fork of the repository, make your changes, and test that the CI passes. You can do this locally by downloading act and call

act -j test-nightly

Alternatively, if you want to add a separate chapter, a Jupyter notebook can be added to a pull request, without integrating it into the tutorial. If so, the notebook will be reviewed and modified to be included in the tutorial.

Any code added to the tutorial should work in parallel. If any changes are made to ipynb files, please ensure that these changes are reflected in the corresponding py files by using jupytext:

python3 -m jupytext --sync  */*.ipynb

Any code added to the tutorial should work in parallel.

Dependencies

It is adviced to use a pre-installed version of DOLFINx, for instance through conda or docker. Remaining dependencies can be installed with

python3 -m pip install --no-binary=h5py -e .

Docker images

Docker images for this tutorial can be found in the packages tab

Additional requirements on top of the dolfinx/lab:nightly images can be found at Dockerfile and pyproject.toml

An image building DOLFINx, Basix, UFL and FFCx from source can be built using:

docker build -f ./docker/Dockerfile -t local_lab_env .

from the root of this repository, and run

 docker run --rm -ti -v $(pwd):/root/shared -w /root/shared  --init -p 8888:8888 local_lab_env

from the main directory.

dolfinx-tutorial's People

Contributors

abhi-k9 avatar ampdes avatar arashgmn avatar cmaurini avatar godsic avatar igorbaratta avatar ishaandesai avatar jorgensd avatar juliusgh avatar minrk avatar mmoelter avatar mscroggs avatar qlro avatar remdelaportemathurin avatar simo-11 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

dolfinx-tutorial's Issues

chapter2/ns_code1.html

Some typos can be found in chapter2/ns_code1.html.

  1. bewteen -> between
  2. accross -> across
  3. viscity -> viscosity
  4. u_x''(y) = \frac{\partial p}{\partial x)} \rightarrow u_x''(y) = \frac{\partial p}{\partial x}
  5. \frac{\partial^2 p}{\partial^2 x} \rightarrow \frac{\partial^2 p}{\partial x^2}
  6. \partial p/\partial x\;\; \text{s a constant} \rightarrow \partial p/\partial x \;\;\text{is a constant}
  7. u=(0,0,0) on the walls y = 0.1. -> u=(0,0,0) on the walls y = 0, 1.
  8. i n 2D or 3D -> in 2D or 3D
  9. betwen -> between
  10. differnent -> different
  11. oposed -> opposed
  12. createing -> creating
  13. spacces -> spaces
  14. spacecs -> spaces
  15. methids -> methods
  16. } Since we have two different function spaces,-> Since we have two different function spaces,
  17. elasticty -> elasticity
  18. myltigrid -> multigrid
  19. u is the known -> u is unknown
  20. convetion -> convention

Issue on page /chapter1/membrane_code.html

How to project a ufl.Product into an appropriate function space

I wonder that where the ufl.Product is used.

Permute topology data from MSH-ordering to dolfinx-ordering

Here, G is missing.

Issue on page /chapter1/nitsche.html

In the text, it says

and h is the circumradius of the mesh element

In the code, it says

h = 2 * Circumradius(mesh)

I think that the text should say

h is the diameter of the circumscribed sphere of the mesh element

compute_boundary_facets returns booleans?

In the first demo, the function dolfinx.mesh.compute_boundary_facets is said to return an array of booleans where it seems to return 0 or 1. Should it be fixed? or is it something I got wrong?

... using dolfinx.mesh.compute_boundary_facets. This function returns an array of booleans of the same size as the number of facets on this processor, where True indicates that the local facet is on the boundary

Thanks for the tutorial!

Second-Order Ellipse Contains Mixed Partial Derivatives

For a second-order elliptic equation of the form, the third term is a mixed partial derivative

I have figured out how to use fenics to solve the Laplace equation where the grid region is a unit circle, but I now have a problem when there are mixed partial derivatives. I have tried converting the above equation to canonical form, but this will affect the solution area changing, no longer a canonical circular area. I would like to ask how to deal with this item in fenics? Is there a corresponding solution? thanks.

Nonlinear Poisson tutorial

Hi @jorgensd,

Although a pretty minor detail, but isn't scatter_forward repeated in the Nonlinear poisson tutorial at the end? NewtonSolver.solve() automatically applies scatter_forward to the solution, as I can see here?

On another note, do you feel that adding an example on, say, implementing the Newton's method by hand would add value to tutorial? This could be illustrative in use cases where one needs to implement their own nonlinear solve? Something like this for the nonlinear poisson

from ufl import TrialFunction, derivative
Jac = derivative(F, uh, TrialFunction(V))

bilinear_form = fem.form(Jac)
linear_form = fem.form(-F)

du = fem.Function(V, name="incr_u")

bilinf = fem.assemble.create_matrix(bilinear_form)
linf = fem.assemble.create_vector(linear_form)

# zero the entries
bilinf.zeroEntries()

fem.assemble_matrix(bilinf, bilinear_form, bcs=bcs)
bilinf.assemble()

with linf.localForm() as loc:
    loc.set(0.)

fem.assemble_vector(linf, linear_form)

fem.apply_lifting(linf, [bilinear_form], [bcs])
linf.ghostUpdate(addv=PETSc.InsertMode.ADD_VALUES, mode=PETSc.ScatterMode.REVERSE)
fem.set_bc(linf, bcs)

res_0 = linf.norm()
res = res_0
print(f"Initial residual norm: {res_0}")
solver = PETSc.KSP().create(mesh.comm)
solver.setType(PETSc.KSP.Type.PREONLY)
solver.getPC().setType(PETSc.PC.Type.LU)
solver.setOperators(bilinf)
solver.solve(linf, du.vector)
du.x.scatter_forward()
uh.vector.axpy(1.0, du.vector)
iters = 0
maxIter = 30

while res/res_0 > 1.e-8 and iters < maxIter:

    
    bilinf.zeroEntries()
    fem.assemble_matrix(bilinf, bilinear_form, bcs=bcs_hom)
    bilinf.assemble()

    with linf.localForm() as loc:
        loc.set(0.)

    fem.assemble_vector(linf, linear_form)
    fem.apply_lifting(linf, [bilinear_form], [bcs_hom])
    linf.ghostUpdate(addv=PETSc.InsertMode.ADD_VALUES, mode=PETSc.ScatterMode.REVERSE)
    fem.set_bc(linf, bcs_hom)
    solver.setOperators(bilinf)
    solver.solve(linf, du.vector)
    du.x.scatter_forward()
    uh.vector.axpy(1.0, du.vector)
    res = linf.norm()
    print(f"norm: {res}")
    iters += 1

instead of the call to NewtonSolver.

Issue on page /chapter1/fundamentals_code.html

Hi. When I was try to run the command

mpirun -n 2 python3 t1.py

I received the message

AttributeError: module 'dolfinx.mesh' has no attribute 'create_unit_square'

I didn't find the create_unit_square function in the module dolfinx.

Issue on page /chapter2/diffusion_code.html :

While trying to run the diffusion problem on a jupyter notebook,
I found myself unable to generate the assembly matrix for the bilinear form.
The code is pasted from the fenics website.
The returned error is "ArityMissmatch: Failure to conjugate test function in complex Form".
But the equation given is correct.

error_report_dolfinx_diffusion
error_report_dolfinx_diffusion2
error_report_dolfinx_diffusion3
error_report_dolfinx_diffusion4

Add section on form compiler parameters

Something along the lines of:

import dolfinx
from mpi4py import MPI
import os
import time
import ufl
from pathlib import Path
N = 3
mesh = dolfinx.UnitCubeMesh(MPI.COMM_WORLD, N, N, N)
V = dolfinx.FunctionSpace(mesh, ("CG", 3))
u = ufl.TrialFunction(V)
v = ufl.TestFunction(V)
a = ufl.inner(ufl.grad(u), ufl.grad(v)) * ufl.dx

cache_dir = f"{str(Path.cwd())}/.cache"


def compile_form(a, jit_parameters):
    os.system(f"rm -rf {jit_parameters['cache_dir']}")
    a_ = dolfinx.fem.Form(a, jit_parameters=jit_parameters)
    start = time.time()
    dolfinx.fem.assemble_matrix(a_)
    end = time.time()
    print(f"Assemble matrix {jit_parameters['cffi_extra_compile_args']}: {end-start}")
    os.system(f"rm -rf {jit_parameters['cache_dir']}")


compile_form(a, jit_parameters={"cffi_extra_compile_args": [
             "-Ofast", "-march=native"], "cache_dir": cache_dir + "native", "cffi_libraries": ["m"], "cffi_verbose": False})

compile_form(a, jit_parameters={"cffi_extra_compile_args": [
             "-Ofast"], "cache_dir": cache_dir, "cffi_libraries": ["m"], "cffi_verbose": False})
compile_form(a, jit_parameters={"cffi_extra_compile_args": [
             "-O2", "-march=native"], "cache_dir": cache_dir + "native", "cffi_libraries": ["m"], "cffi_verbose": False})

compile_form(a, jit_parameters={"cffi_extra_compile_args": [
             "-O2"], "cache_dir": cache_dir, "cffi_libraries": ["m"], "cffi_verbose": False})
compile_form(a, jit_parameters={"cffi_extra_compile_args": [
             "-O3", "-march=native"], "cache_dir": cache_dir + "native", "cffi_libraries": ["m"], "cffi_verbose": False})

compile_form(a, jit_parameters={"cffi_extra_compile_args": [
             "-O3"], "cache_dir": cache_dir, "cffi_libraries": ["m"], "cffi_verbose": False})

Issue on page /chapter2/heat_code.html

Create the matrix and and vector for the linear problem

Double and here.

Verifying the numerical solution

Are the errors given here the L2 error and the maximum error at the last moment?

Add License

This book is distributed under the terms of the Creative Commons Attribution 4.0International License (http://creativecommons.org/licenses/by/4.0/), which permits use, duplication,adaptation, distribution and reproduction in any medium or format, as long as you give appropriate credit to the original author(s) and the source, provide a link to the Creative Commons license and indicate if changes were made.

The images or other third party material in this book are included in the work’s Creative Commons license, unless indicated otherwise in the credit line; if such material is not included in the work’s Creative Commons license and the respective action is not permitted by statutory regulation, users will need to obtain permission from the license holder to duplicate, adapt or reproduce the material.The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication does not imply, even in the absence of a specific statement, that such names are exempt from the relevant protective laws and regulations and therefore free for general use.

Issue on page /chapter2/linearelasticity_code.html

I have the following error when running the test case:

Traceback (most recent call last):
File ".py", line 16, in
from dolfinx.mesh import CellType, create_box, locate_entities_boundary
ImportError: cannot import name 'CellType' from 'dolfinx.mesh' (
/spack/var/spack/environments/fenicsx-env/.spack-env/view/lib/python3.9/site-packages/dolfinx/mesh.py)

I have also tried "from dolfinx import " instead, but it stuck again as follows:
Traceback (most recent call last):
File "
**.py", line 18, in
mesh = create_box(MPI.COMM_WORLD, [np.array([0,0,0]), np.array([L, W, W])],
NameError: name 'create_box' is not defined

The version of code I am using is FEniCSX/dolfinX-0.3.0

Issue on page /chapter3/subdomains.html

Hello,

Just a nit: in the create_mesh() helper (taken from https://jorgensd.github.io/dolfinx-tutorial/chapter3/subdomains.html#convert-msh-files-to-xdmf-using-meshio), I believe points should be passed to the meshio.Mesh() constructor if one wants prune_z to work

import meshio
def create_mesh(mesh, cell_type, prune_z=False):
    cells = mesh.get_cells_type(cell_type)
    cell_data = mesh.get_cell_data("gmsh:physical", cell_type)
    points = mesh.points[:,:2] if prune_z else mesh.points
    out_mesh = meshio.Mesh(points=mesh.points, cells={cell_type: cells}, cell_data={"name_to_read":[cell_data]}) # <-- here, should be points=points
    return out_mesh

Thanks for these great tutorials !

Component-wise Dirichlet BCs

I had bad time figuring out how to correctly write component-wise Dirichlet BCs.
I was not able to find an example in the tutorial (maybe this is my fault).
I think that adding something more explicit would be useful, like here

Add a performance test

Hi @jorgensd, thanks for the huge work done for the FEniCSx. As one of the many users of FEniCS/FEniCSx, I really think at least two points of FEniCSx are attracting: (1) convenience for solving PDEs and (2) the high computational efficiency based on parallel computation. I think the first point is already well illustrated in this tutorial. However, it would be better to illustrate the computational efficiency of FEniCSx versus other software such as Matlab.

Issue on page /chapter1/fundamentals_code.html

Should use:

    bndry_facets = np.where(np.array(cpp.mesh.compute_boundary_facets(mesh.topology)) == 1)[0]

In every place where we have the full boundary as BC. Expose locate_entities_boundary in a later demo

Parallel `Function` evaluation and `GhostMode.shared_facet`

I am trying to evaluate function in parallel like demonstrated in Chapter 1 of the tutorial and, then, Gatherv on rank 0

    bbox_tree = dolfinx.geometry.BoundingBoxTree(mesh, mesh.geometry.dim)

    pts = np.vstack(np.meshgrid(xx, yy, [z])).reshape(3, -1).T
    cells = []
    pts_on_proc = []
    for pt in pts:
        cell_candidates = dolfinx.geometry.compute_collisions_point(
            bbox_tree, pt)
        cell = dolfinx.geometry.select_colliding_cells(
            mesh, cell_candidates, pt, 1)
        if len(cell) == 1:
            pts_on_proc.append(pt)
            cells.append(cell[0])

    q_vals_on_proc = Q.eval(pts_on_proc, cells)

    val_counts = np.array(
        MPI.COMM_WORLD.gather(q_vals_on_proc.size, root=0))

    if MPI.COMM_WORLD.rank == 0:
        q_vals = np.empty(sum(val_counts), dtype=np.float64)
    else:
        q_vals = None

    MPI.COMM_WORLD.Gatherv(sendbuf=q_vals_on_proc, recvbuf=(
        q_vals, val_counts), root=0)

Eventually I end up with more values than grid points. This makes me think that GhostMode.shared_facet leads to a given point residing on multiple ranks. Is it a bug or intended behavior?

Dockerfile dolfinx/lab not able to run (em) tutorial?

First, awesome project and great tutorials! Very excited to get this running!

For now, I'm running from the docker image:

docker run -p 8888:8888 dolfinx/lab

I ran into a few issues though: first, pythreejs needed to be installed:

root@b8715fff55a6:~# pip install pythreejs

which I did inside a terminal in the JL interface, after which I could load the library, but then got errors "model cannot be found".

My guess is that the JL instance needs to be restarted after the package is installed, but I'm a bit of a docker noob and cannot figure out how to do this: if I stop the container and restart, there is no persistance of the changes I made...

I'll probably go whole-hog and install things properly in a conda env for now. But I guess probably there is a relatively simple fix in configuring the dolfinx/lab docker image?

Cheers,.
Gary

TypeError in Fundamentals Code with latest dolfinx

I get a typeerror in chapter 1 fundamentals_code.ipynb at cell 14:

import dolfinx.plot; topology, cell_types = dolfinx.plot.create_vtk_topology(mesh, mesh.topology.dim)

The error seems to be with the mesh type.

TypeError Traceback (most recent call last)
/tmp/ipykernel_101/4156726744.py in
1 import dolfinx.plot
----> 2 topology, cell_types = dolfinx.plot.create_vtk_topology(mesh, mesh.topology.dim)

/usr/lib/python3.9/functools.py in wrapper(*args, **kw)
875 '1 positional argument')
876
--> 877 return dispatch(args[0].class)(*args, **kw)
878
879 funcname = getattr(func, 'name', 'singledispatch function')

/usr/local/dolfinx-real/lib/python3.8/dist-packages/dolfinx/plot.py in create_vtk_topology(mesh, dim, entities)
76
77 # Array holding the cell type (shape) for each cell
---> 78 e_type = cpp.mesh.cell_entity_type(mesh.topology.cell_type, dim)
79 degree = _element_degree(e_type, geometry_entities.shape[1])
80 if degree == 1:

TypeError: cell_entity_type(): incompatible function arguments. The following argument types are supported:
1. (arg0: dolfinx.cpp.mesh.CellType, arg1: int, arg2: int) -> dolfinx.cpp.mesh.CellType

Invoked with: <CellType.quadrilateral: -4>, 2

Update all plotting

Matplotlib is now deprecated, and usage of pyvista should be implemented everywhere

  • Fundamentals
  • Membrane
  • Diffusion
  • Linear elasticity
  • Subdomain and bc demos

Issue on page /chapter2/diffusion_code.html

In the next line of equation (26), domain [-2,-2] x [2,2] should be domain [-2,2] x [-2,2] in mathematical terms, right?

There are also typos as follows:

  • abd -> and
  • # Plot every 20th time step -> # Plot every 15th time step

Issue on page /chapter1/nitsche.html

from ufl import (Circumradius, FacetNormal, SpatialCoordinate, TrialFunction, TestFunction,
                 div, dx, ds, grad, inner, grad)

Is it necessary to import grad twice?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.