femlabpy.io.gmsh#

Gmsh mesh import and normalization for femlabpy workflows.

Workflow role#

This module reads .msh files and converts them into a normalized GmshMesh structure that the rest of the library can consume without caring about Gmsh version differences. It handles both the older ASCII layout and newer 4.x meshes when the optional official SDK is installed.

Public entry points#

  • load_gmsh returns a rich normalized mesh object with convenient element groups and compatibility aliases.

  • load_gmsh2 preserves the older FemLab-facing calling style while still building on the same parser and normalized data model.

Functions#

TypedDict(typename[, fields, total])

A simple typed namespace.

import_module(name[, package])

Import a module.

load_gmsh(filename)

Read a Gmsh mesh using the legacy load_gmsh.m semantics.

load_gmsh2(filename[, which])

Read a Gmsh mesh using the more flexible load_gmsh2.m semantics.

Function Reference#

femlabpy.io.gmsh.TypedDict(typename, fields=None, /, *, total=True, **kwargs)[source]#

A simple typed namespace. At runtime it is equivalent to a plain dict.

TypedDict creates a dictionary type that expects all of its instances to have a certain set of keys, where each key is associated with a value of a consistent type. This expectation is not checked at runtime but is only enforced by type checkers. Usage:

class Point2D(TypedDict):
    x: int
    y: int
    label: str

a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK
b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check

assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')

The type info can be accessed via the Point2D.__annotations__ dict, and the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. TypedDict supports two additional equivalent forms:

Point2D = TypedDict('Point2D', x=int, y=int, label=str)
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})

By default, all keys must be present in a TypedDict. It is possible to override this by specifying totality. Usage:

class point2D(TypedDict, total=False):
    x: int
    y: int

This means that a point2D TypedDict can have any of the keys omitted.A type checker is only expected to support a literal False or True as the value of the total argument. True is the default, and makes all items defined in the class body be required.

The class syntax is only supported in Python 3.6+, while two other syntax forms work for Python 2.7 and 3.2+

femlabpy.io.gmsh.import_module(name, package=None)[source]#

Import a module.

The ‘package’ argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import.

femlabpy.io.gmsh.load_gmsh(filename) GmshMesh[source]#

Read a Gmsh mesh using the legacy load_gmsh.m semantics.

Parameters:
filename:

Path to a Gmsh .msh file. Legacy 2.x ASCII files are parsed directly. Modern 4.x files are converted through the optional official gmsh SDK when the mesh extra is installed.

Returns:
GmshMesh

Normalized mesh object exposing both Python fields and legacy MATLAB aliases.

Notes

The returned GmshMesh stores explicit type arrays whose last column contains the first element tag, matching the original classroom loaders.

femlabpy.io.gmsh.load_gmsh2(filename, which=None) GmshMesh[source]#

Read a Gmsh mesh using the more flexible load_gmsh2.m semantics.

Parameters:
filename:

Path to a Gmsh .msh file.

which:

Optional iterable of element-type ids whose explicit arrays should be materialized. None loads all explicit arrays, while -1 or an empty iterable reproduces the MATLAB behavior of skipping them.

Returns:
GmshMesh

Normalized mesh object with optional explicit topology tables.

Classes#

GmshMesh(positions, element_infos, ...)

Parsed Gmsh mesh with both normalized Python fields and legacy FemLab aliases.

ParsedElement

Normalized intermediate representation for one Gmsh element row.

Path(*args, **kwargs)

PurePath subclass that can make system calls.

TemporaryDirectory([suffix, prefix, dir, ...])

Create and return a temporary directory.

Class Reference#

class femlabpy.io.gmsh.GmshMesh(positions: ~numpy.ndarray, element_infos: ~numpy.ndarray, element_tags: ~numpy.ndarray = <factory>, element_nodes: ~numpy.ndarray = <factory>, nb_type: ~numpy.ndarray = <factory>, points: ~numpy.ndarray = <factory>, lines: ~numpy.ndarray = <factory>, lines2: ~numpy.ndarray = <factory>, triangles: ~numpy.ndarray = <factory>, quads: ~numpy.ndarray = <factory>, tets: ~numpy.ndarray = <factory>, tets10: ~numpy.ndarray = <factory>, hexa: ~numpy.ndarray = <factory>, hexa20: ~numpy.ndarray = <factory>, hexa27: ~numpy.ndarray = <factory>, prism: ~numpy.ndarray = <factory>, prism15: ~numpy.ndarray = <factory>, prism18: ~numpy.ndarray = <factory>, pyramid: ~numpy.ndarray = <factory>, pyramid13: ~numpy.ndarray = <factory>, pyramid14: ~numpy.ndarray = <factory>, qtriangles: ~numpy.ndarray = <factory>, quads8: ~numpy.ndarray = <factory>, quads9: ~numpy.ndarray = <factory>, bounds_min: ~numpy.ndarray = <factory>, bounds_max: ~numpy.ndarray = <factory>, legacy_element_infos: ~numpy.ndarray = <factory>, legacy_element_tags: ~numpy.ndarray = <factory>, loader_name: str = 'load_gmsh2', explicit_types: frozenset[int] = <factory>, nodes_per_type_of_element: ~numpy.ndarray = <factory>)[source]#

Bases: object

Parsed Gmsh mesh with both normalized Python fields and legacy FemLab aliases.

Lowercase attributes such as positions, element_infos, and triangles form the stable Python API used internally by femlabpy. Uppercase aliases such as POS, ELE_INFOS, TRIANGLES, nbTriangles, MIN, and MAX are exposed through __getattr__ to mimic the original MATLAB loaders.

property_numbers(element_refs: ndarray, *, info_column: int | None = None) ndarray[source]#

Return property numbers or info columns for one-based element references.

Parameters:
element_refs:

One-based element numbers.

info_column:

Optional zero-based column index into element_infos. When omitted, the first entry of element_tags is returned, matching the legacy FemLab interpretation of physical-region numbers.

Returns:
ndarray

Integer property numbers aligned with element_refs.

class femlabpy.io.gmsh.ParsedElement[source]#

Bases: TypedDict

Normalized intermediate representation for one Gmsh element row.

class femlabpy.io.gmsh.Path(*args, **kwargs)[source]#

Bases: PurePath

PurePath subclass that can make system calls.

Path represents a filesystem path but unlike PurePath, also offers methods to do system calls on path objects. Depending on your system, instantiating a Path will return either a PosixPath or a WindowsPath object. You can also instantiate a PosixPath or WindowsPath directly, but cannot instantiate a WindowsPath on a POSIX system or vice versa.

classmethod cwd()[source]#

Return a new path pointing to the current working directory (as returned by os.getcwd()).

classmethod home()[source]#

Return a new path pointing to the user’s home directory (as returned by os.path.expanduser(‘~’)).

samefile(other_path)[source]#

Return whether other_path is the same or not as this file (as returned by os.path.samefile()).

iterdir()[source]#

Iterate over the files in this directory. Does not yield any result for the special paths ‘.’ and ‘..’.

glob(pattern)[source]#

Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.

rglob(pattern)[source]#

Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.

absolute()[source]#

Return an absolute version of this path. This function works even if the path doesn’t point to anything.

No normalization is done, i.e. all ‘.’ and ‘..’ will be kept along. Use resolve() to get the canonical path to a file.

resolve(strict=False)[source]#

Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows).

stat(*, follow_symlinks=True)[source]#

Return the result of the stat() system call on this path, like os.stat() does.

owner()[source]#

Return the login name of the file owner.

group()[source]#

Return the group name of the file gid.

open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)[source]#

Open the file pointed by this path and return a file object, as the built-in open() function does.

read_bytes()[source]#

Open the file in bytes mode, read it, and close the file.

read_text(encoding=None, errors=None)[source]#

Open the file in text mode, read it, and close the file.

write_bytes(data)[source]#

Open the file in bytes mode, write to it, and close the file.

write_text(data, encoding=None, errors=None, newline=None)[source]#

Open the file in text mode, write to it, and close the file.

Return the path to which the symbolic link points.

touch(mode=438, exist_ok=True)[source]#

Create this file with the given access mode, if it doesn’t exist.

mkdir(mode=511, parents=False, exist_ok=False)[source]#

Create a new directory at this given path.

chmod(mode, *, follow_symlinks=True)[source]#

Change the permissions of the path, like os.chmod().

lchmod(mode)[source]#

Like chmod(), except if the path points to a symlink, the symlink’s permissions are changed, rather than its target’s.

Remove this file or link. If the path is a directory, use rmdir() instead.

rmdir()[source]#

Remove this directory. The directory must be empty.

lstat()[source]#

Like stat(), except if the path points to a symlink, the symlink’s status information is returned, rather than its target’s.

rename(target)[source]#

Rename this path to the target path.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

replace(target)[source]#

Rename this path to the target path, overwriting if that path exists.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

Make this path a symlink pointing to the target path. Note the order of arguments (link, target) is the reverse of os.symlink.

Make this path a hard link pointing to the same file as target.

Note the order of arguments (self, target) is the reverse of os.link’s.

Make the target path a hard link pointing to this path.

Note this function does not make this path a hard link to target, despite the implication of the function and argument names. The order of arguments (target, link) is the reverse of Path.symlink_to, but matches that of os.link.

Deprecated since Python 3.10 and scheduled for removal in Python 3.12. Use hardlink_to() instead.

exists()[source]#

Whether this path exists.

is_dir()[source]#

Whether this path is a directory.

is_file()[source]#

Whether this path is a regular file (also True for symlinks pointing to regular files).

is_mount()[source]#

Check if this path is a POSIX mount point

Whether this path is a symbolic link.

is_block_device()[source]#

Whether this path is a block device.

is_char_device()[source]#

Whether this path is a character device.

is_fifo()[source]#

Whether this path is a FIFO.

is_socket()[source]#

Whether this path is a socket.

expanduser()[source]#

Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)

class femlabpy.io.gmsh.TemporaryDirectory(suffix=None, prefix=None, dir=None, ignore_cleanup_errors=False)[source]#

Bases: object

Create and return a temporary directory. This has the same behavior as mkdtemp but can be used as a context manager. For example:

with TemporaryDirectory() as tmpdir:

Upon exiting the context, the directory and everything contained in it are removed.