tetgen

A Python interface to the C++ TetGen library to generate tetrahedral meshes of any 3D polyhedral domains

https://github.com/pyvista/tetgen

Science Score: 36.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
  • Academic publication links
    Links to: acm.org
  • Committers with academic emails
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (14.5%) to scientific vocabulary

Keywords

3d mesh mesh-generation tetrahedral-meshing

Keywords from Contributors

open-science vtk fem finite-element-analysis finite-elements mesh-processing meshviewer
Last synced: 6 months ago · JSON representation

Repository

A Python interface to the C++ TetGen library to generate tetrahedral meshes of any 3D polyhedral domains

Basic Info
  • Host: GitHub
  • Owner: pyvista
  • License: other
  • Language: C++
  • Default Branch: main
  • Homepage: http://tetgen.pyvista.org
  • Size: 117 MB
Statistics
  • Stars: 267
  • Watchers: 13
  • Forks: 36
  • Open Issues: 24
  • Releases: 7
Topics
3d mesh mesh-generation tetrahedral-meshing
Created over 7 years ago · Last pushed 6 months ago
Metadata Files
Readme License

README.rst

tetgen
======

.. image:: https://img.shields.io/pypi/v/tetgen.svg?logo=python&logoColor=white
   :target: https://pypi.org/project/tetgen/

This Python library is an interface to Hang Si's
`TetGen `__ C++ software.
This module combines speed of C++ with the portability and ease of installation
of Python along with integration to `PyVista `_ for
3D visualization and analysis.
See the `TetGen `__ GitHub page for more details
on the original creator.

This Python library uses the C++ source from TetGen (version 1.6.0,
released on August 31, 2020) hosted at `libigl/tetgen `__.

Brief description from
`Weierstrass Institute Software `__:

    TetGen is a program to generate tetrahedral meshes of any 3D polyhedral domains.
    TetGen generates exact constrained Delaunay tetrahedralization, boundary
    conforming Delaunay meshes, and Voronoi partitions.

    TetGen provides various features to generate good quality and adaptive
    tetrahedral meshes suitable for numerical methods, such as finite element or
    finite volume methods. For more information of TetGen, please take a look at a
    list of `features `__.

License (AGPL)
--------------

The original `TetGen `__ software is under AGPL
(see `LICENSE `_) and thus this
Python wrapper package must adopt that license as well.

Please look into the terms of this license before creating a dynamic link to this software
in your downstream package and understand commercial use limitations. We are not lawyers
and cannot provide any guidance on the terms of this license.

Please see https://www.gnu.org/licenses/agpl-3.0.en.html

Installation
------------

From `PyPI `__

.. code:: bash

    pip install tetgen

From source at `GitHub `__

.. code:: bash

    git clone https://github.com/pyvista/tetgen
    cd tetgen
    pip install .


Basic Example
-------------
The features of the C++ TetGen software implemented in this module are
primarily focused on the tetrahedralization a manifold triangular
surface.  This basic example demonstrates how to tetrahedralize a
manifold surface and plot part of the mesh.

.. code:: python

    import pyvista as pv
    import tetgen
    import numpy as np
    pv.set_plot_theme('document')

    sphere = pv.Sphere()
    tet = tetgen.TetGen(sphere)
    tet.tetrahedralize(order=1, mindihedral=20, minratio=1.5)
    grid = tet.grid
    grid.plot(show_edges=True)

.. figure:: https://github.com/pyvista/tetgen/raw/main/doc/images/sphere.png
    :width: 300pt

    Tetrahedralized Sphere

Extract a portion of the sphere's tetrahedral mesh below the xy plane and plot
the mesh quality.

.. code:: python

    # get cell centroids
    cells = grid.cells.reshape(-1, 5)[:, 1:]
    cell_center = grid.points[cells].mean(1)

    # extract cells below the 0 xy plane
    mask = cell_center[:, 2] < 0
    cell_ind = mask.nonzero()[0]
    subgrid = grid.extract_cells(cell_ind)

    # advanced plotting
    plotter = pv.Plotter()
    plotter.add_mesh(subgrid, 'lightgrey', lighting=True, show_edges=True)
    plotter.add_mesh(sphere, 'r', 'wireframe')
    plotter.add_legend([[' Input Mesh ', 'r'],
                        [' Tessellated Mesh ', 'black']])
    plotter.show()

.. image:: https://github.com/pyvista/tetgen/raw/main/doc/images/sphere_subgrid.png

Here is the cell quality as computed according to the minimum scaled jacobian.

.. code::

   Compute cell quality

   >>> cell_qual = subgrid.cell_quality()['scaled_jacobian']

   Plot quality

   >>> subgrid.plot(scalars=cell_qual, stitle='Quality', cmap='bwr', clim=[0, 1],
   ...              flip_scalars=True, show_edges=True)

.. image:: https://github.com/pyvista/tetgen/raw/main/doc/images/sphere_qual.png


Using a Background Mesh
-----------------------
A background mesh in TetGen is used to define a mesh sizing function for
adaptive mesh refinement. This function informs TetGen of the desired element
size throughout the domain, allowing for detailed refinement in specific areas
without unnecessary densification of the entire mesh. Here's how to utilize a
background mesh in your TetGen workflow:

1. **Generate the Background Mesh**: Create a tetrahedral mesh that spans the
   entirety of your input piecewise linear complex (PLC) domain. This mesh will
   serve as the basis for your sizing function.

2. **Define the Sizing Function**: At the nodes of your background mesh, define
   the desired mesh sizes. This can be based on geometric features, proximity
   to areas of interest, or any criterion relevant to your simulation needs.

3. **Optional: Export the Background Mesh and Sizing Function**: Save your
   background mesh in the TetGen-readable `.node` and `.ele` formats, and the
   sizing function values in a `.mtr` file. These files will be used by TetGen
   to guide the mesh generation process.

4. **Run TetGen with the Background Mesh**: Invoke TetGen, specifying the
   background mesh. TetGen will adjust the mesh according to the provided
   sizing function, refining the mesh where smaller elements are desired.

**Full Example**

To illustrate, consider a scenario where you want to refine a mesh around a
specific region with increased detail. The following steps and code snippets
demonstrate how to accomplish this with TetGen and PyVista:

1. **Prepare Your PLC and Background Mesh**:

   .. code-block:: python

      import pyvista as pv
      import tetgen
      import numpy as np

      # Load or create your PLC
      sphere = pv.Sphere(theta_resolution=10, phi_resolution=10)

      # Generate a background mesh with desired resolution
      def generate_background_mesh(bounds, resolution=20, eps=1e-6):
          x_min, x_max, y_min, y_max, z_min, z_max = bounds
          grid_x, grid_y, grid_z = np.meshgrid(
              np.linspace(xmin - eps, xmax + eps, resolution),
              np.linspace(ymin - eps, ymax + eps, resolution),
              np.linspace(zmin - eps, zmax + eps, resolution),
              indexing="ij",
          )
          return pv.StructuredGrid(grid_x, grid_y, grid_z).triangulate()

      bg_mesh = generate_background_mesh(sphere.bounds)

2. **Define the Sizing Function and Write to Disk**:

   .. code-block:: python

      # Define sizing function based on proximity to a point of interest
      def sizing_function(points, focus_point=np.array([0, 0, 0]), max_size=1.0, min_size=0.1):
          distances = np.linalg.norm(points - focus_point, axis=1)
          return np.clip(max_size - distances, min_size, max_size)

      bg_mesh.point_data['target_size'] = sizing_function(bg_mesh.points)

      # Optionally write out the background mesh
      def write_background_mesh(background_mesh, out_stem):
          """Write a background mesh to a file.

          This writes the mesh in tetgen format (X.b.node, X.b.ele) and a X.b.mtr file
          containing the target size for each node in the background mesh.
          """
          mtr_content = [f"{background_mesh.n_points} 1"]
          target_size = background_mesh.point_data["target_size"]
          for i in range(background_mesh.n_points):
              mtr_content.append(f"{target_size[i]:.8f}")

          pv.save_meshio(f"{out_stem}.node", background_mesh)
          mtr_file = f"{out_stem}.mtr"

          with open(mtr_file, "w") as f:
              f.write("\n".join(mtr_content))

      write_background_mesh(bg_mesh, 'bgmesh.b')

3. **Use TetGen with the Background Mesh**:


   Directly pass the background mesh from PyVista to ``tetgen``:

   .. code-block:: python

      tet_kwargs = dict(order=1, mindihedral=20, minratio=1.5)
      tet = tetgen.TetGen(mesh)
      tet.tetrahedralize(bgmesh=bgmesh, **tet_kwargs)
      refined_mesh = tet.grid

   Alternatively, use the background mesh files.

   .. code-block:: python

      tet = tetgen.TetGen(sphere)
      tet.tetrahedralize(bgmeshfilename='bgmesh.b', **tet_kwargs)
      refined_mesh = tet.grid


This example demonstrates generating a background mesh, defining a spatially
varying sizing function, and using this background mesh to guide TetGen in
refining a PLC. By following these steps, you can achieve adaptive mesh
refinement tailored to your specific simulation requirements.


Acknowledgments
---------------
Software was originally created by Hang Si based on work published in
`TetGen, a Delaunay-Based Quality Tetrahedral Mesh Generator `__.

Owner

  • Name: PyVista
  • Login: pyvista
  • Kind: organization
  • Email: info@pyvista.org
  • Location: The Future

A community effort to make 3D visualization and analysis more approachable

GitHub Events

Total
  • Create event: 13
  • Release event: 1
  • Issues event: 6
  • Watch event: 39
  • Delete event: 11
  • Issue comment event: 16
  • Push event: 18
  • Pull request review event: 11
  • Pull request event: 31
  • Fork event: 4
Last Year
  • Create event: 13
  • Release event: 1
  • Issues event: 6
  • Watch event: 39
  • Delete event: 11
  • Issue comment event: 16
  • Push event: 18
  • Pull request review event: 11
  • Pull request event: 31
  • Fork event: 4

Committers

Last synced: almost 3 years ago

All Time
  • Total Commits: 86
  • Total Committers: 7
  • Avg Commits per committer: 12.286
  • Development Distribution Score (DDS): 0.337
Top Committers
Name Email Commits
Alex Kaszynski a****p@g****m 57
Bane Sullivan b****n@g****m 22
banesullivan b****i@g****m 3
Nick Vazquez n****z@g****m 1
darikg d****g@u****m 1
Stef Smeets s****s@u****m 1
Tetsuo Koyama t****0@g****m 1

Issues and Pull Requests

Last synced: 6 months ago

All Time
  • Total issues: 45
  • Total pull requests: 71
  • Average time to close issues: about 2 months
  • Average time to close pull requests: 8 days
  • Total issue authors: 34
  • Total pull request authors: 13
  • Average comments per issue: 1.91
  • Average comments per pull request: 0.82
  • Merged pull requests: 61
  • Bot issues: 0
  • Bot pull requests: 30
Past Year
  • Issues: 4
  • Pull requests: 33
  • Average time to close issues: 4 days
  • Average time to close pull requests: 3 days
  • Issue authors: 4
  • Pull request authors: 6
  • Average comments per issue: 0.25
  • Average comments per pull request: 0.79
  • Merged pull requests: 27
  • Bot issues: 0
  • Bot pull requests: 23
Top Authors
Issue Authors
  • banesullivan (8)
  • MbBrainz (2)
  • Lorenzomarta (2)
  • MichaelHillier (2)
  • steersteer (2)
  • liblaf (1)
  • tftangming (1)
  • stefsmeets (1)
  • heidtn (1)
  • YMX2022 (1)
  • Telos4 (1)
  • ttsesm (1)
  • sfladi (1)
  • pk1234dva (1)
  • mathematicalmichael (1)
Pull Request Authors
  • akaszynski (22)
  • dependabot[bot] (19)
  • pre-commit-ci[bot] (11)
  • tkoyama010 (5)
  • thefloe1 (3)
  • banesullivan (2)
  • johnnynunez (2)
  • angela-ko (2)
  • user27182 (1)
  • stefsmeets (1)
  • nickvazz (1)
  • darikg (1)
  • mathematicalmichael (1)
Top Labels
Issue Labels
bug (3) enhancement (1) question (1) PyVista (1)
Pull Request Labels

Packages

  • Total packages: 1
  • Total downloads:
    • pypi 35,240 last-month
  • Total dependent packages: 4
  • Total dependent repositories: 11
  • Total versions: 29
  • Total maintainers: 2
pypi.org: tetgen

Python interface to tetgen

  • Versions: 29
  • Dependent Packages: 4
  • Dependent Repositories: 11
  • Downloads: 35,240 Last month
Rankings
Dependent packages count: 2.4%
Dependent repos count: 4.4%
Average: 5.2%
Stargazers count: 5.4%
Downloads: 6.9%
Forks count: 7.1%
Maintainers (2)
Last synced: 6 months ago

Dependencies

.github/workflows/build-and-deploy.yml actions
  • actions/checkout v3 composite
  • actions/download-artifact v3 composite
  • actions/upload-artifact v3 composite
  • pypa/cibuildwheel v2.11.4 composite
  • pypa/gh-action-pypi-publish v1.5.0 composite
.github/workflows/docbuild.yml actions
  • JamesIves/github-pages-deploy-action 4.1.4 composite
  • actions/checkout v3 composite
  • actions/setup-python v4 composite
  • pyvista/setup-headless-display-action v1 composite
requirements.txt pypi
  • Sphinx <=2.0.0
  • ansys_corba *
  • doctr *
  • pyansys *
  • pymeshfix *
  • sphinx-autobuild >
  • sphinx-copybutton *
  • sphinx-gallery *
  • sphinx-notfound-page >=0.3.0
  • sphinx-rtd-theme *
  • sphinxcontrib-napoleon *
  • sphinxcontrib-websupport *
requirements_docs.txt pypi
  • Sphinx <7.0
  • matplotlib *
  • pyacvd *
  • pydata-sphinx-theme *
  • pymeshfix *
  • pyvista *
  • sphinx-copybutton *
  • sphinx-notfound-page >=0.3.0
  • sphinx_gallery *
requirements_test.txt pypi
  • pymeshfix >=0.13.4 test
  • pytest * test
  • pytest-cov * test
setup.py pypi
  • numpy >1.16.0
pyproject.toml pypi