2D Geometry & Meshing Guide (Gmsh & Netgen)
EMUstack solves for the electromagnetic Bloch modes of 2D periodically structured layers (NanoStruct(‘2D_array’, …)) by discretizing the 2D unit cell into high-order finite elements in NGSolve.
To support both legacy simulation scripts and pure-Python workflows, EMUstack provides two complete 2D meshing pipelines that converge into the same ngsolve.Mesh representation:
The Gmsh Pipeline (Classic Workflow — ``.geo``): Reads a parameterized Gmsh
.geoscript (or a pre-generated.mail/.mshfile), substitutes geometry parameters fromgeo_params, invokes the externalgmshbinary to triangulate the unit cell, and imports the resulting mesh into Netgen/NGSolve with periodic vertex identifications.The Netgen Pipeline (Native Pure-Python Workflow — ``.py``): Executes a pure-Python geometry builder (
build_unit_cell(...)in a*.pytemplate) to construct a curved second-order periodicngsolve.Meshdirectly in memory—requiring zero external binaries and zero temporary disk files.Within a Netgen
.pytemplate, you can choose between two routes depending on the complexity of your resonator geometry:Netgen Route B1 — High-Level Helper
meshing.unit_cell()(Standard Inclusions): If your unit cell is composed of one or more standard geometric primitives—circles, rotated ellipses, squares, rectangles, concentric rings, or dimers (such as inellipse_msh_template.pyor the two tilted elliptical bars inchiral_qbic_gorkunov_msh_template.py)—you do not need to write low-level Netgen CSG code. You simply normalize your dimensions, describe each inclusion as a Python dictionary ({"kind": "ellipse", ...}), and pass the list tomeshing.unit_cell(), which builds the periodic box, curved splines, domain tags, and mesh automatically.Netgen Route B2 — Direct
netgen.geom2d.SplineGeometry(Fancier / Arbitrary Custom Shapes): If you need a fancier or arbitrary custom shape that is not one of the standard primitives supported bymeshing.unit_cell()(for example: an L-shaped nanoantenna, a split-ring resonator with a cut gap, a crescent, a polygon, or freeform Bézier curves), you bypassmeshing.unit_cell()and construct anetgen.geom2d.SplineGeometrydirectly insidebuild_unit_cell(...).
Note
How EMUstack Selects the Pipeline:
Passing a Python template
geo_file='... .py'always runs the native Netgen pipeline.Passing a Gmsh script
geo_file='... .geo'runs the Gmsh pipeline (unless overridden).For built-in
NanoStructshapes without ageo_file(inc_shape='circle','ellipse','square','rectangle','ring','dimer'), the pipeline is controlled either globally viaobjects.default_mesher = 'gmsh'(default) or'netgen', or per layer viaNanoStruct(..., mesher='netgen').
Using the Shipped Templates
EMUstack ships 30 mesh templates inside the package (EMUstack/backend/data/meshes/ in the
repository, inside site-packages once EMUstack is installed). You never need their path:
pass the file name as geo_file and the parameters as geo_params:
from EMUstack.backend import objects, materials, meshing
layer = objects.NanoStruct(
'2D_array', geo_file='ellipse_msh_template.geo', # or the short name 'ellipse.geo'
geo_params={'period': 400.0, 'diameter1': 160.0, 'ellipticity': 0.3, 'angle': 0.5,
'lc': 0.1, 'lc2': 2.0},
background=materials.Air, inclusion_a=materials.Si_c, height_nm=100.0)
meshing.list_templates() # names of all shipped templates
geo_file is looked up in this order:
Your working directory (or the path you give), so your own files always win.
The shipped templates, by full name (
ellipse_msh_template.geo), short name (ellipse.geo,ellipse.py) or old v1 name (ring1_msh_template.geo).
The extension picks the mesher: .geo templates are meshed by gmsh, .py templates by
netgen.
To start your own geometry from a shipped template, copy it into your project and edit the copy:
meshing.copy_template('ellipse.geo') # writes ./ellipse_msh_template.geo
meshing.copy_template('ellipse.geo', 'my_cell.geo')
Because the working directory is searched first, geo_file='ellipse_msh_template.geo' then
uses your edited copy. Give it a new name (my_cell.geo) to keep both. To read a shipped
template without copying it, meshing.resolve_mesh_file_path('ellipse.geo') returns its path.
Lengths are in nm and angles in radians unless the table says otherwise. Every template also
takes the mesh sizes lc (background) and lc2, lc3, … (finer sizes lc/lcN at
the inclusions; see Concept 6).
Template |
Mesher |
Geometry |
Parameters |
|---|---|---|---|
|
gmsh |
4x4 grid of inclusions (circle, ellipse or square), numbered row by row from the top left. |
|
|
gmsh |
One inclusion: circle, ellipse ( |
|
|
gmsh |
Two circular inclusions per cell. |
|
|
gmsh |
Three circular inclusions per cell. |
|
|
gmsh |
2x2 grid of inclusions (circle, ellipse or square); |
|
|
gmsh |
3x3 grid of circular inclusions. |
|
|
gmsh |
L-shaped inclusion with a rounded corner. |
|
|
gmsh |
Split-ring resonator with its open side at the top. |
|
|
netgen |
Four rotated bar dimers in a C4-symmetric cell (Gorkunov et al.). |
|
|
netgen |
Bar dimer of Gorkunov et al.; |
|
|
netgen |
Chiral quasi-BIC cell; |
|
|
gmsh |
Chiral slit pattern, slits moved by |
|
|
gmsh |
Cross of size |
|
|
gmsh |
Cross-shaped shell of wall |
|
|
gmsh |
Two circles separated by |
|
|
gmsh |
Inclusion inside two strips ( |
|
|
gmsh |
Egg-shaped inclusion containing a circular inclusion of radius |
|
|
gmsh |
Egg-shaped inclusion made of arcs of radii |
|
|
gmsh |
ELLE shape (Zanotto et al., Nanophotonics 8, 2291 (2019)); |
|
|
gmsh |
Rotated ellipse ( |
|
|
netgen |
Rotated ellipse ( |
|
|
gmsh |
One inclusion in a hexagonal lattice. |
|
|
gmsh |
Rectangle |
|
|
gmsh |
Rectangular shell of wall |
|
|
gmsh |
Ring: outer |
|
|
gmsh |
Row of 2 inclusions; period, size and spacing are set inside the file (edit a copy). |
|
|
gmsh |
Row of 5 inclusions; period, size and spacing are set inside the file (edit a copy). |
|
|
gmsh |
Two squares (sides |
|
|
gmsh |
Two rectangular shells of wall |
|
|
gmsh |
Inclusion inside a strip of width |
|
Where the Meshes Are Written
With gmsh, NanoStruct writes three files per mesh: the .geo with the parameters filled
in, the .msh made by gmsh, and the .mail that EMUstack reads. They go in a folder named
emustack_meshes, so you can open them in gmsh to inspect the mesh:
Geometry |
Meshes written to |
|---|---|
Built-in shape ( |
|
Your own |
|
Any of the above, with |
that folder |
from EMUstack.backend import meshing
meshing.mesh_dir = '/scratch/me/meshes' # every mesh goes here, e.g. on a cluster
layer.mesh_dir # folder of this layer's mesh
layer.mesh_file # its .mail file name
The file names hold the template name, the periods and the parameters, for example
ellipse400_0_400_0__diameter1160_lc0_1.mail. If the folder cannot be written (a read-only
shared folder, for example), the meshes go to your user cache folder instead
(~/.cache/emustack/meshes on Linux, ~/Library/Caches/emustack/meshes on macOS,
%LOCALAPPDATA%\emustack\meshes on Windows), with a warning.
NanoStruct meshes again on every run by default (force_mesh=True, as in version 1).
With force_mesh=False it reuses a mesh already in the folder, unless your .geo has
changed since. The netgen mesher (.py templates, mesher='netgen') keeps meshes in memory
and writes no files.
—
Part I: General Presentation & the 6 Core Concepts
Regardless of whether you use the Gmsh pipeline (``.geo``) or the Netgen pipeline (``.py``, via Route B1 or Route B2), building a valid 2D periodic unit-cell mesh in EMUstack always requires the exact same six conceptual stages.
Stage / Concept |
Gmsh Pipeline ( |
Netgen Route B1: |
Netgen Route B2: Direct |
|---|---|---|---|
1. Parameter Injection |
Textual substitution of |
Python signature inspection of |
Python signature inspection of |
2. Coordinate Normalization |
Physical lengths in nm are divided by |
Physical lengths in nm are divided by |
Physical lengths in nm are divided by |
3. Periodic Outer Boundaries |
Outer edges tagged as |
Automated by |
Append primary |
4. Interior Inclusions |
|
Automated by |
Append custom |
5. Subdomain Material Tags |
|
Automated by |
Set |
6. Refinement & Meshing |
Point sizes |
Automated by |
Call |
Concept 1: Parameter Injection (geo_file & geo_params)
When you instantiate objects.NanoStruct('2D_array', geo_file=..., geo_params={...}), all geometric and mesh refinement parameters (period, period_y, diameter1, ellipticity, angle, lc, lc2, lc3; the names are the same for .geo and .py templates, see Naming: One Vocabulary for .geo, .py and unit_cell) can be passed directly inside the geo_params dictionary—without repeating legacy positional arguments like period, diameter1, ellipticity, or inc_shape='custom'. EMUstack locates geo_file (first in your working directory, then among the shipped templates; see Using the Shipped Templates) and dispatches geo_params to the selected template:
In the Gmsh pipeline,
NanoStruct/meshing.mesh_from_geo()reads the.geofile as text and replaces placeholder assignments such asperiod = 0;,period_y = 0;,diameter1 = 0;,ellipticity = 0;,angle = 0;,lc = 0;, andlc2 = lc/1;with the numerical values fromgeo_params. If a key ingeo_paramsdoes not have a matching placeholder in the.geofile, aKeyErroris raised immediately.In the Netgen pipeline (both Routes B1 and B2),
meshing.mesh_from_py()dynamically imports the.pymodule, inspects the Python signature ofbuild_unit_cell(...)usinginspect.signature, verifies that every key ingeo_paramsis a valid parameter ofbuild_unit_cell(or an old name of one) (raising aTypeErroron typos), and callsbuild_unit_cell(**call_params).
Naming: One Vocabulary for .geo, .py and unit_cell
The three ways of describing a unit cell use the same words for the same quantities:
Template files are named
<shape>_msh_template.geo(gmsh) or<shape>_msh_template.py(netgen), where<shape>is theNanoStruct(inc_shape=...)name when there is one (ring,rectangle,cross_shell, …).N_msh_template.geoholdsNcircular inclusions per cell. A template can also be given by its short name:geo_file='ring.geo'.Template parameters (
.geoplaceholders,.pykeyword arguments andgeo_paramskeys) share one set of names. Lengths are in nm and angles in radians, unless the name ends in_deg.unit_cell inclusion keys use the same words in normalized coordinates:
kind(the same shape names),center,radius,width,height,side,angle/angle_deg,radius_out/radius_in.
Old names keep working everywhere: old file names are looked up in meshing.LEGACY_TEMPLATE_NAMES; old parameter names are listed in meshing.PARAM_ALIASES (shared by all templates) or in the (legacy: ...) comment of the template’s placeholder line; old unit_cell keys are in meshing.INCLUSION_KEY_ALIASES. A parameter name present in the template is always filled as is, so custom templates written with the old names behave exactly as before, and accept the new names too.
Template |
Parameters |
Old names |
|---|---|---|
all |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
unchanged; |
|
|
unchanged; their shape parameters are normalized to the period |
Mesh sizes keep their names everywhere: lc is the background size and lc2, lc3, … are refinement divisors (lcN = lc/1; in a .geo file).
A few templates have layout rules:
4_,9_and16_place their inclusions on a 2×2, 3×3 and 4×4 grid, numbered row by row from the top left. Inclusion 1 isinclusion_a, all othersinclusion_b.posxandposymove the inclusions towards the cell centre.strip_puts the inclusion (diameter1) inside a strip of widthstrip(diameter2forNanoStruct) that runs along x, so the strip must be wider than the inclusion and narrower than the cell.double_strip_adds a band of total widthstrip2(diameter3) around it.NanoStructchecks these rules before meshing.
gmsh never returns on some invalid geometries, such as lines that cross an inclusion. EMUstack stops gmsh after meshing.gmsh_timeout seconds (default 600, or the EMUSTACK_GMSH_TIMEOUT environment variable) and raises an error that names the .geo file.
Renaming a .py Template Parameter Safely: @meshing.legacy_params
A .geo template keeps its old names in a (legacy: ...) comment. A .py template is a Python function, so it needs a Python tool for the same job: the meshing.legacy_params() decorator.
The problem. Suppose a template was written with a cryptic keyword:
def build_unit_cell(period=400.0, a1=None, lc=0.12):
...
and you rename a1 to the readable diameter1. Every script that still calls build_unit_cell(a1=300), or passes geo_params={'a1': 300} to NanoStruct, now fails with TypeError: unexpected keyword argument 'a1'. Keeping both keywords in the signature would work, but the function would then have two parameters for one quantity, and every template would need the same “if a1 is given, copy it to diameter1” code.
The solution. Write the function with the new name only, and declare the old name once, above it:
from EMUstack.backend import meshing
@meshing.legacy_params(a1="diameter1") # old name="new name"
def build_unit_cell(period=400.0, diameter1=None, lc=0.12):
... # the body only ever sees diameter1
The decorator wraps the function in a thin layer that renames old keywords before the call. You can list several pairs, as the Gorkunov template does: @meshing.legacy_params(theta="theta_deg", l="length", w="width", d="z_offset", rot1="angle1", rot2="angle2").
What happens on each call. With the template above:
build_unit_cell(diameter1=300) # new name: passed through unchanged
build_unit_cell(a1=300) # old name: renamed to diameter1=300 first
build_unit_cell(500, 300) # positional: untouched (period=500, diameter1=300)
build_unit_cell(a1=300, diameter1=250) # both: which one is meant? refuse instead of guessing
# TypeError: build_unit_cell() got both 'a1' and its new name 'diameter1'
Step by step, the wrapper:
looks at the keyword arguments of the call;
for each
old="new"pair, ifoldwas passed, moves its value tonew, or raises theTypeErrorabove ifnewwas passed as well;calls the real function, which never sees an old name.
Under the hood. The whole decorator is a dozen lines of meshing:
def legacy_params(**renames):
def decorator(fn):
@functools.wraps(fn) # keep name, docstring, signature
def wrapper(*args, **kwargs):
for old, new in renames.items():
if old in kwargs:
if new in kwargs:
raise TypeError(f"{fn.__name__}() got both '{old}' and its new name '{new}'")
kwargs[new] = kwargs.pop(old)
return fn(*args, **kwargs)
wrapper.legacy_params = dict(renames) # lets mesh_from_py see the old names
return wrapper
return decorator
Two details make it fit the rest of EMUstack:
functools.wrapskeeps the function’s name, docstring and signature.inspect.signature(build_unit_cell)still shows(period=400.0, diameter1=None, lc=0.12), sohelp(), the API reference and tab completion show only the new names.wrapper.legacy_paramsrecords the renames (here{'a1': 'diameter1'}).meshing.mesh_from_py()checks everygeo_paramskey against the builder’s signature and raisesTypeError: Unexpected parameter ...on a typo. It reads this attribute, so it accepts'a1'as a valid key and passes it on asdiameter1.
How a ``NanoStruct`` call reaches the template. The rename works the same whichever way the template is called:
NanoStruct(geo_file='ellipse_msh_template.py', geo_params={'a1': 300, ...})
-> meshing.mesh_from_py(...) 'a1' is valid: listed in build_unit_cell.legacy_params
-> build_unit_cell(diameter1=300, ...) mesh_from_py already uses the new name
import ellipse_msh_template (calling the template directly)
ellipse_msh_template.build_unit_cell(a1=300)
-> wrapper renames a1 -> diameter1
-> build_unit_cell(diameter1=300)
Recipe: renaming a parameter of your own template.
Rename the parameter in the signature and in the body (
a1->diameter1).Add
@meshing.legacy_params(a1="diameter1")directly abovedef build_unit_cell.Mention the old name in the docstring, so readers know where it went.
Check both spellings give the same mesh, for example
build_unit_cell(a1=300)andbuild_unit_cell(diameter1=300).
If a template defines build_geometry as an alias that calls build_unit_cell(*args, **kwargs), the alias inherits the renames.
What it does not do.
It renames, it does not convert. The old and new keywords must mean exactly the same value in the same units.
theta->theta_degis fine because both are degrees. If you change a parameter from degrees to radians, or from nm to a fraction of the period, a rename would silently give wrong geometry. Keep the old parameter and convert it in the body instead.It only applies to keyword arguments. Positional calls are untouched, so keep the parameter in the same position when you rename it.
It is only for ``.py`` templates.
.geotemplates use the(legacy: ...)comment,unit_cellinclusion keys usemeshing.INCLUSION_KEY_ALIASES, and the names shared by all templates (d_in_nm,a1, …) are inmeshing.PARAM_ALIASES.
Concept 2: Coordinate Normalization to a Dimensionless Unit Cell
All 2D meshes in EMUstack are constructed in dimensionless coordinates normalized by the unit-cell pitch along \(x\) (period \(= a\)):
Every physical dimension in nanometers—such as a cylinder diameter \(D\), ellipse semi-axes \(r_x, r_y\), resonator width \(w\), length \(l\), or inter-resonator gap \(g\)—is divided by period before constructing the geometry.
Why normalize? In the 2D finite-element solver (fem_2d), the free-space wavenumber \(k_0 = 2\pi/\lambda\) is scaled by period. Because the mesh itself is dimensionless, the unit cell is meshed only once when NanoStruct is instantiated and is reused across all wavelengths in a spectral sweep without re-meshing.
Concept 3: Outer Unit-Cell Boundaries & Periodic Node Identification
To enforce Bloch quasi-periodicity across the unit cell,
NGSolve’s Periodic(HCurl * H1, phase=...) space requires that opposite outer boundaries (Left \(\leftrightarrow\) Right and Bottom \(\leftrightarrow\) Top) have identical 1D mesh discretizations and explicit periodic vertex identifications:
In the Gmsh pipeline, the four outer boundary edges are tagged as
Physical Line(1..4). Whenmeshing.import_gmsh_mesh()ingests the.mshfile, it locates all vertices on \(x = x_{\min}\) and \(x = x_{\max}\) (and \(y = y_{\min}\), \(y = y_{\max}\)), verifies that opposite faces have the exact same node count, sorts them by coordinate, and pairs them via 1-basedngm.AddPointIdentification(p1, p2, id_nr, IdentificationType.PERIODIC).In the Netgen pipeline, the left edge (\(\tilde{x}=0\)) is appended as primary segment
i_land the right edge (\(\tilde{x}=1\)) is appended in the same bottom-to-top direction withcopy=i_l. Likewise, the bottom edge (\(\tilde{y}=0\)) is appended as primary segmenti_band the top edge (\(\tilde{y}=d_y\)) in the same left-to-right direction withcopy=i_b. Thecopy=argument instructs Netgen to clone the 1D mesh nodes from the primary edge onto its partner edge and automatically register the periodic vertex identifications. (When using Route B1, :func:`meshing.unit_cell` sets up this outer periodic box for you automatically; when using Route B2, you write these 5 lines at the top of your ``SplineGeometry``.)
Concept 4: Interior Inclusions & High-Order Curved Boundaries
Approximating curved dielectric or metallic resonators (such as circular nanopillars or tilted elliptical bars in a high-\(Q\) quasi-BIC metasurface) with straight-edged polygons introduces artificial corner singularities and staircase errors. Both pipelines represent curved boundaries using second-order isoparametric curved elements:
In the Gmsh pipeline, curved boundaries are defined using Gmsh’s built-in
CircleorEllipsisarc primitives (optionally rotated viaRotate) and meshed either as 6-node quadratic triangles (gmsh -2 -order 2) or curved to second order upon Netgen import (ngm.Curve(2)).In the Netgen pipeline, curved boundaries are represented in
netgen.geom2d.SplineGeometryusing 3-point quadratic rational Bézier spline segments (["spline3", pt0, pt_ctrl, pt1]) together withngm.Curve(2):In Route B1 (
meshing.unit_cell()): You simply specify a dictionary such as{"kind": "ellipse", "center": (xc, yc), "rx": rx, "ry": ry, "angle": alpha, "tag": 2, "lc": lc2}. Internally,meshing.unit_cell()divides the circle or ellipse into \(N_{\text{seg}} = 24\) angular sectors \([a_0, a_1]\) (\(\Delta\theta = 15^\circ\)) and callsmeshing.arc_control_points()to compute the start point \(\mathbf{P}_0\), the end point \(\mathbf{P}_1\), and the exact off-curve tangent intersection control point \(\mathbf{P}_{\text{ctrl}}\):\[\begin{split}\mathbf{P}_{\text{ctrl}} = \mathbf{c} + \begin{pmatrix} \cos\alpha & -\sin\alpha \\ \sin\alpha & \cos\alpha \end{pmatrix} \begin{pmatrix} r_x \sec(\Delta\theta / 2) \cos\theta_{\text{mid}} \\ r_y \sec(\Delta\theta / 2) \sin\theta_{\text{mid}} \end{pmatrix}, \qquad \theta_{\text{mid}} = \frac{a_0 + a_1}{2}.\end{split}\]In Route B2 (Direct
SplineGeometry): For arbitrary polygons or custom resonators, you append straight segments viageo.Append(["line", p0, p1], ...)and curved segments viageo.Append(["spline3", pt0, pt_ctrl, pt1], ...)(you can even call the helpermeshing.arc_control_points()for circular/elliptical fillets or arcs inside your custom shape).
Concept 5: Subdomain Material Tagging (bg, inc2, inc3, …)
During the finite-element assembly (fem_2d), EMUstack maps each mesh subdomain to the refractive index of the corresponding material passed to objects.NanoStruct:
Integer Tag |
Netgen Material Name |
Gmsh Physical Surface |
|
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
In the Gmsh pipeline, you explicitly group closed
Line Loopdefinitions intoPlane Surfaceentities (subtracting interior inclusion loops from the outer unit-cell loop) and assignPhysical Surface(1)to the background andPhysical Surface(2)to the inclusion.In the Netgen pipeline, 2D regions are defined topologically by directed boundary curves via
leftdomainandrightdomain: as you walk along a segment from its start point to its end point,leftdomainis the region ID to your left andrightdomainis the region ID to your right (where0denotes the exterior of the computational domain). When an inclusion boundary is traversed counter-clockwise, its interior lies on the left (leftdomain=tag) and the surrounding background lies on the right (rightdomain=1). In Route B1, you simply set"tag": 2(or3..6) in each inclusion dictionary andmeshing.unit_cell()setsleftdomain,rightdomain, andgeo.SetMaterial(...)automatically. In Route B2, you passleftdomain=tag, rightdomain=1directly togeo.Append(...)and callgeo.SetMaterial(...).
Concept 6: Mesh Refinement Controls (lc, lc2, ..., lc_n vs. Netgen maxh) & Verification
1. The General Role of lc and lc2, lc3, ..., lc_n
Mesh resolution in EMUstack is controlled in dimensionless unit-cell units (fractions of period):
lc(baseline background mesh size): Characteristic triangle edge length in the background medium (domaintag = 1,"bg") and along the outer periodic unit-cell boundaries. For example,lc = 0.08produces roughly \(1 / 0.08 \approx 12\text{--}13\) elements across the unit cell.lc2, lc3, ..., lc_n(dimensionless local mesh-scaling factors, \(\text{lc}_n > 0\)): Scalelcto set the local target element size \(h_n\) at specific geometric features:\[h_n = \frac{\text{lc}}{\text{lc}_n} \qquad (\text{for any } \text{lc}_n > 0).\]\(\text{lc}_n > 1\) \(\implies h_n < \text{lc}\) (finer mesh than the background—for example, inside or along the boundary of a high-index dielectric or plasmonic resonator where internal wavelengths are shorter and local fields are sharper).
\(\text{lc}_n = 1\) \(\implies h_n = \text{lc}\) (same mesh size as the background).
\(0 < \text{lc}_n < 1\) \(\implies h_n > \text{lc}\) (coarser mesh than the background—for example, inside a low-index air hole etched in a high-index slab, or at the interior center of a large inclusion whose boundary is already finely resolved).
Important
Do lc2, lc3, ..., lc_n Always Map 1-to-1 to Subdomains or Inclusions? No.
While it is often convenient to think of lc_n as the refinement factor of an inclusion or material domain, in general a mesh-scaling parameter lc_n can control any local geometric feature:
An embedded interior point: In
ellipse_msh_template.geo(Example A below), there is only one elliptical inclusion (Physical Surface(2)), yet there are three mesh parameters:lcon the outer unit-cell corners,lc2on the ellipse perimeter (lc / lc2), andlc3on an isolated point embedded at the center of the ellipse (Point(5)viaPoint{5} In Surface{12};with sizelc / lc3) to grade the interior mesh smoothly between the boundary and the center.Individual inclusions (
"lc": lc_n): In a multi-resonator unit cell, you can pass as manylc_nparameters as you need (lc2, lc3, lc4, ..., lc_n) and assign"lc": lc_ndirectly inside each inclusion dictionary inmeshing.unit_cell()—even when all inclusions share the same material"tag": 2.Subdomain tags (
**lc_kwargs): If an inclusion dictionary omits"lc",meshing.unit_cell()also accepts arbitrarylc2=..., lc3=..., ..., lc_n=...keyword arguments (**lc_kwargs) and mapslc_nby default to subdomaintag = n(falling back tolc2).
2. lc (Gmsh) vs. maxh (Netgen) — How the Two Meshers Differ
Under the hood, Gmsh and Netgen control mesh element sizes using different geometric primitives and terminology:
In Gmsh (
lcon 0D Points): Gmsh attaches a characteristic length (lc) to 0DPointentities (Point(i) = {x, y, 0, lc_i};) and interpolates element sizes across curves and surfaces. In.geotemplates, EMUstack substituteslc2 = lc/1;withlc2 = lc/val;.In Netgen (
maxhon 1D Curves & 2D Domains): Netgen’sSplineGeometrydoes not assign characteristic lengths to points on spline curves; instead, it controls element sizes via a maximum element size (maxh) passed to 1D boundary segments (geo.Append(..., maxh=...)), 2D subdomains (geo.SetDomainMaxH(tag, maxh)), andgeo.GenerateMesh(maxh=...).How EMUstack Bridges
lcandmaxh:In Netgen Route B1 (
meshing.unit_cell()): You use EMUstack’s uniformlcnotation everywhere—writing"lc": lc2,"lc": lc3, …,"lc": lc_ndirectly in each inclusion dictionary (or passinglc2, lc3, ..., lc_nvia**lc_kwargs)—andmeshing.unit_cell()internally converts each factorlc_ninto Netgen’smaxh = lc / lc_non both the boundary splines and the subdomain.In Netgen Route B2 (Direct
SplineGeometry): Because you call Netgen’s nativegeo.Append(...)andgeo.SetDomainMaxH(...)methods directly, you computeinc_maxh = lc / lc2yourself in Python and pass it to Netgen’smaxh=keyword argument.
Once the mesh is generated in meshing.unit_cell(), it automatically runs four sanity assertions:
ngm.GetNrIdentifications() == 4(periodic boundary tables exist).ngm.GetCurveOrder() >= 2(second-order curved elements are active).len(mesh.GetPeriodicNodePairs(VERTEX)) > 0(opposite boundary vertices are paired).\(\left|\int_{\Omega} 1\,dA - 1 \times d_y\right| < 10^{-11}\) (exact unit-cell area conservation).
—
Part II: Step-by-Step Practical Examples
To reinforce the 6 Core Concepts from Part I, we now examine three concrete examples where each practical step (`Step 1` through `Step 6`) maps directly to `Concept 1` through `Concept 6` above:
Example A (Gmsh Pipeline):
ellipse_msh_template.geo— a rotated elliptical nanohole/nanopillar unit cell in Gmsh, passing all parameters viageo_params.Example B1 (Netgen Route B1 — Standard Inclusions via
meshing.unit_cell()):ellipse_msh_template.pyandchiral_qbic_gorkunov_msh_template.py— showing how standard inclusions (such as single or multiple rotated ellipses) are built effortlessly by passing aninclusionsdictionary list tomeshing.unit_cell().Example B2 (Netgen Route B2 — Fancier Custom Shapes via Direct
SplineGeometry): Walking through all 6 steps usingnetgen.geom2d.SplineGeometrydirectly when you need a geometry beyond the standard primitives ofmeshing.unit_cell().
—
Example A: Step-by-Step Gmsh Template (ellipse_msh_template.geo)
Below is the step-by-step breakdown of EMUstack/backend/data/meshes/ellipse_msh_template.geo (for the general rotated case angle != 0).
Step 1 (Concept 1 — Parameter Placeholders)
At the top of ellipse_msh_template.geo, every parameter that can be overridden by geo_params is initialized with a 0 (or lc/1) placeholder:
// Force Gmsh to output legacy MSH 2.2 format required by Netgen ReadGmsh
Mesh.MshFileVersion = 2.2;
d = 1; // Normalized unit-cell width along x
period = 0; // Replaced by period (in nm) (legacy: d_in_nm)
period_y = 0; // Replaced by period_y (in nm) (legacy: dy_in_nm)
diameter1 = 0; // Replaced by major diameter (in nm) (legacy: a1)
ellipticity = 0; // Replaced by (rx - ry) / rx
angle = 0; // Replaced by rotation angle (in radians)
lc = 0; // Replaced by background element size
lc2 = lc/1; // Replaced by lc / lc2 (on ellipse boundary)
lc3 = lc/1; // Replaced by lc / lc3 (at ellipse center)
When you pass geo_params={'period': 400.0, 'diameter1': 300.0, 'ellipticity': 0.5, 'angle': np.pi/3, 'lc': 0.08, 'lc2': 4.0, 'lc3': 2.0}, EMUstack replaces period = 0; with period = 400.0;, diameter1 = 0; with diameter1 = 300.0;, lc2 = lc/1; with lc2 = lc/4.0;, and so on. The (legacy: ...) comments record the old placeholder names, so geo_params={'d_in_nm': 400.0, 'a1': 300.0, ...} fills the same placeholders.
Step 2 (Concept 2 — Coordinate Normalization)
Next, the script converts the physical dimensions period, period_y, and diameter1 (in nanometers) into normalized unit-cell coordinates where the width along \(x\) is d = 1:
dy = period_y / period; // Normalized unit-cell height along y
radius1 = (diameter1 / (2 * period)) * d; // Normalized semi-major axis rx
hy = dy;
hx = 0.0;
Step 3 (Concept 3 — Outer Unit-Cell Box & Physical Boundary Lines)
The four corners of the unit cell \([0, 1] \times [-d_y, 0]\) are created with characteristic mesh size lc and connected into outer boundary lines Line(1..4), closed into Line Loop(9), and exported as Physical Line(1..4):
Point(1) = {0, 0, 0, lc};
Point(2) = {0, -hy, 0, lc};
Point(3) = {d, -hy, 0, lc};
Point(4) = {d, 0, 0, lc};
Line(1) = {1, 2}; // Left boundary (x = 0)
Line(2) = {2, 3}; // Bottom boundary (y = -dy)
Line(3) = {3, 4}; // Right boundary (x = 1)
Line(4) = {4, 1}; // Top boundary (y = 0)
Line Loop(9) = {1, 2, 3, 4};
Physical Line(1) = {1};
Physical Line(2) = {2};
Physical Line(3) = {3};
Physical Line(4) = {4};
When the generated mesh is imported into NGSolve by meshing.import_gmsh_mesh(), the vertices on Line(1) and Line(3) (and on Line(2) and Line(4)) are matched and paired via AddPointIdentification for Bloch periodicity.
Step 4 (Concept 4 — Rotated Elliptical Inclusion)
The ellipse center Point(5) is placed at \((0.5, -0.5\,d_y)\) with mesh size lc3, and the four cardinal vertices Point(6..9) of the unrotated ellipse (with semi-axes \(r_x = \text{radius1}\) and \(r_y = \text{radius1}\,(1 - \text{ellipticity})\)) are created with boundary mesh size lc2. Gmsh’s Rotate command then rotates Point{6,7,8,9} around the center by angle (around the \(z\)-axis {0, 0, 1}), and four Ellipsis arcs join them into Line Loop(10):
// Center of the ellipse
Point(5) = {d/2, -hy/2, 0, lc3};
// Unrotated cardinal endpoints on the ellipse perimeter (mesh size lc2)
Point(6) = {d/2, -hy/2 + (radius1 - ellipticity*radius1), 0, lc2};
Point(7) = {d/2 - radius1, -hy/2, 0, lc2};
Point(8) = {d/2, -hy/2 - (radius1 - ellipticity*radius1), 0, lc2};
Point(9) = {d/2 + radius1, -hy/2, 0, lc2};
// Rotate cardinal points around (0.5*d, -0.5*dy, 0) by angle (in radians)
Rotate{{0, 0, 1}, {0.5 * d, -0.5 * dy, 0}, angle} {Point{6, 7, 8, 9};}
// Connect the 4 elliptical quadrants: Ellipsis(id) = {start, center, maj_pt, end}
Ellipsis(5) = {9, 5, 6, 6};
Ellipsis(6) = {6, 5, 7, 7};
Ellipsis(7) = {7, 5, 8, 8};
Ellipsis(8) = {8, 5, 9, 9};
Line Loop(10) = {5, 6, 7, 8};
Step 6 (Concept 6 — Interior Mesh Control & Calling from NanoStruct)
Finally, Point{5} In Surface{12}; embeds the center point inside the ellipse surface so Gmsh respects lc3 at the center of the inclusion:
Point{5} In Surface{12};
To use this Gmsh template in a simulation script, pass all geometric and meshing parameters directly inside the geo_params dictionary:
import numpy as np
from EMUstack.backend import objects, materials
nh_layer = objects.NanoStruct(
'2D_array',
geo_file='ellipse_msh_template.geo',
geo_params={
'period': 400.0,
'diameter1': 300.0,
'ellipticity': 0.5,
'angle': np.pi / 3,
'lc': 0.08,
'lc2': 4.0,
'lc3': 2.0,
},
background=materials.Au,
inclusion_a=materials.Air,
height_nm=50.0,
)
—
Example B1: Netgen Route B1 — Standard Inclusions via meshing.unit_cell() (ellipse_msh_template.py & chiral_qbic_gorkunov_msh_template.py)
When your unit cell consists of one or more standard geometric primitives (circles, rotated ellipses, squares, rectangles, concentric rings, or dimers), you do not need to construct a SplineGeometry by hand. Instead, you use meshing.unit_cell(), which automates Steps 3, 4, 5, and 6 from a list of inclusion dictionaries.
Let us see how both ellipse_msh_template.py (single rotated ellipse) and chiral_qbic_gorkunov_msh_template.py (a two-ellipse quasi-BIC dimer) are implemented using this route. Chiral_qBIC_Optical_Chirality.ipynb uses chiral_qbic_gorkunov_c4_msh_template.py, which builds the same kind of dimer four times per cell, rotated by 90° each time, as in the paper by Gorkunov et al.
Step 1 (Concept 1 — Python Function Signature & Parameter Validation)
The template defines build_unit_cell(...) with explicit keyword arguments and defaults:
In
ellipse_msh_template.py(single rotated ellipse):from typing import Optional import ngsolve as ngs from EMUstack.backend import meshing @meshing.legacy_params(a1="diameter1") # the old name a1 still works def build_unit_cell( period: float = 400.0, period_y: Optional[float] = None, diameter1: Optional[float] = None, ellipticity: Optional[float] = None, angle: Optional[float] = None, lc: float = 0.12, lc2: float = 5.0, lc3: float = 1.0, ) -> ngs.Mesh:
In
chiral_qbic_gorkunov_msh_template.py(two tilted elliptical bars separated by a gap):@meshing.legacy_params(theta="theta_deg", d="z_offset", l="length", w="width", rot1="angle1", rot2="angle2") def build_unit_cell( period: float = 480.0, period_y: Optional[float] = None, theta_deg: float = 3.5, # Tilt angle in degrees z_offset: float = 10.0, # Vertical offset in nm length: float = 220.0, # Bar length in nm (major axis 2*ry) width: float = 70.0, # Bar width in nm (minor axis 2*rx) gap: float = 15.0, # Edge-to-edge gap between bars in nm include_bar1: bool = True, # Toggle left bar (for 3-layer z-slicing) include_bar2: bool = True, # Toggle right bar (for 3-layer z-slicing) angle1: Optional[float] = None, # Bar rotations in radians angle2: Optional[float] = None, lc: float = 0.08, # Background mesh size (fraction of period) lc2: float = 2.0, # Inclusion refinement factor (inc = lc / lc2) lc3: float = 1.0, curve_order: int = 2, **kwargs ) -> ngs.Mesh:
Step 2 (Concept 2 — Coordinate Normalization to \([0, 1] \times [0, d_y]\))
Next, physical lengths in nanometers are divided by period (\(a\)) so the unit cell spans \([0, 1] \times [0, d_y]\) with its center at \((0.5, 0.5\,d_y)\):
In
ellipse_msh_template.py:py = period if period_y is None else period_y dy = float(py) / float(period) rx = float(diameter1) / (2.0 * float(period)) ry = rx * (1.0 - float(ellipticity)) ang_rad = float(angle) center = (0.5, dy / 2.0)
In
chiral_qbic_gorkunov_msh_template.py:py = period if period_y is None else period_y dy = float(py) / float(period) a = float(period) theta_rad = np.deg2rad(float(theta_deg)) angle1 = +0.5 * theta_rad if angle1 is None else angle1 angle2 = -0.5 * theta_rad if angle2 is None else angle2 rx = 0.5 * float(width) / a ry = 0.5 * float(length) / a sep = (float(width) + float(gap)) / a c1 = (0.5 - 0.5 * sep, 0.5 * dy) c2 = (0.5 + 0.5 * sep, 0.5 * dy)
Steps 3, 4, 5, & 6 (Concepts 3–6 — Automated by meshing.unit_cell())
Because both templates use standard elliptical inclusions, Steps 3 through 6 require only a few lines of Python:
Build the
inclusionslist of dictionaries—where each dictionary specifies the shape"kind"(Step 4), the material"tag"(Step 5), and the inclusion’s mesh-scaling factor"lc": lc_n(Step 6, whichmeshing.unit_cell()converts internally to Netgen’smaxh = lc / lc_n):In
ellipse_msh_template.py:inclusions = [{ "kind": "ellipse", "center": center, "rx": rx, "ry": ry, "angle": ang_rad, "tag": 2, # Maps to inclusion_a "lc": lc2, # Converted internally to maxh = lc / lc2 }]
In
chiral_qbic_gorkunov_msh_template.py:inclusions = [] if include_bar1: inclusions.append({ "kind": "ellipse", "center": c1, "rx": rx, "ry": ry, "angle": float(angle1), "tag": 2, "lc": lc2, }) if include_bar2: inclusions.append({ "kind": "ellipse", "center": c2, "rx": rx, "ry": ry, "angle": float(angle2), "tag": 2, "lc": lc2, })
Call
meshing.unit_cell()withinclusions,dy=dy, and the background mesh sizelc=lc(Steps 3 & 6):return meshing.unit_cell(inclusions, dy=dy, lc=lc)
Tip
Using an arbitrary number of
lc_nparameters ("lc": lc_nand**lc_kwargs):You can define as many
lc_nparameters (lc2, lc3, lc4, ..., lc_n) inbuild_unit_cell(...)andgeo_paramsas you have inclusions, and map"lc": lc_ndirectly inside each inclusion dictionary (where \(\text{lc}_n > 1\) refines and \(0 < \text{lc}_n < 1\) coarsens relative tolc):inclusions = [ {"kind": "ellipse", "center": c1, "rx": rx1, "ry": ry1, "tag": 2, "lc": lc2}, {"kind": "circle", "center": c2, "radius": r2, "tag": 2, "lc": lc3}, {"kind": "square", "center": c3, "side": s3, "tag": 3, "lc": lc4}, ] return meshing.unit_cell(inclusions, dy=dy, lc=lc)
Alternatively, if your inclusions have distinct tags (
"tag": 2, 3, ..., n) and omit the"lc"key in their dictionaries, you can passlc2=lc2, lc3=lc3, lc4=lc4, ...directly as keyword arguments (**lc_kwargs) tomeshing.unit_cell().
What meshing.unit_cell() Supports vs. When to Take Route B2
All standard inclusion shapes supported out of the box by meshing.unit_cell() are listed below (old short keys are shown in brackets and still work):
|
Required / Optional Keys |
Description |
|---|---|---|
|
|
Circular inclusion of normalized radius |
|
|
Elliptical inclusion with semi-axes |
|
|
Axis-aligned rectangular or square inclusion centered at |
|
|
Annular ring between inner radius |
|
|
Symmetric pair of inclusions separated along \(x\) by edge-to-edge |
Important
The Exact Role and Boundary of meshing.unit_cell():
Use Route B1 (
meshing.unit_cell()) whenever your unit cell consists of one or more non-overlapping inclusions drawn from the 6 standard shapes in the table above (in any combination of positionscenter, sizes, rotation angles, and material tags2..6).Use Route B2 (Direct
SplineGeometry, shown next) whenever you need a fancier custom inclusion that is not in the table above—for example, an L-shaped resonator, a split-ring with an angular cut, a crescent, a triangle/hexagonal prism, a rotated rectangle, or freeform splines.
Calling ellipse_msh_template.py and chiral_qbic_gorkunov_msh_template.py from NanoStruct
To run ellipse_msh_template.py, you pass the exact same geo_params dictionary as in the Gmsh example—simply changing .geo to .py:
import numpy as np
from EMUstack.backend import objects, materials
nh_layer = objects.NanoStruct(
'2D_array',
geo_file='ellipse_msh_template.py',
geo_params={
'period': 400.0,
'diameter1': 300.0,
'ellipticity': 0.5,
'angle': np.pi / 3,
'lc': 0.08,
'lc2': 4.0,
'lc3': 2.0,
},
background=materials.Au,
inclusion_a=materials.Air,
height_nm=50.0,
)
Similarly, to build the chiral qBIC dimer layer with chiral_qbic_gorkunov_msh_template.py and plot the triangulated mesh:
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
from EMUstack.backend import objects, materials
period = 480.0
lay2 = objects.NanoStruct(
'2D_array',
geo_file='chiral_qbic_gorkunov_msh_template.py',
geo_params={
'period': period,
'theta_deg': 3.5,
'include_bar1': True,
'include_bar2': True,
'lc': 0.15,
'lc2': 1.5,
},
background=materials.Material(1.0),
inclusion_a=materials.Material(4.0 + 0.01j),
height_nm=90.0,
)
# Visually inspect the generated mesh and material tags (1 = bg, 2 = inc2)
x_nm = lay2.x_arr[0] * period
y_nm = lay2.x_arr[1] * period
triangles = lay2.table_nod[:3].T - 1
triang = mtri.Triangulation(x_nm, y_nm, triangles)
fig, ax = plt.subplots(figsize=(5, 5))
ax.tripcolor(triang, facecolors=lay2.type_el, cmap='coolwarm', edgecolors='k', lw=0.4)
ax.set_aspect('equal')
ax.set_xlabel('x (nm)')
ax.set_ylabel('y (nm)')
ax.set_title(f'Chiral qBIC Unit Cell ({lay2.n_msh_pts} vertices, {lay2.n_msh_el} triangles)')
—
Example B2: Netgen Route B2 — Fancier Custom Shapes via Direct SplineGeometry
When you need a fancier resonator geometry that is not one of the standard primitives in meshing.unit_cell() (or if you want to understand what meshing.unit_cell() does under the hood), your build_unit_cell(...) function constructs a netgen.geom2d.SplineGeometry directly, performing all 6 steps explicitly in Python.
Below is the step-by-step walkthrough of how to build a custom SplineGeometry template (illustrated for an L-shaped nanoantenna, along with how curved "spline3" arcs are added).
Step 1 (Concept 1 — Python Function Signature)
Define build_unit_cell(...) in your custom .py file (e.g., l_antenna_template.py) with your custom geometric parameters and mesh controls:
import netgen.geom2d as g2
import ngsolve as ngs
from ngsolve.fem import NODE_TYPE
def build_unit_cell(
period: float = 500.0,
period_y: float = 500.0,
arm_len: float = 300.0,
arm_width: float = 100.0,
lc: float = 0.10,
lc2: float = 2.5,
curve_order: int = 2,
) -> ngs.Mesh:
Step 2 (Concept 2 — Coordinate Normalization to \([0, 1] \times [0, d_y]\))
Divide all physical dimensions in nanometers by period so the geometry lives inside \([0, 1] \times [0, d_y]\):
dy = float(period_y) / float(period)
L_arm = float(arm_len) / float(period)
W_arm = float(arm_width) / float(period)
inc_h = lc / lc2 # Convert EMUstack's (lc, lc2) into Netgen's maxh
Step 3 (Concept 3 — Outer Unit-Cell Box & Periodic copy= Boundaries)
Instantiate geo = g2.SplineGeometry(), add the 4 corners of the normalized unit cell, and append the primary left and bottom edges followed by their periodic copies right (copy=i_l) and top (copy=i_b):
geo = g2.SplineGeometry()
# 1. Add the 4 corner points of [0, 1] x [0, dy]
P = [geo.AddPoint(*q) for q in [(0, 0), (1.0, 0), (1.0, dy), (0, dy)]]
# 2. Periodic x-boundaries: Left (P0 -> P3) is primary; Right (P1 -> P2) is its copy
i_l = geo.Append(["line", P[0], P[3]], leftdomain=0, rightdomain=1, bc="left", maxh=lc)
geo.Append(["line", P[1], P[2]], leftdomain=1, rightdomain=0, bc="right", maxh=lc, copy=i_l)
# 3. Periodic y-boundaries: Bottom (P0 -> P1) is primary; Top (P3 -> P2) is its copy
i_b = geo.Append(["line", P[0], P[1]], leftdomain=1, rightdomain=0, bc="bottom", maxh=lc)
geo.Append(["line", P[3], P[2]], leftdomain=0, rightdomain=1, bc="top", maxh=lc, copy=i_b)
Note
Always ensure that left and right are traversed in the same direction (both bottom-to-top: P[0]->P[3] and P[1]->P[2]), and that bottom and top are traversed in the same direction (both left-to-right: P[0]->P[1] and P[3]->P[2]).
Step 4 (Concept 4 — Drawing the Custom Inclusion with "line" and "spline3")
Add the vertices (and any spline control points) of your custom resonator in counter-clockwise order, and connect them with geo.Append(...):
For straight polygon edges (such as the 6 vertices of our L-shaped antenna): Use
["line", start_pt, end_pt]:x0, y0 = 0.5 - L_arm / 2.0, 0.5 * dy - L_arm / 2.0 pts_L = [ (x0, y0), (x0 + L_arm, y0), (x0 + L_arm, y0 + W_arm), (x0 + W_arm, y0 + W_arm), (x0 + W_arm, y0 + L_arm), (x0, y0 + L_arm), ] Q = [geo.AddPoint(*p) for p in pts_L] for i in range(len(Q)): geo.Append( ["line", Q[i], Q[(i + 1) % len(Q)]], leftdomain=2, rightdomain=1, bc="inc2", maxh=inc_h, )
For curved boundary arcs (e.g., rounded corners, crescents, or split rings): Use
["spline3", pt0, pt_ctrl, pt1], wherept0andpt1are the arc endpoints andpt_ctrlis the off-curve tangent intersection control point. For circular or elliptical arcs spanning angle \([a_0, a_1]\), you can call the built-in helpermeshing.arc_control_points()directly:# Example: appending a curved circular/elliptical arc from angle a0 to a1 pt0, pt_ctrl, pt1 = meshing.arc_control_points( geo, kind="circle", c=(0.5, 0.5 * dy), a0=a0, a1=a1, r=radius ) geo.Append(["spline3", pt0, pt_ctrl, pt1], leftdomain=2, rightdomain=1, bc="inc2", maxh=inc_h)
Step 5 (Concept 5 — Oriented Domain Tagging leftdomain / rightdomain & Materials)
Because the vertices Q[0] -> Q[1] -> ... -> Q[5] -> Q[0] wind counter-clockwise around the L-antenna, the interior of the antenna is always to the left of each segment (leftdomain=2) and the background is to the right (rightdomain=1).
Next, assign the domain material names and maximum element sizes (“bg” for domain 1 and “inc2” for domain 2, or “inc3”..”inc6” if you have multiple distinct inclusion materials):
geo.SetMaterial(1, "bg")
geo.SetDomainMaxH(1, lc)
geo.SetMaterial(2, "inc2")
geo.SetDomainMaxH(2, inc_h)
Step 6 (Concept 6 — Mesh Generation, Curving ngm.Curve(2), & Calling from NanoStruct)
Finally, generate the mesh, curve any spline boundaries to polynomial order curve_order=2, and return the ngsolve.Mesh:
ngm = geo.GenerateMesh(maxh=lc)
ngm.Curve(curve_order)
mesh = ngs.Mesh(ngm)
# Optional sanity checks
assert ngm.GetNrIdentifications() == 4, "periodic identifications missing"
assert len(mesh.GetPeriodicNodePairs(NODE_TYPE.VERTEX)) > 0
return mesh
You can then invoke l_antenna_template.py from objects.NanoStruct using geo_params in the exact same way as any other template:
from EMUstack.backend import objects, materials
l_layer = objects.NanoStruct(
'2D_array',
geo_file='l_antenna_template.py',
geo_params={
'period': 500.0,
'arm_len': 320.0,
'arm_width': 90.0,
'lc': 0.08,
'lc2': 3.0,
},
background=materials.Air,
inclusion_a=materials.Au,
height_nm=60.0,
)
—
meshing Module API Reference
Geometry and Meshing Module for EMUstack.
Provides: - Built-in Netgen Meshing: Native Netgen SplineGeometry cell builder (unit_cell) with periodic boundaries and exact Bézier curved inclusions. - Gmsh Template Import: Gmsh MSH 2.2 importer (import_gmsh_mesh) with 1-based AddPointIdentification. - .mail file reader and importer (read_mail_file) converting legacy .mail to linear MSH 2.2. - Periodic Boundary Coupling: algebraic constraint operator (bloch_constraint). - Bloch product spaces (bloch_spaces) with mandatory assertions.
Naming is shared by the three ways of describing a unit cell (see the “Templates & naming” section of the docs):
.geo(gmsh) and.py(netgen) templates are named<shape>_msh_template.<ext>and take the same parameter names, in nm:period,period_y,diameter1,width,thickness, … Angles are in radians unless the name ends in_deg.unit_celltakes inclusion dicts in normalized coordinates with the matching keys:kind,center,radius,width,angle, …
Old file names, old parameter names and old dict keys keep working through the alias tables below.
- meshing.arc_control_points(geo: netgen.geom2d.SplineGeometry, kind: str, c: Tuple[float, float], a0: float, a1: float, r: float | None = None, rx: float | None = None, ry: float | None = None, angle: float = 0.0) Tuple[int, int, int][source]
Calculate Bézier control points for quadratic rational arc.
- meshing.arc_segments(r: float, c: Tuple[float, float], nseg: int = 12)[source]
Generate nseg angle intervals (a0, a1) for a full circle/ellipse.
- meshing.bloch_spaces(mesh: ngsolve.Mesh, dy: float, order: int, kx: float, ky: float, period_x: float = 1.0) ngsolve.comp.FESpace[source]
Create periodic HCurl * H1 product Bloch space with phase convention exp(-i k.r).
- meshing.conv_gmsh(root: str) Tuple[int, int][source]
Mesh root.geo with gmsh and write root.mail, as legacy EMUstack’s conv_gmsh.f does.
Same gmsh command line as legacy (6-node triangles, MSH 2.2 set by the templates). The .mail holds every node with the physical tag of the boundary line it lies on (0 inside), and every triangle with its physical surface tag. Unlike legacy, nodes keep gmsh’s order instead of being renumbered for bandwidth; the mesh is the same. Returns (number of nodes, number of triangles).
- meshing.copy_template(name: str, dest: str = '.', overwrite: bool = False) str[source]
Copy a shipped template to dest (a folder or a file name) and return the new path.
Use it to start your own geometry from a shipped one. Files in the working directory are found before the shipped templates, so after
copy_template('ellipse.geo'),geo_file='ellipse_msh_template.geo'meshes your edited copy.
- meshing.fill_geo_template(text: str, params: Dict[str, Any], fmt: str = '%f', strict: bool = True, optional: Iterable[str] = (), template: str = 'template') str[source]
Fill the placeholders of a .geo template.
Each key fills the placeholder of the same name. If the template has no such placeholder, the key’s other spellings are tried: the shared ones in
PARAM_ALIASES(d_in_nm<->period,a1<->diameter1, …) and the(legacy: ...)tags of the template itself. So old keys fill renamed templates, and new keys fill old custom templates.name = 0;becomesname = <value>;andname = lc/1;becomesname = lc/<value>;. Numbers are written withfmt; strings are written as they are. When two keys fill the same placeholder, the later one wins.A key that matches no placeholder raises
KeyErrorwhenstrictis set, unless it is listed inoptional; otherwise it is ignored.
- meshing.geo_placeholders(text: str) Tuple[Dict[str, str], Dict[str, str]][source]
Find the placeholders of a .geo template.
Returns
(placeholders, legacy):placeholdersmaps each name to"value"(name = 0;) or"lc"(name = lc/1;), andlegacymaps each legacy name declared with(legacy: ...)to its current name.
- meshing.gmsh_available() bool[source]
True if a gmsh binary is found and starts (checked once per process).
- meshing.import_gmsh_mesh(msh_path: str, period_x: float = 1.0, period_y: float | None = None, method: str = 'IIA', curve_order: int = 2) ngsolve.Mesh[source]
Import a legacy Gmsh MSH 2.2 mesh and configure 2D periodic identifications.
Parameters: - msh_path: path to .msh file (must be MSH 2.2, linear elements) - period_x: cell width in x - period_y: cell height in y (if None, determined from mesh coordinates) - method: ‘IIA’ (native 1-based AddPointIdentification) or ‘IIB’ (unconstrained for bloch_constraint) - curve_order: curve order to apply (>= 2)
- meshing.is_shipped_template(path: str) bool[source]
True if path is one of the templates shipped inside the package.
- meshing.legacy_params(**renames: str)[source]
Let a template builder accept old keyword names after a rename.
@legacy_params(a1="diameter1")abovedef build_unit_cell(..., diameter1=None, ...)turns a call witha1=300intodiameter1=300. Passing both names raisesTypeError. The renames are stored on the function aslegacy_params, somesh_from_pyaccepts the old names ingeo_paramstoo. It only renames; values are not converted. See “Renaming a .py Template Parameter Safely” in the meshing guide.
- meshing.list_templates() List[str][source]
File names of the mesh templates shipped with EMUstack.
.geotemplates are meshed with gmsh,.pytemplates with netgen. Pass a name (or its short form, e.g.'ellipse.geo') asNanoStruct(geo_file=...).
- meshing.mail_to_msh22(mail_path: str) str[source]
Convert .mail file to Gmsh MSH 2.2 linear triangles string.
- meshing.mesh_folder(source: str | None = None) str[source]
Folder where the mesh made from the template source is written (and created).
meshing.mesh_dir(or theEMUSTACK_MESH_DIRenvironment variable), when set;for a .geo outside the package:
emustack_meshes/next to that file;for shipped templates and built-in shapes (
sourceNone):emustack_meshes/in the current working directory.
If that folder cannot be written, the user cache folder (or the system temp folder) is used instead, with a warning.
- meshing.mesh_from_geo(geo_file: str, geo_params: Dict[str, Any] | None = None, period: float = 1.0, period_y: float | None = None, lc: float = 0.1, lc2: float = 1.0, lc3: float = 1.0, curve_order: int = 2) ngsolve.Mesh[source]
Universal Gmsh .geo loader with parameter substitution and MSH 2.2 ingestion.
- meshing.mesh_from_py(py_file: str, geo_params: Dict[str, Any] | None = None, period: float = 1.0, period_y: float | None = None, lc: float = 0.1, lc2: float = 1.0, lc3: float = 1.0, curve_order: int = 2, **lc_kwargs: float) ngsolve.Mesh[source]
Universal Netgen Python .py geometry loader with signature validation.
- meshing.param_equivalents(name: str) Tuple[str, ...][source]
Other spellings of a template parameter (
"a1" -> ("diameter1",)).
- meshing.parse_mail_data(mail_path: str)[source]
Parse .mail file into raw numpy tables (table_nod, type_el, x_arr, npt, nel).
- meshing.read_mail_file(mail_path: str, method: str = 'IIA') Tuple[ngsolve.Mesh, ndarray, ndarray, ndarray, int, int][source]
Read a .mail file, convert to linear MSH 2.2, import into Netgen/NGSolve, and return mesh + arrays.
- meshing.resolve_mesh_file_path(filename: str) str[source]
Find a .geo, .py, .msh or .mail file.
Looks in the current directory first, then in
backend/data/meshes. A template can be given by its full name (ring_msh_template.geo), its old name (ring1_msh_template.geo) or its short name (ring.geo).
- meshing.unit_cell(inclusions: Any, dx: Any = 1.0, dy: float = 1.0, lc: float = 0.1, curve_order: int = 2, nseg: int = 24, **lc_kwargs: Any) ngsolve.Mesh[source]
Build a periodic 2D unit cell mesh using native Netgen SplineGeometry.
All lengths are normalized to the period along x. The old call
unit_cell(dy, inclusions, period_x=...)still works.- Parameters:
inclusions (list of dict) –
One dict per inclusion. Keys (old spellings in brackets still work):
"kind"["shape"]:"circle"(default),"ellipse","square","rectangle","ring"or"dimer""center"["c"]:(x, y), default(dx/2, dy/2)circle/ellipse:
"radius"["r"] or"rx","ry"square/rectangle:
"side"["s"] or"width","height"["w","h"]ring:
"radius_out","radius_in"["r_out","r_in"]dimer:
"radius","gap"and"sub_kind"("circle"or a square with"side"/"width"/"height")"angle": rotation in radians, or"angle_deg"["rot"] in degrees"tag": material tagn >= 2(domain"inc<n>", default 2)"lc": refinement factor,maxh = lc / lc_n(finer when > 1), or"maxh"directly;"nseg": arcs per curved boundary
dx (float, default 1.0) – Unit-cell width and height (
dy = period_y / period).dy (float, default 1.0) – Unit-cell width and height (
dy = period_y / period).lc (float, default 0.1) – Background mesh size (domain
"bg").curve_order (int, default 2) – Netgen geometric curvature order (>= 2).
nseg (int, default 24) – Default number of arcs per curved boundary (at least 12).
**lc_kwargs (float) –
lc2, lc3, ..., lc<n>: refinement factor of inclusions withtag = nthat do not set their own"lc".