Fields and Schemas#

A mesh has named fields, such as "pressure", "velocity", and "stress". Each field has a tensor rank: 0 for a scalar, 1 for a vector, 2 for a rank-2 tensor, and so on. The rank sets the transformation law of the field, which is how its values change when you rotate or reflect the frame. A scalar does not change. A vector \(v\) becomes \(R v\), and a rank-2 tensor \(T\) becomes \(R T R^\top\).

physicsnemo.mesh.fields lets a model declare the rank of each field that it reads or writes, and check data against that declaration. A plain concatenation of channels loses this information.

any rank JSON round trip rank, symmetry, parity

Two rows of three panels. Top: a square triangle mesh colored by pressure, the same mesh with arrows that point mostly to the right, and the same mesh with flat ellipses. Bottom: the mesh rotated by 30 degrees inside a dashed outline of the original square. The colors stay on their vertices, and the arrows and ellipses tilt by 30 degrees.

Fig. 35 Three fields declared with FieldSchema on a planar mesh, before and after mesh.rotate(math.radians(30), transform_point_data=True). The pressure keeps its values, the velocity turns as \(v' = R v\), and the symmetric stress turns as \(T' = R T R^\top\).#

The most-used members are the following:

FieldSchema.parse

A schema from a mapping, such as one loaded from JSON.

physicsnemo.mesh.fields.FieldSchema.parse
FieldSchema.check

Every missing field and rank mismatch in one error.

physicsnemo.mesh.fields.FieldSchema.check
RankSpec

The rank, symmetry, and parity of one field.

physicsnemo.mesh.fields.RankSpec

Example#

Declare a schema, attach matching data to a mesh, and check it:

import json
import math

import torch
from physicsnemo.mesh import FieldSchema, RankSpec
from physicsnemo.mesh.primitives.planar import unit_square

schema = FieldSchema.parse(
    {
        "pressure": {"rank": 0},
        "velocity": RankSpec(rank=1),
        "stress": {"rank": 2, "symmetric": True},
    }
)
print(schema.ranks)  # {'pressure': 0, 'velocity': 1, 'stress': 2}
print(json.dumps(schema))
# {"pressure": {"rank": 0}, "velocity": {"rank": 1},
#  "stress": {"rank": 2, "symmetric": true}}

mesh = unit_square.load(subdivisions=2)  # 25 points in 2D
n = mesh.n_points
mesh.point_data["pressure"] = mesh.points[:, 0] + mesh.points[:, 1]
mesh.point_data["velocity"] = torch.tensor([1.0, 0.0]).expand(n, 2).clone()
mesh.point_data["stress"] = torch.diag(torch.tensor([2.0, 1.0])).expand(n, 2, 2).clone()

schema.check(mesh.point_data, label="point data")  # no error

FieldSchema.check() reports every missing field and every rank mismatch in one ValueError. It allows extra fields in the data:

outputs = FieldSchema.parse({"pressure": {"rank": 0}, "wall_shear": {"rank": 1}})
try:
    outputs.check(mesh.point_data, label="point data")
except ValueError as error:
    print(error)
# point data does not contain its declared fields:
#   - missing field 'wall_shear' (declared rank 1)

A rotation with transform_point_data=True applies the transformation law of each field. transform() and its wrappers read the rank from the trailing shape of each tensor:

rotated = mesh.rotate(angle=math.pi / 2, transform_point_data=True)
print(torch.equal(rotated.point_data["pressure"], mesh.point_data["pressure"]))  # True
print(rotated.point_data["velocity"][0])  # about (0, 1)
print(rotated.point_data["stress"][0])    # about [[1, 0], [0, 2]]

Declaration Grammar#

FieldSchema.parse() is the entry point for constructor arguments and configuration files. It accepts these forms:

  • A field is a RankSpec, or a mapping of its attributes: {"rank": 2, "symmetric": True}. The key "rank" is required. A bare integer raises TypeError. Write {"rank": 0}, not 0.

  • A group is a mapping of fields or of other groups, such as {"surface": {"shear": {"rank": 1}}}. {} is an empty group.

  • A dotted name is the same nesting. "surface.shear" and the nested group above give the same field.

The schema stores flat, dotted names. FieldSchema.key() converts a dotted name to a TensorDict key, for example "surface.shear" to ("surface", "shear"). Parsing validates the declaration, so an invalid schema cannot exist. Both types are read-only dict subclasses, so a schema serializes to JSON as it is written, and FieldSchema.parse reads the JSON back to an equal schema.

RankSpec has three attributes:

  • rank: the number of spatial indices. A field with rank \(r\) in \(d\) spatial dimensions has the trailing shape \((d,)^r\) (RankSpec.shape()).

  • symmetric: whether a field of rank 2 or more is unchanged when you swap its indices. The default is False.

  • parity: "even" for a true tensor, or "odd" for a pseudotensor, which also changes sign under a reflection. A pseudotensor example is the curl of a velocity field in 3D. The default is "even".

Each channel of a model is a separate named field. A schema has no unnamed feature axis.

How Models Use Schemas#

A model takes its schemas as constructor arguments, parses them with FieldSchema.parse(), and checks its inputs with FieldSchema.check() at the start of forward. The JSON form goes into the checkpoint with the other constructor arguments. FieldSchema.from_tensordict() derives a schema from data, with the rank read from each leaf’s shape. Shapes do not record symmetry or parity, so these attributes take their defaults.

The GLOBE model (physicsnemo.experimental.models.globe.GLOBE) is the in-tree user. It takes an output_schema, one schema for each boundary condition type in boundary_source_schemas, and an optional global_schema. In forward, it checks the cell data of each boundary mesh and the global data against these schemas. GLOBE builds its features from scalars and true vectors, so it raises NotImplementedError for a field of rank 2 or more or with parity="odd".

Field Associations#

Each field belongs to one of three containers on a Mesh: point_data (one value for each point), cell_data (one value for each cell), or global_data (one value for the mesh). Two names in physicsnemo.mesh describe these containers. physicsnemo.mesh.mesh defines them, and physicsnemo.mesh exports them:

physicsnemo.mesh.mesh.MeshFieldAssociation#

The type Literal["point_data", "cell_data", "global_data"]. Each value is the name of a Mesh attribute, so getattr(mesh, association) returns the container.

physicsnemo.mesh.mesh.MESH_FIELD_ASSOCIATIONS#

The tuple ("point_data", "cell_data", "global_data"), which holds the values of MeshFieldAssociation for checks at run time.

from physicsnemo.mesh import MESH_FIELD_ASSOCIATIONS

for association in MESH_FIELD_ASSOCIATIONS:
    print(association, list(getattr(mesh, association).keys()))
# point_data ['pressure', 'velocity', 'stress']
# cell_data []
# global_data []

Choosing Between Similar Tools#

Use the following guidelines to choose between similar tools:

  • Use FieldSchema.parse() for declarations that a user writes. Use the FieldSchema constructor only for a flat mapping of RankSpec values.

  • Use FieldSchema.check() to make sure that data matches a declaration. Use FieldSchema.from_tensordict() to infer a declaration from data.

  • A schema only declares transformation laws. To apply them to data, use transform(), rotate(), or scale() with transform_point_data, transform_cell_data, or transform_global_data. These functions select fields by shape and do not read a schema, so they treat every field as a true tensor.

Summary#

RankSpec

Transformation law of one named tensor field.

FieldSchema

Read-only dict from dotted field names to RankSpec.

RankSpecLike

One field's declaration as RankSpec.parse() accepts it.

FieldSchemaLike

a FieldSchema, or a mapping from names to field declarations and nested groups.

API Reference#

class physicsnemo.mesh.fields.RankSpec(
rank: int,
symmetric: bool = False,
parity: Literal['even', 'odd'] = 'even',
)[source]#

Transformation law of one named tensor field.

A read-only dict of the attributes that differ from their defaults, so it serializes to JSON as the declaration a user writes: RankSpec(2, symmetric=True) is {"rank": 2, "symmetric": True}. Equal laws are equal specs, however they were spelled.

Parameters:
  • rank (int) – Number of spatial indices: 0 for a scalar, 1 for a vector, 2 for a rank-2 tensor, and so on.

  • symmetric (bool, default=False) – Whether the field is fully symmetric under any permutation of its indices. Only meaningful for rank >= 2; rejected below that.

  • parity ({"even", "odd"}, default="even") – "even" for a true tensor and "odd" for a pseudotensor, which additionally flips sign under an improper rotation.

Examples

>>> spec = RankSpec.parse({"rank": 2, "symmetric": True})
>>> spec
RankSpec(rank=2, symmetric=True)
>>> spec.shape(3), spec.numel(3)
((3, 3), 9)
>>> spec == RankSpec(2, symmetric=True, parity="even")
True
numel(n_spatial_dims: int) → int[source]#

Number of components per point, n_spatial_dims ** rank: the element count of shape().

property parity: Literal['even', 'odd']#

"even" for a true tensor, "odd" for a pseudotensor.

classmethod parse(
spec: RankSpec | Mapping[str, Any],
*,
label: str = 'field',
) → RankSpec[source]#

Normalize a field declaration to a RankSpec.

Parameters:
  • spec (RankSpec or Mapping) – An existing RankSpec, or a mapping with the required key "rank" and the optional keys "symmetric" and "parity".

  • label (str, default="field") – Name of the declaration in error messages.

Raises:
  • TypeError – If spec is neither form (a bare integer is refused: write {"rank": 0}), or a key has the wrong type.

  • ValueError – If the mapping has unknown keys or lacks "rank", or a value is invalid (negative rank, bad parity, symmetric below rank 2).

property rank: int#

Number of spatial indices.

shape(n_spatial_dims: int) → tuple[int, ...][source]#

Trailing component shape: () at rank 0, (n_spatial_dims,) * rank above.

property symmetric: bool#

Whether the field is fully symmetric under index permutation.

class physicsnemo.mesh.fields.FieldSchema(
fields: Mapping[str, RankSpec],
)[source]#

Read-only dict from dotted field names to RankSpec.

Build one with parse() from the declaration grammar (nested groups, dotted names, {"rank": ...} fields), or directly from a flat mapping of RankSpec values. Either way the schema is validated on construction: names are non-empty dotted strings, no name is declared twice, and no name is both a field and a group of fields. Insertion order is kept. A schema serializes to JSON as {dotted name: declaration}, which parse() reads back to an equal schema.

Parameters:

fields (Mapping[str, RankSpec]) – Flat mapping from dotted field name to its transformation law.

Examples

>>> schema = FieldSchema.parse({"pressure": {"rank": 0}, "fluid": {"velocity": {"rank": 1}}})
>>> list(schema)
['pressure', 'fluid.velocity']
>>> schema.ranks
{'pressure': 0, 'fluid.velocity': 1}
>>> schema.key("fluid.velocity")
('fluid', 'velocity')
>>> import json
>>> json.dumps(schema)
'{"pressure": {"rank": 0}, "fluid.velocity": {"rank": 1}}'
check(
data: TensorDict,
*,
label: str,
) → None[source]#

Raise unless data holds every field of this schema at its rank.

Additional leaves in data are allowed, whatever their names. Missing fields and rank mismatches are reported together.

Parameters:
  • data (TensorDict) – The data to check.

  • label (str) – Name of the data in the error message, e.g. "boundary data".

Raises:

ValueError – If a field is missing or has a different rank.

count(rank: int) → int[source]#

Number of fields of the given rank.

classmethod from_tensordict(
data: TensorDict,
) → FieldSchema[source]#

The schema implied by a TensorDict’s leaf shapes.

A leaf’s rank is its number of non-batch dimensions: for point data with batch size (N,), (N,) is rank 0 and (N, D) is rank 1. Symmetry and parity cannot be read from shapes and take their defaults.

static key(name: str) → str | tuple[str, ...][source]#

A dotted field name as a TensorDict key: "a" -> "a", "a.b" -> ("a", "b").

classmethod parse(
spec: FieldSchema | Mapping[str, RankSpec | Mapping[str, Any]],
*,
label: str = 'fields',
) → FieldSchema[source]#

Parse the declaration grammar into a schema.

Parameters:
  • spec (FieldSchemaLike) – A FieldSchema (returned unchanged), or a mapping whose values are fields (a RankSpec, or a mapping of values such as {"rank": 0}) or nested groups (a mapping of fields or groups). A name may contain "." to denote the same nesting.

  • label (str, default="fields") – Name of the declaration in error messages, e.g. "outputs".

Raises:
  • TypeError – If spec is not a mapping, a name is not a string, or a field declaration is not an accepted form.

  • ValueError – If a field declaration is invalid, a mapping mixes field attributes with nested fields, a name is declared twice, a name has an empty path component, or a name is both a field and a group of fields.

property ranks: dict[str, int]#

Dotted field name to integer rank, in schema order.

physicsnemo.mesh.fields.RankSpecLike#

One field’s declaration as RankSpec.parse() accepts it.

alias of RankSpec | Mapping[str, Any]

physicsnemo.mesh.fields.FieldSchemaLike#

a FieldSchema, or a mapping from names to field declarations and nested groups.

Type:

A schema declaration as FieldSchema.parse() accepts it

alias of FieldSchema | Mapping[str, RankSpec | Mapping[str, Any]]