r"""Integration and averaging over 2D cuts of the flow.
Reduces a cut -- a structured 2D :class:`~ember.block.Block` or an
:class:`~ember.unstructured.UnstructuredBlock` surface -- to the flows through
it and to representative averages, for comparison with mean-line design points
and measurements:
* :func:`flow_mass`, :func:`flow_conserved` and :func:`total_area`, the mass
and conserved flows through the cut and its vector area;
* :func:`area_average` and :func:`mass_average` of any nodal scalar;
* :func:`mix_out`, the uniform state carrying the same conserved flows,
optionally taken isentropically to another area;
* :func:`streamtube`, the part of a structured cut carrying a given fraction
of the mass flow, such as the stream tube at mid-span.
As discussed by :cite:t:`Cumpsty2005`, reducing a non-uniform flow to a
uniform one loses information, so the conserved quantities should be chosen
for the purpose. :cite:t:`Burdett2022` show that mixed-out averages are the
least sensitive to where along the flow the cut is taken. Averages are taken
in whatever frame their argument is given: pass a relative-frame quantity for
a relative-frame average.
"""
import numpy as np
from ember import util
from ember import block_util
from ember import perturbation
from ember import set_iterative
from ember.block import Block
from ember.unstructured import UnstructuredBlock
def _get_axes(axes, block):
"""Validate `axes`, returning the face axes to sum over.
Unstructured blocks have one axis of faces, summed whole; structured 2D
blocks have two, either or both of which may be summed.
"""
if isinstance(block, UnstructuredBlock):
if axes is not None:
raise ValueError("For unstructured blocks, axes must be None.")
axes = (0,)
else:
axes = (0, 1) if axes is None else tuple(axes)
if (
not axes
or any(ax not in (0, 1) for ax in axes)
or len(set(axes)) != len(axes)
):
raise ValueError(
"For structured grids, axes must be a non-empty tuple of distinct "
f"integers from (0, 1), got {axes}."
)
return axes
def _get_dA(block):
"""Face area vectors, quads of a structured block or triangles otherwise."""
return block.dA if isinstance(block, UnstructuredBlock) else block.dA_quad
def _get_dA_nd(block):
"""Nondimensional counterpart of :func:`_get_dA`."""
return block.dA_nd if isinstance(block, UnstructuredBlock) else block.dA_quad_nd
def _node_to_face_2d(nodal_data):
r"""Average nodal values to face centres for 2D data.
For a :math:`(n_i, n_j)` array of nodal values, the face-centred value is
.. math::
\bar{q}_{i,j} = \tfrac{1}{4}\bigl(
q_{i,j} + q_{i+1,j} + q_{i+1,j+1} + q_{i,j+1}\bigr)
Parameters
----------
nodal_data : Array, shape (ni, nj, ...)
Values at grid nodes.
Returns
-------
Array, shape (ni-1, nj-1, ...)
Values averaged to face centres.
"""
return 0.25 * (
nodal_data[:-1, :-1, ...]
+ nodal_data[1:, :-1, ...]
+ nodal_data[1:, 1:, ...]
+ nodal_data[:-1, 1:, ...]
)
def _node_to_face(nodal_data, block):
"""Distribute nodal data to faces, checking it has one value per node.
Axes after the node axes are carried through to the faces unchanged.
"""
shape = (block.n_node,) if isinstance(block, UnstructuredBlock) else block.shape
if np.shape(nodal_data)[: len(shape)] != shape:
raise ValueError(
f"Nodal data must lead with the shape of the block's nodes, {shape}, "
f"got {np.shape(nodal_data)}."
)
if isinstance(block, UnstructuredBlock):
# Average over each face's nodes
return block._to_faces(nodal_data)
else:
# Use 2D node_to_face distribution
return _node_to_face_2d(nodal_data)
def _face_corners(nodal, block):
"""Nodal scalar at the corners of each face, shape ``(*faces, n_corner)``."""
nodal = np.asarray(nodal)
if isinstance(block, UnstructuredBlock):
return nodal[block._i_face]
return np.stack(
[nodal[:-1, :-1], nodal[1:, :-1], nodal[1:, 1:], nodal[:-1, 1:]], axis=-1
)
def _group(face, block, axes):
"""Gather a face array into the groups of faces summed over `axes`.
Returns `face`, of shape ``(*faces, ...)``, reshaped to ``(n_group,
n_per_group, ...)``, and the shape of the groups: the face axes not in
`axes`, so ``()`` when every face is summed into one group.
"""
axes = _get_axes(axes, block)
n_axes = 1 if isinstance(block, UnstructuredBlock) else 2
keep = [ax for ax in range(n_axes) if ax not in axes]
face = np.moveaxis(face, keep + list(axes), list(range(n_axes)))
group_shape = face.shape[: len(keep)]
n_per = int(np.prod(face.shape[len(keep) : n_axes]))
grouped = face.reshape((int(np.prod(group_shape)), n_per) + face.shape[n_axes:])
return grouped, group_shape
def _flow(block):
"""The :class:`~ember.block.Block` holding the flow of `block`: the nodes
of an :class:`~ember.unstructured.UnstructuredBlock`, a structured block
itself."""
return block.nodes if isinstance(block, UnstructuredBlock) else block
def _flux_ref(block):
r"""Reference scales of the five conserved-flux columns, shape (5,).
The dimensional flux tensor is the nondimensional one scaled column by
column, because the reference scales satisfy :math:`p_\mathrm{ref} =
\rho_\mathrm{ref} V_\mathrm{ref}^2` and :math:`u_\mathrm{ref} =
V_\mathrm{ref}^2` (see :mod:`ember.fluid`).
"""
flow = _flow(block)
rhoV_ref, V_ref = flow.fluid.rhoV_ref, flow.fluid.V_ref
return np.array(
[
rhoV_ref,
rhoV_ref * V_ref,
rhoV_ref * V_ref,
rhoV_ref * V_ref * flow.L_ref,
rhoV_ref * V_ref**2,
],
dtype=np.float32,
)
def _flux_tensor(rhoV, per_mass, P, r, Omega):
"""Assemble the flux tensor, shape ``(..., 3, 5)``, from the mass flux
`rhoV`, shape ``(..., 3)``, the conserved variables per unit mass
`per_mass`, ``(..., 5)``, and the pressure and radius."""
flux = rhoV[..., :, None] * per_mass[..., None, :]
flux[..., 0, 1] += P # x-momentum
flux[..., 1, 2] += P # r-momentum
flux[..., 2, 3] += P * r # angular momentum
flux[..., 2, 4] += Omega * r * P # energy, through a rotating face
return flux
def _per_mass_nd(flow):
"""Nondimensional conserved variables per unit mass at the nodes,
``(1, Vx, Vr, r Vt, ho)``, shape ``(..., 5)``."""
V = flow.Vxrt_nd
return np.stack(
(
np.ones_like(flow.rho_nd),
V[..., 0],
V[..., 1],
V[..., 2] * flow.r_nd,
flow.ho_nd,
),
axis=-1,
)
def _flux_face_nd(block):
"""Nondimensional flux tensor on the faces of a cut, shape ``(*faces, 3, 5)``.
The mass flux and the conserved variables per unit mass are each averaged
from the nodes to the faces, and multiplied there: the product of
averages the solver's own face flows take, so that a cut on grid faces
carries the solver's discrete flows through them. Scaled by
:func:`_flux_ref` it is in SI.
"""
if not (isinstance(block, UnstructuredBlock) or block.ndim == 2):
raise ValueError(
f"Need a structured 2D or an unstructured block, got ndim={block.ndim}."
)
flow = _flow(block)
def face(nodal):
return _node_to_face(nodal, block)
return _flux_tensor(
face(flow.Vxrt_nd * flow.rho_nd[..., None]),
face(_per_mass_nd(flow)),
face(flow.P_nd),
face(flow.r_nd),
flow.Omega_nd,
)
def _flux_point_nd(states):
"""Nondimensional flux tensor of each state of a block on its own, shape
``(..., 3, 5)``: what a set of uniform states, as the mixed-out states of
:func:`mix_out`, carry through a face."""
return _flux_tensor(
states.Vxrt_nd * states.rho_nd[..., None],
_per_mass_nd(states),
states.P_nd,
states.r_nd,
states.Omega_nd,
)
def _face_mass_flow(block):
"""Mass flow through each face [kg/s], rho V dotted with the face area.
The mass column of the flux tensor, but formed alone, with no equation of
state evaluation: what makes :func:`flow_mass` cheap.
"""
flow = _flow(block)
rhoV = _node_to_face(flow.Vxrt * flow.rho[..., None], block)
return util.dot(rhoV, _get_dA(block))
def _negligible(net, gross):
"""Whether each net mass flow is negligible next to its gross face flow.
Relative rather than absolute, so the test does not depend on the scale
of the case. The float32 face flows cancel no better than about one part
in a million, so a net flow below that is indistinguishable from zero.
"""
return np.abs(net) <= 1e-6 * gross
def _check_net_flow(net, gross, what):
"""Raise if the net mass flow is negligible, see :func:`_negligible`."""
if np.any(_negligible(net, gross)):
raise ValueError(f"Net mass flux through the block is zero, {what}")
def _dot_conserved(flux, dA, axes):
"""Dot the conserved flux tensor with face areas and sum over `axes`.
`flux` has shape ``(..., 3, 5)`` and `dA` ``(..., 3)``; the result has the
five conserved components last, the face axes in `axes` summed away.
"""
return np.sum(
np.einsum(
"...ij,...i->...j",
flux,
dA,
),
axis=axes,
)
def _integrate_scalar(scalar_face, dA_face, axes):
"""Integrate a face-centred scalar times face area magnitude over `axes`.
`scalar_face` may carry axes after the face axes, integrated separately.
"""
assert dA_face.shape[-1] == 3
dA = util.vecnorm(dA_face)
assert scalar_face.shape[: dA.ndim] == dA.shape
return np.sum(scalar_face * _trailing(dA, scalar_face), axis=axes)
def _trailing(face, data):
"""Append unit axes to face-shaped `face` to broadcast against `data`.
`data` has the face axes, or what remains of them after a sum, followed
by any trailing axes of the field being averaged.
"""
face = np.asarray(face)
return face.reshape(face.shape + (1,) * (np.ndim(data) - face.ndim))
[docs]
def flow_mass(block, axes=None):
r"""Integrate mass flow through faces of a 2D block.
Calculates the mass flow over the block faces,
.. math::
\dot{m} = \int \rho \mathbf{V}\cdot\mathrm{d}\mathbf{A} \,.
This is the first component of :func:`flow_conserved`, but needs no
equation-of-state evaluation, so is several times cheaper on a structured
block: use it where only the mass flow is wanted.
Parameters
----------
block : Block, shape (ni, nj), or UnstructuredBlock
2D structured block or unstructured surface.
axes : tuple of int, optional
For a structured block, the face axes to sum over: ``(0,)``, ``(1,)`` or
the default ``(0, 1)``, all of them. For an unstructured block,
must be None, and every face is summed.
Returns
-------
mass_flow : float or Array
Mass flow through the block [kg/s]: a scalar if every face axis is
summed, else one value per face along the axis not in `axes`.
"""
axes = _get_axes(axes, block)
return np.sum(_face_mass_flow(block), axis=axes)
[docs]
def flow_conserved(block, axes=None):
r"""Integrate conserved flows through faces of a 2D block.
Calculates the conserved flows over the block faces,
.. math::
\int \mathcal{F}\cdot\mathrm{d}\mathbf{A} \,,
where the conserved flux tensor :math:`\mathcal{F}` carries the fluxes of
mass, axial momentum, radial momentum, angular momentum and stagnation
enthalpy (energy),
.. math::
\mathcal{F} = \rho \mathbf{V}
\begin{bmatrix} 1 \\ V_x \\ V_r \\ r V_\theta \\ h_0 \end{bmatrix}
+ p
\begin{bmatrix}
\mathbf{0} \\ \mathbf{e}_x \\ \mathbf{e}_r
\\ r\,\mathbf{e}_\theta \\ \Omega r\,\mathbf{e}_\theta
\end{bmatrix} \,.
Parameters
----------
block : Block, shape (ni, nj), or UnstructuredBlock
2D structured block or unstructured surface.
axes : tuple of int, optional
For a structured block, the face axes to sum over: ``(0,)``, ``(1,)`` or
the default ``(0, 1)``, all of them. For an unstructured block,
must be None, and every face is summed.
Returns
-------
flow_conserved : Array, shape (5,) or (n, 5)
Flows of mass [kg/s], axial and radial momentum [N], angular momentum
[N m] and energy [W], summed over every face, or over `axes` leaving
one row per face along the other axis.
"""
axes = _get_axes(axes, block)
flow_nd = _dot_conserved(_flux_face_nd(block), _get_dA_nd(block), axes)
return flow_nd * _flux_ref(block) * _flow(block).L_ref ** 2
[docs]
def total_area(block):
r"""Compute total vector area of a 2D block.
Calculates the total vector area as the integral of the face area vectors,
.. math::
\mathbf{A} = \int \mathrm{d}\mathbf{A} \,.
For a cut of constant :math:`x` the axial component is its annulus area;
a cut that is not flat in the meridional plane has both axial and radial
components.
Parameters
----------
block : Block, shape (ni, nj), or UnstructuredBlock
2D structured block or unstructured surface.
Returns
-------
A : Array, shape (3,)
Total vector area [m^2], components :math:`(A_x, A_r, A_\theta)`.
Raises
------
ValueError
If `block` is structured but not 2D.
"""
return _total_area_nd(block) * _flow(block).L_ref ** 2
def _total_area_nd(block):
r"""Total vector area over :math:`L_\mathrm{ref}^2`, shape (3,)."""
if not (isinstance(block, UnstructuredBlock) or block.ndim == 2):
raise ValueError(
f"Need a structured 2D or an unstructured block, got ndim={block.ndim}."
)
axes = _get_axes(None, block)
return np.sum(_get_dA_nd(block), axis=axes)
[docs]
def area_average(scalar_node, block, axes=None):
r"""Take area-weighted average of a 2D nodal scalar field.
Calculates the area-weighted average of the scalar field :math:`\phi`,
.. math::
\bar{\phi} = \frac{\int \phi\, \mathrm{d}A}{\int \mathrm{d}A} \,.
Parameters
----------
scalar_node : Array, shape (ni, nj, ...) or (n_node, ...)
Scalar field at the nodes of `block`, such as ``block.s``. Any
frame-dependent quantity is averaged in whatever frame it is given,
so pass ``block.ho_rel``, say, for a relative-frame average. Axes
after the node axes are averaged separately, so several fields
stacked on a last axis, ``np.stack([block.ho, block.s], axis=-1)``,
are averaged in one pass.
block : Block, shape (ni, nj), or UnstructuredBlock
2D structured block or unstructured surface.
axes : tuple of int, optional
For a structured block, the face axes to average over: ``(0,)``, ``(1,)`` or
the default ``(0, 1)``, all of them. For an unstructured block,
must be None, and every face is averaged.
Returns
-------
avg_scalar : float or Array
Area-weighted average: a scalar if every face axis is averaged,
else one value per face along the axis not in `axes`, followed by
any trailing axes of `scalar_node`.
Raises
------
ValueError
If `scalar_node` does not lead with one value per node.
"""
axes = _get_axes(axes, block)
scalar_face = _node_to_face(scalar_node, block)
dA = _get_dA(block)
numerator = _integrate_scalar(scalar_face, dA, axes)
denominator = np.sum(util.vecnorm(dA), axis=axes)
return numerator / _trailing(denominator, numerator)
[docs]
def mass_average(scalar_node, block, axes=None):
r"""Take mass-weighted average of a 2D nodal scalar field.
Calculates the mass-weighted average of the scalar field :math:`\phi`,
.. math::
\bar{\phi} = \frac{\int \phi\, \rho \mathbf{V}\cdot\mathrm{d}\mathbf{A}}
{\int \rho \mathbf{V}\cdot\mathrm{d}\mathbf{A}} \,.
Parameters
----------
scalar_node : Array, shape (ni, nj, ...) or (n_node, ...)
Scalar field at the nodes of `block`, such as ``block.s``. Any
frame-dependent quantity is averaged in whatever frame it is given,
so pass ``block.ho_rel``, say, for a relative-frame average. Axes
after the node axes are averaged separately, so several fields
stacked on a last axis, ``np.stack([block.ho, block.s], axis=-1)``,
are averaged in one pass.
block : Block, shape (ni, nj), or UnstructuredBlock
2D structured block or unstructured surface.
axes : tuple of int, optional
For a structured block, the face axes to average over: ``(0,)``, ``(1,)`` or
the default ``(0, 1)``, all of them. For an unstructured block,
must be None, and every face is averaged.
Returns
-------
avg_scalar : float or Array
Mass-weighted average: a scalar if every face axis is averaged,
else one value per face along the axis not in `axes`, followed by
any trailing axes of `scalar_node`.
Raises
------
ValueError
If the net mass flux through the block is zero, or, for a partial
average, through any one strip; or if `scalar_node` does not lead
with one value per node.
"""
axes = _get_axes(axes, block)
scalar_face = _node_to_face(scalar_node, block)
dm = _face_mass_flow(block)
numerator = np.sum(scalar_face * _trailing(dm, scalar_face), axis=axes)
denominator = np.sum(dm, axis=axes)
# A partial reduction -- `axes=(1,)` to average over the pitch and keep the
# span, say -- leaves arrays here, checked element by element.
_check_net_flow(
denominator,
np.sum(np.abs(dm), axis=axes),
"so it has no mass average. Consider using area_average() instead.",
)
return numerator / _trailing(denominator, numerator)
[docs]
def mix_out(block, AR=1.0, axes=None):
r"""Mix out a 2D cut to uniformity, optionally then changing its area.
The mixed-out state is the uniform flow that, passed through the total
area :math:`\mathbf{A} = \int \mathrm{d}\mathbf{A}`, carries the same
conserved flows as the non-uniform cut. Its conserved variables
:math:`\mathcal{U}` are found by solving
.. math::
\mathcal{F}(\mathcal{U})\cdot\mathbf{A}
= \int \mathcal{F}\cdot\mathrm{d}\mathbf{A} \,,
for the five conserved flows (mass, axial and radial momentum, angular
momentum and energy), where :math:`\mathcal{F}` is the flux tensor of
:func:`flow_conserved`, by Newton steps with a backtracking line search.
With `axes`, each strip of faces summed over them is mixed out on its own,
as a pitchwise mix-out gives one state per strip along the span.
Two uniform states carry the flows, one subsonic and one supersonic
through the cut, linked by a normal shock. The result is supersonic if
the mass-averaged Mach number through the cut exceeds one and the
supersonic state does not lower the entropy below the cut's mass average,
which mixing cannot do; otherwise subsonic. A near-sonic cut may have
neither: it is choked, and :class:`RuntimeError` is raised.
The optional area ratio ``AR`` then takes the uniform state isentropically
to ``AR`` times its area, conserving mass, stagnation enthalpy, entropy
and angular momentum :math:`r V_\theta` while holding the pitch angle
:math:`\beta`. This step is reversible, so the mixing loss is independent
of ``AR``. It stays on the meridional branch of the mixed-out state, and
raises :class:`RuntimeError` if it would choke.
Parameters
----------
block : Block, shape (ni, nj), or UnstructuredBlock
2D structured block or unstructured surface.
AR : float, default 1.0
Area ratio of the isentropic area change after mixing out; ``AR<1``
contracts the uniform state, ``AR=1`` leaves it at constant area.
axes : tuple of int, optional
For a structured block, the face axes to mix over: ``(1,)`` mixes
each strip of faces along axis 1, one state per strip along axis 0,
``(0,)`` the reverse, and the default ``(0, 1)`` the whole cut. For
an unstructured block, must be None.
Returns
-------
mix : Block, shape () or (n,)
New block holding the mixed-out state, or one per strip, with the
fluid, reference length, rotation speed, blade count and label of the
cut. Each state sits at the root mean square of its faces' least and
greatest radius, and the midpoints of their axial and circumferential
extents. Velocities are absolute, as on the cut.
Raises
------
ValueError
If `AR` is not positive, or the cut is not a surface of revolution:
its faces have area in the circumferential direction.
RuntimeError
If the Newton iteration fails to converge for any state, as when its
strip is choked, or if the area change would choke the flow.
"""
if not AR > 0.0:
raise ValueError(f"Area ratio must be positive, got AR={AR}.")
# Every face array is gathered into groups, one per mixed-out state: the
# whole cut is one group, a pitchwise mix-out one per spanwise strip. All
# that follows runs per group, nondimensionally, as does the Jacobian from
# ember.perturbation, so no reference scales appear in it.
pts = _flow(block)
face_flow = _dot_conserved(_flux_face_nd(block), _get_dA_nd(block), axes=())
face_flow, group_shape = _group(face_flow, block, axes)
def grouped(face):
return _group(face, block, axes)[0]
def total(grouped_face):
"""Sum over each group's faces, accumulated in float64. The faces of
a group lie along a strided axis, which numpy would add one by one
in float32, losing the accuracy of its pairwise summation: on a
thousand faces, 1e-5 of the area, and the flows with it."""
return np.sum(grouped_face, axis=1, dtype=np.float64).astype(np.float32)
dA = grouped(_get_dA_nd(block)) # (n, faces per group, 3)
A = total(dA)
flow = total(face_flow)
flow_gross = total(np.abs(face_flow))
n = A.shape[0]
# Each group's mass flow positive
sign = np.where(flow[:, 0] <= 0.0, -1.0, 1.0)
A *= sign[:, None]
flow *= sign[:, None]
# The cut must be a surface of revolution, with no theta area on any face
# -- not merely in total, as a cut wavy round the pitch cancels in sum
# yet carries flow through its theta faces that no uniform state can.
# Gross rather than per face, at a tilt of 1e-3: float32 positions on a
# fine pitchwise mesh leave about 1e-4 of a face's area in theta.
tilt = total(np.abs(dA[..., 2])) / total(util.vecnorm(dA[..., :2]))
if not np.all(tilt < 1e-3):
raise ValueError(
"Cut is not a surface of revolution: its faces have "
f"{np.max(tilt):.2e} of their meridional area in the theta direction."
)
A = A[:, :2] # Drop theta component
A_ref = np.linalg.norm(A, axis=1)
# A block for the mixed-out states, with the metadata of the cut, each at
# the extents of its own group's faces
mix = Block(shape=(n,))
mix.set_fluid(pts.fluid)
mix.set_L_ref(pts.L_ref)
mix.set_Omega(pts.Omega)
mix.set_Nb(pts.Nb)
mix.set_label(pts.label)
def extent(nodal):
corners = grouped(_face_corners(nodal, block))
return corners.min(axis=(1, 2)), corners.max(axis=(1, 2))
r_lo, r_hi = extent(pts.r)
mix.set_r(np.sqrt(0.5 * (r_lo**2 + r_hi**2)))
mix.set_x(0.5 * np.add(*extent(pts.x)))
mix.set_t(0.5 * np.add(*extent(pts.t)))
r_mid_nd = 0.5 * np.add(*extent(pts.r_nd))
# Initial guess the mean of the face-averaged conserved variables, written
# direct on the ND storage. This skips set_conserved's density/finite
# validation, which a mean of valid input data cannot trip; the line
# search rejects any step to a non-positive density.
cons_face = grouped(_node_to_face(pts.conserved_nd, block))
cons_guess = total(cons_face) / cons_face.shape[1]
mix.conserved_nd[...] = cons_guess
mix.update_cached_conserved()
# Absolute tolerances for the flows, on the same ND scale as the flows
rho, V = mix.rho_nd, mix.V_nd
atol = (
np.stack(
[rho * V, rho * V**2, rho * V**2, rho * V**2 * r_mid_nd, rho * V**3],
axis=-1,
)
* A_ref[:, None]
* 1e-4
)
# No tighter than float32 can resolve the flows. At low Mach number the
# momentum and energy flows are almost all pressure and static enthalpy,
# which the dynamic scales above leave out, and one rounding of them
# exceeds those scales below Ma=0.02 or so.
atol = np.maximum(atol, 4.0 * np.finfo(np.float32).eps * flow_gross)
# The Newton step works in the frame of the cut's own normal, fixed, so
# one rotation serves every iteration. Not the flow's pitch angle: through
# a cut the flow crosses obliquely, as at a radial impeller exit, the
# Jacobian there is the flux through the wrong face and the steps wander
# off rather than converge.
chi = np.arctan2(A[:, 1], A[:, 0])
cos, sin = np.cos(chi), np.sin(chi)
rot_to, rot_from = util.rotation_matrices(chi)
def residual():
"""Error in the five flows, and its largest component over atol."""
flux_mix = _flux_point_nd(mix)[:, :2, :]
err_flow = flow - _dot_conserved(flux_mix, A, axes=())
return err_flow, np.max(np.abs(err_flow) / atol, axis=1)
def supersonic():
"""Whether each mixed-out flow through its faces is supersonic."""
return (mix.Vx * cos + mix.Vr * sin) / mix.a > 1.0
# Constant-area mixing has a subsonic and a supersonic solution, linked by
# a normal shock. The branch is chosen by the mass-averaged Mach number
# through the faces, independent of how the nodes are spaced; a subsonic
# group cannot mix out supersonic, mixing at constant area driving the
# flow towards sonic but not across. A group carrying no net mass flow
# has no mass average, and is taken as subsonic.
dm = grouped(_face_mass_flow(block))
net = total(dm)
has_flow = ~_negligible(net, total(np.abs(dm)))
net_or_one = np.where(has_flow, net, 1.0)
def mass_average_grouped(nodal):
return total(grouped(_node_to_face(nodal, block)) * dm) / net_or_one
# The node sound speed once: for a real fluid it is a costly evaluation
a = pts.a
Ma_cut = np.where(
has_flow,
cos * mass_average_grouped(pts.Vx / a) + sin * mass_average_grouped(pts.Vr / a),
0.0,
)
def solve(target, which):
"""Newton-solve the groups in `which` for the branches in `target`.
Returns the flow errors and the iteration count. The guess is the
mean state, its velocity through the faces moved across sonic if it
lies on the other branch, keeping its static state and its velocity
along them. Each group keeps its own step length, and stops when no
step reduces its residual.
"""
cons = mix.conserved_nd
cons[which] = cons_guess[which]
mix.update_cached_conserved()
move = which & (supersonic() != target)
if move.any():
c = cons[move]
Vn = (c[:, 1] * cos[move] + c[:, 2] * sin[move]) / c[:, 0]
Ma = np.where(
target[move],
np.maximum(Ma_cut[move], 1.1),
np.minimum(Ma_cut[move], 0.9),
)
dVn = mix.a_nd[move] * Ma - Vn
c[:, 1] += c[:, 0] * dVn * cos[move]
c[:, 2] += c[:, 0] * dVn * sin[move]
c[:, 4] += 0.5 * c[:, 0] * ((Vn + dVn) ** 2 - Vn**2)
cons[move] = c
mix.update_cached_conserved()
# Newton with a backtracking line search: the full step is halved
# until it lands on a positive density, on the branch, and reduces the
# largest scaled residual. A Newton step shrinks every residual to
# first order, so a short one always does, until round-off: when none
# does, the float32 fixed point is reached. Running to it, not merely
# into atol, keeps the answer independent of input ordering; atol
# scales the five residuals and checks convergence.
err_flow, err = residual()
active = which.copy()
niter = 0
while active.any() and niter < 100:
niter += 1
# Resolve to velocities through and along the faces, the frame in
# which the Jacobian below is the flux through them. The momentum
# errors are turned into the same frame, so each correction lands
# on the component it belongs to, and the correction turned back.
err_flux = err_flow / A_ref[:, None]
err_flux[:, 1:3] = util.matvec(rot_to, err_flux[:, 1:3])
block_util.resolve_to_interface(mix, rot_to)
d = util.matvec(perturbation.flux_to_conserved(mix), err_flux)
block_util.resolve_from_interface(mix, rot_from)
d[:, 1:3] = util.matvec(rot_from, d[:, 1:3])
# One step length per group. A trial step can land outside the
# range of a real fluid's fit, and its NaN properties are rejected
# like any other failed step.
cons0 = mix.conserved_nd.copy()
accepted = cons0.copy()
step = np.ones(n)
pending = active.copy()
with np.errstate(invalid="ignore", over="ignore", divide="ignore"):
for _ in range(12):
trial = np.where(
pending[:, None], cons0 + step[:, None] * d, accepted
)
mix.conserved_nd[...] = trial
mix.update_cached_conserved()
err_flow_trial, err_trial = residual()
ok = pending & (mix.rho > 0.0) & (supersonic() == target)
ok &= err_trial < err
accepted[ok] = trial[ok]
err_flow[ok], err[ok] = err_flow_trial[ok], err_trial[ok]
pending &= ~ok
if not pending.any():
break
step[pending] *= 0.5
active &= ~pending
mix.conserved_nd[...] = accepted
mix.update_cached_conserved()
return err_flow, niter
target = Ma_cut > 1.0
err_flow, niter = solve(target, np.ones(n, dtype=bool))
# The supersonic solution can lower the entropy, when a strong shear
# layer would have to accelerate past every stream in it to mix out
# supersonic. No such flow exists: it must shock, and the subsonic
# solution is the mixed-out state. The margin admits round-off in the
# reversible limit of a uniform supersonic cut, which mixes out to itself.
shock = supersonic()
if shock.any():
shock &= mix.s < mass_average_grouped(pts.s) - 1e-4 * mix.Rgas
if shock.any():
err_shock, niter_shock = solve(target & ~shock, shock)
err_flow[shock] = err_shock[shock]
niter = max(niter, niter_shock)
# Written as `not all(... < atol)` so that a NaN residual counts as a
# failure rather than slipping past a `>=` test.
failed = ~np.all(np.abs(err_flow) < atol, axis=1)
if failed.any():
idx = np.flatnonzero(failed)
Ma_mix = (mix.Vx * cos + mix.Vr * sin) / mix.a
near_sonic = idx[np.abs(Ma_mix[idx] - 1.0) < 0.1]
Ma_sonic = ", ".join(f"{m:.3f}" for m in Ma_mix[near_sonic])
choked = (
f" The flow through the faces of states {near_sonic.tolist()} has been"
f" driven to Ma={Ma_sonic}, so they are probably choked: no uniform"
" state at constant area carries their flows."
if near_sonic.size
else ""
)
raise RuntimeError(
f"Failed to converge mixing for states {idx.tolist()} of {n} after "
f"{niter} iterations, err_flow={err_flow[idx]}, atol={atol[idx]}, "
f"conserved={mix.conserved[idx]}." + choked
)
# Optionally take the uniform states isentropically from their areas to
# AR times them. This is a reversible second step that leaves the mixing
# loss unchanged. It cannot carry the flow across sonic, so stays on each
# state's branch, and chokes if AR is below the sonic area ratio.
if AR != 1.0:
set_iterative.set_ho_s_rhoVm_Vt_Beta(
mix,
mix.ho,
mix.s,
mix.rho * mix.Vm / AR,
mix.Vt,
Beta=mix.Beta,
supersonic=mix.Vm > mix.a,
)
# One state per group: a 0D block when every face axis is mixed over
return mix[0].copy() if group_shape == () else mix
[docs]
def streamtube(block, lo, hi, along=0):
r"""Extract the stream tube of a structured 2D cut between two mass fractions.
Integrates the mass flow strip by strip along axis `along`, summing across the
other axis, to give a cumulative mass fraction :math:`\psi` running from
zero at the first node to one at the last. The stream tube is the region
:math:`\mathrm{lo} \le \psi \le \mathrm{hi}`, so ``lo=0.45, hi=0.55`` on a
hub-to-casing axis is the stream tube carrying the central tenth of the
flow. It is bounded by surfaces of constant mass fraction, as in a
throughflow calculation, so is a true stream tube only as far as the flow
does not migrate across those surfaces; this cut alone cannot tell.
The two ends of the stream tube sit at fractional node positions inside the
strips where :math:`\psi` first reaches `lo` and `hi`. The data are
interpolated linearly to those two positions and the original nodes
between them are copied through, so the stream tube keeps the resolution of the
cut it came from. Each end is placed by bisection on the mass flow of the
partial strip it bounds, integrated just as :func:`flow_mass` integrates
the stream tube, so it carries :math:`\mathrm{hi} - \mathrm{lo}` of the flow
to round-off --- not merely to within the variation of flux and face area
across a strip, which a linear interpolation of :math:`\psi` would leave.
The first crossing is taken rather than an inverse interpolation of
:math:`\psi`, which need not be monotonic: a strip of backflow in a corner
elsewhere on the cut does not stop the stream tube being found.
Parameters
----------
block : Block, shape (ni, nj)
Structured 2D block.
lo, hi : float
Mass fractions bounding the stream tube, :math:`0 \le \mathrm{lo} <
\mathrm{hi} \le 1`.
along : int, default 0
Axis along which the mass fraction runs. The stream tube spans the whole of
the other axis. Note the sense is opposite to ``axes`` in the
averaging functions, which names the axes summed over.
Returns
-------
tube : Block, shape (ntube, nj) or (ni, ntube)
New block holding the stream tube, with the metadata of `block`.
Raises
------
ValueError
If `block` is unstructured or not 2D, if `along` is not 0 or 1, if the
fractions are out of order or out of range, or if the net mass flux
through the block is zero.
"""
if isinstance(block, UnstructuredBlock) or block.ndim != 2:
raise ValueError("streamtube requires a structured 2D block.")
if along not in (0, 1):
raise ValueError(f"along must be 0 or 1, got {along}.")
if not 0.0 <= lo < hi <= 1.0:
raise ValueError(f"Need 0 <= lo < hi <= 1, got lo={lo}, hi={hi}.")
# Mass through each strip between adjacent nodes along `along`
dm_face = _face_mass_flow(block)
dm = np.sum(dm_face, axis=1 - along, dtype=float)
total = dm.sum()
_check_net_flow(total, np.sum(np.abs(dm_face)), "so it has no mass fraction.")
# Dividing by a signed total makes the fraction run zero to one whichever
# way the flow crosses the cut. The last node is pinned to one, so that
# round-off cannot leave hi=1 short of it.
psi = np.concatenate([[0.0], np.cumsum(dm)]) / total
psi[-1] = 1.0
# Rows along the mass-fraction axis, so both ends are found and built the same way
# whichever axis the fraction runs along.
data = np.moveaxis(block._data, along, 0)
def fraction(p0, p1):
"""Mass fraction between fractional positions p0 < p1 in one strip."""
return flow_mass(_interpolate_rows(block, data, [p0, p1], along)) / total
# The low end: the partial strip from it up to the next node must carry
# what that node's fraction exceeds `lo` by.
k = int(np.argmax(psi >= lo))
if psi[k] == lo:
pos_lo = float(k)
else:
need = psi[k] - lo
pos_lo = _bisect(lambda p: fraction(p, k) < need, k - 1, k)
# The high end: the partial strip up to it must carry what `hi` exceeds the
# start of that strip by. The strip starts at the low end if both ends fall
# in the same one.
k = int(np.argmax(psi >= hi))
if psi[k] == hi:
pos_hi = float(k)
else:
start = max(k - 1, pos_lo)
need = hi - max(psi[k - 1], lo)
pos_hi = _bisect(lambda p: fraction(start, p) >= need, start, k)
# An end within float32 round-off of a node -- the bisection resolves it
# no closer than about 1e-7 of a strip -- is put on it. Left a hair
# short, the node would be copied through as well, making a strip of
# faces with next to no area. The mass this moves is below round-off.
pos_lo, pos_hi = (
float(np.round(p)) if abs(p - np.round(p)) < 1e-5 else p
for p in (pos_lo, pos_hi)
)
inner = np.arange(np.floor(pos_lo) + 1, np.ceil(pos_hi))
pos = np.concatenate([[pos_lo], inner, [pos_hi]])
return _interpolate_rows(block, data, pos, along)
def _bisect(past, a, b, n=60):
"""Return the point in [a, b] where the predicate `past` turns true.
`past` is false at `a` and true at `b`. Sixty halvings of a unit interval
reach the spacing of doubles, so the result is as exact as the predicate.
"""
for _ in range(n):
p = 0.5 * (a + b)
if past(p):
b = p
else:
a = p
return 0.5 * (a + b)
def _interpolate_rows(block, data, pos, axis):
"""Return a block of `data` rows linearly interpolated to positions `pos`.
`data` has its interpolation axis first; the result has it back at `axis`.
A position on the last node is taken from the last strip rather than past
it.
"""
pos = np.asarray(pos, dtype=float)
j0 = np.minimum(np.floor(pos).astype(int), data.shape[0] - 2)
w = (pos - j0)[:, None, None]
rows = np.moveaxis((1.0 - w) * data[j0] + w * data[j0 + 1], 0, axis)
out = block.empty(shape=rows.shape[:-1])
out._data = rows
return out