From 2ef96e9e4391816f5a7aafb840099625c03da9d0 Mon Sep 17 00:00:00 2001
From: Vaggelis Papoutsis <vaggelisp@gmail.com>
Date: Mon, 10 Jun 2024 14:52:58 +0300
Subject: [PATCH] BUG: adjointRotatingWallVelocity causes sensitivities to
 crash. Fixes #3180

---
 .../incompressibleAdjointSolver.C             | 28 ++++++++++---------
 1 file changed, 15 insertions(+), 13 deletions(-)

diff --git a/src/optimisation/adjointOptimisation/adjoint/solvers/adjointSolvers/incompressible/incompressibleAdjointSolver/incompressibleAdjointSolver.C b/src/optimisation/adjointOptimisation/adjoint/solvers/adjointSolvers/incompressible/incompressibleAdjointSolver/incompressibleAdjointSolver.C
index cd6cc6839dd..fa3770a874f 100644
--- a/src/optimisation/adjointOptimisation/adjoint/solvers/adjointSolvers/incompressible/incompressibleAdjointSolver/incompressibleAdjointSolver.C
+++ b/src/optimisation/adjointOptimisation/adjoint/solvers/adjointSolvers/incompressible/incompressibleAdjointSolver/incompressibleAdjointSolver.C
@@ -420,19 +420,21 @@ void Foam::incompressibleAdjointSolver::accumulateBCSensitivityIntegrand
         fvPatchVectorField& Uab = UaBoundary[patchI];
         if (isA<adjointVectorBoundaryCondition>(Uab))
         {
-            const fvPatch& patch = mesh_.boundary()[patchI];
-            tmp<vectorField> tnf = patch.nf();
-            const scalarField& magSf = patch.magSf();
-
-            tmp<vectorField> DvDbMult =
-                nuEffBoundary[patchI]*(Uab.snGrad() + (gradUabf[patchI] & tnf))
-    //        - (nf*pa.boundaryField()[patchI])
-              + adjointTurbulence().adjointMomentumBCSource()[patchI];
-            bcDxDbMult()[patchI] +=
-                (
-                    DvDbMult
-                  & refCast<adjointVectorBoundaryCondition>(Uab).dxdbMult()
-                )*magSf*dt;
+            tmp<tensorField> dxdbMult =
+                refCast<adjointVectorBoundaryCondition>(Uab).dxdbMult();
+            if (dxdbMult)
+            {
+                const fvPatch& patch = mesh_.boundary()[patchI];
+                tmp<vectorField> tnf = patch.nf();
+                const scalarField& magSf = patch.magSf();
+
+                tmp<vectorField> DvDbMult =
+                    nuEffBoundary[patchI]
+                   *(Uab.snGrad() + (gradUabf[patchI] & tnf))
+        //        - (nf*pa.boundaryField()[patchI])
+                  + adjointTurbulence().adjointMomentumBCSource()[patchI];
+                bcDxDbMult()[patchI] += (DvDbMult & dxdbMult())*magSf*dt;
+            }
         }
     }
 }
-- 
GitLab