Source code for openairbearing.core.meshes

"""Meshes for film domains, with quadratic elements and curved edges.

Each builder returns ``(basis, edges)`` where ``edges`` maps an edge name to
the degrees of freedom on it. Lengths are in m and angles in rad. Flat faces
use their own (x, y). A cylinder is unrolled to (s, z) with s = R·theta,
which is exact because the surface is developable, and is periodic in s. Any
other surface of revolution is meshed in (s, theta), periodic in theta
(``unwrapped``).

Annular meshes are structured in (r, theta) and curved so that circles are
represented to the accuracy of the quadratic elements. The disc is an O-grid.
"""

from __future__ import annotations

from dataclasses import replace

import numpy as np
from skfem import (
    Basis,
    ElementQuad2,
    ElementTriP2,
    MeshQuad,
    MeshQuad1DG,
    MeshQuad2,
    MeshTri,
    MeshTri2,
)

__all__ = [
    "annulus",
    "annular_sectors",
    "cylinder",
    "cylinder_pads",
    "disc",
    "disc_circles",
    "element_edges",
    "graded",
    "marked",
    "rectangle",
    "reference_corners",
    "triangles",
    "unwrapped",
]


def _edge_dofs(coordinate, value, scale) -> np.ndarray:
    """Degrees of freedom whose coordinate equals value, to 1e-9 of scale."""
    return np.where(np.abs(coordinate - value) < 1e-9 * scale)[0]


# Layout of the disc mesh, as shares: the first circle of nodes over the
# radius, the corners of the core over that first circle, and how far the
# sides of the core are bent from straight (0) to that circle (1). On a porous
# pad against the closed form at nrefs = 4, a first circle at 0.5, 0.65, 0.75
# and 0.85 gives flow errors at a 1 µm film of 1.1e-3, 5.5e-4, 2.9e-4 and
# 1.1e-4, and 0.75 the smallest error of the tilt stiffness; the other two
# change nothing beyond the fifth digit between 0.5 and 0.7, and 0.3 and 0.7.
_DISC_FIRST_CIRCLE = 0.75
_DISC_CORNER = 0.6
_DISC_BULGE = 0.5

# Local nodes of a quadratic quadrilateral on a grid of half elements: the
# corners counter-clockwise, the middle of the edge after each, the centre.
_QUAD2_NODES = ((0, 0), (2, 0), (2, 2), (0, 2), (1, 0), (2, 1), (1, 2), (0, 1), (1, 1))


[docs] def disc( radius: float, nrefs: int = 4, grading: float = 2.0, rings=(), radial: int | None = None, ): """Circular face of quadrilaterals, refined toward the rim. An O-grid: a square core with bent sides at the centre, a band that turns it into a circle, and from there rings of elements between circles, out to the rim. Lines of nodes run straight from the core to the rim at equal angles. Stacked through the depth of a restrictor these elements are hexahedra. The edge is "rim". nrefs: the core has 2**(nrefs - 1) elements along a side, so there are four times as many around; half as many layers turn the core into the first circle and, without rings, as many again as the core has along a side lie between that circle and the rim. One more refinement divides the error by about 15 (flow of a porous pad at a 1 µm film: 2.9e-4 at nrefs = 4). grading: the rings get thinner toward the rim, where the pressure falls to ambient: the last one is (1 / their number)**grading of the distance from the first circle to the rim. 1 is uniform. Of 1.5, 2 and 2.5, 2 gives the smallest load error and a flow error within a tenth of the smallest. rings: radii that carry a circle of nodes, such as the edges of a feed groove or hole behind the restrictor, or of an insert. The first circle is at 0.75 of the radius or at the smallest of these radii, whichever is less, so a small one makes a small core. The elements get thinner toward each of these radii from both sides, down to the thickness of the rim ring of the plain mesh, and toward the rim: at the edge of a feed the pressure in the restrictor is singular. That takes more rings, about twice the elements for two radii. For a pad of 18.5 mm fed between 8 and 12 mm the load at nrefs = 4 is 0.02 % high, against 2.3 % low without the circles. radial: the refinement along the radius, when it should differ from nrefs: the layers to the first circle and the rings are those of nrefs = radial, while nrefs still sets the core and the number of elements around. For a pad whose solution does not change around (axial motion, feeds in circles about the centre) a low nrefs with a higher radial costs a fraction of the same refinement everywhere: a ring-fed pad at nrefs = 2, radial = 3 has stiffness and flow within 0.3 % of nrefs = 4. The rim is a parabola through three points of the circle on each element, which leaves the area short by a fraction pi**4 / (30 N**4) for N elements around (3e-6 at nrefs = 4). nrefs and radial below 2, and rings outside the pad, are a ValueError. """ if nrefs < 2 or (radial is not None and radial < 2): raise ValueError("nrefs and radial must be at least 2.") marks = sorted({float(r) for r in rings}) if marks and not 0.0 < marks[0] <= marks[-1] < radius: raise ValueError("rings must lie between the centre and the rim.") n = 2 ** (nrefs - 1) # elements along a side of the core half = 2 * n # half elements along a side around = 4 * half # half elements around first = min([_DISC_FIRST_CIRCLE * radius, *marks]) corner = _DISC_CORNER * first def side(angle): """Radius of the core's side at an angle from the middle of that side.""" straight = corner / np.sqrt(2.0) / np.cos(angle) return (1.0 - _DISC_BULGE) * straight + _DISC_BULGE * corner # The core, between its four sides (a Coons patch), with the nodes of a # side at equal angles as seen from the centre. angle = np.pi / 4.0 * (2.0 * np.arange(half + 1) / half - 1.0) along, across = side(angle) * np.sin(angle), side(angle) * np.cos(angle) bottom, top = np.array([along, -across]), np.array([along, across]) left, right = np.array([-across, along]), np.array([across, along]) u, v = np.meshgrid( np.arange(half + 1) / half, np.arange(half + 1) / half, indexing="ij" ) b, t = bottom[:, :, None], top[:, :, None] core = ( (1.0 - v) * b + v * t + (1.0 - u) * left[:, None, :] + u * right[:, None, :] - (1.0 - u) * (1.0 - v) * b[:, :1] - u * (1.0 - v) * b[:, -1:] - (1.0 - u) * v * t[:, :1] - u * v * t[:, -1:] ) # fmt: skip # Outside the core: level 0 is the edge of the core, the levels up to # 2·n_turn go from there to the first circle in equal steps along each # line of nodes, and the rest are circles. n_radial = n if radial is None else 2 ** (radial - 1) n_turn = max(1, n_radial // 2) circles = _ring_radii(first, radius, n_radial, grading, marks) n_rings = circles.size - 1 levels = 2 * (n_turn + n_rings) theta = 2.0 * np.pi * np.arange(around) / around edge = side(np.mod(theta + np.pi / 4.0, np.pi / 2.0) - np.pi / 4.0) share = np.arange(n_turn + 1) / n_turn if first in marks: # the edge of a feed: thinner layers toward it share = 1.0 - (1.0 - share) ** grading # The middle nodes of a layer sit in its middle: graded themselves they # would be off it, and the element would fold at the first circle. share = np.interp(np.arange(2 * n_turn + 1) / 2.0, np.arange(n_turn + 1), share) share = share[:, None] turn = (1.0 - share) * edge + share * first circles = np.interp( np.arange(2 * n_rings + 1) / 2.0, np.arange(n_rings + 1), circles ) rho = np.vstack([turn, np.tile(circles[1:, None], around)]) outside = np.array([rho * np.cos(theta), rho * np.sin(theta)]) points = np.hstack([core.reshape(2, -1), outside[:, 1:].reshape(2, -1)]) def in_core(i, j): return i * (half + 1) + j def outside_core(level, j): level, j = np.broadcast_arrays(level, np.mod(j, around)) # level 0 is the edge of the core, counter-clockwise from the middle # of its right side which, k = np.divmod(j + n, half) which = which % 4 i_edge = np.choose(which, [half, half - k, 0, k]) j_edge = np.choose(which, [k, half, half - k, 0]) return np.where( level == 0, in_core(i_edge, j_edge), (half + 1) ** 2 + (level - 1) * around + j, ) def elements(index, n_first, n_second): first_, second = np.meshgrid( 2 * np.arange(n_first), 2 * np.arange(n_second), indexing="ij" ) return np.array( [index(first_.ravel() + a, second.ravel() + b) for a, b in _QUAD2_NODES] ) nodes = np.hstack( [elements(in_core, n, n), elements(outside_core, levels // 2, around // 2)] ) vertices, corners = np.unique(nodes[:4], return_inverse=True) mesh = MeshQuad2.from_mesh(MeshQuad(points[:, vertices], corners.reshape(4, -1))) # from_mesh puts the other nodes on straight edges: move every node to # its place on the curved grid x = mesh.doflocs.copy() x[:, Basis(mesh, ElementQuad2()).element_dofs] = points[:, nodes] basis = Basis(replace(mesh, doflocs=x), ElementQuad2()) return basis, {"rim": _edge_dofs(np.hypot(*basis.doflocs), radius, radius)}
def _ring_radii(first, radius, n, grading, marks) -> np.ndarray: """Radii of the circles from first to radius, packed toward marks and rim. Without marks: n rings, thinner toward the rim. With marks, each part between two of them (and the rim) gets thinner toward both of its ends, and as many rings as it takes for the ones at its ends to be as thin as the rim ring of the mesh without marks: the pressure in a restrictor is singular at the edge of a feed, and falls steeply at the rim. Rings twice as thick at the ends save a fifth of the elements and triple the flow error of a thin film. first counts as a mark when it is in marks; otherwise the part from first to the smallest mark gets thinner toward the mark only. """ inside = [m for m in marks if m > first * (1.0 + 1e-12)] if not marks: t = np.linspace(0.0, 1.0, n + 1) return first + (radius - first) * (1.0 - (1.0 - t) ** grading) # thickness of the rim ring of the mesh without marks thin = (1.0 - _DISC_FIRST_CIRCLE) * radius / n**grading knots = [first, *inside, radius] radii = [np.array([first])] for k, (a, b) in enumerate(zip(knots[:-1], knots[1:], strict=True)): if k == 0 and len(inside) == len(marks): # first is not a mark count = int(np.ceil(((b - a) / thin) ** (1.0 / grading))) packed = 1.0 - (1.0 - np.linspace(0.0, 1.0, count + 1)) ** grading else: # graded() has end elements of (2 / count)**grading of half count = int(np.ceil(2.0 * ((b - a) / (2.0 * thin)) ** (1.0 / grading))) packed = graded(0.0, 1.0, max(count, 2) + 1, grading) radii.append((a + (b - a) * packed)[1:]) radii[-1][-1] = b return np.concatenate(radii) # Layout of the disc with element edges on circles (disc_circles), as # lengths of the element edges at nrefs = 0 (each refinement halves them): # - away from the circles and the rim: this share of the radius; # - on the rim and on the circles: this share of that, but at least this # many edges around a circle (a share of 2**nrefs); # - where two of them come close: this share of the gap, halved with each # refinement from nrefs = 3 on, and at most half of it; # - growing with the distance from them at this rate. # Against nrefs = 5 on the Hosokawa 2015 insert pads (0.25 to 17 µm), the # load at nrefs = 4 is within 5e-4 and the flow within 1.6e-3, both at the # smallest gap (the rim layer of a film that thin) and within 2e-5 from # 3 µm up; at nrefs = 3 within 1.2e-3 and 6.4e-3. A rate of 0.3 (that of the # DistMesh examples) left the middle of the 12 mm inserts with a few large # elements; 0.2 grades them in. _CIRCLES_FAR = np.pi _CIRCLES_EDGE = 0.25 _CIRCLES_AROUND = 3.0 _CIRCLES_GAP = 2.0 _CIRCLES_GROWTH = 0.2 # A free node keeps this share of the local length from every circle and # the rim. Then each edge along a circle is an edge of the Delaunay # triangulation: no node is inside the circle that has the edge as its # diameter (at the length's growth rate, 0.7 keeps a node at least 0.61 of # a length away, against half a length plus the sag of the arc). _CIRCLES_BAND = 0.7 # DistMesh: at most this many steps of the spring model, then this many of # Laplace smoothing. More steps do not raise the smallest angle of the # triangles; the smoothing does, from 8 to 23 degrees on the four-insert # pad at nrefs = 2 (at least 22 on every mesh of the tests). _CIRCLES_STEPS = 100 _CIRCLES_SMOOTHING = 3 # The samples of the curves, 512 and 4096 around, are made finer where a # step along a curve is longer than this share of what is sampled: the # length a narrow place asks for (between two of them the length grows at # most by the growth rate times half a step), and the length along the # curve, summed to place its nodes. Neither is made finer on the meshes of # the tests at nrefs = 2 and 3, nor on the Hosokawa 2015 pads at nrefs 4. _CIRCLES_SPOTS = 1.5 _CIRCLES_FINE = 0.5 # The free nodes start from triangular lattices, each over the boxes of a # quadtree whose size is at most the local length there, at half that box # size; the boxes and the nodes then follow the length (their number that of # the elements), not the smallest length over the whole disc.
[docs] def disc_circles(radius: float, circles, nrefs: int = 3): """Circular face of quadratic triangles whose edges follow given circles. circles are (x, y, r) each: the centre and the radius of a circle, such as the edge of a feed insert or of a hole set off the centre of the pad. They may lie side by side or one inside another, but neither cut nor touch each other or the rim. A feed whose edges are these circles is then exact up to the curved elements, where on ``disc`` an off-centre one would be a staircase of elements. The edge is "rim". The face is triangulated with nodes along every circle and the rim; the other nodes are spread by the spring model of DistMesh (P.-O. Persson, G. Strang, SIAM Review 46 (2004) 329-345) to a length that is smallest on the circles and the rim, and where they come close to each other, and grows away from them. The elements are quadratic triangles (six nodes); an edge on a circle is a parabola through three points of it, as the rim of ``disc``: the area inside a circle of N elements is short by about pi**4 / (30 N**4) of it. Triangles, not quadrilaterals: these nodes have no structure to give quadrilaterals a grading or square corners. nrefs: one more halves every element. A circle has at least 3·2**nrefs elements around. The mesh has no symmetry; it is the same on every call (the random thinning of the starting nodes has a fixed seed). Its size, and the memory and time it takes, follow the elements it makes: a gap g between circles of radius r adds about (r / g)**0.5 elements along it, a small circle about 3·2**nrefs around it. nrefs below 2, a circle that is not (x, y, r) with r > 0, and a circle that cuts, touches or coincides with another or the rim (to 1e-12 of the radius) are a ValueError. """ from scipy.spatial import Delaunay, cKDTree if nrefs < 2: raise ValueError("nrefs must be at least 2.") circles = [list(np.ravel(c)) for c in circles] if any(len(c) != 3 for c in circles): raise ValueError("each circle is (x, y, r).") curves = np.array([[0.0, 0.0, radius], *circles], float) centre, a = curves[:, :2], curves[:, 2] if np.any(a <= 0.0): raise ValueError("each circle needs a radius above zero.") # the gap between two curves along the line of their centres; the rim # is a curve around the others apart = np.hypot(*(centre[:, None, :] - centre[None, :, :]).transpose(2, 0, 1)) beside = apart >= a[:, None] + a[None, :] gap = np.where( beside, apart - a[:, None] - a[None, :], np.abs(a[:, None] - a[None, :]) - apart, ) np.fill_diagonal(gap, np.inf) # 1e-12 of the radius: the rounding of distances of the order of the # radius, so that circles given as touching are taken as touching touch = np.any(gap <= 1e-12 * radius) if touch or np.any(beside[0, 1:]) or np.any(a[1:] >= radius): raise ValueError( "the circles must lie inside the rim, and neither cut nor touch " "each other or the rim." ) scale = 2.0**-nrefs far = _CIRCLES_FAR * radius * scale edge = np.minimum(_CIRCLES_EDGE * far, 2.0 * np.pi * a / _CIRCLES_AROUND * scale) narrow = min(0.5, _CIRCLES_GAP * scale) def distance(x): """Signed distance of points (2, n) from each curve: (curves, n).""" return np.hypot(x[0] - centre[:, :1], x[1] - centre[:, 1:]) - a[:, None] # Narrow places: points of a curve where another is nearer than its own # length allows, with the length they need. The length anywhere is the # least of what each curve and each of these points asks for there. def on_curve(k, angle): return centre[k][:, None] + a[k] * np.array([np.cos(angle), np.sin(angle)]) spots, spot_length = [], [] for k in range(a.size): def need(angle, k=k): others = np.abs(np.delete(distance(on_curve(k, angle)), k, axis=0)) return narrow * (others.min(axis=0) if others.size else np.inf + angle) around, want = _resolved(512, a[k], need, edge[k], _CIRCLES_SPOTS) around, want = around[:-1], want[:-1] # 2 pi is 0 spots.append(on_curve(k, around[want < edge[k]])) spot_length.append(want[want < edge[k]]) spots, spot_length = np.hstack(spots), np.concatenate(spot_length) tree = cKDTree(spots.T) if spot_length.size else None def length(x): out = np.minimum( far, np.min(edge[:, None] + _CIRCLES_GROWTH * np.abs(distance(x)), axis=0) ) if tree is not None: # the eight nearest narrow points are enough d, i = tree.query(x.T, k=min(8, spot_length.size)) d, i = d.reshape(x.shape[1], -1), i.reshape(x.shape[1], -1) out = np.minimum(out, np.min(spot_length[i] + _CIRCLES_GROWTH * d, axis=1)) return out # Fixed nodes along each curve, spaced at the length there, and the # pairs of neighbours along it, which must become element edges. fixed, chords, owner = [], [], [] for k in range(a.size): fine, along = _resolved( 4096, a[k], lambda t, k=k: length(on_curve(k, t)), np.inf, _CIRCLES_FINE, ) # fmt: skip steps = np.concatenate([[0.0], np.cumsum(np.diff(fine) * a[k] / along[1:])]) count = max(int(np.ceil(steps[-1])), 6) angle = np.interp(np.arange(count) * steps[-1] / count, steps, fine) first = sum(f.shape[1] for f in fixed) fixed.append( centre[k][:, None] + a[k] * np.array([np.cos(angle), np.sin(angle)]) ) chords.append( first + np.array([np.arange(count), np.roll(np.arange(count), -1)]) ) owner.append(np.full(count, k)) fixed, chords, owner = np.hstack(fixed), np.hstack(chords), np.concatenate(owner) n_fixed = fixed.shape[1] # Free nodes: a triangular lattice at half the local length or finer, # thinned at random to the local one, and the centre of every circle; # none nearer a curve than the band. lattice = _graded_lattice(radius, length) thin = np.random.default_rng(0).random(lattice.shape[1]) kept = thin < (lattice[2] / length(lattice[:2])) ** 2 free = np.hstack([lattice[:2, kept], centre[1:].T]) side = np.sign(distance(free)) side[0] = -1.0 # inside the rim keep = np.all(side * distance(free) >= _CIRCLES_BAND * length(free), axis=0) free, side = free[:, keep], side[:, keep] def off_curves(x): """Free nodes moved back out of the band of any curve, on their side.""" band = _CIRCLES_BAND * length(x) for k in range(a.size): v = x - centre[k][:, None] r = np.hypot(*v) near = side[k] * (r - a[k]) < band x[:, near] = centre[k][:, None] + v[:, near] * ( (a[k] + side[k, near] * band[near]) / r[near] ) return x def bars_of(points): triangles = Delaunay(points.T).simplices return np.unique( np.sort(triangles[:, [0, 1, 1, 2, 2, 0]].reshape(-1, 2), axis=1), axis=0 ) # DistMesh: the edges are springs that push only, a fifth longer than # the local length so that the nodes fill the face; triangulate again # when a node has moved a tenth of its length. points, last = np.hstack([fixed, free]), None for _ in range(_CIRCLES_STEPS): if last is None or np.max(np.hypot(*(points - last)) / length(points)) > 0.1: last, bars = points.copy(), bars_of(points) vec = points[:, bars[:, 0]] - points[:, bars[:, 1]] long = np.hypot(*vec) want = length(0.5 * (points[:, bars[:, 0]] + points[:, bars[:, 1]])) want *= 1.2 * np.sqrt(np.sum(long**2) / np.sum(want**2)) push = np.maximum(want - long, 0.0) / long * vec force = np.zeros_like(points) for c in range(2): np.add.at(force[c], bars[:, 0], push[c]) np.add.at(force[c], bars[:, 1], -push[c]) move = 0.2 * force[:, n_fixed:] points[:, n_fixed:] = off_curves(points[:, n_fixed:] + move) if np.max(np.hypot(*move) / length(points[:, n_fixed:])) < 1e-3: break for _ in range(_CIRCLES_SMOOTHING): # each free node to its neighbours' mean bars = bars_of(points) total, count = np.zeros_like(points), np.zeros(points.shape[1]) for c in range(2): np.add.at(total[c], bars[:, 0], points[c, bars[:, 1]]) np.add.at(total[c], bars[:, 1], points[c, bars[:, 0]]) np.add.at(count, bars.ravel(), 1.0) points[:, n_fixed:] = off_curves(total[:, n_fixed:] / count[n_fixed:]) tri = Delaunay(points.T).simplices.T # every edge of the triangles, and which of them lie along a curve ends = np.sort(np.stack([tri, np.roll(tri, -1, axis=0)]), axis=0).reshape(2, -1) bars = np.unique(ends, axis=1) on_curve = np.full(bars.shape[1], -1) known = { (int(i), int(j)): k for (i, j), k in zip(np.sort(chords, axis=0).T, owner[chords[0]], strict=True) } for b, (i, j) in enumerate(bars.T): on_curve[b] = known.pop((int(i), int(j)), -1) if known: # not met so far; the band is there to prevent it raise RuntimeError("the triangulation left out an edge along a circle.") # Quadratic triangles: the middle node of an edge along a curve is moved # onto it, along the radius of that curve, which puts it in the middle # of the arc between the two ends. mesh = MeshTri2.from_mesh(MeshTri(points, np.ascontiguousarray(tri))) x = mesh.doflocs.copy() curved = on_curve >= 0 straight = 0.5 * (points[:, bars[0, curved]] + points[:, bars[1, curved]]) gap_, nearest = cKDTree(straight.T).query(x.T) # 1e-12 of the radius: the middle nodes of MeshTri2 are the same means # of the two ends, to rounding; the next node is half an element away match = gap_ < 1e-12 * radius for k in np.unique(on_curve[curved]): moved = match & (on_curve[curved][nearest] == k) v = x[:, moved] - centre[k][:, None] x[:, moved] = centre[k][:, None] + v * (a[k] / np.hypot(*v)) basis = Basis(replace(mesh, doflocs=x), ElementTriP2()) return basis, {"rim": _edge_dofs(np.hypot(*basis.doflocs), radius, radius)}
def _resolved(n, a, f, cap, share): """Angles 0 to 2 pi around a circle of radius a, n apart or closer, so that each step along it is at most share of min(f, cap) at its ends; and min(f, cap) there. Steps are halved where they are too long.""" angle = 2.0 * np.pi * np.arange(n + 1) / n while True: value = np.minimum(f(angle), cap) long = a * np.diff(angle) > share * np.minimum(value[:-1], value[1:]) if not long.any(): return angle, value middle = 0.5 * (angle[:-1] + angle[1:]) angle = np.sort(np.concatenate([angle, middle[long]])) def _graded_lattice(radius, length): """Nodes of triangular lattices over the disc, finer where length is. A quadtree over the square around the disc: a box is split while it is larger than the least length in it, bounded below by the length at its middle less the growth rate times its half-diagonal (``length`` grows no faster than _CIRCLES_GROWTH). Each box that is not split holds the nodes, in it, of the triangular lattice of spacing half its size that starts at (-radius, -radius) (in integer counts, so that boxes of one size share their lattice and no node is in two boxes). Returns (3, n): the nodes, and the spacing of the lattice of each. """ rows = np.sqrt(3.0) / 4.0 # lattice rows per box of the same level nodes, size, boxes = [], 2.0 * radius, np.zeros((2, 1), dtype=np.int64) # the candidate lattice nodes of a box: columns 2i + j % 2 / 2 and rows j di, dj = np.meshgrid(np.arange(-1, 3), np.arange(0, 5)) while boxes.size: middle = -radius + (boxes + 0.5) * size reach = size / np.sqrt(2.0) boxes = boxes[:, np.hypot(*middle) < radius + reach] middle = -radius + (boxes + 0.5) * size split = size > length(middle) - _CIRCLES_GROWTH * reach bx, by = boxes[:, ~split] j = np.ceil(by / rows).astype(np.int64)[:, None] + dj.ravel() i = 2 * bx[:, None] + di.ravel() column = i + 0.5 * (j % 2) inside = (column >= 2 * bx[:, None]) & (column < 2 * bx[:, None] + 2) inside &= (j * rows >= by[:, None]) & (j * rows < by[:, None] + 1) h = 0.5 * size x = -radius + h * np.vstack([column[inside], 2.0 * rows * j[inside]]) nodes.append(np.vstack([x, np.full(x.shape[1], h)])) kids = boxes[:, split] * 2 boxes = np.hstack([kids + [[a], [b]] for a in (0, 1) for b in (0, 1)]) size *= 0.5 return np.hstack(nodes) def _polar_quads(r, th, closed: bool): """Structured quad mesh on a polar grid, with mid nodes moved onto the circles.""" nt = len(th) R, TH = np.meshgrid(r, th, indexing="ij") p = np.vstack([(R * np.cos(TH)).ravel(), (R * np.sin(TH)).ravel()]) t = [] for i in range(len(r) - 1): for j in range(nt if closed else nt - 1): a, b = i * nt + j, i * nt + (j + 1) % nt t.append([a, a + nt, b + nt, b]) mesh = MeshQuad2.from_mesh(MeshQuad(p, np.array(t, dtype=np.int64).T)) # Mid-edge and centre nodes between two grid angles sit on the chord; # move them out to the arc. dth = th[1] - th[0] x = mesh.doflocs.copy() angle = np.mod(np.arctan2(x[1], x[0]) - th[0], 2.0 * np.pi) frac = np.mod(angle / dth, 1.0) between = np.abs(frac - 0.5) < 0.25 x[:, between] /= np.cos(dth / 2.0) return replace(mesh, doflocs=x)
[docs] def annulus( r_in: float, r_out: float, n_circ: int = 96, n_radial: int = 16, grading=2.0 ): """Closed annular face, refined toward both circles. Edges: "inner", "outer". n_circ and n_radial are the numbers of elements around and across; grading = 1 is uniform across. """ r = graded(r_in, r_out, n_radial + 1, grading) th = np.linspace(0.0, 2.0 * np.pi, n_circ, endpoint=False) basis = Basis(_polar_quads(r, th, closed=True), ElementQuad2()) rd = np.hypot(*basis.doflocs) return basis, { "inner": _edge_dofs(rd, r_in, r_out), "outer": _edge_dofs(rd, r_out, r_out), }
def _pads(a_nodes, b_nodes_per_pad): """Disjoint tensor patches in a parameter plane (a, b), as one quadratic mesh. a_nodes are shared by every pad; each entry of b_nodes_per_pad gives one pad's nodes in the other direction. The pads do not touch, so each keeps its own edges. """ mesh = None for b_nodes in b_nodes_per_pad: patch = MeshQuad.init_tensor(a_nodes, b_nodes) mesh = patch if mesh is None else mesh + patch return MeshQuad2.from_mesh(mesh) def _pad_angles(n_pads, pad_angle, offset, n_circ, grading): """Node angles along the arc of each pad, after checking that the pads fit.""" if not 0.0 < pad_angle * n_pads < 2.0 * np.pi * (1.0 + 1e-12): raise ValueError("The pads must fit in one turn without overlapping.") if np.isclose(pad_angle * n_pads, 2.0 * np.pi): raise ValueError("Pads that fill the whole turn are a closed surface.") centres = offset + 2.0 * np.pi * np.arange(n_pads) / n_pads return [ graded(c - pad_angle / 2.0, c + pad_angle / 2.0, n_circ + 1, grading) for c in centres ]
[docs] def annular_sectors( r_in: float, r_out: float, n_pads: int = 3, pad_angle: float = np.deg2rad(100.0), offset: float = 0.0, n_circ: int = 20, n_radial: int = 12, grading: float = 2.0, ): """Sector pads of an annulus, equally spaced, as one mesh. Pad k is centred at angle offset + 2 pi k / n_pads and spans pad_angle, with n_circ elements along its arc and n_radial across. Every pad is refined toward its four edges, and its curved edges follow the circles to the accuracy of the quadratic elements. The edge "edge" is every edge of every pad. """ r = graded(r_in, r_out, n_radial + 1, grading) polar = _pads(r, _pad_angles(n_pads, pad_angle, offset, n_circ, grading)) radius, angle = polar.doflocs mesh = replace( polar, doflocs=np.vstack([radius * np.cos(angle), radius * np.sin(angle)]) ) basis = Basis(mesh, ElementQuad2()) return basis, {"edge": basis.get_dofs().all()}
[docs] def cylinder_pads( radius: float, length: float, n_pads: int = 3, pad_angle: float = np.deg2rad(100.0), offset: float = 0.0, n_circ: int = 20, n_axial: int = 12, z_centre: float = 0.0, grading: float = 2.0, ): """Partial-arc pads of a cylinder, unrolled to (s, z), as one mesh. Pad k is centred at angle offset + 2 pi k / n_pads and spans pad_angle, with n_circ elements along its arc and n_axial along the axis; s = radius·theta and z runs length / 2 to either side of z_centre. Every pad is refined toward its four edges. The edge "edge" is every edge of every pad. """ z = graded(z_centre - length / 2.0, z_centre + length / 2.0, n_axial + 1, grading) angles = _pad_angles(n_pads, pad_angle, offset, n_circ, grading) # the patches are laid out with z first so the shared nodes are the axial ones flipped = _pads(z, [radius * th for th in angles]) mesh = replace(flipped, doflocs=flipped.doflocs[::-1].copy()) basis = Basis(mesh, ElementQuad2()) return basis, {"edge": basis.get_dofs().all()}
[docs] def rectangle(lx: float, ly: float, nx: int = 32, ny: int = 32, grading: float = 2.0): """Rectangle of lx by ly centred at the origin, refined toward its edges. Edges: "left", "right" (x = -lx/2, lx/2), "bottom", "top" (y = -ly/2, ly/2). nx and ny are the numbers of elements; grading = 1 is uniform. """ x = graded(-lx / 2.0, lx / 2.0, nx + 1, grading) y = graded(-ly / 2.0, ly / 2.0, ny + 1, grading) basis = Basis(MeshQuad.init_tensor(x, y), ElementQuad2()) xd, yd = basis.doflocs scale = max(lx, ly) return basis, { "left": _edge_dofs(xd, x[0], scale), "right": _edge_dofs(xd, x[-1], scale), "bottom": _edge_dofs(yd, y[0], scale), "top": _edge_dofs(yd, y[-1], scale), }
[docs] def cylinder( radius: float, length: float, n_circ: int = 96, n_axial: int = 16, z_centre: float = 0.0, grading: float = 2.0, axial_marks=(), ): """Full cylinder unrolled to (s, z), periodic in s, refined toward both ends. Edges: "end_low", "end_high", at z = z_centre - length / 2 and z_centre + length / 2. n_circ and n_axial are the numbers of elements around and along the axis; grading = 1 is uniform along the axis. axial_marks are axial positions that must carry a line of nodes, such as the edges of a feed groove behind the restrictor; the nearest line of the graded mesh is moved onto each (``marked``). """ s = radius * np.linspace(0.0, 2.0 * np.pi, n_circ + 1) z = graded(z_centre - length / 2.0, z_centre + length / 2.0, n_axial + 1, grading) z = marked(z, axial_marks) basis = Basis(MeshQuad1DG.init_tensor(s, z, periodic=[0]), ElementQuad2()) zd = basis.doflocs[1] return basis, { "end_low": _edge_dofs(zd, z[0], length), "end_high": _edge_dofs(zd, z[-1], length), }
[docs] def marked(nodes: np.ndarray, marks) -> np.ndarray: """The nodes with the nearest interior one moved onto each mark. Every mark needs a node of its own, so there must be enough of them between the ends: a mark outside the ends, more marks than interior nodes, or nodes left out of order are a ValueError. """ nodes = np.array(nodes, dtype=float) taken = set() for mark in sorted(marks): if not nodes[0] < mark < nodes[-1]: raise ValueError(f"mark {mark} is not inside the mesh") order = np.argsort(np.abs(nodes[1:-1] - mark)) + 1 k = next((int(i) for i in order if int(i) not in taken), None) if k is None: raise ValueError("more marks than interior node lines") taken.add(k) nodes[k] = mark if np.any(np.diff(nodes) <= 0.0): raise ValueError("too few node lines for these marks: use a finer mesh") return nodes
[docs] def graded(start: float, stop: float, n: int, ratio: float = 2.0) -> np.ndarray: """n nodes from start to stop, refined toward both ends for ratio > 1. The end elements are (2 / (n - 1)) ** ratio of half the length; ratio = 1 is uniform. """ t = np.linspace(-1.0, 1.0, n) t = np.sign(t) * (1.0 - (1.0 - np.abs(t)) ** ratio) return start + (stop - start) * 0.5 * (t + 1.0)
[docs] def unwrapped(s_nodes, n_theta: int = 48): """Surface of revolution in (s, theta), periodic in theta. s_nodes are the node positions along the meridian in m and n_theta the number of elements around; theta is in rad. The mesh does not know the radius at each s: give it to the film as its metric. Edges: "s_min", "s_max". """ s_nodes = np.asarray(s_nodes, dtype=float) theta = np.linspace(0.0, 2.0 * np.pi, n_theta + 1) mesh = MeshQuad1DG.init_tensor(s_nodes, theta, periodic=[1]) basis = Basis(mesh, ElementQuad2()) sd = basis.doflocs[0] scale = s_nodes[-1] - s_nodes[0] return basis, { "s_min": _edge_dofs(sd, s_nodes[0], scale), "s_max": _edge_dofs(sd, s_nodes[-1], scale), }
[docs] def reference_corners(basis) -> np.ndarray: """Corners of the reference element of a basis, in order around it: (2, corners).""" if basis.mesh.t.shape[0] == 3: return np.array([[0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) return np.array([[0.0, 1.0, 1.0, 0.0], [0.0, 0.0, 1.0, 1.0]])
[docs] def element_edges(basis, steps: int = 4) -> np.ndarray: """Points along every edge of every element, for drawing the mesh. Returns an array of shape (2, elements, edges, steps + 1): each edge of each element at steps + 1 equally spaced points of the reference element, from one corner to the next, through the element's own geometry. That is the geometry the solver integrates over, so a curved edge comes out curved and a surface that closes on itself is unrolled with its seam at both ends. An edge shared by two elements appears in both. """ corners = reference_corners(basis) n_edges, t = corners.shape[1], np.linspace(0.0, 1.0, steps + 1) local = np.concatenate( [ corners[:, [k]] * (1.0 - t) + corners[:, [(k + 1) % n_edges]] * t for k in range(n_edges) ], axis=1, ) return basis.mapping.F(local).reshape(2, -1, n_edges, steps + 1)
[docs] def triangles(basis, nodal, max_elements: int = 4000) -> tuple: """A nodal field as flat triangles, for drawing. Returns (x, t, values): points of shape (2, n), triangles of shape (3, m) and the field at the points. Each quadratic element is cut into four flat pieces, unless the mesh has more than max_elements elements, and each quadrilateral into two triangles. """ nrefs = 1 if basis.mesh.nelements <= max_elements else 0 mesh, values = basis.refinterp(nodal, nrefs=nrefs) t = mesh.t[:4] if "Quad" in type(mesh).__name__ else mesh.t[:3] if t.shape[0] == 4: t = np.hstack([t[[0, 1, 2]], t[[0, 2, 3]]]) return mesh.p, t, values