Source code for openairbearing.study

"""Studies: one request in, one result document out.

A study evaluates one or more bearing cases over zero, one or two swept
quantities. Request and result are plain JSON-ready dicts in SI units, so
the same call serves a script, a notebook and a web front end:

    result = run({
        "cases": [
            {"name": "A", "case": {"kind": "circular_pad"}},
            {"name": "B", "case": {"kind": "circular_pad", "radius": 25e-3}},
        ],
        "sweep": [{"path": "position.h", "values": [3e-6, 5e-6, 8e-6]}],
    })
    result["cases"][0]["outputs"]["force.h"]["values"]   # N, one per gap

A case entry may also hold "position", the coordinates that differ from the
default position of its kind. A swept path is either "position.<name>" (h,
rx, x, ... of the position) or a case field by dotted path ("ps",
"porous.kappa", "radius"). Every case in the request is swept over the same
axes, which is what makes them comparable; a path a case does not have is
an error. "stiffness": True in the request adds the static stiffness matrix
to the outputs of every point ("stiffness.h.h", ...).

Each output holds its SI unit, its display unit and an array shaped like the
sweep axes. A point that cannot be evaluated (contact, no convergence) is
None in every output and listed under "errors" with its index and the
reason.

Besides ``run`` there are computations on one case at one position, for a
form to show beside the study: ``field`` (pressure and gap over the film),
``mesh``, ``free_flow`` and ``permeability``.
"""

from __future__ import annotations

import concurrent.futures
import dataclasses
import hashlib
import itertools
import json
import math
import subprocess
import time
from datetime import UTC, datetime
from pathlib import Path

import numpy as np
from scipy.optimize import brentq

from . import __version__
from . import display as _display
from .core import cases as _cases
from .core.film import FilmSolveError, solve_static, stiffness
from .core.film import free_flow as _film_free_flow
from .core.meshes import element_edges as _element_edges
from .core.meshes import triangles as _triangles
from .core.restrictor import Porous as _Porous
from .display import dof_units as _dof_units

__all__ = [
    "MODEL_VERSION",
    "SCHEMA_VERSION",
    "BODY_WEIGHT",
    "VOLUME_WEIGHT",
    "cache_key",
    "field",
    "free_flow",
    "free_flow_offered",
    "idle_rules",
    "mesh",
    "permeability",
    "position_display",
    "run",
    "solve_count",
    "validate",
    "work",
]

SCHEMA_VERSION = "0.1"


def _model_version() -> str:
    """The package version, with the commit when run from a source checkout.

    A released package is identified by its version. Between releases the
    numbers change from commit to commit under one version, so a checkout
    adds the commit it is at ("1.0.0+g1a2b3c4"); changes not yet
    committed do not show.
    """
    root = Path(__file__).resolve().parent.parent
    if not (root / ".git").exists():  # installed: not this project's checkout
        return __version__
    try:
        commit = subprocess.run(
            ["git", "-C", str(root), "rev-parse", "--short", "HEAD"],
            capture_output=True,
            text=True,
            timeout=5,
            check=True,
        ).stdout.strip()
    except (OSError, subprocess.SubprocessError):
        return __version__
    return f"{__version__}+g{commit}" if commit else __version__


# Identifies the numerics a result was computed with: it is written into
# every result and is part of the key cached results are stored under.
MODEL_VERSION = _model_version()

MAX_AXES = 2
MAX_NAME = 80  # characters of a case name
# What a solve with the volume restrictor model counts for in ``work``, where
# a solve with the column model counts 1 per node. Measured per node of the
# film mesh and solve, in one process:
# - column model: 20 to 47 µs up to 19 000 nodes, 44 to 65 µs at 37 000;
# - volume model, on the depth mesh of ``restrictor.depth_edges``: 590 µs at
#   470 nodes, 1 540 µs at 1 800 (circular pad), 3 190 to 3 370 µs at 4 200
#   (rectangular pad), 1 220 to 1 940 µs at 6 300 (annular pad, journal).
# On one mesh the volume model is thus 17 to 90 times slower than the
# column model, more on a larger mesh; below the 5 000 nodes a public server
# allows it (``ui.server.PUBLIC``) at most about 3 400 µs. The weight is set
# from that worst case, because it is there for a limit on what a stranger
# may ask of a public server: below that cap, work × 35 µs is then an upper
# bound on the processor time of a volume-model study. 3 400 µs over 35 µs
# for the column model is 97; the weight is 120, a fifth above, as a margin
# for the scatter of the measurements. For the column model the count is an
# estimate only (a solve costs up to twice 35 µs per node on the largest
# meshes); what holds whatever the estimate misses is the time limit of a
# study. The usual volume study, a pad of 1 800 nodes, is counted about two
# and a half times what it costs.
VOLUME_WEIGHT = 120.0
# What a node of a porous body (a monolithic thrust bushing) counts for in
# ``work``, in the same units. Measured per body node and solve, in one
# process: 57 µs at 5 500 body nodes, 139 at 14 000, 247 at 26 000, 291 at
# 29 000, 607 at 54 000. The cost per node grows with the body, as a direct
# solve in three dimensions does, so a weight holds only below a cap on the
# body: a public server allows 30 000 body nodes (``ui.server.PUBLIC``),
# where it is about 300 µs. The weight is that over 35 µs, rounded up. Above
# the cap the count is low; a server without the cap relies on the time limit
# of a study, and on its memory.
BODY_WEIGHT = 10.0
_POSITION = "position."  # prefix of a swept position coordinate


def _case(case_doc: dict):
    """The case of a case document, as the workbench solves it.

    A restrictor with its rim closed (rim_open False) and an open depth
    given (rim_open_depth) has the depth left out: the form keeps a depth
    typed while the rim is open, so that ticking the rim again brings it
    back, and marks it as without effect while the rim is closed
    (``idle_rules``). The volume model refuses such a restrictor in a
    direct call from Python, where a depth asked for and not used is an
    error; here the solve goes on as if no depth had been typed. The case
    document itself, which the form saves and shares, keeps the depth, and
    so does the cache key: two requests that differ only in such a depth
    are solved and cached apart, with the same result.
    """
    case = _cases.case_from_dict(case_doc)
    for name in _restrictors(case):
        porous = getattr(case, name)
        if not porous.rim_open and porous.rim_open_depth is not None:
            porous = dataclasses.replace(porous, rim_open_depth=None)
            case = dataclasses.replace(case, **{name: porous})
    return case


[docs] def cache_key(request: dict) -> str: """SHA-256 (hex) of the model version and the request with sorted keys.""" canonical = json.dumps(request, sort_keys=True, separators=(",", ":")) return hashlib.sha256(f"{MODEL_VERSION}\n{canonical}".encode()).hexdigest()
[docs] def position_display(name: str) -> dict: """Label, SI unit, display unit and scale of a position coordinate.""" unit = _dof_units(name)[0] if name == "h": label = "Film thickness" elif unit == "m": label = f"Displacement {name}" else: label = f"Rotation {name}" if name == "rz" else f"Tilt {name}" return {"label": label, "unit": unit, **_display.unit(unit)}
def _axis_info(path: str, case) -> dict: """Label and units of a swept path of a case; ValueError if it has none.""" if path.startswith(_POSITION): name = path.removeprefix(_POSITION) if name not in case.default_position(): raise ValueError(f"{case.kind} has no position coordinate {name!r}") return position_display(name) _cases.get_path(case, path) # raises for an unknown field for row in _cases.describe(case): if row["path"] == path and row["type"] in ("int", "float"): return {key: row[key] for key in ("label", "unit", "display", "scale")} raise ValueError(f"{path!r} is not a number that can be swept") def _point_outputs(state, K) -> dict: """Outputs of one solved point, {key: (value, SI unit)}; K adds stiffness.""" film = state.film out = {} for name, value in zip(film.dof_names, state.wrench, strict=True): out[f"force.{name}"] = (float(value), _dof_units(name)[1]) out["flow_supply"] = (state.flow_supply, "kg/s") out["flow_normal"] = (state.flow_normal, "m³/s") for region, value in state.flow_regions.items(): out[f"flow_supply.{region}"] = (value, "kg/s") for edge, value in state.flow_out.items(): out[f"flow_out.{edge}"] = (value, "kg/s") out["h_min"] = (state.h_min, "m") out["shear.1"] = (float(state.shear[0]), "N") out["shear.2"] = (float(state.shear[1]), "N") if K is not None: for i, a in enumerate(film.dof_names): for j, b in enumerate(film.dof_names): unit = f"{_dof_units(a)[1]}/{_dof_units(b)[0]}" out[f"stiffness.{a}.{b}"] = (float(K[i, j]), unit) return out _LABELS = { "force": "Film force", "stiffness": "Stiffness", "flow_supply": "Supply mass flow", "flow_normal": "Supply flow, free gas", "flow_out": "Outflow", "h_min": "Minimum film thickness", "shear": "Shear force", } def _output_label(key: str) -> str: head, _, rest = key.partition(".") if head == "stiffness": force, _, motion = rest.partition(".") name = "Stiffness" if force == motion else "Coupling stiffness" return f"{name} {force}, {motion}" if head == "force" and _dof_units(rest)[1] == "N·m": return f"Film moment {rest}" label = _LABELS.get(head, head) return f"{label} {rest.replace('.', ', ').replace('_', ' ')}" if rest else label def _clean(value): """Nested lists with NaN and inf as None, ready for JSON.""" if isinstance(value, list): return [_clean(v) for v in value] return None if value is None or not math.isfinite(value) else value def _solve_chunk(case_doc: dict, points: list, with_stiffness: bool) -> list: """Solve some positions of one case, in the caller or in a worker process. points is [(index, position dict)]. Returns [(index, outputs dict or error text)]; a case that cannot be built gives its error at every point. """ try: case = _case(case_doc) film = case.film() except (ValueError, FilmSolveError) as exc: return [(index, str(exc)) for index, _ in points] out = [] for index, position in points: q = [position[name] for name in film.dof_names] try: state = solve_static(film, q) K = stiffness(film, q) if with_stiffness else None except FilmSolveError as exc: out.append((index, str(exc))) continue out.append((index, _point_outputs(state, K))) return out def _chunks(entry: dict, axes: list, chunk_size: int): """Work for one case: (case document, [(index, position)]) per chunk. Changing a case field rebuilds the film and changing the position does not, so every chunk holds positions of one film. """ # a swept open depth is set again on each point; _solve_chunk, which # builds the film, leaves it out there too where the rim is closed base = _case(entry["case"]) shape = tuple(len(a["values"]) for a in axes) position_axes = [i for i, a in enumerate(axes) if a["path"].startswith(_POSITION)] field_axes = [i for i in range(len(axes)) if i not in position_axes] for field_index in itertools.product(*(range(shape[i]) for i in field_axes)): case = base for i, k in zip(field_axes, field_index, strict=True): case = _cases.set_path(case, axes[i]["path"], axes[i]["values"][k]) points = [] for position_index in itertools.product( *(range(shape[i]) for i in position_axes) ): index = [0] * len(axes) position = {**case.default_position(), **entry.get("position", {})} for i, k in zip(field_axes, field_index, strict=True): index[i] = k for i, k in zip(position_axes, position_index, strict=True): index[i] = k position[axes[i]["path"].removeprefix(_POSITION)] = axes[i]["values"][k] points.append((tuple(index), position)) doc = _cases.case_to_dict(case) for start in range(0, len(points), chunk_size): yield doc, points[start : start + chunk_size] def _assemble(entry: dict, axes: list, solved: list) -> dict: """The result entry of one case from its solved points.""" base = _cases.case_from_dict(entry["case"]) # as sent: it is shown back shape = tuple(len(a["values"]) for a in axes) values, units, errors = {}, {}, [] for index, outcome in sorted(solved, key=lambda item: item[0]): if isinstance(outcome, str): errors.append({"index": list(index), "message": outcome}) continue for key, (value, unit) in outcome.items(): if key not in values: values[key] = np.full(shape, np.nan) units[key] = unit values[key][index] = value return { "name": entry.get("name", base.kind), "kind": base.kind, "case": _cases.case_to_dict(base), "position": {**base.default_position(), **entry.get("position", {})}, "outputs": { key: { "label": _output_label(key), "unit": units[key], **_display.unit(units[key]), "values": _clean(values[key].tolist()), } for key in values }, "errors": errors, } # The keys a study request, its case entries and its sweep axes may hold. A key # that is not one of them is refused: a misspelt "sweep" or "position" would # otherwise run something other than what was asked for, without a word. _REQUEST_KEYS = ("cases", "sweep", "stiffness") _ENTRY_KEYS = ("name", "case", "position") _AXIS_KEYS = ("path", "values") # What an axis of a result carries besides (``validate``, ``run``): taken and # ignored, so that an axis copied from a result sweeps the same again. They # only say how the values are shown and change nothing that is computed. _AXIS_SHOWN = ("label", "unit", "display", "scale") def _known_keys(document, known: tuple, what: str) -> None: """Raise ValueError naming the keys of document that are not in known.""" if not isinstance(document, dict): raise ValueError(f"{what} is a JSON object, not {type(document).__name__}.") unknown = sorted(set(document) - set(known)) if unknown: raise ValueError( f"{what} has no {', '.join(repr(k) for k in unknown)}; it takes " f"{', '.join(repr(k) for k in known)}." )
[docs] def validate(request: dict) -> list: """Check a request without solving anything; return its sweep axes. An axis is {"path", "label", "unit", "display", "scale", "values"}, with the values in the SI unit. Raises ValueError with the reason if the request cannot be run, also for a key the request, a case entry or a sweep axis does not take (_REQUEST_KEYS, _ENTRY_KEYS, _AXIS_KEYS). An axis may also hold what an axis of a result carries (label, unit, display, scale: _AXIS_SHOWN), which is ignored, so that an axis of a result can be swept again as it is. A request that is not shaped as the module describes can also raise KeyError, TypeError or AttributeError. """ _known_keys(request, _REQUEST_KEYS, "A study request") entries = request.get("cases") or [] if not entries: raise ValueError("A study needs at least one case.") for entry in entries: _known_keys(entry, _ENTRY_KEYS, "A case entry") sweep = request.get("sweep") or [] for axis in sweep: _known_keys(axis, _AXIS_KEYS + _AXIS_SHOWN, "A sweep axis") if len(sweep) > MAX_AXES: raise ValueError(f"A study sweeps at most {MAX_AXES} quantities.") paths = [axis["path"] for axis in sweep] if len(set(paths)) != len(paths): raise ValueError("The same quantity is swept twice.") first = _case(entries[0]["case"]) axes = [] for axis in sweep: values = [float(v) for v in axis["values"]] if not values: raise ValueError(f"Sweep over {axis['path']!r} has no values.") if not all(math.isfinite(v) for v in values): raise ValueError( f"Sweep over {axis['path']!r} has a value that is not a number." ) for entry in entries[1:]: # every case must understand the path _axis_info(axis["path"], _case(entry["case"])) axes.append( {"path": axis["path"], **_axis_info(axis["path"], first), "values": values} ) names = [] for entry in entries: case = _case(entry["case"]) for axis in axes: # swept values must respect the field limits too if not axis["path"].startswith(_POSITION): for value in axis["values"]: _cases.set_path(case, axis["path"], value) position = entry.get("position", {}) unknown = set(position) - set(case.default_position()) if unknown: raise ValueError( f"{case.kind} has no position coordinate {sorted(unknown)}" ) for name, value in position.items(): if not math.isfinite(float(value)): raise ValueError(f"Position coordinate {name!r} is not a number.") name = entry.get("name", case.kind) if not isinstance(name, str) or len(name) > MAX_NAME: raise ValueError(f"A case name is a text of at most {MAX_NAME} characters.") names.append(name) if len(set(names)) != len(names): raise ValueError("Case names must be unique within a study.") return axes
def _position_of(case, film, position: dict | None) -> list: """The position of a film as a list, from the default one and what differs.""" position = {**case.default_position(), **(position or {})} unknown = set(position) - set(film.dof_names) if unknown: raise ValueError(f"{case.kind} has no position coordinate {sorted(unknown)}") return [float(position[name]) for name in film.dof_names]
[docs] def field(case_doc: dict, position: dict | None = None) -> dict: """Pressure and gap over the film of one case at one position. position holds the coordinates that differ from the default position of the case. Returns a JSON-ready triangle mesh in the film coordinates: "x", "y" (with their names and units), the triangles "i", "j", "k", and nodal "p" (absolute pressure, Pa) and "h" (gap, m), plus the ambient pressure "pa" (Pa) and the integrated "outputs" of that point. Raises ValueError for a bad case or position and FilmSolveError (a RuntimeError) if the point cannot be solved. """ case = _case(case_doc) film = case.film() q = _position_of(case, film, position) state = solve_static(film, q) x, t, p = _triangles(film.basis, state.p) def rounded(values): return [float(f"{v:.6g}") for v in values] axes = [] for (name, unit), values in zip(film.coords, x, strict=True): shown = _display.unit(unit, coordinate=True) axes.append({"name": name, "unit": unit, **shown, "values": rounded(values)}) return { "kind": case.kind, "position": dict(zip(film.dof_names, q, strict=True)), "x": axes[0], "y": axes[1], "i": t[0].tolist(), "j": t[1].tolist(), "k": t[2].tolist(), "p": {"unit": "Pa", **_display.unit("Pa"), "values": rounded(p)}, "h": { "unit": "m", **_display.unit("m"), "values": rounded(film.gap(x, np.asarray(q)) * np.ones(x.shape[1])), }, "pa": film.pa, "outputs": { key: { "label": _output_label(key), "unit": unit, **_display.unit(unit), "values": _clean(value), } for key, (value, unit) in _point_outputs(state, None).items() }, }
[docs] def solve_count(request: dict) -> int: """Film solves a request asks for. One per case and sweep point; stiffness costs two more per position coordinate at every point. ``work`` weighs them by the size of the mesh. """ points = 1 for axis in request.get("sweep") or []: points *= max(len(axis.get("values") or []), 1) total = 0 for entry in request.get("cases") or []: n_q = len(_case(entry["case"]).default_position()) total += points * (1 + 2 * n_q if request.get("stiffness") else 1) return total
[docs] def work(request: dict) -> dict: """What a request will cost, found without solving anything. The number of solves alone does not say how long a study runs: a solve on the largest mesh takes hundreds of times longer than one on the default mesh, and the volume restrictor model 17 to 90 times longer than the column model on the same mesh (counted VOLUME_WEIGHT times, its worst case on a mesh a public server allows). Returns - "solves": film solves, as ``solve_count``; - "nodes": pressure unknowns of the largest film mesh among the cases; - "nodes_volume": the same among the cases that use the volume model or a porous body (0 if none does); - "nodes_body": nodes of the largest porous body among the cases (0 if none has one); - "work": the sum over the cases of solves × nodes, with the solves of the volume model counted VOLUME_WEIGHT times, and those of a case on a porous body as its body nodes counted BODY_WEIGHT times. A swept whole-number field (a mesh size, a number of pads) counts at its largest value. Each case says its size without being solved (``Case.size``): a film takes well under a second to build even for the largest mesh, and a porous body is counted without being built. Raises ValueError for a case that cannot be built. """ sweep = request.get("sweep") or [] points = 1 for axis in sweep: points *= max(len(axis.get("values") or []), 1) out = {"solves": 0, "nodes": 0, "nodes_volume": 0, "nodes_body": 0, "work": 0.0} for entry in request.get("cases") or []: case = _case(entry["case"]) for axis in sweep: if axis["path"].startswith(_POSITION) or not axis.get("values"): continue current = _cases.get_path(case, axis["path"]) if isinstance(current, int) and not isinstance(current, bool): case = _cases.set_path(case, axis["path"], max(axis["values"])) size = case.size() nodes, body = size["film"], size["body"] n_q = len(case.default_position()) solves = points * (1 + 2 * n_q if request.get("stiffness") else 1) out["solves"] += solves out["nodes"] = max(out["nodes"], nodes) if size["model"] in ("volume", "body"): out["nodes_volume"] = max(out["nodes_volume"], nodes) if body: out["nodes_body"] = max(out["nodes_body"], body) out["work"] += _weighted(size, solves) return out
def _weighted(size: dict, solves: int) -> float: """Work of solves on one case of the given ``Case.size``, as ``work`` counts it.""" if size["body"]: return solves * size["body"] * BODY_WEIGHT weight = VOLUME_WEIGHT if size["model"] == "volume" else 1.0 return solves * size["film"] * weight
[docs] def run(request: dict, progress=None, executor=None) -> dict: """Run a study request and return its result document. The result holds "axes" (as ``validate`` returns them), one entry per case under "cases" with its "outputs" and "errors", and "provenance" with the model version, the cache key and the running time in s. Raises as ``validate`` does for a request that cannot be run. progress, if given, is called as progress(done, total) as points finish; raising from it cancels the run. executor, if given, is a concurrent.futures executor (normally a ProcessPoolExecutor) that the points are dealt out to; without one they are solved here, in order. With an executor, progress is also called about twice a second while nothing finishes, so that a run can be stopped during a long solve; a solve that has started is not interrupted by that, only abandoned. """ axes = validate(request) entries = request["cases"] with_stiffness = bool(request.get("stiffness", False)) total = len(entries) * int(np.prod([len(a["values"]) for a in axes] or [1])) done = 0 def advance(count): nonlocal done done += count if progress is not None: progress(done, total) started = time.perf_counter() solved = [[] for _ in entries] if executor is None: for n, entry in enumerate(entries): for doc, points in _chunks(entry, axes, chunk_size=1): solved[n].extend(_solve_chunk(doc, points, with_stiffness)) advance(len(points)) else: # Small chunks keep every worker busy and the progress bar moving. workers = getattr(executor, "_max_workers", 4) chunk_size = max(1, min(8, total // (4 * workers) or 1)) pending = {} for n, entry in enumerate(entries): for doc, points in _chunks(entry, axes, chunk_size): future = executor.submit(_solve_chunk, doc, points, with_stiffness) pending[future] = (n, len(points)) waiting = set(pending) try: while waiting: finished, waiting = concurrent.futures.wait( waiting, timeout=0.5, return_when=concurrent.futures.FIRST_COMPLETED ) for future in finished: n, count = pending[future] solved[n].extend(future.result()) advance(count) if not finished: advance(0) # nothing new: only lets the caller stop the run except BaseException: for future in pending: future.cancel() raise results = [_assemble(entry, axes, solved[n]) for n, entry in enumerate(entries)] return { "schema_version": SCHEMA_VERSION, "axes": axes, "cases": results, "provenance": { "model_version": MODEL_VERSION, "cache_key": cache_key(request), "created": datetime.now(UTC).isoformat(timespec="seconds"), "elapsed_s": round(time.perf_counter() - started, 3), "points": total, }, }
[docs] def mesh(case_doc: dict, max_drawn: int = 20_000) -> dict: """The film mesh of one case, for drawing: where the elements are and how many. Returns the element edges in the film coordinates as one broken line, "lines": {"x": [...], "y": [...]} with None between edges, next to "x" and "y" (name, unit and display unit of each coordinate), the number of "elements" and of "nodes" (the pressure unknowns: the elements are quadratic, so there is a node on every edge too). An edge that is curved in the film coordinates is drawn through five points on it. A surface that closes on itself (a journal) is shown unrolled, with the seam at both ends. "edge" holds the shortest and the longest element edge in m when both coordinates are plain lengths, and is None for a surface with a metric, where the film coordinates are not distances. A mesh of more than max_drawn elements is counted and measured but not drawn: "lines" is then None, because the edges would be tens of megabytes that show as a solid area. Raises ValueError for a bad case. """ case = _case(case_doc) film = case.film() basis = film.basis # every edge of every element, at five points: (2, edges, 5) points = _element_edges(basis, 4).reshape(2, -1, 5) a, mid, b = points[:, :, 0], points[:, :, 2], points[:, :, -1] # an edge shared by two elements is drawn once scale = np.ptp(points, axis=(1, 2)).max() _, first = np.unique(np.round(mid / scale * 1e7), axis=1, return_index=True) points, a, mid, b = points[:, first], a[:, first], mid[:, first], b[:, first] def rounded(values): return [None if v != v else float(f"{v:.5g}") for v in values] lines = None if basis.mesh.nelements <= max_drawn: straight = np.hypot(*(mid - 0.5 * (a + b))) <= 1e-6 * np.hypot(*(b - a)) ends = np.stack([a, b], axis=2)[:, straight] pieces = [] for part in (ends, points[:, ~straight]): # two points, or all five gap = np.full((2, part.shape[1], 1), np.nan) pieces.append(np.concatenate([part, gap], axis=2).reshape(2, -1)) line = np.concatenate(pieces, axis=1) lines = {"x": rounded(line[0]), "y": rounded(line[1])} axes = [] for name, unit in film.coords: shown = _display.unit(unit, coordinate=True) axes.append({"name": name, "unit": unit, **shown}) edge = None if film.metric is None and all(unit == "m" for _, unit in film.coords): length = np.hypot(*np.diff(points, axis=2)).sum(axis=1) edge = { "unit": "m", **_display.unit("m", coordinate=True), "min": float(length.min()), "max": float(length.max()), } return { "kind": case.kind, "x": axes[0], "y": axes[1], "lines": lines, "elements": int(basis.mesh.nelements), "nodes": int(basis.N), "edge": edge, }
# ------------------------------------------------- fields that change nothing _VOLUME_ONLY = "Used by the volume restrictor model only." # Per restrictor field: when it has no effect on a study, by the field of # the same restrictor whose value switches it off. _RESTRICTOR_IDLE = { "layer_flow_reduction": [ { "path": "model", "is": ["column"], "why": "The column model takes the permeability of the restrictor " "as a whole, layer included, so the solution does not see the " "layer. The volume model does.", } ], "layer_thickness": [ {"path": "model", "is": ["column"], "why": _VOLUME_ONLY}, { "path": "layer_flow_reduction", "is": [0.0], "why": "There is no surface layer while its flow reduction is 0.", }, ], "inplane_ratio": [{"path": "model", "is": ["column"], "why": _VOLUME_ONLY}], "rim_open": [{"path": "model", "is": ["column"], "why": _VOLUME_ONLY}], "rim_open_depth": [ {"path": "model", "is": ["column"], "why": _VOLUME_ONLY}, { "path": "rim_open", "is": [False], "why": "The rim is sealed over its whole height while it is not open.", }, ], } # The same per field of the case itself. _CASE_IDLE = { "form_error": [ { "path": "form_error_type", "is": ["none"], "why": "The form error shape is none.", } ], "form_error_type": [ {"path": "form_error", "is": [0.0], "why": "The form error is 0."} ], "lobes": [{"path": "roundness", "is": [0.0], "why": "The out of roundness is 0."}], "lobe_angle": [ {"path": "roundness", "is": [0.0], "why": "The out of roundness is 0."} ], }
[docs] def idle_rules(kind: str) -> dict: """When a field of a case kind has no effect on a study, and why. Returns {field path: [rule, ...]} for the fields that can be without effect. A rule is {"path": other field, "is": [values], "why": text}: the field changes nothing while the other field has one of those values. A form uses this to mark such fields instead of leaving the user to find out from identical results. """ paths = {row["path"] for row in _cases.describe(kind)} rules = {name: rule for name, rule in _CASE_IDLE.items() if name in paths} for path in paths: restrictor, _, name = path.rpartition(".") if restrictor and name in _RESTRICTOR_IDLE: rules[path] = [ {**rule, "path": f"{restrictor}.{rule['path']}"} for rule in _RESTRICTOR_IDLE[name] ] return rules
# ------------------------------------------------------- free flow, permeability def _restrictors(case) -> list: """Names of the restrictors of a case ("porous", and more for some kinds).""" return [ f.name for f in dataclasses.fields(case) if isinstance(getattr(case, f.name), _Porous) ] def _alone(case, restrictor: str): """The case with every other restrictor made solid.""" names = _restrictors(case) if restrictor not in names: raise ValueError(f"{case.kind} has no restrictor {restrictor!r}") for other in names: if other != restrictor: case = _cases.set_path(case, f"{other}.kappa", 0.0) return case def _measured(case, restrictor: str, measured_at: float | None): """The case as its free flow is measured: one restrictor, at one pressure.""" case = _alone(case, restrictor) if measured_at is not None: measured_at = float(measured_at) if not math.isfinite(measured_at): raise ValueError( "The pressure of the free-flow measurement is not a number." ) case = _cases.set_path(case, "ps", measured_at) if case.ps <= case.pa: raise ValueError("Free flow is measured at a supply pressure above ambient.") return case def _not_on_a_body(case, what: str) -> None: """Refuse a case whose film sits on a porous body, before building it. The body of a monolithic thrust bushing is a flow problem of its own: building it and solving its free flow takes far longer than a form can wait for, and no permeability of one face follows from it. """ if getattr(case, "construction", None) == "monolithic": raise ValueError( f"{what} is not offered for a monolithic thrust bushing: gas passes " "between its faces inside the body, which has to be solved as a " "whole. Measure the faces of a bonded bushing, or use " "core.free_flow on the film of the case." )
[docs] def free_flow_offered(case_doc: dict, what: str = "The free flow of each restrictor"): """Raise ValueError if free flow is not offered for a case; builds nothing. For a caller that would otherwise build the film first (the server counts its nodes): the body of a monolithic thrust bushing takes far longer to build than a form can wait for. ``what`` starts the message. """ _not_on_a_body(_case(case_doc), what)
[docs] def free_flow(case_doc: dict, measured_at: dict | None = None) -> dict: """Free flow of every restrictor of a case, the usual permeability measurement. The bare restrictor vents from a supply pressure straight to the ambient pressure of the case, with no film in front of it (see ``core.film.free_flow``). measured_at gives the absolute supply pressure of the measurement in Pa for each restrictor, {"porous": 0.5e6}; a restrictor it leaves out is measured at the supply pressure of the case. Returns the flow as free gas at ambient pressure with its unit, {"unit", "display", "scale", "values": {"porous": m³/s, ...}}: one value per restrictor of the case, each over its own face. Raises ValueError for a bad case, a pressure not above ambient, a restrictor the relation does not cover (fed over part of its back, or with an open rim) and a monolithic thrust bushing (``core.free_flow`` computes that one). """ case = _case(case_doc) _not_on_a_body(case, "The free flow of each restrictor") measured_at = measured_at or {} unknown = set(measured_at) - set(_restrictors(case)) if unknown: raise ValueError(f"{case.kind} has no restrictor {sorted(unknown)}") values = { name: _film_free_flow(_measured(case, name, measured_at.get(name)).film()) for name in _restrictors(case) } return {"unit": "m³/s", **_display.unit("m³/s"), "values": values}
[docs] def permeability( case_doc: dict, restrictor: str, flow: float, measured_at: float | None = None ) -> float: """Permeability (m²) that gives a restrictor of a case the free flow ``flow``. The inverse of ``free_flow``: flow is in m³/s of free gas at the ambient pressure of the case, measured at the absolute supply pressure measured_at (Pa; the supply pressure of the case if not given); restrictor names the one it was measured on ("porous"). Everything else about the case stays as it is, so thickness, face area, wall curvature, gas, inertial resistance and Knudsen skin are those of the case. Raises ValueError for a flow that is not positive, if no permeability gives that flow (the inertial resistance or the skin alone limits it) and where ``free_flow`` does. """ flow = float(flow) if not math.isfinite(flow) or flow <= 0.0: raise ValueError("Free flow must be a positive number.") case = _case(case_doc) _not_on_a_body(case, "Permeability from a free flow") case = _measured(case, restrictor, measured_at) # The film is built once at a reference permeability; another value only # scales the permeability over the face of this restrictor. reference = 1e-15 film = _cases.set_path(case, f"{restrictor}.kappa", reference).film() over_face = film.porous.kappa def flow_at(kappa: float) -> float: if callable(over_face): scaled = lambda x: over_face(x) * (kappa / reference) # noqa: E731 else: scaled = kappa porous = dataclasses.replace(film.porous, kappa=scaled) return _film_free_flow(dataclasses.replace(film, porous=porous)) beta = film.porous.inertial_resistance skin = film.porous.knudsen_resistance darcy = not callable(beta) and beta == 0.0 if darcy and not callable(skin) and skin == 0.0: return reference * flow / flow_at(reference) # Darcy: flow follows kappa # With inertial resistance or a Knudsen skin the flow rises with # permeability toward a limit, so the permeability is found between # bounds far outside any material (m²). low, high = 1e-24, 1e-6 limit = flow_at(high) if flow >= limit: shown = _display.unit("m³/s") what = "inertial resistance" if not darcy else "Knudsen skin" raise ValueError( f"The {what} alone limits the free flow of this " f"restrictor to {limit * shown['scale']:.4g} {shown['display']} at " "the pressure of the measurement." ) exponent = brentq( lambda e: flow_at(10.0**e) - flow, math.log10(low), math.log10(high), xtol=1e-12 ) return 10.0**exponent