From acfe947c6d09697d9c94eb2734ed922c351ff2da Mon Sep 17 00:00:00 2001 From: Tyagi Date: Mon, 5 Oct 2026 12:31:11 +1100 Subject: [PATCH 1/4] fix: match PETSc integer width in boundary registration Use the PETSc header's PetscInt rather than a private C int typedef. Allocate component and constraint-index arrays with PETSc.IntType and use PetscInt for boundary label storage and Cython component views, avoiding int32 buffers passed to an int64 PETSc API. Add Couette regression cases for inferred and legacy explicit component lists. Both fail on the published Gadi int64 image at the component dtype assertion and pass against the existing Mac int32 installation; isolated int64 rebuild validation follows. Underworld development team with AI support from Claude Code --- .../cython/petsc_generic_snes_solvers.pyx | 52 +++++++++---------- src/underworld3/cython/petsc_types.pxd | 4 +- ...st_0764_petsc_index_boundary_conditions.py | 44 ++++++++++++++++ 3 files changed, 73 insertions(+), 27 deletions(-) create mode 100644 tests/test_0764_petsc_index_boundary_conditions.py diff --git a/src/underworld3/cython/petsc_generic_snes_solvers.pyx b/src/underworld3/cython/petsc_generic_snes_solvers.pyx index d4227e83d..ab69a1d01 100644 --- a/src/underworld3/cython/petsc_generic_snes_solvers.pyx +++ b/src/underworld3/cython/petsc_generic_snes_solvers.pyx @@ -2777,7 +2777,7 @@ class SolverBaseClass(uw_object): "with None / sympy.oo entries in 'conds' instead, e.g. " "conds=(None, 5, 1.2)", DeprecationWarning, stacklevel=3) - components = np.array(components, dtype=np.int32, ndmin=1) + components = np.array(components, dtype=PETSc.IntType, ndmin=1) elif components is None: cpts_list = [] @@ -2785,7 +2785,7 @@ class SolverBaseClass(uw_object): if fn != sympy.oo and fn != -sympy.oo: cpts_list.append(i) - components = np.array(cpts_list, dtype=np.int32, ndmin=1) + components = np.array(cpts_list, dtype=PETSc.IntType, ndmin=1) else: raise TypeError("Unsupported BC 'components' argument") @@ -4009,8 +4009,8 @@ class SNES_Scalar(SolverBaseClass): self.dm.createDS() # set functions - cdef int ind=1 - cdef int [::1] comps_view # for numpy memory view + cdef PetscInt ind=1 + cdef PetscInt [::1] comps_view # for numpy memory view cdef DM cdm = self.dm cdef DS ds = self.dm.getDS() cdef PtrContainer ext = self.compiled_extensions @@ -4271,8 +4271,8 @@ class SNES_Scalar(SolverBaseClass): return # set functions - cdef int ind=1 - cdef int [::1] comps_view # for numpy memory view + cdef PetscInt ind=1 + cdef PetscInt [::1] comps_view # for numpy memory view cdef DM cdm = self.dm cdef DS ds = self.dm.getDS() cdef PtrContainer ext = self.compiled_extensions @@ -4906,7 +4906,7 @@ class SNES_Vector(SolverBaseClass): ]) import numpy as np - components = np.arange(cdim, dtype=np.int32) + components = np.arange(cdim, dtype=PETSc.IntType) self.natural_bcs.append(BC( 0, components, fn_f, fn_F, None, @@ -4970,8 +4970,8 @@ class SNES_Vector(SolverBaseClass): ## This part is done once on the solver dm ... not required every time we update the functions ... ## the values of the natural bcs can be updated - cdef int ind=1 - cdef int [::1] comps_view # for numpy memory view + cdef PetscInt ind=1 + cdef PetscInt [::1] comps_view # for numpy memory view cdef DM cdm = self.dm for index,bc in enumerate(self.natural_bcs): @@ -5295,8 +5295,8 @@ class SNES_Vector(SolverBaseClass): return # set functions - cdef int ind=1 - cdef int [::1] comps_view # for numpy memory view + cdef PetscInt ind=1 + cdef PetscInt [::1] comps_view # for numpy memory view cdef DM cdm = self.dm cdef DS ds = self.dm.getDS() cdef PtrContainer ext = self.compiled_extensions @@ -5735,8 +5735,8 @@ class SNES_MultiComponent(SolverBaseClass): self.dm.createDS() - cdef int ind=1 - cdef int [::1] comps_view + cdef PetscInt ind=1 + cdef PetscInt [::1] comps_view cdef DM cdm = self.dm for index, bc in enumerate(self.natural_bcs): @@ -6022,8 +6022,8 @@ class SNES_MultiComponent(SolverBaseClass): print(f"SNES_MultiComponent ({self.name}): SNES solver does not need to be rebuilt", flush=True) return - cdef int ind=1 - cdef int [::1] comps_view + cdef PetscInt ind=1 + cdef PetscInt [::1] comps_view cdef DM cdm = self.dm cdef DS ds = self.dm.getDS() cdef PtrContainer ext = self.compiled_extensions @@ -7151,7 +7151,7 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): ]) import numpy as np - components = np.arange(dim, dtype=np.int32) + components = np.arange(dim, dtype=PETSc.IntType) self.natural_bcs.append(BC( 0, components, fn_f, fn_F, fn_p, @@ -8682,8 +8682,8 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): ## This part is done once on the solver dm ... not required every time we update the functions ... ## the values of the natural bcs can be updated - cdef int ind=1 - cdef int [::1] comps_view # for numpy memory view + cdef PetscInt ind=1 + cdef PetscInt [::1] comps_view # for numpy memory view cdef DM cdm = self.dm for index,bc in enumerate(self.natural_bcs): @@ -8729,15 +8729,15 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): # u-row traction h·n and the uh Jacobian) and once for the multiplier # field (carries the h-row constraint n·u−g and the hu Jacobian). # Guarded: no-op for ordinary Stokes. - cdef int [::1] cbc_comps_view - cdef int [::1] cbc_hcomps_view + cdef PetscInt [::1] cbc_comps_view + cdef PetscInt [::1] cbc_hcomps_view for cbc in self._block_constraint_bcs: cbc_boundary = cbc.boundary cbc_value = mesh.boundaries[cbc_boundary].value ind = cbc_value cbc_fid_h = cbc.lam._solver_field_id - cbc_comps = np.arange(mesh.dim, dtype=np.int32) + cbc_comps = np.arange(mesh.dim, dtype=PETSc.IntType) cbc_comps_view = cbc_comps cbc.petsc_id_u = PetscDSAddBoundary_UW(cdm.dm, 6, @@ -8752,7 +8752,7 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): &ind, NULL, ) - cbc_hcomps = np.array([0], dtype=np.int32) + cbc_hcomps = np.array([0], dtype=PETSc.IntType) cbc_hcomps_view = cbc_hcomps cbc.petsc_id_h = PetscDSAddBoundary_UW(cdm.dm, 6, @@ -8964,11 +8964,11 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): fidx |= set(extra_field[(p, f)]) if fidx: fidx = sorted(fidx) - Snew.setFieldConstraintIndices(p, f, np.array(fidx, dtype=np.int32)) + Snew.setFieldConstraintIndices(p, f, np.array(fidx, dtype=PETSc.IntType)) point_local.extend(field_offset + i for i in fidx) field_offset += fdof if point_local: - Snew.setConstraintIndices(p, np.array(sorted(point_local), dtype=np.int32)) + Snew.setConstraintIndices(p, np.array(sorted(point_local), dtype=PETSc.IntType)) dm.setLocalSection(Snew) # Force the global-section rebuild (and fail fast if malformed); the @@ -8987,8 +8987,8 @@ class SNES_Stokes_SaddlePt(SolverBaseClass): return # set functions - cdef int ind=1 - cdef int [::1] comps_view # for numpy memory view + cdef PetscInt ind=1 + cdef PetscInt [::1] comps_view # for numpy memory view cdef DM cdm = self.dm cdef DS ds = self.dm.getDS() cdef PtrContainer ext = self.compiled_extensions diff --git a/src/underworld3/cython/petsc_types.pxd b/src/underworld3/cython/petsc_types.pxd index 07ce18876..af86c5f3a 100644 --- a/src/underworld3/cython/petsc_types.pxd +++ b/src/underworld3/cython/petsc_types.pxd @@ -1,7 +1,9 @@ # Underworld Cython declarations to use PetscDS functionality # The following aren't available via petsc4py - Oct2021 -ctypedef int PetscInt +# PETSc selects this width in petscconf.h; a local C int alias breaks int64 builds. +cdef extern from "petscsystypes.h": + ctypedef int PetscInt ctypedef double PetscReal ctypedef double PetscScalar ctypedef int PetscErrorCode diff --git a/tests/test_0764_petsc_index_boundary_conditions.py b/tests/test_0764_petsc_index_boundary_conditions.py new file mode 100644 index 000000000..04ba418e8 --- /dev/null +++ b/tests/test_0764_petsc_index_boundary_conditions.py @@ -0,0 +1,44 @@ +"""Boundary registration must preserve PETSc's configured integer width. + +The exact Couette solution is u=(y, 0), p=constant on the unit square. +Exercise both inferred and legacy explicit component lists, including [0, 1], +which a 64-bit PETSc build misread as 4294967296 from a 32-bit buffer. +""" + +import numpy as np +import pytest +from petsc4py import PETSc + +import underworld3 as uw + +pytestmark = pytest.mark.level_1 + + +@pytest.mark.tier_a +@pytest.mark.parametrize("explicit_components", [False, True]) +def test_couette_boundary_components_use_petsc_integer_width(explicit_components): + mesh = uw.meshing.StructuredQuadBox(elementRes=(4, 4), qdegree=3) + velocity = uw.discretisation.MeshVariable("index_velocity", mesh, 2, degree=2) + pressure = uw.discretisation.MeshVariable("index_pressure", mesh, 1, degree=1) + stokes = uw.systems.Stokes(mesh, velocityField=velocity, pressureField=pressure) + stokes.constitutive_model = uw.constitutive_models.ViscousFlowModel + stokes.constitutive_model.Parameters.viscosity = 1 + stokes.bodyforce = (0, 0) + y = mesh.N.y + for boundary in ("Top", "Bottom", "Left", "Right"): + if explicit_components: + with pytest.warns(DeprecationWarning, match="components"): + stokes.add_dirichlet_bc((y, 0), boundary, (0, 1)) + else: + stokes.add_dirichlet_bc((y, 0), boundary) + + for bc in stokes.essential_bcs: + assert bc.components.dtype == np.dtype(PETSc.IntType) + np.testing.assert_array_equal(bc.components, [0, 1]) + + stokes.tolerance = 1e-9 + stokes.solve() + assert stokes.snes.getConvergedReason() > 0 + coords = velocity.coords + expected = np.column_stack((coords[:, 1], np.zeros(len(coords)))) + np.testing.assert_allclose(velocity.array[:, 0, :], expected, rtol=1e-7, atol=1e-8) From 46a90631b02910cd1a960cb753b01e97c440dbc6 Mon Sep 17 00:00:00 2001 From: Tyagi Date: Mon, 5 Oct 2026 12:33:03 +1100 Subject: [PATCH 2/4] fix: use PETSc header types for JIT solver callbacks Remove the generated callback header's private int32 PetscInt alias. Residual and Jacobian callbacks must use the same configured integer width as PETSc and the compiled Cython declarations. Underworld development team with AI support from Claude Code --- src/underworld3/utilities/_jitextension.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/underworld3/utilities/_jitextension.py b/src/underworld3/utilities/_jitextension.py index 6387b33e3..d0e7a1bb1 100644 --- a/src/underworld3/utilities/_jitextension.py +++ b/src/underworld3/utilities/_jitextension.py @@ -1455,10 +1455,7 @@ def _patch_coords(expr): # Create header top content. h_str = """ -typedef int PetscInt; -typedef double PetscReal; -typedef double PetscScalar; -typedef int PetscBool; +#include #include // Adding missing function implementation From 34839d9d7a63f73a0e4989497bdd0c14063e156f Mon Sep 17 00:00:00 2001 From: Tyagi Date: Mon, 5 Oct 2026 12:34:57 +1100 Subject: [PATCH 3/4] test: cover int-width boundary registration in 3D and traction solves Verify exact Couette flow for inferred and explicit Dirichlet components in two and three dimensions, and for natural traction conditions. All five baselines pass on the existing int32 installation; the int64 isolated build exercises the same cases. Underworld development team with AI support from Claude Code --- ...st_0764_petsc_index_boundary_conditions.py | 48 +++++++++++++++---- 1 file changed, 39 insertions(+), 9 deletions(-) diff --git a/tests/test_0764_petsc_index_boundary_conditions.py b/tests/test_0764_petsc_index_boundary_conditions.py index 04ba418e8..db27edfff 100644 --- a/tests/test_0764_petsc_index_boundary_conditions.py +++ b/tests/test_0764_petsc_index_boundary_conditions.py @@ -16,29 +16,59 @@ @pytest.mark.tier_a @pytest.mark.parametrize("explicit_components", [False, True]) -def test_couette_boundary_components_use_petsc_integer_width(explicit_components): - mesh = uw.meshing.StructuredQuadBox(elementRes=(4, 4), qdegree=3) - velocity = uw.discretisation.MeshVariable("index_velocity", mesh, 2, degree=2) +@pytest.mark.parametrize("dim", [2, 3]) +def test_couette_boundary_components_use_petsc_integer_width(explicit_components, dim): + mesh = uw.meshing.StructuredQuadBox(elementRes=(4,) * dim, qdegree=3) + velocity = uw.discretisation.MeshVariable("index_velocity", mesh, dim, degree=2) pressure = uw.discretisation.MeshVariable("index_pressure", mesh, 1, degree=1) stokes = uw.systems.Stokes(mesh, velocityField=velocity, pressureField=pressure) stokes.constitutive_model = uw.constitutive_models.ViscousFlowModel stokes.constitutive_model.Parameters.viscosity = 1 - stokes.bodyforce = (0, 0) + stokes.bodyforce = (0,) * dim y = mesh.N.y - for boundary in ("Top", "Bottom", "Left", "Right"): + conds = (y,) + (0,) * (dim - 1) + boundaries = ["Top", "Bottom", "Left", "Right"] + if dim == 3: + boundaries += ["Front", "Back"] + for boundary in boundaries: if explicit_components: with pytest.warns(DeprecationWarning, match="components"): - stokes.add_dirichlet_bc((y, 0), boundary, (0, 1)) + stokes.add_dirichlet_bc(conds, boundary, tuple(range(dim))) else: - stokes.add_dirichlet_bc((y, 0), boundary) + stokes.add_dirichlet_bc(conds, boundary) for bc in stokes.essential_bcs: assert bc.components.dtype == np.dtype(PETSc.IntType) - np.testing.assert_array_equal(bc.components, [0, 1]) + np.testing.assert_array_equal(bc.components, np.arange(dim)) stokes.tolerance = 1e-9 stokes.solve() assert stokes.snes.getConvergedReason() > 0 coords = velocity.coords - expected = np.column_stack((coords[:, 1], np.zeros(len(coords)))) + expected = np.zeros((len(coords), dim)) + expected[:, 0] = coords[:, 1] + np.testing.assert_allclose(velocity.array[:, 0, :], expected, rtol=1e-7, atol=1e-8) + + +@pytest.mark.tier_a +def test_couette_natural_boundary_components_use_petsc_integer_width(): + """Unit shear: natural BC terms enter the residual with minus the traction.""" + mesh = uw.meshing.StructuredQuadBox(elementRes=(4, 4), qdegree=3) + velocity = uw.discretisation.MeshVariable("traction_velocity", mesh, 2, degree=2) + pressure = uw.discretisation.MeshVariable("traction_pressure", mesh, 1, degree=1) + stokes = uw.systems.Stokes(mesh, velocityField=velocity, pressureField=pressure) + stokes.constitutive_model = uw.constitutive_models.ViscousFlowModel + stokes.constitutive_model.Parameters.viscosity = 1 + stokes.bodyforce = (0, 0) + stokes.add_dirichlet_bc((mesh.N.y, 0), "Top") + stokes.add_dirichlet_bc((mesh.N.y, 0), "Bottom") + stokes.add_natural_bc((0, 1), "Left") + stokes.add_natural_bc((0, -1), "Right") + for bc in stokes.natural_bcs: + assert bc.components.dtype == np.dtype(PETSc.IntType) + np.testing.assert_array_equal(bc.components, [0, 1]) + stokes.tolerance = 1e-9 + stokes.solve() + assert stokes.snes.getConvergedReason() > 0 + expected = np.column_stack((velocity.coords[:, 1], np.zeros(len(velocity.coords)))) np.testing.assert_allclose(velocity.array[:, 0, :], expected, rtol=1e-7, atol=1e-8) From 391296aa13ae45b102fe7cbca850240f478b06ba Mon Sep 17 00:00:00 2001 From: Tyagi Date: Mon, 5 Oct 2026 14:41:47 +1100 Subject: [PATCH 4/4] test: bound round-off in the enclosed Couette pressure solve The all-Dirichlet Couette problem has constant pressure. On four Gadi ranks the Schur right-hand side is about 5.6e-14; the default absolute tolerance of 1e-50 and relative tolerance of 1e-10 force an unattainable residual target and cause pressure divergence followed by NaN velocity subsolves. This also reproduces on unchanged upstream development with int32. Declare the constant-pressure nullspace and use a test-specific pressure-block absolute tolerance of 1e-12. Retain the original velocity accuracy, convergence, component-value and PETSc integer-width assertions. All five analytic regressions pass on four ranks with PETSc 3.25.4 int32 and int64 on Gadi. Production solver defaults are unchanged. Underworld development team with AI support from Claude Code --- tests/test_0764_petsc_index_boundary_conditions.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/test_0764_petsc_index_boundary_conditions.py b/tests/test_0764_petsc_index_boundary_conditions.py index db27edfff..2903962d3 100644 --- a/tests/test_0764_petsc_index_boundary_conditions.py +++ b/tests/test_0764_petsc_index_boundary_conditions.py @@ -41,6 +41,10 @@ def test_couette_boundary_components_use_petsc_integer_width(explicit_components assert bc.components.dtype == np.dtype(PETSc.IntType) np.testing.assert_array_equal(bc.components, np.arange(dim)) + stokes.petsc_use_pressure_nullspace = True + # The exact pressure is constant. Its Schur RHS is round-off (~6e-14) + # in parallel, so a purely relative subsolve asks for unattainable accuracy. + stokes.petsc_options["fieldsplit_pressure_ksp_atol"] = 1e-12 stokes.tolerance = 1e-9 stokes.solve() assert stokes.snes.getConvergedReason() > 0