upxo.meshing.conformal_mesher2d module

2D grain-boundary-conformal meshing for UPXO tessellations.

confMesh2d is the legacy pygmsh path and is deprecated. New work must use confMesh2dGMSH (raw gmsh API) or gsmesh2d.mesh_gs.

class upxo.meshing.conformal_mesher2d.confMesh2d(gtess=None)[source]

Bases: object

Deprecated pygmsh orchestrator for 2D conformal grain-structure meshing.

Deprecated since version Use: confMesh2dGMSH or upxo.meshing.gsmesh2d.mesh_gs(). Instantiating this class emits DeprecationWarning.

Builds conformal FE meshes on geometric polycrystals (typically vtpolyxtal2d / VTGS), with triangle or quad elements via pygmsh-oriented paths.

Usage (legacy)

>>> from upxo.meshing.conformal_mesher2d import confMesh2d as cm2d
>>> m = confMesh2d.from_geometric_pxtal(pxtal=..., xbound=..., ybound=...)
>>> m.femesh_pygmsh(elementShape='tri', elementOrder=1, ...)
gtess

Geometric tessellation / polycrystal source.

nodes, elConn, elsets, elsets_eltype

Mesh connectivity and element-set bookkeeping after meshing.

elementShape, elementOrder, meshingAlgorithmID

Element and algorithm settings.

ValidElTypesOptions = ('triangle', 'quad')
gtess
classmethod from_geometric_pxtal(gsgen_method='shapely_pxtal_load', pxtal=None, xbound=None, ybound=None)[source]

Class method to mesh geometrified grain struture.

Deprecated: prefer building Shapely flat_cells and calling confMesh2dGMSH.femesh_gmsh() or upxo.meshing.gsmesh2d.mesh_gs().

femesh_pygmsh(elementShape='tri', elementOrder=1, meshingAlgorithmID=4, elsize_global=[1.0], intermediateFilename='femesh', intermediateFileformat='vtk')[source]

Femesh via pygmsh.

Deprecated: use confMesh2dGMSH.femesh_gmsh().

set_fids(geomObject)[source]

Assign each cell feature, a unique ID (fid) starting from 1.

Parameters:

geomObject (list of shapely geometries Geometries that will be used to form feature IDs.)

Example

gsConfMesh.set_fids(gsConfMesh.gtess.L0.pxtal.geoms)

filter_mesh()[source]

Filter mesh.

get_mesh_geometry()[source]

Return the mesh geometry.

assess_quality(qualityMeasures=['aspect_ratio', 'skew', 'min_angle', 'area'])[source]

Assess quality.

see_mesh_quality(mqm_data, mqm_dataframe, data_to_vis='mesh > quality > field', qualityMeasures=['aspect_ratio', 'skew', 'min_angle', 'area'])[source]

See mesh quality.

see_femesh(*args, **kwargs)[source]

See femesh.

find_meshCellFeatTypes()[source]

Find meshCellFeatTypes.

find_lineFeatLocation()[source]

Find lineFeatLocation.

find_GBlines()[source]

Find GBlines.

find_availableFeatures()[source]

Find availableFeatures.

find_availableElTypes()[source]

Find availableElTypes.

find_availableElTypeID()[source]

Find availableElTypeID.

build_nodes()[source]

Build and return nodes.

rebuild_elConnectivity()[source]

Rebuild elconnectivity.

get_elCentroids_singleElType(nodes, elConn)[source]

Return the elCentroids singleElType.

form_elsets_elType()[source]

Form elsets eltype.

get_elCentroids()[source]

Return the elCentroids.

find_elID_ranges()[source]

Find elID ranges.

form_elsets()[source]

Consilidates elment sets of all element types into one single dictionary.

extract_gblines_for_grain(grain_name)[source]

Extract gblines for grain.

extract_gblines_grains()[source]

Extract gblines grains.

extract_gbnodes_grains()[source]

Extract gbnodes grains.

extract_gbnodeCoords_grains()[source]

Extract gbnodecoords grains.

extract_gbCoords_ckdTrees(preserve_ZDim=False)[source]

Extract gbcoords ckdtrees.

calc_element_qualities(ar=True, saa=False, throw=False)[source]

Return the element qualities.

find_elIDs_by_quality(**kwargs)[source]

Find elIDs by quality.

plot_elements_geometric_grain(grain_name, **kwargs)[source]

Visualise elements geometric grain using Matplotlib or PyVista.

plot_elements_by_elIDs(element_ids, **kwargs)[source]

Visualise elements by elIDs using Matplotlib or PyVista.

plot_elements_geometric_grains(**kwargs)[source]

Visualise elements geometric grains using Matplotlib or PyVista.

extract_gb_elements_for_grain(grain_name)[source]

Extract gb elements for grain.

collect_gb_elements_for_grains(grain_ids=None, grain_names=None, prefix='grain')[source]

Orchestrator to extract GB elements for multiple grains using extract_gb_elements_for_grain. Accepts either grain_ids or grain_names. If grain_ids are provided, uses prefix + ‘.’ + str(grainid) to form grain names.

see_gbElements_grains(grain_name, **kwargs)[source]

See gbelements grains.

build_global_element_numbering()[source]

Build and return global element numbering.

find_el_neigh(element_ids, n_order=1, eltype=None, include_self=False)[source]

Find el neigh.

find_nthOrderNeigh(n_order, el_subset, include_self=False)[source]

Find nthOrderNeigh.

resolve_eltypes(grain_name, grainElements, grainCoordinates, eltypes=None)[source]

Resolve eltypes.

build_element_ids_by_band(grain_name, bands, eltypes, grainElements, nearest_dist_by_type)[source]

Build and return element ids by band.

pick_contrasting_colours_from_cmap(n_colours, cmap_name='nipy_spectral')[source]

Pick contrasting colours from cmap.

resolve_band_colours(bands, band_colours=None, auto_cmap='nipy_spectral')[source]

Resolve band colours.

resolve_plot_eltype(eltypes, plot_eltype=None)[source]

Resolve plot eltype.

plot_band_elements(element_ids_by_band, bands, plot_eltype, gbcoords, gblines_by_grain=None, colours_to_use=None, title='Selected elements by band', band_facecolors=False)[source]

Visualise band elements using Matplotlib or PyVista.

select_elements_in_bands(grain_name, bands, gbnodeCoords, grainCoordinates, grainElements, eltypes=None, plot_eltype='quad', gblines_by_grain=None, plot=True, band_colours=None, auto_cmap='nipy_spectral', band_facecolors=False)[source]

Select elements in bands.

fids
pxtal_mesh
grid
mesherTool
elementShape
elementOrder
meshingAlgorithmID
filtered_cells
filtered_mesh
nodes
elConn
meshCellFeatTypes
lineFeatLocation
GBlines
availableFeatures
availableElTypes
availableElTypeID
elsets_eltype
elsets
elID_ranges
class upxo.meshing.conformal_mesher2d.confMesh2dGMSH[source]

Bases: object

Conformal 2D FE mesher via the raw gmsh API (no pygmsh).

Accepts Shapely grain polygons (flat_cells) and optional gid_map, then meshes with GB-refined / bulk size controls. Mirrors post-processing from confMesh2d (ELSETs, boundary / grain / GB NSETs) so pygmsh can be phased out without breaking workflows.

Typical workflow

>>> from upxo.meshing.conformal_mesher2d import confMesh2dGMSH as cm2dg
>>> m = confMesh2dGMSH()
>>> m.femesh_gmsh(flat_cells, gid_map,
...               mesh_size_gb=0.75, mesh_size_bulk=4.5,
...               mesh_algo=8, mesh_order=1, recombine_to_quads=True)
>>> m.form_elsets_gmsh()
>>> m.build_boundary_nsets(); m.build_grain_nsets(); m.build_gb_nset()

Geometric polycrystals (the old confMesh2d.from_geometric_pxtal path) use from_geometric_pxtal() then femesh_gmsh().

ValidElTypesOptions = ('triangle', 'quad')
gtess
fids
gid_map
flat_cells
point_registry
surface_tags
physical_surface_tags
mesherTool
elementShape
elementOrder
meshingAlgorithmID
recombine_to_quads
nodes
elConn
GBlines
availableFeatures
availableElTypes
availableElTypeID
elsets_eltype
elsets
elID_ranges
nsets
grid
validation_report
fidelity_report
quality_report
classmethod from_geometric_pxtal(gsgen_method='shapely_pxtal_load', pxtal=None, xbound=None, ybound=None)[source]

Build a confMesh2dGMSH from a geometric polycrystal.

Drop-in replacement for the deprecated confMesh2d.from_geometric_pxtal. Call femesh_gmsh() afterwards (flat_cells may be omitted; they are taken from the tessellation).

set_fids(geomObject)[source]

Assign 1-based feature IDs from a sequence of grain geometries.

femesh_gmsh(flat_cells=None, gid_map=None, mesh_size_gb=1.0, mesh_size_bulk=4.0, mesh_algo=6, mesh_order=1, recombine_to_quads=False, out_dir=None, basename='gs_mesh', formats=None, field_sampling=None, n_threads=None, snap_tol=None, island_cover_frac=0.95, validate=True, verbose=False, dist_min=None, dist_max=None, clean_geometry=True, unify_winding=True, optimize=False, mesh_size_from_curvature=False, fidelity_tol=None)[source]

Full gmsh meshing pipeline.

Parameters:
  • flat_cells (dict or None) – {flat_id: shapely.geometry.Polygon}. If None, uses cells stored by from_geometric_pxtal().

  • gid_map (dict, optional) – {flat_id: original_grain_id}. If None, flat_id is used as-is.

  • mesh_size_gb (float) – Target element size on grain boundaries.

  • mesh_size_bulk (float) – Target element size in grain interiors.

  • mesh_algo (int) – gmsh mesh algorithm ID (e.g. 6=Frontal, 8=Frontal-Delaunay quads).

  • mesh_order (int) – Element order (1=linear, 2=quadratic).

  • recombine_to_quads (bool) – Whether to recombine triangles into quads after meshing.

  • out_dir (str or None) – Directory to write exported mesh files. No export when None.

  • basename (str) – Filename stem for exported files (extension appended per format).

  • formats (list of str or None) – File format extensions to export, e.g. ['msh', 'inp', 'vtk'].

  • field_sampling (int or None) – Distance-field samples per curve. None chooses from curve count.

  • n_threads (int or None) – Gmsh Mesh.MaxNumThreads. None uses os.cpu_count().

  • snap_tol (float or None) – Point-merge quantum. None is 1e-9 of the domain diagonal.

  • island_cover_frac (float) – Fraction of an inner polygon’s area that must lie in an outer polygon to treat it as an island (strict contains is too brittle after smoothing).

  • validate (bool) – Raise if a grain has no elements or inverted elements are found.

  • verbose (bool) – Let Gmsh print to the terminal.

  • dist_min (float or None) – Threshold-field distances. Defaults: mesh_size_gb and 2 * mesh_size_bulk.

  • dist_max (float or None) – Threshold-field distances. Defaults: mesh_size_gb and 2 * mesh_size_bulk.

  • clean_geometry (bool) – Snap near-duplicate vertices, drop collapsed edges, and orient rings CCW/CW before Gmsh.

  • unify_winding (bool) – Reverse clockwise elements after extract so signed areas are >= 0.

  • optimize (bool) – Run Gmsh Laplace2D (then Relocate2D if available) after generate. Leftover triangles after recombination are kept.

  • mesh_size_from_curvature (bool) – Let Gmsh grade size from GB curvature in addition to the distance Threshold field.

  • fidelity_tol (float or None) – If set, raise when max grain-area relative error exceeds this.

static prepare_grain_polygons(flat_cells, min_edge=None, snap_tol=1e-09)[source]

Snap near-duplicate vertices, drop collapsed edges, orient rings.

Exterior rings are forced CCW and interiors CW (Shapely orient). Invalid results fall back to the input polygon.

report_fidelity(flat_cells=None)[source]

Compare mesh grain area and GB length to the input Shapely polygons.

Relative error is |mesh - shapely| / shapely per original grain id. Shared GB edges are counted once in the mesh length and match polygon.boundary.length per grain (each shared edge appears on two grain boundaries).

report_quality()[source]

Aspect-ratio and min-angle statistics (corners only on quadratic).

get_elCentroids_singleElType(nodes, elConn)[source]

Return the elCentroids singleElType.

form_elsets_gmsh(flat_cells=None, prefix='grain.', verbose=False, verify_shapely=False)[source]

Build per-grain element sets.

Default source is Gmsh physical-group / surface ownership recorded at extract time. The old centroid-in-polygon walk is kept as an optional check (verify_shapely=True) or as a fallback if physical ELSETs were not built.

Parameters:
  • flat_cells (dict or None) – {flat_id: shapely.geometry.Polygon}. Defaults to the dict used in femesh_gmsh().

  • prefix (str) – Prefix for element set names (default ‘grain.’).

  • verbose (bool) – Print per-element-type progress.

  • verify_shapely (bool) – Also run the centroid-in-polygon assignment and warn if the grain membership counts disagree.

find_elID_ranges()[source]

Find elID ranges.

get_elCentroids()[source]

Return the elCentroids.

build_boundary_nsets(tol=1e-06)[source]

Build node sets for domain boundaries and corners.

Populates self.nsets with keys:

‘LEFT’, ‘RIGHT’, ‘BOTTOM’, ‘TOP’, ‘BOTTOM_LEFT’, ‘BOTTOM_RIGHT’, ‘TOP_LEFT’, ‘TOP_RIGHT’

using node coordinates from self.nodes.

build_grain_nsets()[source]

Build per-grain node sets from self.elsets_eltype. Populates self.nsets with keys matching elset names (e.g. ‘grain.1’).

build_gb_nset()[source]

Build a node set containing all grain-boundary nodes. Populates self.nsets[‘GB’].

extract_gblines_for_grain(grain_name)[source]

Extract gblines for grain.

extract_gblines_grains()[source]

Extract gblines grains.

extract_gbnodes_grains()[source]

Extract gbnodes grains.

extract_gbnodeCoords_grains()[source]

Extract gbnodecoords grains.

extract_gbCoords_ckdTrees(preserve_ZDim=False)[source]

Extract gbcoords ckdtrees.

extract_gb_elements_for_grain(grain_name)[source]

Extract gb elements for grain.

collect_gb_elements_for_grains(grain_ids=None, grain_names=None, prefix='grain')[source]

Collect gb elements for grains.

get_mesh_geometry()[source]

Return (points_2d, lines, triangles, quads) arrays for plotting.

see_femesh(*args, **kwargs)[source]

See femesh.

plot_by_grain(**kwargs)[source]

Grain-coloured 2D mesh plot. See upxo.viz.meshviz.plot_conformal_2d_by_grain.

export_abaqus_inp(path, **kwargs)[source]

Abaqus .inp export. See upxo.meshing.writer_ABQ.export_confmesh2d_inp.

see_gbElements_grains(grain_name, **kwargs)[source]

See gbelements grains.

calc_element_qualities(ar=True, saa=False, throw=False)[source]

Return the element qualities.

find_elIDs_by_quality(**kwargs)[source]

Find elIDs by quality.

find_el_neigh(element_ids, n_order=1, eltype=None, include_self=False)[source]

Find el neigh.

find_nthOrderNeigh(n_order, el_subset, include_self=False)[source]

Find nthOrderNeigh.

build_global_element_numbering()[source]

Build and return global element numbering.

resolve_eltypes(grain_name, grainElements, grainCoordinates, eltypes=None)[source]

Resolve eltypes.

build_element_ids_by_band(grain_name, bands, eltypes, grainElements, nearest_dist_by_type)[source]

Build and return element ids by band.

pick_contrasting_colours_from_cmap(n_colours, cmap_name='nipy_spectral')[source]

Pick contrasting colours from cmap.

resolve_band_colours(bands, band_colours=None, auto_cmap='nipy_spectral')[source]

Resolve band colours.

resolve_plot_eltype(eltypes, plot_eltype=None)[source]

Resolve plot eltype.

plot_elements_geometric_grain(grain_name, **kwargs)[source]

Visualise elements geometric grain using Matplotlib or PyVista.

plot_elements_by_elIDs(element_ids, **kwargs)[source]

Visualise elements by elIDs using Matplotlib or PyVista.

plot_elements_geometric_grains(**kwargs)[source]

Visualise elements geometric grains using Matplotlib or PyVista.

plot_band_elements(element_ids_by_band, bands, plot_eltype, gbcoords, gblines_by_grain=None, colours_to_use=None, title='Selected elements by band', band_facecolors=False)[source]

Visualise band elements using Matplotlib or PyVista.

select_elements_in_bands(grain_name, bands, gbnodeCoords, grainCoordinates, grainElements, eltypes=None, plot_eltype='quad', gblines_by_grain=None, plot=True, band_colours=None, auto_cmap='nipy_spectral', band_facecolors=False)[source]

Select elements in bands.