Skip to content

Commit

Permalink
Merge branch 'master' of https://github.com/hpgem/nanomesh into master
Browse files Browse the repository at this point in the history
  • Loading branch information
stefsmeets committed Jan 20, 2022
2 parents b58bc7b + 71ee103 commit 0ec293c
Show file tree
Hide file tree
Showing 10 changed files with 689 additions and 607 deletions.
27 changes: 17 additions & 10 deletions nanomesh/mesh.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

from types import MappingProxyType
from typing import TYPE_CHECKING, Dict, List, Sequence

import matplotlib.pyplot as plt
Expand Down Expand Up @@ -45,6 +46,7 @@ class BaseMesh:
def __init__(self,
points: np.ndarray,
cells: np.ndarray,
fields: Dict[str, int] = None,
region_markers: List[RegionMarker] = None,
**cell_data):
"""Base class for meshes.
Expand All @@ -55,6 +57,8 @@ def __init__(self,
Array with points.
cells : (i, j) np.ndarray[int]
Index array describing the cells of the mesh.
fields : Dict[str, int]:
Mapping from field names to labels
region_markers : List[RegionMarker], optional
List of region markers used for assigning labels to regions.
Defaults to an empty list.
Expand All @@ -68,11 +72,22 @@ def __init__(self,
else:
self.default_key = list(cell_data.keys())[0]

if not fields:
fields = {}

self.points = points
self.cells = cells
self.field_to_number = fields
self.region_markers = [] if region_markers is None else region_markers
self.cell_data = cell_data

@property
def number_to_field(self):
"""Mapping from numbers to fields, proxy to `.field_to_number`."""
return MappingProxyType(
{v: k
for k, v in self.field_to_number.items()})

def add_region_marker(self, region_marker: RegionMarkerLike):
"""Add marker to list of region markers.
Expand Down Expand Up @@ -240,7 +255,6 @@ class LineMesh(BaseMesh):
def plot_mpl(self,
ax: plt.Axes = None,
key: str = None,
fields: Dict[int, str] = None,
**kwargs) -> plt.Axes:
"""Simple line mesh plot using `matplotlib`.
Expand All @@ -262,9 +276,6 @@ def plot_mpl(self,
if not ax:
fig, ax = plt.subplots()

if fields is None:
fields = {}

if key is None:
try:
key = tuple(self.cell_data.keys())[0]
Expand All @@ -277,7 +288,7 @@ def plot_mpl(self,
for cell_data_val in np.unique(cell_data):
vert_x, vert_y = self.points.T

name = fields.get(cell_data_val, cell_data_val)
name = self.number_to_field.get(cell_data_val, cell_data_val)

lineplot(
ax,
Expand Down Expand Up @@ -330,7 +341,6 @@ def plot(self, **kwargs):
def plot_mpl(self,
ax: plt.Axes = None,
key: str = None,
fields: Dict[int, str] = None,
**kwargs) -> plt.Axes:
"""Simple mesh plot using `matplotlib`.
Expand All @@ -353,9 +363,6 @@ def plot_mpl(self,
if not ax:
fig, ax = plt.subplots()

if fields is None:
fields = {}

if key is None:
try:
key = tuple(self.cell_data.keys())[0]
Expand All @@ -368,7 +375,7 @@ def plot_mpl(self,
for cell_data_val in np.unique(cell_data):
vert_x, vert_y = self.points.T

name = fields.get(cell_data_val, cell_data_val)
name = self.number_to_field.get(cell_data_val, cell_data_val)

ax.triplot(vert_y,
vert_x,
Expand Down
29 changes: 22 additions & 7 deletions nanomesh/mesh2d/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,14 @@ def simple_triangulate(points: np.ndarray,
return mesh


def pad(mesh: LineMesh,
*,
side: str,
width: int,
label: int = None) -> LineMesh:
def pad(
mesh: LineMesh,
*,
side: str,
width: int,
label: int = None,
name: str = None,
) -> LineMesh:
"""Pad a triangle mesh (2D).
Parameters
Expand All @@ -104,6 +107,9 @@ def pad(mesh: LineMesh,
label : int, optional
The label to assign to the padded area. If not defined, generates the
next unique label based on the existing ones.
name : str, optional
Name of the added region. Note that in case of conflicts, the `label`
takes presedence over the `name`.
Returns
-------
Expand All @@ -115,8 +121,17 @@ def pad(mesh: LineMesh,
ValueError
When the value of `side` is invalid.
"""
labels = [m.label for m in mesh.region_markers]
names = [m.name for m in mesh.region_markers]

if (label in labels) and (name is None):
name = [m.name for m in mesh.region_markers if m.label == label][0]

if name and (name in names) and (label is None):
label = [m.label for m in mesh.region_markers if m.name == name][0]

if label is None:
label = mesh.labels.max() + 1
label = max(max(labels) + 1, 2)

if width == 0:
return mesh
Expand Down Expand Up @@ -171,7 +186,7 @@ def pad(mesh: LineMesh,
cells = np.vstack([mesh.cells, additional_segments])

center = corners.mean(axis=0)
region_markers = mesh.region_markers + [RegionMarker(label, center)]
region_markers = mesh.region_markers + [RegionMarker(label, center, name)]

new_mesh = mesh.__class__(
points=all_points,
Expand Down
8 changes: 7 additions & 1 deletion nanomesh/mesh2d/mesher.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def generate_regions(polygons: List[Polygon]) -> List[Tuple[int, np.ndarray]]:
point = polygon.find_point()

# in LineMesh format
regions.append((label + 1, point))
regions.append((1, point))

return regions

Expand Down Expand Up @@ -223,6 +223,12 @@ def triangulate(self,
mesh.set_field_data('triangle', {0: 'background', 1: 'feature'})
mesh.set_field_data('line', {0: 'body', 1: 'external', 2: 'internal'})

fields = {
m.label: m.name
for m in self.contour.region_markers if m.name
}
mesh.set_field_data('triangle', fields)

return mesh

def generate_domain_mask_from_contours(
Expand Down
19 changes: 14 additions & 5 deletions nanomesh/mesh_container.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ def number_to_field(self):
dim_name = CellType(dimension).name.lower()
number_to_field[dim_name][number] = field

return MappingProxyType(dict(number_to_field))
return MappingProxyType(
{k: MappingProxyType(v)
for k, v in number_to_field.items()})

@property
def field_to_number(self):
Expand All @@ -39,22 +41,24 @@ def field_to_number(self):
dim_name = CellType(dimension).name.lower()
field_to_number[dim_name][field] = number

return MappingProxyType(dict(field_to_number))
return MappingProxyType(
{k: MappingProxyType(v)
for k, v in field_to_number.items()})

def set_field_data(self, cell_type: str, field_data: Dict[int, str]):
"""Update the values in `.field_data`.
Parameters
----------
cell_type : str
Cell type to update the values ofr.
Cell type to update the values for.
field_data : dict
Dictionary with key-to-number mapping, i.e.
`field_data={0: 'green', 1: 'blue', 2: 'red'}`
maps `0` to `green`, etc.
"""
try:
input_field_data = dict(self.number_to_field)[cell_type]
input_field_data = dict(self.number_to_field[cell_type])
except KeyError:
input_field_data = {}

Expand Down Expand Up @@ -144,7 +148,12 @@ def get(self, cell_type: str = None) -> BaseMesh:

cell_data = self.get_all_cell_data(cell_type)

return BaseMesh.create(cells=cells, points=points, **cell_data)
fields = self.field_to_number.get(cell_type, None)

return BaseMesh.create(cells=cells,
points=points,
fields=fields,
**cell_data)

def get_all_cell_data(self, cell_type: str = None) -> dict:
"""Get all cell data for given `cell_type`.
Expand Down
3 changes: 2 additions & 1 deletion nanomesh/region_markers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from dataclasses import dataclass
from typing import Tuple, Union
from typing import Optional, Tuple, Union

import numpy.typing as npt

Expand All @@ -8,6 +8,7 @@
class RegionMarker:
label: int
coordinates: npt.NDArray
name: Optional[str] = None


RegionMarkerLike = Union[RegionMarker, Tuple[int, npt.NDArray]]
45 changes: 27 additions & 18 deletions notebooks/sample_data/How to pad a 2D mesh.ipynb

Large diffs are not rendered by default.

Binary file modified tests/baseline_images/test_mesh/line_mesh.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified tests/baseline_images/test_mesh/triangle_mesh.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit 0ec293c

Please sign in to comment.