API reference

Modules at the package root apply to every structure. The geo and mesh subpackages hold one module per structure or strategy.

Operations on segmented LabelMaps that apply to any knee structure.

class kneemesh.vol.ContourSlice(points, center, u_axis, v_axis, normal, area, straight_from=None)[source]

Bases: object

An ordered closed contour of a surface in a plane through a curve, normal to it unless tilted.

Parameters:
points

(N, 3) physical points around the contour, counterclockwise about normal. The closing point is not repeated. Each corner tracked through the slices, such as a meniscus’s sharp inner edge, lies at the same index on every slice, the sharpest at index 0, and points are evenly spaced between them, so corresponding points match along the curve. Without corners, points are evenly spaced from wherever best lines them up with the previous slice’s.

Type:

numpy.ndarray

center

Point on the curve where the plane is centered.

Type:

numpy.ndarray

u_axis

Unit vector in the plane.

Type:

numpy.ndarray

v_axis

Unit vector in the plane. (u_axis, v_axis, normal) is right-handed.

Type:

numpy.ndarray

normal

Unit normal of the plane: the curve’s tangent at center, or tilted from it to keep neighboring slices apart (see slice_isocontour).

Type:

numpy.ndarray

area

Area enclosed by the contour.

Type:

float

straight_from

For a contour whose thin inner edge was clipped, the index of the cut’s first corner: the contour is curved from points[0], the cut’s other corner, to points[straight_from], and straight from there through the remaining points back to points[0]. None for a contour that is curved all the way around.

Type:

int | None

kneemesh.vol.signed_distance_field(label_map, label=1, sigma=None)[source]

Compute a smoothed signed distance to a label’s boundary, in physical units.

A recursive Gaussian removes the voxel staircase from the field’s level sets.

Parameters:
  • label_map (Image) – 3D LabelMap of sitkUInt8, sitkUInt16, or sitkInt16 pixels.

  • label (int) – Value of the structure.

  • sigma (float | None) – Gaussian standard deviation in physical units, applied equally to every axis. By default each axis uses the sigma whose central 95% spans 3 of that axis’s voxel edges. 0 disables smoothing.

Returns:

A float image that is negative inside the label and positive outside. Without smoothing, its zero level set lies on the voxel edges of the label’s boundary.

Raises:

ValueError – If the image is not a 3D LabelMap of an accepted pixel type, the label is absent, or sigma is negative.

Return type:

Image

kneemesh.vol.extract_isocontour(distance_field, level=0.0)[source]

Extract a triangle mesh at a given distance from a label’s boundary.

Parameters:
  • distance_field (Image) – Float image from signed_distance_field.

  • level (float) – Distance of the surface from the label boundary. Positive values lie outside the label.

Returns:

A closed triangle mesh in physical coordinates.

Raises:

ValueError – If the distance field never reaches level.

Return type:

vtkPolyData

kneemesh.vol.smooth_isocontour(mesh, iterations=50, pass_band=0.001)[source]

Smooth a surface mesh with a windowed sinc filter, keeping its connectivity.

Boundary and feature-edge smoothing are off, so any open edges stay in place, and non-manifold smoothing is on. Coordinates are normalized to the unit cube while filtering, so the result does not depend on the physical scale.

Parameters:
  • mesh (vtkPolyData) – Surface from extract_isocontour.

  • iterations (int) – Number of filter iterations, which is the degree of the filter’s polynomial. More iterations follow the pass band more closely. 0 returns the mesh unchanged.

  • pass_band (float) – Pass band of the filter, between 0 and 2. Lower values smooth more and shrink the surface more.

Returns:

A new smoothed mesh, or mesh itself when iterations is 0.

Raises:

ValueError – If iterations is negative or pass_band is not in (0, 2].

Return type:

vtkPolyData

kneemesh.vol.require_3d_label_map(label_map)[source]

Raise ValueError unless label_map is a 3D LabelMap of an accepted pixel type.

Parameters:

label_map (Image)

Return type:

None

Operations shared by every cartilage: telling its articular side from the side against its bone.

kneemesh.cartilage.DEFAULT_SIDE_COSINE = 0.3

Default cosine between a surface normal and the bone’s distance gradient beyond which a point is on one side.

class kneemesh.cartilage.CartilageSides(articular, bone)[source]

Bases: object

Points of a cartilage surface on its articular side and on the side against its bone.

Points whose normals run roughly along the bone’s surface, around the cartilage’s perimeter, belong to neither.

Parameters:
articular

(N, 3) physical points whose outward normals point away from the bone.

Type:

numpy.ndarray

bone

(M, 3) physical points whose outward normals point toward the bone.

Type:

numpy.ndarray

kneemesh.cartilage.classify_sides(surface, bone_distance_field, side_cosine=0.3)[source]

Split a closed cartilage surface into its articular and bone sides.

Only the largest connected piece of the surface is used, so small islands of the segmentation are dropped. Each point’s outward normal is compared with the gradient of the bone’s distance field there, which points away from the bone wherever the bone is. This works for any cartilage, unlike comparing normals with one axis, which cannot separate the sides of the femoral cartilage wrapping the condyles.

Parameters:
  • surface (vtkPolyData) – Closed cartilage surface from extract_isocontour or smooth_isocontour.

  • bone_distance_field (Image) – Signed distance field of the bone from signed_distance_field.

  • side_cosine (float) – A point is on the articular side when the cosine between its normal and the gradient is at least this, and on the bone side when it is at most the negative of this. Higher values drop more of the steep perimeter between the sides.

Returns:

The points on each side.

Raises:

ValueError – If side_cosine is not in (0, 1), or a side has no points.

Return type:

CartilageSides

kneemesh.cartilage.field_value(image, points)[source]

Return a scalar image’s trilinearly interpolated values at (N, 3) physical points, clamped at its edges.

Parameters:
Return type:

ndarray

kneemesh.cartilage.field_gradient(image, points)[source]

Return a scalar image’s physical gradient at (N, 3) physical points, interpolated trilinearly.

Parameters:
Return type:

ndarray

Multilabel segmentations: a LabelMap with a name for each label, and assembling one from single-label LabelMaps.

class kneemesh.segmentation.Segmentation(image, labels)[source]

Bases: object

A LabelMap holding several structures, and the name of each structure’s label.

Parameters:
image

3D LabelMap of sitkUInt8, sitkUInt16, or sitkInt16 pixels.

Type:

SimpleITK.SimpleITK.Image

labels

Label value of each structure, by name. Other values in image are allowed and ignored.

Type:

dict[str, int]

value(name)[source]

Return the label value of the named structure.

Raises:

ValueError – If no label has that name.

Parameters:

name (str)

Return type:

int

mask(name)[source]

Return a sitkUInt8 image that is 1 on the named structure and 0 elsewhere.

Parameters:

name (str)

Return type:

Image

kneemesh.segmentation.assemble_label_maps(label_maps, interpolator='label_gaussian', padding=4)[source]

Resample single-label LabelMaps onto one grid and combine them into a multilabel Segmentation.

Every nonzero voxel of an input belongs to its structure. The shared grid takes the first input’s direction cosines, the smallest voxel spacing of any input along each axis, and the bounding box of all inputs in physical space, padded with background on every side. Input axes count toward the shared axis nearest them in direction, and the grid’s voxel faces line up with the input that has the smallest spacing along each axis. Structures get label values 1, 2, … in the order given. Where resampled structures overlap, the one given later wins.

Parameters:
  • label_maps (Mapping[str, Image]) – Single-label 3D LabelMaps by structure name.

  • interpolator (Interpolator) – “label_gaussian” resamples with sitkLabelGaussian, which smooths the voxel staircase on finer grids. “nearest_neighbor” uses sitkNearestNeighbor.

  • padding (int) – Background voxels added beyond the bounding box on each side.

Returns:

The assembled segmentation, sitkUInt8 for up to 255 structures and sitkUInt16 above that.

Raises:

ValueError – If label_maps is empty, an input is not a 3D LabelMap of an accepted pixel type or has no foreground, interpolator is unknown, padding is negative, or a structure vanishes in resampling or is entirely covered by later ones.

Return type:

Segmentation

B-rep values, gmsh sessions, and B-spline construction shared by every structure.

class kneemesh.brep.BRep(text)[source]

Bases: object

A B-rep shape held as the text of an Open Cascade .brep file.

Parameters:

text (str)

kneemesh.brep.gmsh_session()[source]

Run a block on a temporary gmsh model, leaving gmsh as it was found.

Return type:

Generator[None]

kneemesh.brep.export_brep()[source]

Return the current gmsh model’s highest-dimension shapes as a BRep. Call inside gmsh_session.

Return type:

BRep

kneemesh.brep.chord_parameters(points)[source]

Return parameters from 0 to 1 proportional to chord length around a closed contour, ending at the repeated first point.

Parameters:

points (ndarray)

Return type:

ndarray

kneemesh.brep.periodic_spline(points, spline_order, parameters=None)[source]

Return a periodic B-spline through points.

Parameters:
  • points (ndarray) – (N, 3) points around a closed contour, without the closing point repeated.

  • spline_order (int) – Polynomial degree.

  • parameters (ndarray | None) – N + 1 increasing parameters from 0 to 1, the last for the repeated first point. By default proportional to chord length. Splines through equally many points at the same parameters share one knot vector.

Return type:

BSpline

kneemesh.brep.open_chord_parameters(points)[source]

Return parameters from 0 to 1 proportional to chord length along an open sequence of points.

Parameters:

points (ndarray)

Return type:

ndarray

kneemesh.brep.clamped_interpolation(parameters, points, degree)[source]

Return the knots and poles of a clamped B-spline through points at parameters.

Averaged knots make this work at any degree. Both ends are pinned to the exact end points, so curves fitted to the same end points meet exactly.

Parameters:
Return type:

tuple[ndarray, ndarray]

kneemesh.brep.add_bspline_curve(knots, poles, degree)[source]

Add an open B-spline curve from scipy-style full knots and poles, returning its tag.

Parameters:
Return type:

int

kneemesh.brep.add_swept_surface(rows, degree, along, along_degree)[source]

Add a B-spline surface through section curves sharing one knot vector, returning its tag.

Each column of poles is interpolated along the curve at the same parameters, so a surface’s edge depends only on that edge’s points and matches its neighbor’s exactly.

Parameters:
Return type:

int

kneemesh.brep.add_periodic_swept_surface(splines, point_count, along, along_degree)[source]

Add a closed B-spline surface through periodic section splines sharing one knot vector, returning its tag.

Each column of poles is interpolated along the curve at the parameters along, as in add_swept_surface, so the surface passes exactly through every section and its two end rims are those sections’ curves. Lofting with addThruSections instead lets Open Cascade’s approximation overshoot in the end spans where real sections taper, folding the surface so gmsh cannot mesh it.

Parameters:
  • splines (list[BSpline]) – Periodic splines from periodic_spline at shared parameters, in order along the curve.

  • point_count (int) – Number of points each spline interpolates.

  • along (ndarray) – Parameter of each section along the curve, from 0 to 1.

  • along_degree (int) – Degree along the curve, at most len(splines) - 1.

Return type:

int

kneemesh.brep.periodic_poles_and_knots(spline, point_count)[source]

Return a periodic spline’s poles and knots as Open Cascade takes them.

Parameters:
Return type:

tuple[ndarray, list[float]]

kneemesh.brep.add_closed_wire(spline, point_count)[source]

Add a closed wire of one periodic B-spline, returning its tag.

Parameters:
Return type:

int

kneemesh.brep.split_periodic_spline(spline, parameters)[source]

Split a periodic spline exactly into clamped splines at parameters.

parameters must be sorted, distinct, and start at 0, so the last piece ends at 1.

Parameters:
Return type:

list[BSpline]

kneemesh.brep.add_closed_points(poles)[source]

Add a point per pole, returning their tags with the first repeated at the end.

gmsh treats a B-spline whose first and last point tags match as periodic.

Parameters:

poles (ndarray)

Return type:

list[int]

kneemesh.brep.contours_to_polydata(slices)[source]

Assemble contour slices into a single poly data of closed polylines.

Parameters:

slices (list[ContourSlice]) – Contours from slice_isocontour.

Returns:

A vtkPolyData with one vtkPolyLine per slice, in the order given. Each polyline ends on its own first point id to close the contour, so no point is duplicated.

Raises:

ValueError – If slices is empty.

Return type:

vtkPolyData

kneemesh.brep.resample_closed(loop, count)[source]

Return count points evenly spaced in length around a closed Kochanek spline through a loop.

Parameters:
  • loop (ndarray) – (N, D) points around a closed loop, without the first repeated, with D of 2 or 3.

  • count (int) – Number of points to return.

Returns:

(count, D) points, starting at the loop’s first point.

Return type:

ndarray

kneemesh.brep.sample_closed(loop, fractions)[source]

Return points at fractions of the length around a closed Kochanek spline through a loop.

Parameters:
  • loop (ndarray) – (N, D) points around a closed loop, without the first repeated, with D of 2 or 3.

  • fractions (ndarray) – Fractions of the length from the loop’s first point, taken modulo 1.

Returns:

(len(fractions), D) points.

Return type:

ndarray

kneemesh.brep.butterfly_split_indices(loops, turns=None)[source]

Return four sorted point indices splitting every loop into the arcs of a butterfly partition.

The splits divide the loop into arcs of equal length, by chord length averaged over all loops. Their rotation minimizes the turning angle, averaged over all loops, near them: each point’s turn is weighted by a Gaussian of its distance from the nearest split. The first split is a point index and the others may fall between points.

Parameters:
  • loops (Sequence[ndarray]) – (N, D) points around closed loops, all with the same N, without the first repeated.

  • turns (ndarray | None) – Cost of a split near each point, by default the turning angle averaged over all loops. Negative costs draw splits toward a point.

Return type:

ndarray

kneemesh.brep.turning_angles(points)[source]

Return the angle in radians that a closed loop of (N, D) points turns at each point.

Parameters:

points (ndarray)

Return type:

ndarray

Tetrahedral meshing of any solid B-rep with gmsh, and the Mesh it returns.

class kneemesh.tet_meshing.Algorithm2D(*values)[source]

Bases: _GmshAlgorithm

gmsh surface meshing algorithms that produce triangles (option Mesh.Algorithm).

gmsh’s “initial mesh only” algorithm crashes the process and BAMG fails on these shapes, so both are omitted.

class kneemesh.tet_meshing.Algorithm3D(*values)[source]

Bases: _GmshAlgorithm

gmsh volume meshing algorithms that produce tetrahedra (option Mesh.Algorithm3D).

gmsh’s R-tree algorithm is omitted because it writes a debug file into the working directory.

kneemesh.tet_meshing.DEFAULT_MIN_SIZE_FRACTION = 0.05

Default smallest element size as a fraction of the shortest side of the shape’s oriented bounding box.

kneemesh.tet_meshing.DEFAULT_MAX_SIZE_FRACTION = 0.25

Default largest element size as a fraction of the shortest side of the shape’s oriented bounding box.

class kneemesh.tet_meshing.Mesh(nodes, elements, element_types, straight_lines=<factory>, faces=<factory>, element_sets=<factory>, node_sets=<factory>, quality=<factory>)[source]

Bases: object

A mesh of volume elements, or of surface elements for a bone’s surface, with its boundary faces and named sets.

Elements are numbered from 0 in the order of elements, each type in turn, then of faces; element_sets hold these numbers (see mesh_sets).

Parameters:
nodes

(N, 3) physical node coordinates.

Type:

numpy.ndarray

elements

Connectivity keyed by gmsh element name, such as “Tetrahedron 4”, “Hexahedron 27”, or “Triangle 6”. Each array is (M, nodes per element) of 0-based indices into nodes, in gmsh’s node ordering.

Type:

dict[str, numpy.ndarray]

element_types

gmsh’s element type number for each key of elements and of faces.

Type:

dict[str, int]

straight_lines

(L, K) indices into nodes of chains of corner nodes that must stay straight, such as the columns through a cartilage sheet’s walls. optimize_hexahedral_mesh keeps each chain’s inner nodes on the segment between its ends. Empty for most meshes.

Type:

numpy.ndarray

faces

A volume mesh’s boundary faces, keyed and ordered as elements are, such as “Triangle 6” for “Tetrahedron 10”, oriented outward. Empty for a surface mesh, whose elements are its surface.

Type:

dict[str, numpy.ndarray]

element_sets

Element numbers of named sets of faces, or of a surface mesh’s elements, such as “surface” or “articular_side”.

Type:

dict[str, numpy.ndarray]

node_sets

Indices into nodes of the nodes of each element set, by the same names.

Type:

dict[str, numpy.ndarray]

quality

Quality metrics by name, each an array of one value per element and face in their numbering, NaN where the metric does not apply (see mesh_optimization.element_quality). Empty unless computed, as the meshing pipeline does.

Type:

dict[str, numpy.ndarray]

property element_count: int

The number of elements and faces together, which element numbers stay below.

with_face_sets(groups=None, faces=None)[source]

Return this volume mesh with its boundary faces and sets: “surface” and one per group.

Parameters:
  • groups (Mapping[str, ndarray] | None) – Boolean masks over the boundary faces, concatenated in the order boundary_faces gives them, by set name.

  • faces (dict[str, ndarray] | None) – The boundary faces, if already found with mesh_sets.boundary_faces.

Return type:

Mesh

kneemesh.tet_meshing.tetrahedral_mesh(brep, min_size=None, max_size=None, elements_per_circle=0, algorithm_2d=Algorithm2D.FRONTAL_DELAUNAY, algorithm_3d=Algorithm3D.DELAUNAY, element_order=1, second_order_incomplete=False, face_groups=None)[source]

Mesh a solid B-rep with tetrahedra.

Parameters:
  • brep (BRep) – A solid, such as contours_to_brep with a cap.

  • min_size (float | None) – Smallest element size, in physical units. By default DEFAULT_MIN_SIZE_FRACTION of the shortest side of the shape’s oriented bounding box, but no more than max_size, which keeps small geometric features and curvature sizing from producing excessively small elements. 0 sets no limit.

  • max_size (float | None) – Largest element size, in physical units. By default DEFAULT_MAX_SIZE_FRACTION of the shortest side of the shape’s oriented bounding box, but no less than min_size. gmsh’s own default, from the shape’s overall extent, is too coarse for thin shapes and can leave them with no tetrahedra at all.

  • elements_per_circle (int) – Size elements so that a full circle of the local surface curvature would hold this many. 0 disables curvature sizing.

  • algorithm_2d (Algorithm2D) – Algorithm for the boundary triangles.

  • algorithm_3d (Algorithm3D) – Algorithm for the tetrahedra.

  • element_order (int) – Polynomial order of the elements. 2 gives 10-node tetrahedra. High-order nodes on the boundary lie on the curved surface, which can invert thin elements beside it, so gmsh’s high-order optimization (Mesh.HighOrderOptimize 2, elastic smoothing then optimization) untangles them: without it the real lateral meniscus’s 10-node tetrahedra had 28 of 1444 with a Jacobian determinant at or below zero at a Gauss point.

  • second_order_incomplete (bool) – Omit interior nodes from high-order elements. Second-order tetrahedra have none, so this only changes orders 3 and up, such as 16-node instead of 20-node third-order tetrahedra.

  • face_groups (Callable[[], dict[str, list[int]]] | None) – Called in the gmsh session after the B-rep is loaded, it names groups of its surfaces’ tags, whose faces make the mesh’s sets beside “surface”, such as mesh.sheet.sheet_face_groups.

Returns:

The tetrahedral mesh, with its boundary faces and sets.

Raises:

ValueError – If a size or count is out of range, brep has no volume, or gmsh fails or produces no tetrahedra.

Return type:

Mesh

kneemesh.tet_meshing.require_element_order(element_order)[source]

Raise ValueError unless element_order is at least 1.

Parameters:

element_order (int)

Return type:

None

kneemesh.tet_meshing.gmsh_options(options)[source]

Set gmsh numeric options for a block, restoring them afterward.

gmsh options are global, so they would otherwise outlive the session when gmsh was already running.

Parameters:

options (dict[str, float | bool])

Return type:

Generator[None]

kneemesh.tet_meshing.import_solid(brep)[source]

Load a B-rep into the current gmsh model, raising ValueError if it has no volume.

Parameters:

brep (BRep)

Return type:

None

kneemesh.tet_meshing.oriented_extents()[source]

Return the side lengths of the current gmsh model’s oriented bounding box, shortest first.

The box’s axes are the principal axes of points sampled on every curve and every non-planar surface. A planar face lies within the convex hull of its boundary, so its curves bound it along any axis, while sampling its parametric rectangle would also take points outside its trimmed region.

Return type:

ndarray

kneemesh.tet_meshing.gmsh_mesh(dimension=3, face_groups=None)[source]

Return the current gmsh model’s elements of a dimension, 3 for volume elements or 2 for surface ones, and their nodes as a Mesh.

A volume mesh of linear or quadratic elements gets its boundary faces and sets: “surface”, and one for each of face_groups, from the faces on those surfaces. A surface mesh’s “surface” sets hold all of it.

Parameters:
Return type:

Mesh

Boundary faces of volume meshes, and the named node and element sets built from them.

A Mesh (tet_meshing.Mesh) numbers its elements, then its boundary faces, each kind in the order of its dict; its element sets hold those numbers, 0-based, and its node sets indices into its nodes. Every structure’s mesh has a “surface” set of its boundary faces, or of its own elements for a bone’s surface mesh, and of their nodes. Structure meshers add named groups of faces, such as a cartilage’s articular side, from the B-rep faces gmsh meshed them on.

kneemesh.mesh_sets.SURFACE = 'surface'

Name of the set of every structure’s boundary faces, or of a surface mesh’s elements, and of their nodes.

kneemesh.mesh_sets.FACE_ELEMENTS: dict[str, tuple[str, int]] = {'Hexahedron 20': ('Quadrilateral 8', 16), 'Hexahedron 27': ('Quadrilateral 9', 10), 'Hexahedron 8': ('Quadrilateral 4', 3), 'Tetrahedron 10': ('Triangle 6', 9), 'Tetrahedron 4': ('Triangle 3', 2)}

The gmsh name and type number of the faces of each volume element that has boundary faces.

kneemesh.mesh_sets.boundary_faces(elements)[source]

Return the faces of volume elements that belong to only one element, keyed by gmsh name, oriented outward.

Parameters:

elements (Mapping[str, ndarray]) – Connectivity of tetrahedra or hexahedra by gmsh name, in gmsh’s node ordering.

Raises:

ValueError – If an element type has no face table here.

Return type:

dict[str, ndarray]

kneemesh.mesh_sets.unshared(faces)[source]

Return a mask of the rows of faces (F, corners) whose set of corner nodes no other row has.

Sorting the rows with lexsort and comparing neighbors is about three times as fast as np.unique(…, axis=0), which sorts them as opaque records.

Parameters:

faces (ndarray)

Return type:

ndarray

kneemesh.mesh_sets.face_groups_of(faces, surfaces)[source]

Return the tag of the surface each face lies on, -1 where none, over the faces concatenated in dict order.

Parameters:
  • faces (Mapping[str, ndarray]) – Boundary faces by gmsh name, as boundary_faces gives.

  • surfaces (Mapping[int, ndarray]) – Corner node indices of the elements gmsh made on each B-rep surface, by its tag.

Return type:

ndarray

kneemesh.mesh_sets.face_sets(elements, faces, groups)[source]

Return element and node sets of a volume mesh’s boundary faces: “surface”, then one per group.

Parameters:
  • elements (Mapping[str, ndarray]) – The mesh’s volume elements by gmsh name, numbered first.

  • faces (Mapping[str, ndarray]) – Its boundary faces by gmsh name, numbered after the elements.

  • groups (Mapping[str, ndarray]) – Boolean masks over the faces concatenated in dict order, by set name.

Return type:

tuple[dict[str, ndarray], dict[str, ndarray]]

kneemesh.mesh_sets.surface_sets(elements)[source]

Return the “surface” element and node sets of a surface mesh: every element and every node it uses.

Parameters:

elements (Mapping[str, ndarray])

Return type:

tuple[dict[str, ndarray], dict[str, ndarray]]

Node optimization of hexahedral meshes for the scaled Jacobian and the Frobenius aspect ratio.

Up to three strategies run in turn on the hexahedra’s corner nodes:

  1. Smart Laplacian smoothing moves each node toward the average of its edge neighbors, keeping a move only if it does not lower the worst scaled Jacobian of the elements around the node.

  2. If any element is still inverted, untangling minimizes the sum of max(0, 0.2 - SJ)^2 over every element corner, which stays finite and smooth through inverted corners, until none is inverted.

  3. Optimization minimizes the sum of 1 / SJ over every element corner, plus aspect_weight times the sum of each corner’s squared Frobenius aspect ratio, by projected gradient descent. Both terms grow without bound as a corner degenerates, so no step can invert an element, and both weigh the worst corners most. 1 / SJ alone squares corners up by stretching elements; the aspect term holds their edge lengths in proportion. A third term, warp_weight times the sum over the boundary quadrilaterals of their squared normalized out-of-plane volume, flattens warped faces on the surface, which corner measures cannot see.

High-order hexahedra are also measured at the points of the Gauss rules simulations integrate them with, where their curved edges can invert an element whose corners are valid. Their Jacobians there are barriers in optimization and targets in untangling, alongside the corners.

Boundary nodes are classified from the mesh’s own boundary quadrilaterals. Where adjacent boundary faces meet at more than a feature angle, their shared edges are feature edges. Surface nodes slide in their tangent plane and may leave it by a fraction of the local element size; nodes on a feature edge slide along it with the same allowance off it; feature corners stay fixed. The inner nodes of a mesh’s straight_lines stay at their fractions along the segment between the line’s ends, which move as their own kind allows. By default the surface nodes’ net offset off their tangent planes is removed, which keeps the mesh’s volume. Tangential travel is also limited, so the tangent plane stays a good model of the surface. High-order nodes follow the corners of their element.

class kneemesh.mesh_optimization.MeshQuality(minimum, mean, inverted, max_aspect, mean_aspect, max_warp, warp_99)[source]

Bases: object

Scaled Jacobian, Frobenius aspect ratio, and surface warp statistics of a hexahedral mesh.

Parameters:
minimum

Smallest element scaled Jacobian (see scaled_jacobians). Negative means an inverted element.

Type:

float

mean

Mean element scaled Jacobian.

Type:

float

inverted

Number of elements with a Jacobian determinant at or below zero at a corner, or for a high-order element, of its own Jacobian at a corner node or Gauss point.

Type:

int

max_aspect

Largest element Frobenius aspect ratio, infinite if any element is inverted.

Type:

float

mean_aspect

Mean element Frobenius aspect ratio, infinite if any element is inverted.

Type:

float

max_warp

Largest warp of a boundary quadrilateral, in degrees (see surface_warps).

Type:

float

warp_99

99th percentile of the boundary quadrilaterals’ warps, in degrees.

Type:

float

kneemesh.mesh_optimization.scaled_jacobians(mesh)[source]

Return each hexahedron’s scaled Jacobian, the smallest over its eight corners and, if high-order, its Gauss points.

A corner’s scaled Jacobian is the determinant of its three edge vectors divided by the product of their lengths: 1 for a right angle corner, 0 for a flat one, and negative for an inverted one. A high-order element is measured instead by its own Jacobian, its tangents along the local axes in place of edges, at its corner nodes and the points of its reduced and full Gauss rules, p and p + 1 along each axis for order p: curved edges can invert it there though its straight-sided corners are valid, and leave it valid though they are not.

Raises:

ValueError – If the mesh has elements other than hexahedra.

Parameters:

mesh (Mesh)

Return type:

ndarray

kneemesh.mesh_optimization.frobenius_aspects(mesh)[source]

Return each hexahedron’s Frobenius aspect ratio, the largest over its eight corners.

A corner’s Frobenius aspect ratio is |E|_F^2 / (3 det(E)^(2/3)) for the matrix E of its three edge vectors, as Verdict’s maximum aspect Frobenius measures it: 1 for a cube’s corner, and larger as the corner’s edges differ in length or leave right angles. It is infinite for a degenerate or inverted corner. High-order elements are measured by their own Jacobian at their corner nodes and Gauss points (see scaled_jacobians).

Raises:

ValueError – If the mesh has elements other than hexahedra.

Parameters:

mesh (Mesh)

Return type:

ndarray

kneemesh.mesh_optimization.surface_warps(mesh)[source]

Return each boundary quadrilateral’s warp, in degrees, from the hexahedra’s corner nodes.

A quadrilateral’s warp is the angle between the normals of the two triangles a diagonal splits it into, the larger over its two diagonals: 0 for a flat face. Scaled Jacobians and aspect ratios, measured at element corners, miss it; it is what makes a mesh’s surface look crumpled.

Raises:

ValueError – If the mesh has elements other than hexahedra.

Parameters:

mesh (Mesh)

Return type:

ndarray

kneemesh.mesh_optimization.mesh_quality(mesh)[source]

Summarize a hexahedral mesh’s scaled Jacobians, Frobenius aspect ratios, and surface warps.

Raises:

ValueError – If the mesh has elements other than hexahedra.

Parameters:

mesh (Mesh)

Return type:

MeshQuality

kneemesh.mesh_optimization.SCALED_JACOBIAN = 'scaled_jacobian'

Name of the scaled Jacobian in element_quality.

kneemesh.mesh_optimization.FROBENIUS_ASPECT = 'frobenius_aspect'

Name of the Frobenius aspect ratio in element_quality.

kneemesh.mesh_optimization.WARP = 'warp'

Name of the quadrilaterals’ warp in element_quality.

kneemesh.mesh_optimization.EDGE_RATIO = 'edge_ratio'

Name of the edge ratio in element_quality.

kneemesh.mesh_optimization.MIN_DIHEDRAL_ANGLE = 'min_dihedral_angle'

Name of the tetrahedra’s smallest dihedral angle in element_quality.

kneemesh.mesh_optimization.element_quality(mesh)[source]

Return quality metrics of every element and face of a mesh, measured on corner nodes, by name.

Each array holds one value per element and face, in their numbering (Mesh.elements, then Mesh.faces), NaN where the metric does not apply, so meshes mixing element shapes take every metric of any of them. Higher-order elements are measured on their corner nodes, as if they were first order, except for the scaled Jacobian and Frobenius aspect ratio of high-order hexahedra and tetrahedra, which take the element’s own Jacobian at its corner nodes and Gauss points (see scaled_jacobians and _sample_basis): curved edges can invert an element whose straight-sided corners are valid, and leave one valid whose corners are not.

  • scaled_jacobian, of volume elements, or of a surface mesh’s elements: the smallest over its corners of the corner’s Jacobian determinant over the product of its edges’ lengths, scaled so the ideal shape (a cube, square, regular tetrahedron, or equilateral triangle) is 1. It is 0 for a degenerate element and negative for an inverted one; triangles, which have no orientation of their own, are never negative.

  • frobenius_aspect, of the same: the largest over its corners of |T|_F^2 / (d det(T)^(2/d)), in d dimensions, for the map T from the ideal shape’s corner to the element’s, as Verdict’s aspect Frobenius: 1 for the ideal shape, larger as edges differ in length or leave the ideal angles, and infinite for an inverted or degenerate element.

  • warp, of quadrilateral faces, or of a surface mesh’s quadrilaterals: the angle between the two triangles either diagonal splits it into, the larger of the two, in degrees (see surface_warps). Present only when the mesh has quadrilaterals.

  • edge_ratio, of volume elements, or of a surface mesh’s elements: the longest edge between corners over the shortest, 1 for the ideal shapes and infinite for a collapsed edge. Comparable across shapes.

  • min_dihedral_angle, of tetrahedra: the smallest angle between two faces along an edge, in degrees, about 70.5 for the regular tetrahedron and 0 for a flat one, a sliver included, which the edge ratio misses. Like the edge ratio it does not see orientation, so an inverted tetrahedron measures as its mirror image does; its scaled Jacobian tells. Present only when the mesh has tetrahedra.

Raises:

ValueError – If the mesh has an element shape other than tetrahedra, hexahedra, triangles, and quadrilaterals.

Parameters:

mesh (Mesh)

Return type:

dict[str, ndarray]

kneemesh.mesh_optimization.optimize_hexahedral_mesh(mesh, laplacian_iterations=10, optimization_iterations=200, surface_deviation=0.1, surface_travel=0.5, feature_angle=30.0, preserve_volume=True, aspect_weight=0.0, warp_weight=0.0)[source]

Move a hexahedral mesh’s nodes to raise its scaled Jacobians, keeping connectivity.

Smart Laplacian smoothing runs first, then optimization of the sum of 1 / SJ over every element corner plus aspect_weight times the sum of their squared Frobenius aspect ratios, plus warp_weight times the sum of the boundary quadrilaterals’ squared warp measures (_warp_objective). Optimization needs every element valid, so if smoothing leaves any corner’s scaled Jacobian below 0.01, inverted or nearly, the mesh is untangled first, by raising every corner’s toward 0.2 until all reach 0.01, and optimization is skipped with a warning if any stays inverted.

High-order hexahedra are also measured at their Gauss points (see scaled_jacobians), where their curved edges can invert them though their corners are valid: smoothing keeps their scaled Jacobians there from falling, untangling raises them as it does the corners’, and optimization adds (1 / SJ - 1 / 0.2)^2 for each below 0.2, a barrier that leaves elements well shaped there alone.

Boundary allowances scale with each node’s local size, the mean length of the element edges at the node. Feature edges are boundary edges where the faces on either side meet at more than feature_angle; nodes where feature edges end, branch, or turn by more than feature_angle are fixed.

Parameters:
  • mesh (Mesh) – Mesh of linear or high-order hexahedra, such as hexahedral_mesh returns.

  • laplacian_iterations (int) – Smart Laplacian sweeps. 0 skips smoothing.

  • optimization_iterations (int) – Gradient steps of the optimization, and at most as many of untangling. 0 skips both.

  • surface_deviation (float) – How far a boundary node may move off its starting tangent plane, or off its feature edge, as a fraction of its local size. 0 keeps boundary nodes on their tangent planes and edge lines.

  • surface_travel (float) – How far a boundary node may slide along its tangent plane or feature edge, as a fraction of its local size.

  • feature_angle (float) – Angle in degrees between boundary face normals above which their shared edge is a feature edge.

  • preserve_volume (bool) – Remove the area-weighted mean of the surface nodes’ offsets off their tangent planes, so they can move out in some places and in at others but not swell or shrink the mesh overall. Without it, optimization tends to push the whole surface outward, adding about 5% to a meniscus at surface_deviation 0.1.

  • aspect_weight (float) – Weight of the squared Frobenius aspect ratios against 1 / SJ. 0 optimizes the scaled Jacobian alone, which can stretch elements: it raised the real medial tibial cartilage’s largest aspect ratio to 42 with its walls free to bend and 11 with them straight, against 6.4 at 0.5. The aspect term also penalizes deliberately elongated elements, such as the meniscus’s along its centerline.

  • warp_weight (float) – Weight of the boundary quadrilaterals’ warp against 1 / SJ, per quadrilateral. 0 leaves warped faces as they are.

Returns:

A new Mesh with the same connectivity and moved nodes. High-order nodes move with the trilinear interpolation of their element’s corner displacements, so curved edges keep their offsets from straight ones.

Raises:

ValueError – If the mesh has elements other than hexahedra or an argument is out of range.

Return type:

Mesh

Removing overclosure: where built structures’ geometry overlaps, moving it apart after every structure is built.

Every structure is built from its own label, and smoothing, thickening, and fitting let neighbors overlap by a few tenths of a millimeter: on the example knee the medial meniscus reaches 0.45 mm into its tibial cartilage, the cartilages 0.15 mm into their bones, and the femoral and tibial cartilages 0.1 mm into each other. resolve_overclosure moves them apart by a priority:

  • Cartilage is thin, so it never yields to a meniscus or bone. Where two cartilages overlap, both articular sides are lowered toward their bones, each by its share of the two local thicknesses, t_a / (t_a + t_b), and the sheets rebuilt (geo.sheet.lower_articular).

  • Every other structure, in priority order, is pushed out of the union of every structure ranked above it: a meniscus by moving its contour points out within their slice planes and lofting them again, which keeps its planar caps and both hexahedral designs, and a bone by moving its surface’s vertices.

Overlaps are measured against each B-rep’s outer boundary, triangulated finely (brep_boundary), and each bone’s surface.

class kneemesh.overclosure.Adjustable(geometry, sheet=None, slices=None, loft=None)[source]

Bases: object

A structure’s geometry and what it was built from, so it can be moved and built again.

Give sheet for a cartilage, slices and loft for a meniscus, and neither for a bone, whose geometry is its surface. A B-rep with neither is never moved.

Parameters:
geometry

The B-rep, or a bone’s closed triangulated surface.

Type:

kneemesh.brep.BRep | vtkmodules.vtkCommonDataModel.vtkPolyData

sheet

The cartilage sheet the B-rep was built from (geo.sheet.sheet_to_brep).

Type:

kneemesh.geo.sheet.CartilageSheet | None

slices

The contours the meniscus’s B-rep was lofted through.

Type:

list[kneemesh.vol.ContourSlice] | None

loft

Builds the meniscus’s B-rep from contours again, as it was built.

Type:

collections.abc.Callable[[list[kneemesh.vol.ContourSlice]], kneemesh.brep.BRep] | None

class kneemesh.overclosure.Obstacle(surface)[source]

Bases: object

A closed triangulated surface whose inside other geometry must leave, with signed distances to it.

Parameters:

surface (vtkPolyData)

distances(points, reach)[source]

Return each of (N, 3) points’ signed distance to the surface, negative inside, and its nearest point on it.

Points farther than reach outside the surface’s bounding box are not measured: their distance is infinite and their nearest point their own.

Parameters:
Return type:

tuple[ndarray, ndarray]

property points: ndarray

The surface’s (N, 3) vertices.

pushes(points, clearance)[source]

Return the (N, 3) moves that take each point inside, or within clearance outside, to clearance outside; zero for the rest.

Parameters:
Return type:

ndarray

recessions(points, clearance)[source]

Return where this surface must move so that (N, 3) points lie clearance outside it, and how.

Returns:

The (M, 3) nearest surface points of the points inside or within clearance outside, and the (M, 3) moves that take the surface there clearance past them, inward.

Parameters:
Return type:

tuple[ndarray, ndarray]

depth(points)[source]

Return how far the deepest of (N, 3) points lies inside the surface, 0 if none does.

Parameters:

points (ndarray)

Return type:

float

kneemesh.overclosure.brep_boundary(brep, size=0.5)[source]

Triangulate a solid B-rep’s outer boundary, leaving out faces between its volumes, such as a meniscus’s butterfly blocks’.

Parameters:
Return type:

vtkPolyData

kneemesh.overclosure.surface_obstacle(geometry)[source]

Return a structure’s geometry as an Obstacle: a B-rep’s outer boundary, or a bone’s surface.

Parameters:

geometry (BRep | vtkPolyData)

Return type:

Obstacle

kneemesh.overclosure.resolve_overclosure(structures, priority, clearance=0.0)[source]

Move overlapping structures apart, leaving clearance between them.

Cartilages, those with a sheet, share each overlap between them by thickness whatever their order in priority. Every other structure, in priority order, highest first, is pushed out of every structure ranked above it, as moved. A structure missing from priority, or a B-rep with neither sheet nor slices, is never moved, but still pushes others ranked below it.

Returns:

Every structure, moved where it overlapped.

Raises:

ValueError – If a cartilage ranks below a structure that can be moved, a meniscus or bone.

Parameters:
Return type:

dict[str, Adjustable]

kneemesh.overclosure.push_surface_out(surface, obstacles, clearance=0.0)[source]

Move a closed triangulated surface’s vertices so it lies clearance outside the obstacles, keeping its triangles.

Each round moves the vertices inside an obstacle out of it, and where an obstacle’s own vertices lie inside the surface, between its vertices, the surface’s vertices around them that face them inward (_spread).

Parameters:
Return type:

vtkPolyData

kneemesh.overclosure.push_meniscus_out(slices, loft, obstacles, clearance=0.0)[source]

Move a meniscus’s contours so its loft lies clearance outside the obstacles, lofting them again in rounds.

Each contour point moves within its slice’s plane (_move_contours). The loft interpolates the contours but can still reach into an obstacle between them, so each round also measures the lofted boundary, both its points inside obstacles and obstacles’ points inside it, and those moves also move the contour points around them that face them (_spread).

Returns:

The moved contours and their loft.

Parameters:
Return type:

tuple[list[ContourSlice], BRep]

Reading and writing LabelMaps as .nii, .nrrd, or .mhd + .raw, segmentations, poly data as .vtp, B-reps as .brep, and bone surfaces as .stl, and writing meshes.

kneemesh.disk.MESH_SET_SUFFIXES = frozenset({'.vtkhdf', '.vtu'})

Mesh formats written with their node and element sets, and the formats of an assembled mesh.

kneemesh.disk.read_label_map(path)[source]

Read a segmented LabelMap from disk.

For a .mhd file, the .raw file it references must also exist.

Raises:

ValueError – If the file format is unsupported or the image is not sitkUInt8, sitkUInt16, or sitkInt16.

Parameters:

path (str | PathLike[str])

Return type:

Image

kneemesh.disk.write_label_map(image, path)[source]

Write a segmented LabelMap to disk, overwriting any existing file.

A .mhd path also writes a .raw file alongside it.

Raises:

ValueError – If the file format is unsupported or the image is not sitkUInt8, sitkUInt16, or sitkInt16.

Parameters:
Return type:

None

kneemesh.disk.segmentation_labels_path(path)[source]

Return where write_segmentation puts the labels of a segmentation written to path: <stem>_labels.json beside it.

Parameters:

path (str | PathLike[str])

Return type:

Path

kneemesh.disk.write_segmentation(segmentation, path)[source]

Write a segmentation’s LabelMap to path and its {name: value} labels as JSON beside it.

The labels go to segmentation_labels_path(path), so the image can be read back with read_segmentation or given to a pipeline as label_map with those labels.

Raises:
  • ValueError – If the file format is unsupported.

  • OSError – If a file cannot be written.

Parameters:
Return type:

None

kneemesh.disk.read_segmentation(path)[source]

Read a segmentation written by write_segmentation.

Raises:
  • ValueError – If the file format is unsupported, the image is not a LabelMap, or the labels are invalid for it.

  • OSError – If the image or its labels file cannot be read.

Parameters:

path (str | PathLike[str])

Return type:

Segmentation

kneemesh.disk.read_poly_data(path)[source]

Read poly data from a VTK XML .vtp file.

Raises:
Parameters:

path (str | PathLike[str])

Return type:

vtkPolyData

kneemesh.disk.write_poly_data(poly_data, path)[source]

Write poly data to a VTK XML .vtp file, overwriting any existing file.

Raises:
  • ValueError – If the suffix is not .vtp.

  • OSError – If the file cannot be written.

Parameters:
Return type:

None

kneemesh.disk.read_brep(path)[source]

Read a B-rep from an Open Cascade .brep file.

Raises:
Parameters:

path (str | PathLike[str])

Return type:

BRep

kneemesh.disk.write_brep(brep, path)[source]

Write a B-rep to an Open Cascade .brep file, overwriting any existing file.

Raises:
  • ValueError – If the suffix is not .brep.

  • OSError – If the file cannot be written.

Parameters:
Return type:

None

kneemesh.disk.read_surface(path)[source]

Read a triangulated surface, such as a bone’s, from a .stl file, merging coincident points.

Raises:
Parameters:

path (str | PathLike[str])

Return type:

vtkPolyData

kneemesh.disk.write_surface(surface, path)[source]

Write a triangulated surface to a binary .stl file, overwriting any existing file.

Raises:
  • ValueError – If the suffix is not .stl.

  • OSError – If the file cannot be written.

Parameters:
Return type:

None

kneemesh.disk.write_mesh(mesh, path)[source]

Write a mesh, overwriting any existing file: with its sets as .vtu or .vtkhdf, or in another format gmsh infers from the extension.

.vtu and .vtkhdf are written as write_meshes writes one structure, with set names as they are. gmsh’s formats include .msh, .vtk, .inp, .unv, .bdf, .med, .mesh, and .su2, and .stl for meshes of triangles; they hold the elements only, without faces or sets.

Raises:
  • ValueError – If gmsh does not recognize the extension.

  • OSError – If the file cannot be written.

Parameters:
Return type:

None

kneemesh.disk.write_meshes(meshes, path)[source]

Write several structures’ meshes as one, overwriting any existing file, as .vtu or .vtkhdf.

Nodes and elements are numbered from 1 through the structures in order, each structure’s elements before its faces, and each structure’s sets are named “<structure>_<set>”, such as “femur_surface”. Every node and element carries its number, as “node_id” and “element_id”, and every element and face its quality metrics in Mesh.quality as cell arrays by name, NaN where a metric does not apply.

  • .vtu: one unstructured grid of every element and face, with a “structure” cell array indexing the field array “structures”, and a point array per node set and a cell array per element set, 1 for members.

  • .vtkhdf: a multiblock with a block per structure, by name, as one structure’s .vtkhdf: an “elements” grid of its elements, and “surfaces” and “node_sets” blocks holding a grid per set, named “<structure>_<set>”, of the set’s faces or of vertices at its nodes. Every grid’s “node_id” numbers the same node at the same coordinates.

Raises:
  • ValueError – If the extension is not .vtu or .vtkhdf, or no meshes are given.

  • OSError – If the file cannot be written.

Parameters:
Return type:

None

Configuration models and parsing them from JSON.

class kneemesh.config.BaseConfig[source]

Bases: BaseModel

Base class for configuration models.

Unknown fields are rejected so that misspelled options fail at load time instead of being silently ignored.

model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

classmethod from_json(path)[source]

Parse and validate a configuration from a JSON file.

Parameters:

path (str | PathLike[str])

Return type:

Self

kneemesh.config.Structure

Names of the knee structures. Keys of labels, label_maps, and breps must be among them, and each picks its pipeline.

alias of Literal[‘lateral_meniscus’, ‘medial_meniscus’, ‘patellar_cartilage’, ‘femoral_cartilage’, ‘lateral_tibial_cartilage’, ‘medial_tibial_cartilage’, ‘femur’, ‘tibia’, ‘patella’]

kneemesh.config.BONES: dict[Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'], Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella']] = {'femoral_cartilage': 'femur', 'lateral_tibial_cartilage': 'tibia', 'medial_tibial_cartilage': 'tibia', 'patellar_cartilage': 'patella'}

The bone under each cartilage, which must be in the same segmentation to orient it.

kneemesh.config.BONE_STRUCTURES: tuple[Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'], ...] = ('femur', 'tibia', 'patella')

The bones, whose geometry is a triangulated surface rather than a B-rep, meshed with their own element types.

kneemesh.config.STRUCTURE_SECTIONS: dict[Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'], str] = {'femoral_cartilage': 'femoral_cartilage', 'femur': 'femur', 'lateral_meniscus': 'meniscus', 'lateral_tibial_cartilage': 'cartilage', 'medial_meniscus': 'meniscus', 'medial_tibial_cartilage': 'cartilage', 'patella': 'patella', 'patellar_cartilage': 'cartilage', 'tibia': 'tibia'}

The section of the B-rep and mesh configurations whose settings each structure takes, unless it has its own (OWN_SECTION_STRUCTURES).

kneemesh.config.CARTILAGE_STRUCTURES: tuple[Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'], ...] = ('patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage')

The cartilages, which overclosure removal never moves for a meniscus or bone, only for each other.

kneemesh.config.DEFAULT_OVERCLOSURE_PRIORITY: tuple[Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'], ...] = ('patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'lateral_meniscus', 'medial_meniscus', 'femur', 'tibia', 'patella')

cartilage, then the menisci, then the bones.

Type:

Default order in which overclosure removal keeps structures in place

kneemesh.config.OWN_SECTION_STRUCTURES: tuple[Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'], ...] = ('lateral_meniscus', 'medial_meniscus', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'patellar_cartilage')

a section named for the structure.

Type:

The structures that share a section, meniscus or cartilage, and can have their own instead

kneemesh.config.ElementType

8-node, 20-node serendipity, or 27-node hexahedra, or 4- or 10-node tetrahedra.

Type:

Element shape and node count

alias of Literal[‘hex8’, ‘hex20’, ‘hex27’, ‘tet4’, ‘tet10’]

kneemesh.config.BoneElementType

3- or 6-node triangles or 4-, 8-, or 9-node quadrilaterals on its surface, or 4- or 10-node tetrahedra.

Type:

A bone’s element shape and node count

alias of Literal[‘tri3’, ‘tri6’, ‘quad4’, ‘quad8’, ‘quad9’, ‘tet4’, ‘tet10’]

class kneemesh.config.LabelMapAssembly(*, label_maps=None, interpolator='label_gaussian', padding=4, output=PosixPath('label_map.nrrd'))[source]

Bases: BaseConfig

Settings for assembling single-label LabelMaps into one multilabel LabelMap.

Structures get label values 1, 2, … in the order of label_maps.

Parameters:
  • label_maps (Annotated[dict[Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'], ~pathlib.Path] | None, ~pydantic.functional_validators.BeforeValidator(func=~kneemesh.config._json_from_text, json_schema_input_type=PydanticUndefined)])

  • interpolator (Interpolator)

  • padding (int)

  • output (Path)

model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class kneemesh.config.SurfaceBrep(*, sigma=None, level=0.0, smoothing_iterations=50, smoothing_pass_band=0.001)[source]

Bases: BaseConfig

Settings shared by every structure for extracting a smooth surface from its label.

Parameters:
model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

kneemesh.config.DEFAULT_INNER_CLIP_RATIO = 0.25

Default height of the cut off the meniscus’s thin inner edge for swept hexahedra, as a fraction of its sections’ mean greatest height.

type kneemesh.config.MeniscusHexDesign = Literal['swept_quads', 'butterfly']

The solid a meniscus’s hexahedra are made from: the lofted solid to sweep quadrilaterals through, or five butterfly blocks.

class kneemesh.config.MeniscusBrep(*, sigma=None, level=0.0, smoothing_iterations=50, smoothing_pass_band=0.001, spacing=5.0, points_per_slice=32, spline_order=3, cap='planar', cap_offset=None, hex_blocks=False, inner_clip_height=None, inner_clip_ratio=None, groove_ratio=0.25, hex_design='butterfly')[source]

Bases: SurfaceBrep

Settings for building the lateral and medial meniscus B-reps, with the defaults of each step.

Parameters:
property resolved_inner_clip_ratio: float

DEFAULT_INNER_CLIP_RATIO for swept_quads hex_blocks and 0 otherwise.

Type:

inner_clip_ratio, or its default

model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class kneemesh.config.CartilageBrep(*, sigma=None, level=0.0, smoothing_iterations=50, smoothing_pass_band=0.001, side_cosine=0.3, perimeter_radius=None, perimeter_inset=0.0, min_thickness=None, hole_thickness=0.05, hex_blocks=False)[source]

Bases: SurfaceBrep

Settings for building the B-reps of the lateral and medial tibial and the patellar cartilage, with the defaults of each step.

Each is a sheet over the plane normal to its thinnest direction, between its articular side and the side against its bone, within a smooth perimeter. Defaults left as None depend on hex_blocks. Either way the B-rep is one solid, which hexahedral meshing partitions itself.

Parameters:
property resolved_perimeter_radius: float

perimeter_radius, or its default for hex_blocks.

property resolved_min_thickness: float

min_thickness, or its default for hex_blocks.

property resolved_hole_thickness: float

hole_thickness, or 0 for hex_blocks.

model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class kneemesh.config.FemoralCartilageBrep(*, sigma=None, level=0.0, smoothing_iterations=50, smoothing_pass_band=0.001, side_cosine=0.3, perimeter_radius=None, perimeter_inset=0.0, min_thickness=None, hole_thickness=0.05, hex_blocks=False)[source]

Bases: CartilageBrep

Settings for building the femoral cartilage’s B-rep, with the defaults of each step.

It is a sheet over the cylinder its bone side wraps, unrolled into a U-shaped domain, between its articular side and the side against the femur. Defaults left as None depend on hex_blocks, as for the other cartilage.

Parameters:
model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class kneemesh.config.BoneBrep(*, sigma=None, level=0.0, smoothing_iterations=50, smoothing_pass_band=0.001, shaft_cut_fraction=0.0, triangle_size=1.0, output='.stl')[source]

Bases: SurfaceBrep

Settings for building a bone’s surface, with the defaults of each step: the femur, tibia, and patella each have a section.

A bone’s geometry is not a B-rep but its closed, triangulated surface, written as .stl: the isocontour of its label with cavities filled, smoothed, and decimated. gmsh reparametrizes it when meshing.

Parameters:
model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class kneemesh.config.StructureMesh(*, min_size=None, max_size=None, elements_per_circle=0, algorithm_2d=Algorithm2D.FRONTAL_DELAUNAY, algorithm_3d=Algorithm3D.DELAUNAY, optimize=False, laplacian_iterations=10, optimization_iterations=200, surface_deviation=0.1, surface_travel=0.5, feature_angle=30.0, preserve_volume=True, aspect_weight=0.0, warp_weight=0.0)[source]

Bases: BaseConfig

Settings shared by every structure for tetrahedral meshing and for optimizing hexahedral meshes.

Parameters:
model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

kneemesh.config.DEFAULT_MENISCUS_ASPECT_WEIGHT = 0.02

Default weight of the squared Frobenius aspect ratios when optimizing meniscus hexahedra.

kneemesh.config.DEFAULT_MENISCUS_WARP_WEIGHT = 50.0

Default weight of the surface quadrilaterals’ warp when optimizing meniscus hexahedra.

class kneemesh.config.MeniscusMesh(*, min_size=None, max_size=None, elements_per_circle=0, algorithm_2d=Algorithm2D.FRONTAL_DELAUNAY, algorithm_3d=Algorithm3D.DELAUNAY, optimize=True, laplacian_iterations=10, optimization_iterations=200, surface_deviation=0.1, surface_travel=0.5, feature_angle=30.0, preserve_volume=True, aspect_weight=0.02, warp_weight=50.0, transverse_size=1.0, circumferential_size=2.0)[source]

Bases: StructureMesh

Settings for meshing the lateral and medial meniscus B-reps, with the defaults of each meshing function.

Hexahedral element types need B-reps with planar caps, which hex_blocks gives: a lofted solid is swept with unstructured quadrilaterals, and butterfly blocks are meshed with structured hexahedra (see hex_design).

Parameters:
model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

kneemesh.config.DEFAULT_CARTILAGE_ASPECT_WEIGHT = 0.5

Default weight of the squared Frobenius aspect ratios when optimizing cartilage hexahedra.

kneemesh.config.DEFAULT_CARTILAGE_ELEMENT_SIZE = 2.0

Default size of cartilage hexahedra along the sheet, in physical units.

class kneemesh.config.CartilageMesh(*, min_size=None, max_size=None, elements_per_circle=0, algorithm_2d=Algorithm2D.FRONTAL_DELAUNAY, algorithm_3d=Algorithm3D.DELAUNAY, optimize=False, laplacian_iterations=10, optimization_iterations=200, surface_deviation=0.1, surface_travel=0.5, feature_angle=30.0, preserve_volume=True, aspect_weight=0.5, warp_weight=0.0, element_size=2.0, elements_through=3, quad_algorithm='quasi_structured', save_partition=False)[source]

Bases: StructureMesh

Settings for meshing the B-reps of the lateral and medial tibial and the patellar cartilage.

Hexahedra are a quadrilateral mesh of one side of the sheet, stacked elements_through deep along straight columns to the other side.

Parameters:
model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class kneemesh.config.FemoralCartilageMesh(*, min_size=None, max_size=None, elements_per_circle=0, algorithm_2d=Algorithm2D.FRONTAL_DELAUNAY, algorithm_3d=Algorithm3D.DELAUNAY, optimize=False, laplacian_iterations=10, optimization_iterations=200, surface_deviation=0.1, surface_travel=0.5, feature_angle=30.0, preserve_volume=True, aspect_weight=0.5, warp_weight=0.0, element_size=2.0, elements_through=3, quad_algorithm='quasi_structured', save_partition=False)[source]

Bases: CartilageMesh

Settings for meshing the femoral cartilage’s B-rep.

Hexahedra are made as for the other cartilage, and tetrahedra default to element_size.

Parameters:
property resolved_max_size: float

max_size, or element_size.

model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class kneemesh.config.OverclosureBrep(*, enabled=False, clearance=0.0, priority=<factory>)[source]

Bases: BaseConfig

Settings for removing overclosure: moving built structures apart where their geometry overlaps.

After every structure is built, each is moved out of the structures that rank above it in priority. Cartilage is thin, so it ranks above every meniscus and bone and never moves for them. Where two cartilages overlap, both articular sides are lowered toward their bones, each by its share of the two local thicknesses, whatever their order. A meniscus moves its contour points out within their slice planes and is lofted again, keeping its caps and hexahedral blocks; a bone moves its surface’s vertices.

Parameters:
  • enabled (bool)

  • clearance (float)

  • priority (Annotated[list[Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella']], ~pydantic.functional_validators.BeforeValidator(func=~kneemesh.config._json_from_text, json_schema_input_type=PydanticUndefined)])

model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class kneemesh.config.LabelMapBrep(*, label_map=None, labels=None, label_maps=None, interpolator='label_gaussian', padding=4, assembled_label_map=None, output='.brep', output_directory=PosixPath('.'), meniscus=<factory>, cartilage=<factory>, lateral_meniscus=None, medial_meniscus=None, lateral_tibial_cartilage=None, medial_tibial_cartilage=None, patellar_cartilage=None, femoral_cartilage=<factory>, femur=<factory>, tibia=<factory>, patella=<factory>, overclosure=<factory>)[source]

Bases: _StructureSections

Settings for building a B-rep of every structure in a segmented LabelMap.

The segmentation is either one multilabel LabelMap, label_map, with labels naming its values, or several single-label LabelMaps, label_maps, that are assembled onto one grid. Give one or the other. Each structure named in labels or label_maps is built by its own pipeline, with the settings of its section such as meniscus, or its own such as lateral_meniscus, and written to <output_directory>/<structure><output>. Bones, including those named only to orient their cartilage, are written as surfaces with their own section’s output, such as femur.output, instead.

Parameters:
  • label_map (Annotated[Path | None, BeforeValidator(func=~kneemesh.config._none_from_text, json_schema_input_type=PydanticUndefined)])

  • labels (Annotated[dict[Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'], int] | None, ~pydantic.functional_validators.BeforeValidator(func=~kneemesh.config._json_from_text, json_schema_input_type=PydanticUndefined)])

  • label_maps (Annotated[dict[Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'], ~pathlib.Path] | None, ~pydantic.functional_validators.BeforeValidator(func=~kneemesh.config._json_from_text, json_schema_input_type=PydanticUndefined)])

  • interpolator (Interpolator)

  • padding (int)

  • assembled_label_map (Annotated[Path | None, BeforeValidator(func=~kneemesh.config._none_from_text, json_schema_input_type=PydanticUndefined)])

  • output (str)

  • output_directory (Path)

  • meniscus (MeniscusBrep)

  • cartilage (CartilageBrep)

  • lateral_meniscus (MeniscusBrep | None)

  • medial_meniscus (MeniscusBrep | None)

  • lateral_tibial_cartilage (CartilageBrep | None)

  • medial_tibial_cartilage (CartilageBrep | None)

  • patellar_cartilage (CartilageBrep | None)

  • femoral_cartilage (FemoralCartilageBrep)

  • femur (BoneBrep)

  • tibia (BoneBrep)

  • patella (BoneBrep)

  • overclosure (OverclosureBrep)

property structures: tuple[Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'], ...]

The structures named in labels or label_maps, in order, or none if neither is given.

output_path(structure)[source]

The B-rep file to write for structure, or the surface file for a bone.

Parameters:

structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

Return type:

Path

bone(structure)[source]

The settings of a bone: femur, tibia, or patella.

Parameters:

structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

Return type:

BoneBrep

model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class kneemesh.config.BoneMesh(*, element_type='tri3', element_size=2.0, cortical_element_size=1.0, cortical_distance=3.0, cancellous_grad=0.5, max_size=4.0, algorithm_2d=Algorithm2D.FRONTAL_DELAUNAY, algorithm_3d=Algorithm3D.DELAUNAY)[source]

Bases: BaseConfig

Settings for meshing a bone’s surface, which gmsh reparametrizes: the femur, tibia, and patella each have a section.

Bones are meshed on their surface with triangles or quadrilaterals, or through their volume with tetrahedra, by their own element_type; the mesh’s element_type does not apply to them. Bones are not meshed with hexahedra.

Parameters:
property element_shape: Literal['triangle', 'quadrilateral', 'tetrahedral']

The shape of element_type.

property element_order: int

The polynomial order of element_type.

property second_order_incomplete: bool

Whether element_type omits the middle node of second-order quadrilaterals.

model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class kneemesh.config.BrepMesh(*, breps=None, element_type='tet4', element_types=None, output='_{element_type}.msh', output_directory=PosixPath('.'), assembled_mesh=None, meniscus=<factory>, cartilage=<factory>, lateral_meniscus=None, medial_meniscus=None, lateral_tibial_cartilage=None, medial_tibial_cartilage=None, patellar_cartilage=None, femoral_cartilage=<factory>, femur=<factory>, tibia=<factory>, patella=<factory>)[source]

Bases: _StructureSections

Settings for meshing the B-rep of each structure.

Each structure in breps is meshed by its own pipeline, with the settings of its section such as meniscus, or its own such as lateral_meniscus, and written to <output_directory>/<structure><output>. Bones are meshed from their surfaces with their own section’s element_type, such as femur.element_type. Every other structure takes element_type unless element_types gives it its own, and the element_shape, element_order, and second_order_incomplete properties describe element_type itself; use for_structure for a structure’s settings.

Parameters:
  • breps (Annotated[dict[Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'], ~pathlib.Path] | None, ~pydantic.functional_validators.BeforeValidator(func=~kneemesh.config._json_from_text, json_schema_input_type=PydanticUndefined)])

  • element_type (Literal['hex8', 'hex20', 'hex27', 'tet4', 'tet10'])

  • element_types (Annotated[dict[Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'], ~typing.Literal['hex8', 'hex20', 'hex27', 'tet4', 'tet10']] | None, ~pydantic.functional_validators.BeforeValidator(func=~kneemesh.config._json_from_text, json_schema_input_type=PydanticUndefined)])

  • output (str)

  • output_directory (Path)

  • assembled_mesh (Annotated[Path | None, BeforeValidator(func=~kneemesh.config._none_from_text, json_schema_input_type=PydanticUndefined)])

  • meniscus (MeniscusMesh)

  • cartilage (CartilageMesh)

  • lateral_meniscus (MeniscusMesh | None)

  • medial_meniscus (MeniscusMesh | None)

  • lateral_tibial_cartilage (CartilageMesh | None)

  • medial_tibial_cartilage (CartilageMesh | None)

  • patellar_cartilage (CartilageMesh | None)

  • femoral_cartilage (FemoralCartilageMesh)

  • femur (BoneMesh)

  • tibia (BoneMesh)

  • patella (BoneMesh)

model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

structure_element_type(structure)[source]

The element type of a structure other than a bone: its entry in element_types, or element_type.

Parameters:

structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

Return type:

Literal[‘hex8’, ‘hex20’, ‘hex27’, ‘tet4’, ‘tet10’]

for_structure(structure)[source]

These settings with element_type set to the structure’s own, so element_shape and the other properties describe it.

Parameters:

structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

Return type:

Self

property element_shape: Literal['tetrahedral', 'hexahedral']

The shape of element_type.

property element_order: int

The polynomial order of element_type.

property second_order_incomplete: bool

Whether element_type omits face and interior nodes.

property output_suffix: str

output with its {element_type} placeholder replaced.

output_path(structure)[source]

The mesh file to write for structure, named with its own element type, a bone’s from its section.

Parameters:

structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

Return type:

Path

bone(structure)[source]

The settings of a bone: femur, tibia, or patella.

Parameters:

structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

Return type:

BoneMesh

partition_path(structure)[source]

The B-rep of a sheet’s hexahedral partition to write for structure, with save_partition.

Parameters:

structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

Return type:

Path

Command-line pipelines for assembling segmentations, building B-reps of knee structures, and meshing them.

kneemesh.pipeline.run_brep(config)[source]

Build a B-rep of every structure in config’s segmentation and write each to config.output_path(structure).

Each structure’s name picks its pipeline. A bone’s geometry is its triangulated surface rather than a B-rep. Each output is written as soon as it is built, or with config.overclosure.enabled, once every structure is built and overlapping ones are moved apart (overclosure.resolve_overclosure).

Returns:

The B-rep of each structure, or the surface of each bone.

Raises:

ValueError – If config gives no segmentation, or it cannot be read or combined.

Parameters:

config (LabelMapBrep)

Return type:

dict[Literal[‘lateral_meniscus’, ‘medial_meniscus’, ‘patellar_cartilage’, ‘femoral_cartilage’, ‘lateral_tibial_cartilage’, ‘medial_tibial_cartilage’, ‘femur’, ‘tibia’, ‘patella’], ~kneemesh.brep.BRep | ~vtkmodules.vtkCommonDataModel.vtkPolyData]

kneemesh.pipeline.build_structure(segmentation, structure, config)[source]

Build one structure’s B-rep, or a bone’s surface, from a segmentation and write it to config.output_path(structure).

The segmentation must name the structure, and a cartilage’s bone too. config’s own labels and label_maps are not read.

Raises:

ValueError – If the segmentation lacks the structure or its bone, or the geometry cannot be built.

Parameters:
  • segmentation (Segmentation)

  • structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

  • config (LabelMapBrep)

Return type:

BRep | vtkPolyData

kneemesh.pipeline.build_adjustable(segmentation, structure, config)[source]

Build one structure as build_structure does, writing it, and return it with what it was built from, for resolve_overclosure.

Raises:

ValueError – If the segmentation lacks the structure or its bone, or the geometry cannot be built.

Parameters:
  • segmentation (Segmentation)

  • structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

  • config (LabelMapBrep)

Return type:

Adjustable

kneemesh.pipeline.meniscus_loft(config)[source]

Return what lofts a meniscus’s contours into its B-rep with a section’s settings, as the pipeline builds it.

Parameters:

config (MeniscusBrep)

Return type:

Callable[[list[ContourSlice]], BRep]

kneemesh.pipeline.run_mesh(config)[source]

Mesh the B-rep of every structure in config.breps, or a bone’s surface, and write each to config.output_path(structure).

Each structure’s name picks its pipeline, and each mesh is written as soon as it is made. With config.assembled_mesh, all of them are then written there as one, renumbered (disk.write_meshes).

Returns:

The mesh of each structure.

Raises:
  • ValueError – If config gives no breps, or a file is not a B-rep or surface.

  • OSError – If a file cannot be read.

Parameters:

config (BrepMesh)

Return type:

dict[Literal[‘lateral_meniscus’, ‘medial_meniscus’, ‘patellar_cartilage’, ‘femoral_cartilage’, ‘lateral_tibial_cartilage’, ‘medial_tibial_cartilage’, ‘femur’, ‘tibia’, ‘patella’], ~kneemesh.tet_meshing.Mesh]

kneemesh.pipeline.run_assembly(config)[source]

Assemble config’s single-label LabelMaps and write the result and its labels to config.output.

Raises:

ValueError – If config gives no label_maps, or they cannot be read or combined.

Parameters:

config (LabelMapAssembly)

Return type:

Segmentation

kneemesh.pipeline.load_segmentation(config)[source]

Read the multilabel LabelMap config names, or assemble its single-label LabelMaps.

An assembled segmentation is also written to config.assembled_label_map when that is set.

Raises:

ValueError – If config gives neither label_map nor label_maps, or a LabelMap cannot be read or combined.

Parameters:

config (LabelMapBrep)

Return type:

Segmentation

class kneemesh.pipeline.Configuration(config, source, saved)[source]

Bases: NamedTuple, Generic

A pipeline’s configuration and the files it came from and was saved to.

Parameters:
  • config (ConfigType)

  • source (Path | None)

  • saved (Path | None)

config: ConfigType

Alias for field number 0

source: Path | None

Alias for field number 1

saved: Path | None

Alias for field number 2

kneemesh.pipeline.configure(config_type, description, argv=None, timestamp=None)[source]

Build a configuration from command-line options, an optional JSON file, and overrides.

Every field of the configuration is an option, such as –points-per-slice for points_per_slice. A field holding another configuration, a section such as meniscus, gives an option for each of its fields, such as –meniscus.points-per-slice. Values given on the command line override those in –config, field by field within sections. The configuration is saved so the run can be repeated: as settings<timestamp>.json in the working directory when there is no –config, or as <config stem>_modified.json beside the file when overrides change it. A config file used without overrides is not copied.

Parameters:
  • config_type (type[ConfigType]) – Configuration model of the command.

  • description (str) – Description for the command’s help.

  • argv (Sequence[str] | None) – Command-line arguments, by default sys.argv[1:].

  • timestamp (str | None) – Timestamp for the settings file name, by default the current time.

Returns:

The configuration, the –config file if any, and the path the configuration was saved to, or None if it was not saved.

Return type:

Configuration

kneemesh.pipeline.assemble_main(argv=None)[source]

Run the LabelMap assembly pipeline from the command line.

Parameters:

argv (Sequence[str] | None)

Return type:

int

kneemesh.pipeline.brep_main(argv=None)[source]

Run the B-rep pipeline from the command line.

Parameters:

argv (Sequence[str] | None)

Return type:

int

kneemesh.pipeline.mesh_main(argv=None)[source]

Run the meshing pipeline from the command line.

Parameters:

argv (Sequence[str] | None)

Return type:

int

Meniscus

B-rep generation for the meniscus, a curved tube lofted through sections normal to its centerline.

kneemesh.geo.meniscus.DEFAULT_GROOVE_RATIO = 0.25

Default depth, as a fraction of their width, up to which a section’s concavities are filled in as noise (see slice_isocontour).

kneemesh.geo.meniscus.centerline(label_map, label=1)[source]

Fit a smooth curve through the centers of a label’s cross-sections.

BinaryThinning only thins in 2D, so the label is projected along the image axis closest to its thinnest direction and the longest path through that skeleton gives a first estimate of the curve. The curve is then repeatedly moved onto the centroids of the label’s cross-sections normal to it.

Parameters:
  • label_map (Image) – 3D LabelMap of sitkUInt8, sitkUInt16, or sitkInt16 pixels.

  • label (int) – Value of the structure to fit.

Returns:

A cubic B-spline over u in [0, 1]. Evaluating it at N parameters gives an (N, 3) array of physical points. Which end of the structure is u = 0 is unspecified.

Raises:

ValueError – If the image is not a 3D LabelMap of an accepted pixel type, or the label is absent or too small to fit.

Return type:

BSpline

kneemesh.geo.meniscus.slice_isocontour(mesh, curve, spacing, points_per_slice=32, clip_height=None, clip_ratio=0.0, groove_ratio=0.25)[source]

Slice a mesh with planes normal to a curve at uniform arc-length spacing.

Slices are spaced exactly spacing apart along the curve, with any remainder split equally between its two ends, and are ordered along the curve from u = 0. Each cut is resampled to ordered points with a closed Kochanek spline: the section’s corners, tracked through the slices by their turning, at the same point indices on every slice, and points evenly spaced between them (_follow_corners). Slices are removed from either end of the curve until one encloses at least 20% of the average area.

Where the curve bends more tightly than the section is wide, or kinks, planes normal to it would cut through their neighbors’ contours, and a loft through them folds. There the planes are tilted apart, their centers staying on the curve, until every contour lies at least a quarter of the spacing in front of the plane before it and behind the plane after it (_separate_planes).

In-plane axes are defined from the curve’s best-fit plane, so they do not twist along a roughly planar curve.

With clip_height or clip_ratio, each section’s thin inner edge, its sharpest corner, is cut off straight where the section first reaches that height, measured across the direction from its centroid to the corner (see _clip_inner_edges). The contour is then its curved part, from one corner of the cut to the other, and a straight run back.

Shallow concavities of each section, grooves the smoothed surface keeps from the label, are treated as noise and filled in toward the section’s convex hull before corners are tracked (_fill_grooves): fully up to groove_ratio of their width deep, fading out at twice that.

Parameters:
  • mesh (vtkPolyData) – Closed surface from extract_isocontour or smooth_isocontour.

  • curve (BSpline) – Curve from centerline.

  • spacing (float) – Arc-length distance between slices, in physical units.

  • points_per_slice (int) – Number of points on each contour.

  • clip_height (float | None) – Height in physical units at which to cut off the sections’ thin inner edges, or None to use clip_ratio.

  • clip_ratio (float) – Height at which to cut off the sections’ thin inner edges, as a fraction of the mean of the sections’ greatest heights, those of their outer sides. 0 keeps the inner edges.

  • groove_ratio (float) – Depth, as a fraction of its width, up to which a section’s concavity is filled in to the section’s convex hull, and partly filled up to twice that. 0 keeps every concavity.

Returns:

The retained ContourSlices.

Raises:

ValueError – If spacing is not positive, points_per_slice is below 3, a clipping height or ratio or groove_ratio is negative, or a retained plane does not cut the mesh in a closed contour.

Return type:

list[ContourSlice]

kneemesh.geo.meniscus.contours_to_brep(slices, spline_order=3, cap='none', cap_offset=None)[source]

Loft a B-spline surface through contour slices, optionally capping its ends.

Each contour becomes a periodic B-spline through all of its points, at parameters shared by every contour, and the surface interpolates those curves in the order given, at parameters proportional to the distance between slice centers. Without caps it spans only the first to last slice.

Parameters:
  • slices (list[ContourSlice]) – Contours from slice_isocontour, in order along the curve.

  • spline_order (int) – Polynomial degree of the contour splines. The degree along the curve is at most 3. 3 is cubic, and 1 gives a ruled surface.

  • cap (Literal['none', 'planar', 'smooth']) – How to close the two ends. “none” leaves an open surface. “planar” closes each end with a flat face in its slice’s plane. “smooth” closes each with a convex dome converging to one point. Either cap produces a closed solid.

  • cap_offset (float | None) – For smooth caps, how far each apex lies beyond its slice’s center along the curve, in physical units. By default, a quarter of the radius of a circle with the end slice’s area.

Returns:

The lofted shape.

Raises:

ValueError – If there are fewer than 2 slices, spline_order is outside 1 to 25, a contour has too few points for spline_order, contours have unequal point counts, cap is unknown, or cap_offset is not positive.

Return type:

BRep

kneemesh.geo.meniscus.contours_to_hex_blocks(slices, spline_order=3)[source]

Build a planar-capped solid from contour slices as five blocks for hexahedral meshing.

The section is split with a butterfly (O-grid) partition: an inner quadrilateral surrounded by four blocks, one for each of four arcs of the boundary. Every boundary point meets a spoke running inward, so the cells along the boundary stay close to square even at its sharp corners. A partition that puts block corners at those corners instead gives cells there the corner’s angle, or nearly 180 degrees where smoothing rounds it.

The four split points divide each contour into arcs of equal length, rotated to keep them as far as possible from the sharpest turns averaged over all slices. Straight spokes run from each split point to a corner of the inner quadrilateral, partway toward the section’s centroid.

The blocks’ faces are B-spline surfaces interpolating the slices with a knot vector shared by every face along the curve, so neighboring faces meet exactly. contours_to_brep builds its surface the same way, but at shared contour parameters rather than split at the block corners, so the two differ slightly.

Parameters:
  • slices (list[ContourSlice]) – Contours from slice_isocontour, in order along the curve, all with the same number of points.

  • spline_order (int) – Polynomial degree of the section curves. The degree along the curve is at most 3.

Returns:

A solid of five blocks, for hexahedral_mesh.

Raises:

ValueError – If there are fewer than 2 slices, spline_order is outside 1 to 25, a contour has too few points for spline_order or fewer than 8, or contours have unequal point counts.

Return type:

BRep

Hexahedral meshing of the meniscus, swept or in butterfly blocks, and the meniscus’s named sets of faces.

hexahedral_mesh takes either B-rep a meniscus’s hexahedra are made from:

  • The lofted solid with planar caps (geo.meniscus.contours_to_brep). One cross-section is meshed with unstructured quadrilaterals (gmsh’s Frontal-Delaunay for quads), and its nodes are mapped onto stations evenly spaced along the loft and joined into hexahedra.

  • The five-block butterfly solid (geo.meniscus.contours_to_hex_blocks), whose blocks are meshed with structured, transfinite hexahedra.

Both meshes of a meniscus have the sets “anterior_horn”, “posterior_horn”, and “body” besides “surface” (mesh_sets): the faces on the caps at either end and on the rest of its surface.

kneemesh.mesh.meniscus.hexahedral_mesh(brep, transverse_size=1.0, circumferential_size=2.0, element_order=1, second_order_incomplete=False)[source]

Mesh a meniscus’s lofted solid with swept hexahedra, or its butterfly blocks with structured ones.

Elements are about transverse_size across the meniscus’s cross-section and circumferential_size along it, its length measured through the sections’ centroids.

A solid of one lofted face and two planar caps, as geo.meniscus.contours_to_brep makes with planar caps, is swept: its middle cross-section is meshed with quadrilaterals of transverse_size, and the section’s nodes are mapped onto stations evenly spaced in length along the loft (see _swept_layers). These hexahedra can start inverted, so optimize them (mesh_optimization.optimize_hexahedral_mesh).

A solid of six-sided blocks with planar caps, such as the five blocks from geo.meniscus.contours_to_hex_blocks, is meshed with transfinite surfaces and volumes: each edge on the caps gets a quarter of the middle section’s perimeter over transverse_size, and the edges running between the caps the length over circumferential_size, so each block is a grid of quadrilaterals swept along the solid.

Parameters:
  • brep (BRep) – A meniscus’s lofted solid with planar caps, or its butterfly blocks.

  • transverse_size (float) – Target length of the elements’ edges across the meniscus.

  • circumferential_size (float) – Target length of the elements’ edges along the meniscus.

  • element_order (int) – Polynomial order of the elements. 2 gives 27-node hexahedra.

  • second_order_incomplete (bool) – Omit face and interior nodes from high-order elements, giving 20-node instead of 27-node second-order hexahedra.

Returns:

The hexahedral mesh.

Raises:

ValueError – If a size is not positive, element_order is out of range, or brep is neither a lofted solid with planar caps nor a solid of six-sided blocks with planar caps.

Return type:

Mesh

kneemesh.mesh.meniscus.ANTERIOR_HORN = 'anterior_horn'

Name of a meniscus mesh’s set of the faces on the cap at its anterior end, and of their nodes.

kneemesh.mesh.meniscus.POSTERIOR_HORN = 'posterior_horn'

Name of a meniscus mesh’s set of the faces on the cap at its posterior end, and of their nodes.

kneemesh.mesh.meniscus.BODY = 'body'

Name of a meniscus mesh’s set of the faces on its surface between the horns’ caps, and of their nodes.

kneemesh.mesh.meniscus.meniscus_face_groups()[source]

Name the current model’s meniscus faces, for tet_meshing.tetrahedral_mesh’s face_groups: its horns’ caps and its body.

The caps are the planar boundary faces, as on hexahedral blocks and planar-capped solids, or, with smooth caps, every boundary face but the largest, the loft. Caps sharing curves make one horn. The anterior horn is the one at lower y: SimpleITK’s physical space is LPS, so y grows toward the patient’s back.

Raises:

ValueError – If the caps do not form two horns.

Return type:

dict[str, list[int]]

Tibial and patellar cartilage

B-rep generation for cartilage sheets, the lateral and medial tibial and the patellar cartilage.

Each sheet is a pair of height fields over a two-dimensional domain: its articular side above and the side against its bone below, within one smooth perimeter in that domain. A frame maps domain points and heights to physical points. For these cartilages it is the plane normal to the sheet’s thinnest principal direction; the femoral cartilage uses the same machinery over a cylinder (geo.femur). Straight walls join the two sides at the perimeter, tilted out of the height lines so they meet both sides closer to right angles.

kneemesh.geo.sheet.DEFAULT_PERIMETER_RADIUS_HEXAHEDRAL = 3.0

Default smallest radius of curvature, in physical units, of the perimeter of a sheet built for hexahedra.

kneemesh.geo.sheet.DEFAULT_PERIMETER_RADIUS_TETRAHEDRAL = 1.0

Default smallest radius of curvature, in physical units, of the perimeter and hole outlines of a sheet built for tetrahedra.

kneemesh.geo.sheet.DEFAULT_MIN_THICKNESS_HEXAHEDRAL = 0.2

Default minimum thickness of a sheet built for hexahedra, as a fraction of its mean thickness.

kneemesh.geo.sheet.DEFAULT_MIN_THICKNESS_TETRAHEDRAL = 0.1

Default minimum thickness of a sheet built for tetrahedra, as a fraction of its mean thickness.

kneemesh.geo.sheet.DEFAULT_HOLE_THICKNESS = 0.05

Default thickness, as a fraction of the mean, below which a sheet built for tetrahedra gets a hole.

class kneemesh.geo.sheet.SheetFrame[source]

Bases: ABC

Coordinates of a sheet: domain points (s, t) and a height along each domain point’s straight line.

Domain lengths approximate physical lengths, and heights grow from the bone toward the articular side. Turning from s toward t is counterclockwise seen from the articular side.

abstractmethod local(points)[source]

Return the (N, 2) domain points and (N,) heights of (N, 3) physical points.

Parameters:

points (ndarray)

Return type:

tuple[ndarray, ndarray]

abstractmethod physical(domain_points, heights)[source]

Return the (N, 3) physical points at (N, 2) domain points and (N,) heights.

Parameters:
Return type:

ndarray

class kneemesh.geo.sheet.PlaneFrame(origin, axes)[source]

Bases: SheetFrame

A plane: domain point (s, t) and height z give origin + s * axes[0] + t * axes[1] + z * axes[2].

Parameters:
origin

Physical origin of the plane.

Type:

numpy.ndarray

axes

(3, 3) right-handed orthonormal rows: the plane’s s and t axes, and its normal, which points from the bone toward the articular side.

Type:

numpy.ndarray

classmethod fit(sides)[source]

Return the plane through the sides’ points normal to their thinnest principal direction, s along the longest.

Parameters:

sides (CartilageSides)

Return type:

PlaneFrame

local(points)[source]

Return the (N, 2) domain points and (N,) heights of (N, 3) physical points.

Parameters:

points (ndarray)

Return type:

tuple[ndarray, ndarray]

physical(domain_points, heights)[source]

Return the (N, 3) physical points at (N, 2) domain points and (N,) heights.

Parameters:
Return type:

ndarray

class kneemesh.geo.sheet.CylinderFrame(center, axes, radius)[source]

Bases: SheetFrame

A cylinder unrolled: s runs along its axis, t is arc length at a reference radius around it, and heights are distances from the axis.

The physical point at (s, t) and height r is center + s * axes[0] + r * (cos(theta) * axes[1] + sin(theta) * axes[2]), with theta = -t / radius. Heights lines are rays from the axis, so the frame suits a sheet that wraps around a convex bone, as the femoral cartilage wraps the condyles.

Parameters:
center

Physical point on the axis at s = 0.

Type:

numpy.ndarray

axes

(3, 3) right-handed orthonormal rows: the axis, the direction from it of t = 0, and their cross product.

Type:

numpy.ndarray

radius

Reference radius that turns angles into arc lengths.

Type:

float

classmethod fit(sides)[source]

Return the cylinder the bone side’s points wrap, with t = 0 in the middle of the arc they span.

The axis is the direction the bone side’s surface normals, estimated from neighboring points, vary least along, as they all would be normal to the axis on a cylinder. Its position is the center of the circle fitted to the bone side projected along it, and the reference radius the mean distance of both sides’ points from it.

Raises:

ValueError – If the sides wrap all the way around, leaving no gap of at least 30 degrees.

Parameters:

sides (CartilageSides)

Return type:

CylinderFrame

local(points)[source]

Return the (N, 2) domain points and (N,) heights of (N, 3) physical points.

Parameters:

points (ndarray)

Return type:

tuple[ndarray, ndarray]

physical(domain_points, heights)[source]

Return the (N, 3) physical points at (N, 2) domain points and (N,) heights.

Parameters:
Return type:

ndarray

class kneemesh.geo.sheet.HeightField(*args, **kwargs)[source]

Bases: Protocol

Heights over a sheet’s domain, such as a RectBivariateSpline.

ev(xi, yi)[source]

Return the heights at domain points (xi, yi).

Parameters:
Return type:

ndarray

class kneemesh.geo.sheet.LoweredHeights(heights, lowering)[source]

Bases: object

Heights lowered by a spline over the domain, such as an articular side moved off another cartilage (lower_articular).

Parameters:
ev(xi, yi)[source]

Return the heights at domain points (xi, yi), less the lowering.

Parameters:
Return type:

ndarray

class kneemesh.geo.sheet.CartilageSheet(frame, perimeter, holes, articular, bone, mean_thickness, min_thickness, tilt, tilt_reach)[source]

Bases: object

A cartilage sheet as heights of its two sides over a domain, within a perimeter.

Parameters:
frame

Maps domain points and heights to physical points.

Type:

kneemesh.geo.sheet.SheetFrame

perimeter

(N, 2) domain points around the sheet, counterclockwise, without the first repeated.

Type:

numpy.ndarray

holes

(M, 2) domain points around each hole, counterclockwise.

Type:

list[numpy.ndarray]

articular

Height of the articular side over the domain.

Type:

kneemesh.geo.sheet.HeightField

bone

Height of the side against the bone, already lowered where the sheet was thinner than its minimum thickness.

Type:

kneemesh.geo.sheet.HeightField

mean_thickness

Mean thickness along the height lines within the perimeter, before thickening.

Type:

float

min_thickness

The thickness thin regions were raised to.

Type:

float

tilt

How far outward the wall’s articular edge lies from its bone edge in the domain at each perimeter point. Each side’s domain points move half of it along the perimeter’s outward normal, the articular side outward and the bone side inward, fading out at tilt_reach inside the perimeter.

Type:

numpy.ndarray

tilt_reach

How far inside the perimeter the tilt fades out.

Type:

float

points(domain_points, side)[source]

Return the physical points on a side, “articular” or “bone”, over (…, 2) domain points, moved by half the tilt near the perimeter.

Parameters:
Return type:

ndarray

tilted(domain_points, side)[source]

Return (N, 2) domain points of a side, moved along the perimeter’s outward normal by half the tilt, out for the articular side and in for the bone side.

The move fades as the square of the distance from the perimeter, out to tilt_reach inside it, at the nearest point of the perimeter. Outside, the same square of the signed distance continues to grow, up to four times the tilt at tilt_reach, so a side’s surface, which reaches past the perimeter to be trimmed, has no crease along it.

Parameters:
Return type:

ndarray

property area: float

The domain area inside the perimeter, less the holes.

thickness(domain_points)[source]

Return the thickness along the height lines at (N, 2) domain points.

Parameters:

domain_points (ndarray)

Return type:

ndarray

covers(domain_points, margin=0.0)[source]

Return which of (N, 2) domain points lie inside the perimeter and outside the holes, or within margin of the perimeter.

Parameters:
Return type:

ndarray

kneemesh.geo.sheet.surface_grid(sheet)[source]

Return the s and t coordinates of the domain grid each side’s surface interpolates in sheet_to_brep.

The grid is spaced _SURFACE_SPACING apart and reaches _SURFACE_MARGIN spacings beyond the perimeter.

Parameters:

sheet (CartilageSheet)

Return type:

tuple[ndarray, ndarray]

kneemesh.geo.sheet.lower_articular(sheet, s, t, lowering)[source]

Return a sheet whose articular side is lowered toward its bone side by (len(s), len(t)) amounts over a domain grid.

The lowering is interpolated by a bicubic spline, so it should be zero, or fade to zero, where the side is to stay as it is. The bone side, the perimeter, and the wall’s tilt are kept.

Parameters:
Return type:

CartilageSheet

kneemesh.geo.sheet.fit_sheet(sides, perimeter_radius=3.0, perimeter_inset=0.0, min_thickness=0.2, hole_thickness=0.0, frame=None)[source]

Fit a cartilage sheet to the two sides of a cartilage surface.

By default the domain is the plane normal to the thinnest principal direction of the side points. Each side’s footprint is where its points project onto the domain, with gaps of a few point spacings closed, and the sheet covers where both footprints overlap, so the steep perimeter between the sides is cut off. The overlap is moved perimeter_inset inward and rounded by rolling a disk of radius perimeter_radius around it, inside and out: a morphological closing then opening, from exact distance maps. Its outline then curves no more tightly than that radius anywhere, concave or convex, which removes the jagged edge and the notches and spurs narrower than the elements that must follow it. A Gaussian of half that radius then smooths the outline’s remaining waviness. Holes in the overlap are filled unless they become holes.

Heights are interpolated linearly between each side’s points on a grid, smoothed lightly, and fitted with bicubic splines. Where the thickness falls below min_thickness of the mean, the bone side is lowered to that thickness by a smooth maximum, leaving the articular side alone.

The wall at the perimeter is tilted so it leaves both sides at about equal angles: where the sheet curves down at its rim, a wall along the height lines meets the articular side at up to 130 degrees or more. A straight wall cannot meet both sides of a tapering rim at right angles, so the tilt balances the two, limited to _MAX_WALL_TILT of the local thickness and _MAX_TILT_REACH of perimeter_radius, and smoothed along the perimeter. Its band fades out at perimeter_radius inside the perimeter.

Parameters:
  • sides (CartilageSides) – Points of the cartilage’s articular and bone sides from classify_sides.

  • perimeter_radius (float) – Smallest radius of curvature of the perimeter and hole outlines, in physical units. Keep it above about half the elements’ size along the perimeter, or elements across a tight notch can invert.

  • perimeter_inset (float) – How far inside the sides’ overlap to put the perimeter, in physical units, cutting off more of the thin rim.

  • min_thickness (float) – Minimum thickness as a fraction of the mean.

  • hole_thickness (float) – Thickness as a fraction of the mean below which the sheet gets a hole, smaller than min_thickness. Regions of the overlap with no cartilage become holes too. Only regions whose outlines lie at least perimeter_radius inside the perimeter become holes; others are thickened. Holes are rounded like the perimeter, so those narrower than perimeter_radius vanish. 0 makes no holes.

  • frame (SheetFrame | None)

Returns:

The fitted sheet.

Raises:

ValueError – If a parameter is out of range, or the sides do not overlap enough to leave a region inside the perimeter.

Return type:

CartilageSheet

kneemesh.geo.sheet.sheet_to_brep(sheet)[source]

Build a solid of a cartilage sheet: its two sides, the wall between them at the perimeter, and the walls of its holes.

Each side is one bicubic B-spline surface interpolating the side’s points over a grid of domain points, trimmed by the perimeter and the hole outlines drawn in its parameter space, so both sides share one parameterization: the surface parameters are the domain coordinates (s, t). Each wall is ruled between matching edges of the two sides, so it is straight from side to side, tilted at the perimeter as fit_sheet describes and along the height lines at the holes. Hexahedral meshing relies on both: mesh.sheet.hexahedral_mesh pairs the sides’ points at equal parameters and follows the walls’ straight lines.

Returns:

The solid as one volume.

Parameters:

sheet (CartilageSheet)

Return type:

BRep

Hexahedral meshing of cartilage sheets: a quadrilateral mesh of one side, extruded through the thickness.

A sheet’s solid (geo.sheet.sheet_to_brep) has two sides that share one parameterization and walls ruled straight between them. One side is meshed with quadrilaterals, and each node’s column runs straight to the other side: from interior nodes to the other side’s point at the same parameters, and from nodes on a rim along the wall’s straight line through them. The columns are divided into layers, so the elements stack through the thickness.

The quadrilaterals come from gmsh, by default from its quasi-structured algorithm, which aligns a cross field (a 4-RoSy field) with the boundary, places the field’s singularities where the shape needs them, and meshes along it, leaving few irregular nodes. The regions those few nodes’ straight lines of edges bound are a partition of the sheet into four-sided blocks, which sheet_partition_brep can build.

Both meshes of a sheet have the sets “articular_side” and “bone_side” besides “surface” (mesh_sets): the faces on the side away from the bone, the side above, and on the side against it.

type kneemesh.mesh.sheet.QuadAlgorithm = Literal['quasi_structured', 'frontal_delaunay']

gmsh’s algorithm for the side’s quadrilaterals: quasi-structured along a cross field, or Frontal-Delaunay for quads with full-quad recombination.

kneemesh.mesh.sheet.ARTICULAR_SIDE = 'articular_side'

Name of a sheet mesh’s set of the faces on its articular side, away from the bone, and of their nodes.

kneemesh.mesh.sheet.BONE_SIDE = 'bone_side'

Name of a sheet mesh’s set of the faces on its side against the bone, and of their nodes.

kneemesh.mesh.sheet.hexahedral_mesh(brep, element_size, elements_through=3, element_order=1, second_order_incomplete=False, quad_algorithm='quasi_structured')[source]

Mesh a cartilage sheet’s solid with hexahedra about element_size across and elements_through thick.

The larger side is meshed with quadrilaterals by quad_algorithm. If gmsh leaves triangles, which Frontal-Delaunay recombination occasionally does, the element size is changed by 2, 4, then 6% each way in turn, and as a last resort a mesh at twice the size is subdivided, each triangle into three quadrilaterals and each quadrilateral into four. Each node’s column runs straight to the other side, and the columns through the walls are the mesh’s straight_lines, so optimization keeps the walls straight.

Parameters:
  • brep (BRep) – A sheet’s solid, such as geo.sheet.sheet_to_brep gives.

  • element_size (float) – Target length of the elements’ edges along the sheet.

  • elements_through (int) – Elements through the thickness.

  • element_order (int) – Polynomial order of the elements. 2 gives 27-node hexahedra.

  • second_order_incomplete (bool) – Omit face and interior nodes from high-order elements, giving 20-node instead of 27-node second-order hexahedra.

  • quad_algorithm (QuadAlgorithm) – gmsh’s algorithm for the side’s quadrilaterals.

Raises:

ValueError – If element_size is not positive, elements_through is below 1, element_order is out of range, brep is not a sheet’s solid, or no quadrilateral mesh could be made.

Return type:

Mesh

kneemesh.mesh.sheet.sheet_face_groups()[source]

Name the current model’s sheet sides, for tet_meshing.tetrahedral_mesh’s face_groups: articular_side and bone_side.

Raises:

ValueError – If the model is not a sheet’s solid.

Return type:

dict[str, list[int]]

kneemesh.mesh.sheet.quadrangulate(surfaces, size, algorithm, name='the surface')[source]

Mesh the current model’s surfaces with quadrilaterals only, about size across.

If gmsh leaves triangles on any of surfaces, which Frontal-Delaunay recombination occasionally does, the size is changed by 2, 4, then 6% each way in turn, and as a last resort a mesh at twice the size is subdivided, each triangle into three quadrilaterals and each quadrilateral into four. Also used for the bones’ surfaces (mesh.bone).

Parameters:
  • surfaces (list[int]) – Tags of the surfaces that must hold quadrilaterals only.

  • size (float) – Target length of the edges.

  • algorithm (QuadAlgorithm) – gmsh’s algorithm for the quadrilaterals.

  • name (str) – What the surfaces are, for messages.

Raises:

ValueError – If no mesh of quadrilaterals only could be made.

Return type:

None

kneemesh.mesh.sheet.stack_layers(layers, quadrangles, order, incomplete, columns=None)[source]

Stack hexahedra on quadrilaterals through layers of their nodes’ positions, without faces or sets.

Each hexahedron spans order + 1 consecutive layers, its nodes matched to the quadrilateral’s nodes at the same reference (u, v). The quadrilaterals’ orientation does not matter: if the hexahedra would come out inverted, the layers are stacked in reverse.

Also used for the meniscus’s swept hexahedra (mesh.meniscus).

Parameters:
  • layers (ndarray) – (L, N, 3) positions of the quadrilaterals’ N nodes in each layer, L = elements * order + 1, the middle layers of quadratic elements included.

  • quadrangles (ndarray) – (Q, 4 or 9) indices of each quadrilateral’s nodes, in gmsh’s ordering.

  • order (int) – Polynomial order of the quadrilaterals and hexahedra, 1 or 2.

  • incomplete (bool) – Make 20-node instead of 27-node hexahedra at order 2.

  • columns (ndarray | None) – Indices of corner nodes whose columns through the layers stay straight, which become the mesh’s straight_lines.

Returns:

The mesh, and the index of each of its nodes’ layer in layers.

Return type:

tuple[Mesh, ndarray]

kneemesh.mesh.sheet.sheet_partition_brep(brep, element_size, quad_algorithm='quasi_structured')[source]

Build the partition of a sheet’s solid into blocks that its hexahedral mesh’s irregular nodes define, one volume per block.

The side is meshed as hexahedral_mesh meshes it. The straight lines of edges through the quadrilaterals’ irregular nodes, interior nodes with other than four quadrilaterals and rim nodes with other than two, run until they reach a rim or another irregular node. They divide the quadrilaterals into four-sided patches of regular grids, the mesh’s base complex. Each patch becomes a block: a patch on each side through its nodes’ columns’ ends, and ruled walls along its columns. The blocks are fragmented so neighbors share faces, as for transfinite meshing.

The quasi-structured algorithm leaves few irregular nodes and so few blocks: 10 on the real lateral tibial cartilage and 32 on the femoral at 2 mm. Frontal-Delaunay quadrilaterals leave many, and most of their blocks would be single elements.

Raises:

ValueError – If brep is not a sheet’s solid, a patch is not a regular grid, as around a hole no line crosses, or fragmenting the blocks fails.

Parameters:
Return type:

BRep

Femoral cartilage

B-rep generation for the femoral cartilage. The femur is not implemented yet.

The femoral cartilage wraps the condyles, so it is a sheet over a cylinder about the knee’s flexion axis rather than over a plane (CylinderFrame). Its domain, unrolled, is a U: the trochlea joins two condylar legs around the intercondylar notch. Its solid is built like the other sheets’ (geo.sheet.sheet_to_brep).

kneemesh.geo.femur.fit_femoral_sheet(sides, perimeter_radius=3.0, perimeter_inset=0.0, min_thickness=0.2, hole_thickness=0.0)[source]

Fit the femoral cartilage as a sheet over the cylinder its bone side wraps.

The arguments are fit_sheet’s; see there. Heights are distances from the cylinder’s axis, and the domain is the cylinder unrolled.

Raises:

ValueError – If a parameter is out of range, the sides wrap too far around to unroll, or they do not overlap enough.

Parameters:
Return type:

CartilageSheet

Bones

Surfaces of the bones: the femur, tibia, and patella.

A bone’s geometry is not a B-rep but its closed, triangulated surface, which gmsh reparametrizes when meshing it (mesh.bone). Bones are not meshed with hexahedra. The surface is the isocontour of the bone’s mask in the voxel map, its cavities filled and, optionally, its shafts cut shorter, smoothed and decimated.

kneemesh.geo.bone.DEFAULT_TRIANGLE_SIZE = 1.0

Default edge length of the bone surface’s triangles after decimation, in physical units.

class kneemesh.geo.bone.ShaftEnd(axis, side, last, first)[source]

Bases: object

Where a bone’s shaft is cut off by the edge of the scan.

Parameters:
axis

Index of the image axis along the shaft.

Type:

int

side

-1 if the shaft leaves the scan at the axis’s low end, 1 at its high end.

Type:

int

last

Index along axis of the label’s last slice at that end.

Type:

int

first

Index along axis of the label’s last slice at the other end.

Type:

int

kneemesh.geo.bone.find_shaft_ends(label_map, label=1)[source]

Find where a bone’s label is cut off by the edge of the scan, as the femur’s and tibia’s shafts are.

A bone that ends inside the scan tapers to a few voxels in its last slice along every image axis, and its slices grow quickly inward; one cut off by the scan ends in a whole cross-section, nearly the same as the slices just inside it.

Raises:

ValueError – If the image is not a 3D LabelMap or the label is absent.

Parameters:
  • label_map (Image)

  • label (int)

Return type:

list[ShaftEnd]

kneemesh.geo.bone.bone_mask(label_map, label=1, shaft_cut_fraction=0.0)[source]

Return a mask of a bone (1 inside, 0 outside) with its cavities filled and its shafts optionally cut shorter.

Each shaft the scan cuts off (find_shaft_ends) loses shaft_cut_fraction of the label’s extent along it, cut square in the voxel map, so the surface ends in a flat face there, rounded at its edge by smoothing. Cavities are then filled, first in each shaft’s new last slice, where a pocket would open onto the flat face, then throughout.

Parameters:
  • label_map (Image) – 3D LabelMap.

  • label (int) – Value of the bone.

  • shaft_cut_fraction (float) – Fraction of the bone’s extent along each shaft cut off by the scan to remove from that end, in [0, 1). 0 keeps the shaft as the scan has it.

Raises:

ValueError – If the image is not a 3D LabelMap, the label is absent, or shaft_cut_fraction is out of range.

Return type:

Image

kneemesh.geo.bone.decimate_surface(surface, triangle_size=1.0)[source]

Reduce a surface’s triangles to about triangle_size across, keeping its shape and volume.

The isocontour’s triangles are a fraction of a voxel across, too many for gmsh to reparametrize quickly: the real femur’s 340,000 took minutes. Quadric decimation to 1 mm edges moves the real bones’ surfaces by at most 0.02 mm.

Raises:

ValueError – If triangle_size is not positive.

Parameters:
  • surface (vtkPolyData)

  • triangle_size (float)

Return type:

vtkPolyData

kneemesh.geo.bone.surface_arrays(surface)[source]

Return a triangulated surface’s (N, 3) points and (M, 3) triangles’ point indices.

Parameters:

surface (vtkPolyData)

Return type:

tuple[ndarray, ndarray]

Surface and tetrahedral meshing of the bones’ triangulated surfaces (geo.bone), which gmsh reparametrizes.

gmsh splits the surface into patches until each can be mapped to a plane (mesh.classifySurfaces with forReparametrization), then builds those maps (mesh.createGeometry). It meshes the patches as it would any surface, and the solid they enclose with tetrahedra. Bones are not meshed with hexahedra.

kneemesh.mesh.bone.DEFAULT_BONE_ELEMENT_SIZE = 2.0

Default size of the elements of a bone’s surface mesh, in physical units.

kneemesh.mesh.bone.DEFAULT_CORTICAL_ELEMENT_SIZE = 1.0

Default edge length of a bone’s tetrahedra within cortical_distance of its surface, in physical units.

kneemesh.mesh.bone.DEFAULT_CORTICAL_DISTANCE = 3.0

Default depth of the shell of cortical_element_size tetrahedra below a bone’s surface, in physical units.

kneemesh.mesh.bone.DEFAULT_CANCELLOUS_GRAD = 0.5

Default growth of a bone’s tetrahedra’s edge length per unit of depth beyond cortical_distance.

kneemesh.mesh.bone.DEFAULT_BONE_MAX_SIZE = 4.0

Default largest edge length of a bone’s tetrahedra, in physical units.

kneemesh.mesh.bone.surface_mesh(surface, element_size=2.0, element_order=1, second_order_incomplete=False, quadrilaterals=False, algorithm_2d=Algorithm2D.FRONTAL_DELAUNAY)[source]

Mesh a bone’s closed surface with triangles or quadrilaterals about element_size across.

Quadrilateral meshes hold quadrilaterals only; see mesh.sheet.quadrangulate. The mesh is smoothed over the whole surface, across the seams between gmsh’s patches, and every node lies on the surface.

Parameters:
  • surface (vtkPolyData) – A closed triangulated surface, such as geo.bone gives.

  • element_size (float) – Target length of the elements’ edges.

  • element_order (int) – Polynomial order of the elements, 1 or 2. 2 gives 6-node triangles or 9-node quadrilaterals, with their new nodes on the surface.

  • second_order_incomplete (bool) – Omit the middle node of second-order quadrilaterals, giving 8-node ones.

  • quadrilaterals (bool) – Mesh with quadrilaterals instead of triangles, by Frontal-Delaunay with full-quad recombination. gmsh’s quasi-structured algorithm took 50 s on the real patella and made elements a third of the size.

  • algorithm_2d (Algorithm2D) – gmsh’s algorithm for triangles.

Raises:

ValueError – If an argument is out of range, or gmsh fails.

Return type:

Mesh

kneemesh.mesh.bone.tetrahedral_mesh(surface, cortical_element_size=1.0, cortical_distance=3.0, cancellous_grad=0.5, max_size=4.0, element_order=1, algorithm_2d=Algorithm2D.FRONTAL_DELAUNAY, algorithm_3d=Algorithm3D.DELAUNAY)[source]

Mesh the solid a bone’s closed surface encloses with tetrahedra, finest in its cortical shell.

Elements are cortical_element_size within cortical_distance of the surface, the shell where the cortical bone lies, and grow deeper in by cancellous_grad per unit of distance, up to max_size: min(max_size, cortical_element_size + cancellous_grad * max(0, d - cortical_distance)) at distance d from the surface.

Parameters:
  • surface (vtkPolyData) – A closed triangulated surface, such as geo.bone gives.

  • cortical_element_size (float) – Edge length of the elements within cortical_distance of the surface, the surface’s included.

  • cortical_distance (float) – Depth below the surface of the shell of cortical_element_size elements.

  • cancellous_grad (float) – Growth of the edge length per unit of depth beyond cortical_distance. Smaller grows more smoothly.

  • max_size (float) – Largest edge length, deep in the cancellous bone.

  • element_order (int) – Polynomial order of the elements, 1 or 2. 2 gives 10-node tetrahedra, with their new boundary nodes on the surface.

  • algorithm_2d (Algorithm2D) – gmsh’s algorithm for the boundary triangles.

  • algorithm_3d (Algorithm3D) – gmsh’s algorithm for the tetrahedra.

Raises:

ValueError – If an argument is out of range, or gmsh fails or makes no tetrahedra.

Return type:

Mesh

GUI

The gui subpackage needs the gui extra.

A trame GUI that runs the pipeline interactively: import labels, configure and build each structure’s geometry and mesh, and view them.

The app imports trame, an optional dependency (pip install kneemesh[gui]), so it is loaded only by main; the other modules, which the GUI’s worker process imports, do not need it.

kneemesh.gui.main()[source]

Run the kneemesh GUI (the kneemesh-gui console script).

Return type:

None

The kneemesh GUI: a trame app that imports labels, configures each structure’s geometry and mesh, runs them, and shows the results.

class kneemesh.gui.app.KneemeshApp(server=None)[source]

Bases: object

The GUI’s state, layout, and handlers, bound to a trame server.

Parameters:

server (Server | None)

set_view_ratio(ratio)[source]

Render the 3D view at ratio pixels per screen pixel, scaling its fonts and lines to match.

Raises:

ValueError – If ratio is not positive.

Parameters:

ratio (float)

Return type:

None

add_label()[source]

Pick a LabelMap to import.

Return type:

None

update_label(entry_id, field, value)[source]

Change an imported label’s structure, value, or whether it is included.

Parameters:
Return type:

None

remove_label(entry_id)[source]

Remove an imported label.

Parameters:

entry_id (int)

Return type:

None

select(node)[source]

Show the settings of a tree node: settings, or geometry:<structure> or mesh:<structure>.

Parameters:

node (str)

Return type:

None

set_own_section(kind, structure, own)[source]

Give a structure settings of its own, starting from those it shares the first time, or let it share them again.

Parameters:
  • kind (Kind)

  • structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

  • own (bool)

Return type:

None

set_element_type(structure, element_type)[source]

Set a structure’s own element type, or with an empty one, let it take the mesh’s.

Parameters:
  • structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

  • element_type (str | None)

Return type:

None

set_brep_path(structure, path)[source]

Set the file a structure is meshed from, or with an empty one, the geometry this GUI writes.

Parameters:
  • structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

  • path (str | None)

Return type:

None

toggle_visibility(structure)[source]

Show or hide a structure in the view.

Parameters:

structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

Return type:

None

toggle_solo(structure)[source]

Show only a structure in the view, or every structure again if it was the only one shown.

Parameters:

structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

Return type:

None

reset_section(kind, section)[source]

Restore a section’s defaults.

Parameters:
  • kind (Kind)

  • section (str)

Return type:

None

build(structure)[source]

Build the geometry of a structure, or of every included one.

Parameters:

structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'] | None)

Return type:

None

resolve_overclosures()[source]

Move every structure with geometry apart from the others where they overlap, by the overclosure settings.

Return type:

None

mesh(structure)[source]

Mesh a structure’s geometry, or that of every structure with geometry.

Parameters:

structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'] | None)

Return type:

None

load_existing()[source]

Show the geometry files already written for the included structures, or given as their geometry files.

Return type:

None

cancel()[source]

Cancel the running job.

Return type:

None

import_config()[source]

Pick a kneemesh-brep, kneemesh-mesh, or kneemesh-assemble JSON configuration to import.

Return type:

None

export_geometry()[source]

Pick where to write the geometry settings and labels as a kneemesh-brep configuration.

Return type:

None

export_mesh()[source]

Pick where to write the mesh settings as a kneemesh-mesh configuration.

Return type:

None

browse_output_directory()[source]

Pick the output directory.

Return type:

None

dialog_open_directory(directory)[source]

List a directory in the file dialog.

Parameters:

directory (str)

Return type:

None

dialog_up()[source]

List the file dialog’s parent directory.

Return type:

None

dialog_click(item)[source]

Open a directory, or select a file, in the file dialog.

Parameters:

item (dict[str, Any])

Return type:

None

dialog_confirm()[source]

Accept the file dialog’s choice and pass it to the action that opened it.

Return type:

None

download_file(path)[source]

A server file’s contents, for the browser to save.

Parameters:

path (str)

Return type:

object

download_outputs()[source]

A zip of the files this session wrote, for the browser to save.

Return type:

object

reset_camera()[source]

Fit the view to what it shows.

Return type:

None

kneemesh.gui.app.zip_files(paths)[source]

A zip of files, each named by its path relative to the deepest directory holding them all.

Parameters:

paths (Iterable[str])

Return type:

bytes

kneemesh.gui.app.main()[source]

Run the GUI’s server and open it in a browser, logging to stderr.

Return type:

None

Form widgets for the B-rep and mesh configurations, derived from their pydantic models, and their values in the GUI’s flat state.

trame tracks changes to top-level state keys only, so every field shown in a form gets its own key: geo__meniscus__spacing for a section’s field, geo__lateral_meniscus__spacing for a structure’s own section’s, and geo__output for a top-level one. output_directory is one key that both configurations share. Fields the GUI manages itself, such as labels, breps, and element_types, have no form.

kneemesh.gui.settings.OUTPUT_DIRECTORY_KEY = 'output_directory'

The state key of the output directory, which the B-rep and mesh configurations share.

kneemesh.gui.settings.OVERCLOSURE_SECTION = 'overclosure'

The geometry section that belongs to no structure, shown on the Settings page rather than a structure’s.

kneemesh.gui.settings.structure_section(structure, own=())[source]

The section a structure’s settings are in: its own, named for it, if it is in own, or else the one it shares.

Parameters:
  • structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

  • own (Collection[str])

Return type:

str

kneemesh.gui.settings.sharing_structures(structure, own=())[source]

The other structures whose settings are in the same section as a structure’s, none if it has its own.

Parameters:
  • structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

  • own (Collection[str])

Return type:

list[Literal[‘lateral_meniscus’, ‘medial_meniscus’, ‘patellar_cartilage’, ‘femoral_cartilage’, ‘lateral_tibial_cartilage’, ‘medial_tibial_cartilage’, ‘femur’, ‘tibia’, ‘patella’]]

class kneemesh.gui.settings.FieldSpec(key, name, section, label, description, widget, items=(), optional=False, integer=False, minimum=None, maximum=None)[source]

Bases: object

How to show one configuration field.

Parameters:
key

The field’s state key.

Type:

str

name

The field’s name in its model.

Type:

str

section

The section holding the field, or None for a top-level field.

Type:

str | None

label

The widget’s label.

Type:

str

description

The field’s description, shown as a tooltip.

Type:

str

widget

The widget to edit it with: an order is a list of all its items, rearranged.

Type:

kneemesh.gui.settings.Widget

items

The choices of a select, or the items of an order.

Type:

tuple[str, …]

optional

Whether the field takes None, shown as an empty field.

Type:

bool

integer

Whether a number field takes integers.

Type:

bool

minimum

The smallest value allowed, or None.

Type:

float | None

maximum

The largest value allowed, or None.

Type:

float | None

kneemesh.gui.settings.state_key(kind, section, name)[source]

The state key of a field of kind’s model, in a section or at the top level.

Parameters:
  • kind (Kind)

  • section (str | None)

  • name (str)

Return type:

str

kneemesh.gui.settings.section_key(kind, section)[source]

The key under which errors of a whole section, from its model’s validators, are reported.

Parameters:
  • kind (Kind)

  • section (str)

Return type:

str

kneemesh.gui.settings.section_names(kind)[source]

The sections of kind’s model, such as meniscus and femur.

Parameters:

kind (Kind)

Return type:

list[str]

kneemesh.gui.settings.structure_section_names(kind)[source]

The sections of kind’s model that hold structures’ settings, shown on the structures’ pages: all but overclosure.

Parameters:

kind (Kind)

Return type:

list[str]

kneemesh.gui.settings.section_fields(kind, section)[source]

The fields of a section of kind’s model, in declaration order.

Parameters:
  • kind (Kind)

  • section (str)

Return type:

list[FieldSpec]

kneemesh.gui.settings.top_fields(kind)[source]

The top-level fields of kind’s model with forms: those that are not sections or managed by the GUI.

Parameters:

kind (Kind)

Return type:

list[FieldSpec]

kneemesh.gui.settings.all_fields(kind)[source]

Every field of kind’s model with a form.

Parameters:

kind (Kind)

Return type:

list[FieldSpec]

kneemesh.gui.settings.state_values(kind, config=None)[source]

The state of every form field of kind’s model, from config or the model’s defaults, and the shared output directory.

A structure’s own section that config leaves out takes the values of the section it shares, so it starts from them when made its own.

Parameters:
Return type:

dict[str, Any]

kneemesh.gui.settings.own_sections(config)[source]

The structures with their own section in a configuration.

Parameters:

config (BaseConfig)

Return type:

list[str]

kneemesh.gui.settings.config_values(kind, state, own=())[source]

Unvalidated values of kind’s model from the state of its forms, with sections nested and empty optional fields as None.

Structures’ own sections are included for the structures in own only. Numbers typed into a form arrive as text, which pydantic’s lax mode parses.

Parameters:
Return type:

dict[str, Any]

kneemesh.gui.settings.validation_errors(kind, error)[source]

Each of a ValidationError’s messages by the state key it concerns.

An error of a field goes under its key, an error of a whole section, from its model’s validators, under section_key, and any other under the model’s prefix, such as “geo”.

Parameters:
Return type:

dict[str, str]

kneemesh.gui.settings.humanize(name)[source]

A field or structure name as a label: lateral_meniscus as Lateral meniscus.

Parameters:

name (str)

Return type:

str

The GUI’s imported labels: reading a LabelMap’s values, numbering them, and composing the included ones into a Segmentation.

A label entry is a plain dict so it can live in trame’s state: id, the path of its LabelMap and its file name, the file_value it has there, the structure it names (or None), the value it takes in the composed segmentation, and whether to include it.

class kneemesh.gui.labels.LabelEntry[source]

Bases: TypedDict

One value of an imported LabelMap, as the GUI’s state holds it.

kneemesh.gui.labels.label_values(image)[source]

The nonzero values in a LabelMap, ascending.

Parameters:

image (Image)

Return type:

list[int]

kneemesh.gui.labels.file_structures(path)[source]

The structure of each value in a LabelMap that kneemesh wrote, from <stem>_labels.json beside it, or by the file’s name.

A file named for a structure, such as tibia.nii, names its only value when it has one; the caller decides that. Unknown names are dropped.

Parameters:

path (str | Path)

Return type:

dict[int, Literal[‘lateral_meniscus’, ‘medial_meniscus’, ‘patellar_cartilage’, ‘femoral_cartilage’, ‘lateral_tibial_cartilage’, ‘medial_tibial_cartilage’, ‘femur’, ‘tibia’, ‘patella’]]

kneemesh.gui.labels.structure_of_name(path)[source]

The structure a file is named for, such as tibia for tibia.nii, or None.

Parameters:

path (str | Path)

Return type:

Literal[‘lateral_meniscus’, ‘medial_meniscus’, ‘patellar_cartilage’, ‘femoral_cartilage’, ‘lateral_tibial_cartilage’, ‘medial_tibial_cartilage’, ‘femur’, ‘tibia’, ‘patella’] | None

kneemesh.gui.labels.new_entries(path, values, existing)[source]

Entries for every value of a newly imported LabelMap, numbered consistently with the existing entries.

A LabelMap of one value takes the next free label value. One of several values keeps its own value where that is free, and otherwise also takes the next free one. Structures come from a <stem>_labels.json beside the file, or for a single value from the file’s name, and are left unset where those name none or a structure another entry already names.

Parameters:
Return type:

list[LabelEntry]

kneemesh.gui.labels.config_entries(label_map, labels, label_maps, values_of)[source]

Entries for the segmentation a LabelMapBrep or LabelMapAssembly configuration reads.

label_map’s values keep their own value, the ones labels names included under their structures, any others excluded and unassigned. Each of label_maps is numbered 1, 2, … in order, as kneemesh-brep assembles them; should one hold several values, its first takes the structure and the others are excluded.

Parameters:
  • label_map (str | Path | None) – A multilabel LabelMap, with labels naming its values.

  • labels (Mapping[Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'], int] | None) – The structure of each of label_map’s values.

  • label_maps (Mapping[Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'], str | ~pathlib.Path] | None) – Single-label LabelMaps by structure, instead of label_map.

  • values_of (Callable[[str], Sequence[int]]) – The nonzero values of the LabelMap at a path.

Return type:

list[LabelEntry]

kneemesh.gui.labels.next_free_value(used)[source]

The smallest label value from 1 up that is not used.

Parameters:

used (Iterable[int])

Return type:

int

kneemesh.gui.labels.entry_problems(entries)[source]

What keeps the included entries from forming a segmentation, or an empty list.

Parameters:

entries (Iterable[LabelEntry])

Return type:

list[str]

kneemesh.gui.labels.missing_bones(structures, entries)[source]

Messages for each cartilage among structures whose bone no included entry names.

Parameters:
  • structures (Iterable[Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella']])

  • entries (Iterable[LabelEntry])

Return type:

list[str]

kneemesh.gui.labels.compose_segmentation(entries, interpolator='label_gaussian', padding=4)[source]

The Segmentation of the included entries, each structure at its entry’s value.

Entries all from one LabelMap are relabelled in place, which keeps the grid and every voxel; values not included become background. Entries from several LabelMaps are each taken as a single-label LabelMap of the voxels at their file_value and assembled onto one grid (segmentation.assemble_label_maps), then relabelled.

Raises:

ValueError – If the entries have problems (entry_problems), or a LabelMap cannot be read or assembled.

Parameters:
Return type:

Segmentation

kneemesh.gui.labels.brep_sources(entries)[source]

The fields of a LabelMapBrep that read the included entries’ segmentation as kneemesh-brep would, or None if none can.

Entries from one LabelMap at their own values become label_map with labels. Entries that are each the only value of their own LabelMap become label_maps, assembled in entry order; kneemesh-brep numbers them 1, 2, … whatever the entries’ values. Anything else, such as several values of one file with others, or renumbered values of one file, has no equivalent, and the composed segmentation must be written instead.

Parameters:

entries (Iterable[LabelEntry])

Return type:

dict[str, Any] | None

kneemesh.gui.labels.label_surface(image, value)[source]

A smooth vtkPolyData surface of the voxels at value, in physical coordinates, as the B-rep pipelines extract one.

The image is cropped around the label first, so large LabelMaps preview quickly.

Raises:

ValueError – If the image holds no voxel at value.

Parameters:
  • image (Image)

  • value (int)

Return type:

Any

Running GUI jobs in a separate process and waiting for them without blocking the GUI’s event loop.

exception kneemesh.gui.jobs.JobError[source]

Bases: Exception

A job failed, was cancelled, or its process died.

class kneemesh.gui.jobs.JobRunner[source]

Bases: object

Runs one job at a time in a spawned process, which a cancel terminates.

property busy: bool

Whether a job is running.

async run(job, on_log)[source]

Run a job (worker.run_job), passing each log record’s level and message to on_log, and return its result.

Raises:

JobError – If a job is already running, or this one fails, is cancelled, or its process dies.

Parameters:
Return type:

dict[str, Any]

cancel()[source]

Terminate the running job, if any; run then raises JobError.

Return type:

None

Pipeline jobs the GUI runs in a separate process, and the surfaces that preview their results.

gmsh holds global state, needs the main thread, and can crash the process, so the GUI runs every job that touches it in a process of its own through run_job. A job reports through a queue: ("log", level, message) for each log record, then ("done", result) or ("error", message).

class kneemesh.gui.worker.JobQueue(*args, **kwargs)[source]

Bases: Protocol

The part of a multiprocessing queue a job puts its reports on.

kneemesh.gui.worker.run_job(job, queue)[source]

Run a GUI job and report its log and result on queue.

A job is a dict whose kind is geometry, mesh, preview, or overclosure:

  • geometry: entries (LabelEntry dicts) composed into a segmentation with interpolator and padding, written to assembled_label_map if that is given, then each of structures built with the LabelMapBrep config and previewed. What each was built from is saved beside its preview, for overclosure jobs.

  • overclosure: the geometry files geometry ({structure: path}) moved apart where they overlap (overclosure.resolve_overclosure), with the overclosure section of the LabelMapBrep config. A cartilage or meniscus moves only if this session built the file, so what it was built from is saved; the rest stay in place. Moved files are rewritten in place and previewed; the result names only those.

  • mesh: the BrepMesh config, whose breps are meshed, each also written as a .vtu preview with its faces and quality metrics.

  • preview: each B-rep in breps ({structure: path}) previewed.

Previews go to preview_directory. The result maps each structure to the paths of its output and its preview.

Parameters:
Return type:

None

kneemesh.gui.worker.brep_surface(brep)[source]

A B-rep’s faces as triangles and its edges as lines, for display, in one vtkPolyData.

The triangles are a coarse gmsh surface mesh, sized from the B-rep’s bounding box and its curvature. A cell array “edge” is 1 on the lines.

Raises:

ValueError – If the B-rep has no faces.

Parameters:

brep (BRep)

Return type:

vtkPolyData

kneemesh.gui.worker.import_solid_or_shell(brep)[source]

Load a B-rep into the current gmsh model, whether it holds a solid or only surfaces.

Parameters:

brep (BRep)

Return type:

None

The GUI’s 3D scene: each structure’s label surface, geometry, and mesh, rendered offscreen for trame’s remote view.

Everything shown runs through a pipeline (_Display): optionally the cells of some types, a crinkle clip by the scene’s plane when clipping is on, which keeps whole cells, the outer faces with nonlinear cells subdivided twice, and point normals split at feature edges, as ParaView’s Generate Surface Normals makes them, for smooth shading.

kneemesh.gui.view.COLORS: dict[Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'], tuple[float, float, float]] = {'femoral_cartilage': (0.8, 0.5, 0.7), 'femur': (0.89, 0.85, 0.76), 'lateral_meniscus': (0.47, 0.67, 0.89), 'lateral_tibial_cartilage': (0.93, 0.55, 0.5), 'medial_meniscus': (0.33, 0.55, 0.82), 'medial_tibial_cartilage': (0.87, 0.45, 0.45), 'patella': (0.92, 0.88, 0.8), 'patellar_cartilage': (0.95, 0.66, 0.42), 'tibia': (0.85, 0.82, 0.72)}

Each structure’s color in the scene.

kneemesh.gui.view.SUBDIVISION_LEVEL = 2

Times each nonlinear face is subdivided for display, so a second-order edge is drawn as 2^2 = 4 segments.

kneemesh.gui.view.FEATURE_ANGLE = 30.0

ParaView’s default.

Type:

Angle in degrees between faces above which point normals are split, so the edge stays sharp

class kneemesh.gui.view.Metric(name, title, higher_is_better, faces=False)[source]

Bases: object

A mesh quality metric the view can color meshes by.

Parameters:
name

Its cell array’s name in a mesh preview (mesh_optimization.element_quality).

Type:

str

title

Its name for display.

Type:

str

higher_is_better

Whether higher values are better, which colors them blue and lower ones red.

Type:

bool

faces

Whether it is measured on boundary faces rather than elements.

Type:

bool

kneemesh.gui.view.METRICS: dict[str, Metric] = {'edge_ratio': Metric(name='edge_ratio', title='Edge ratio', higher_is_better=False, faces=False), 'frobenius_aspect': Metric(name='frobenius_aspect', title='Frobenius aspect ratio', higher_is_better=False, faces=False), 'min_dihedral_angle': Metric(name='min_dihedral_angle', title='Minimum dihedral angle (degrees)', higher_is_better=True, faces=False), 'scaled_jacobian': Metric(name='scaled_jacobian', title='Scaled Jacobian', higher_is_better=True, faces=False), 'warp': Metric(name='warp', title='Surface warp (degrees)', higher_is_better=False, faces=True)}

The quality metrics meshes can be colored by, by name.

The scaled Jacobian is each element’s smallest over its corners and, for high-order elements, its Gauss points (mesh_optimization.element_quality). The minimum dihedral angle applies to tetrahedra alone.

kneemesh.gui.view.edge_lines(grid)[source]

The edges of a grid’s triangles and quadrilaterals, linear or quadratic, each once, as polylines following their curves.

Parameters:

grid (vtkUnstructuredGrid)

Return type:

vtkPolyData

class kneemesh.gui.view.Scene[source]

Bases: object

Actors for each structure’s stages and each imported label, and the offscreen window that renders them.

set_pixel_ratio(ratio)[source]

Scale what is sized in pixels, the scalar bar and line widths, for a view rendered at ratio times its size on screen.

Line widths apply to structures shown afterwards.

Parameters:

ratio (float)

Return type:

None

set_label(entry_id, surface)[source]

Show an imported label’s surface, or remove it with None.

Parameters:
  • entry_id (int)

  • surface (vtkPolyData | None)

Return type:

None

set_geometry(structure, surface)[source]

Show a structure’s geometry: a B-rep preview whose lines are its curves, or a bone’s surface.

Parameters:
  • structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

  • surface (vtkPolyData)

Return type:

None

set_mesh(structure, grid)[source]

Show a structure’s mesh, its outer faces with their edges.

The grid holds a volume mesh’s elements and its boundary faces, or a surface mesh’s elements, with their quality metrics as cell arrays.

Parameters:
  • structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

  • grid (vtkUnstructuredGrid)

Return type:

None

clear(stage, structure)[source]

Remove a structure’s geometry or mesh.

Parameters:
  • stage (Stage)

  • structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

Return type:

None

metrics()[source]

The quality metrics some mesh in the scene carries, in the order of METRICS.

Return type:

list[str]

has(stage, structure)[source]

Whether a structure’s geometry or mesh is in the scene.

Parameters:
  • stage (Stage)

  • structure (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'])

Return type:

bool

set_clipping(enabled, mode='view', offset=0.0)[source]

Crinkle-clip everything by a plane, keeping the cells beyond it and those it crosses, whole.

In “view” mode the plane faces the viewer through the camera’s focal point and turns with the camera. “fixed” freezes the plane as it is when the mode is chosen, so it turns with the geometry. offset moves the plane away from the viewer, as a fraction of the scene’s radius.

Parameters:
  • enabled (bool)

  • mode (ClipMode)

  • offset (float)

Return type:

None

refresh(entries, display, hidden, solo=None, metric=None)[source]

Show what display asks for and color it by structure, or meshes by a quality metric.

“latest” shows each structure’s mesh, else its geometry, else its included label; another mode shows only that stage. Labels not naming a structure show only as labels, in gray. Structures in hidden show nothing, and with solo, only that structure shows. With a metric of METRICS, the meshes shown are colored by it over the range of their values, with a scalar bar; meshes without it are gray.

Parameters:
  • entries (Sequence[LabelEntry])

  • display (DisplayMode)

  • hidden (Collection[str])

  • solo (Literal['lateral_meniscus', 'medial_meniscus', 'patellar_cartilage', 'femoral_cartilage', 'lateral_tibial_cartilage', 'medial_tibial_cartilage', 'femur', 'tibia', 'patella'] | None)

  • metric (str | None)

Return type:

None

reset_camera()[source]

Fit the camera to what is shown, unclipped.

Fitting to the clipped cells instead would close in on them, and the plane, which follows the camera, would then clip closer still.

Return type:

None

kneemesh.gui.view.read_mesh_preview(path)[source]

Read a mesh preview the worker wrote as .vtu.

Raises:

ValueError – If the file is not a VTK XML unstructured grid.

Parameters:

path (str | Path)

Return type:

vtkUnstructuredGrid

kneemesh.gui.view.structure_title(structure)[source]

A structure’s name for display: lateral_meniscus as Lateral Meniscus.

Parameters:

structure (str)

Return type:

str

kneemesh.gui.view.STRUCTURE_ITEMS = [{'title': 'Lateral Meniscus', 'value': 'lateral_meniscus'}, {'title': 'Medial Meniscus', 'value': 'medial_meniscus'}, {'title': 'Patellar Cartilage', 'value': 'patellar_cartilage'}, {'title': 'Femoral Cartilage', 'value': 'femoral_cartilage'}, {'title': 'Lateral Tibial Cartilage', 'value': 'lateral_tibial_cartilage'}, {'title': 'Medial Tibial Cartilage', 'value': 'medial_tibial_cartilage'}, {'title': 'Femur', 'value': 'femur'}, {'title': 'Tibia', 'value': 'tibia'}, {'title': 'Patella', 'value': 'patella'}]

Choices of a structure select.

Listing the server’s directories for the GUI’s file dialog, which picks paths on the machine running the pipeline.

class kneemesh.gui.files.DirectoryEntry[source]

Bases: TypedDict

A file or directory as the file dialog lists it.

kneemesh.gui.files.list_directory(directory, suffixes=())[source]

The directories and files in a directory, directories first, each sorted by name, without hidden ones.

Files are listed only if their name ends with one of suffixes, compared without case, or all files if suffixes is empty. Unreadable entries are skipped.

Raises:

OSError – If the directory cannot be read.

Parameters:
Return type:

list[DirectoryEntry]