Skip to content

Commit

Permalink
Added more inputs, changed solverInto to inputInfo, and added aerothe…
Browse files Browse the repository at this point in the history
…rmal (#745)

* Added field input and verifed its totals.

* Added tests for vector field.

* Added the patchVar input.

* Added CHT.

* Added the missing files.

* Added the missing flag.
  • Loading branch information
friedenhe authored Jan 24, 2025
1 parent 3eeb40f commit 1389913
Show file tree
Hide file tree
Showing 34 changed files with 1,816 additions and 213 deletions.
275 changes: 146 additions & 129 deletions dafoam/mphys/mphys_dafoam.py

Large diffs are not rendered by default.

66 changes: 44 additions & 22 deletions dafoam/pyDAFoam.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,27 +281,37 @@ def __init__(self):
## },
self.function = {}

## Solver input information. Different type of design variables require different keys
## General input information. Different type of inputs require different keys
## For patchVelocity, we need to set a list of far field patch names from which the angle of
## attack is computed, this is usually a far field patch. Also, we need to prescribe
## flow and normal axies, and alpha = atan( U_normal / U_flow ) at patches
## Example
## solverInput = {
## "aero_vol_coords" : {"type": "volCoord"},
## inputInfo = {
## "aero_vol_coords" : {"type": "volCoord", "addToSolver": True},
## "patchV" = {
## "type": "patchVelocity",
## "patches": ["farField"],
## "flowAxis": "x",
## "normalAxis": "y"
## "normalAxis": "y",
## "addToSolver": True,
## },
## "ux0" = {
## "type": "patchVariable",
## "patches": ["inlet"],
## "variable": "U",
## "comp": 0
## "comp": 0,
## "addToSolver": True,
## },
## }
self.solverInput = {}
self.inputInfo = {}

## General input information. Different type of outputs require different keys
## Example
## outputInfo = {
## "T_conduct" : {"type": "thermalVar", "patches": ["wing"]},
## "f_aero": {"type": "surfForce", "patches": ["wing"]}
## }
self.outputInfo = {}

## List of patch names for the design surface. These patch names need to be of wall type
## and shows up in the constant/polyMesh/boundary file
Expand Down Expand Up @@ -620,7 +630,7 @@ def __init__(self):
"fpRelTol": 1e-6,
"fpMinResTolDiff": 1.0e2,
"fpPCUpwind": False,
"dynAdjustTol": True,
"dynAdjustTol": False,
}

## Normalization for residuals. We should normalize all residuals!
Expand Down Expand Up @@ -1485,21 +1495,23 @@ def set_solver_input(self, inputs, DVGeo=None):
"""
Set solver input. If it is forward mode, we also set the seeds
"""
inputDict = self.getOption("solverInput")
inputDict = self.getOption("inputInfo")

for inputName in list(inputDict.keys()):
inputType = inputDict[inputName]["type"]
input = inputs[inputName]
inputSize = len(input)
seeds = np.zeros(inputSize)
if self.getOption("useAD")["mode"] == "forward":
if inputType == "volCoord":
if self.getOption("useAD")["dvName"] not in list(inputDict.keys()):
seeds = self.calcFFD2XvSeeds(DVGeo)
else:
if inputName == self.getOption("useAD")["dvName"]:
seedIndex = self.getOption("useAD")["seedIndex"]
seeds[seedIndex] = 1.0
# this input is attached to solver comp
if "solver" in inputDict[inputName]["components"]:
inputType = inputDict[inputName]["type"]
input = inputs[inputName]
inputSize = len(input)
seeds = np.zeros(inputSize)
if self.getOption("useAD")["mode"] == "forward":
if inputType == "volCoord":
if self.getOption("useAD")["dvName"] not in list(inputDict.keys()):
seeds = self.calcFFD2XvSeeds(DVGeo)
else:
if inputName == self.getOption("useAD")["dvName"]:
seedIndex = self.getOption("useAD")["seedIndex"]
seeds[seedIndex] = 1.0

# here we need to update the solver input for both solver and solverAD
self.solver.setSolverInput(inputName, inputType, inputSize, input, seeds)
Expand Down Expand Up @@ -1659,7 +1671,7 @@ def solveAdjointUnsteady(self):
self.solverAD.createMLRKSPMatrixFree(PCMat, ksp)
functionDict = self.getOption("function")
designVarDict = self.getOption("solverInput")
designVarDict = self.getOption("inputInfo")
# init the dFdW vec
wSize = self.solver.getNLocalAdjointStates()
Expand Down Expand Up @@ -1877,7 +1889,7 @@ def solveAdjoint(self):
# ************ Now compute the total derivatives **********************
Info("Computing total derivatives....")
designVarDict = self.getOption("solverInput")
designVarDict = self.getOption("inputInfo")
for designVarName in designVarDict:
Info("Computing total derivatives for %s" % designVarName)
###################### BC: boundary condition as design variable ###################
Expand Down Expand Up @@ -3016,6 +3028,16 @@ def setStates(self, states):
self.solverAD.updateOFFieldArray(states)

return

def setVolCoords(self, vol_coords):
"""
Set the vol_coords to the OpenFOAM field
"""

self.solver.updateOFMeshArray(vol_coords)
self.solverAD.updateOFMeshArray(vol_coords)

return

def convertMPIVec2SeqArray(self, mpiVec):
"""
Expand Down
2 changes: 1 addition & 1 deletion src/adjoint/DAFunction/DAFunctionForce.C
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ DAFunctionForce::DAFunctionForce(
// initial value for forceDir_. it will be dynamically adjusted later
forceDir_ = {1.0, 0.0, 0.0};
word patchVelocityInputName = functionDict_.getWord("patchVelocityInputName");
dictionary patchVSubDict = daOption_.getAllOptions().subDict("solverInput").subDict(patchVelocityInputName);
dictionary patchVSubDict = daOption_.getAllOptions().subDict("inputInfo").subDict(patchVelocityInputName);
HashTable<label> axisIndices;
axisIndices.set("x", 0);
axisIndices.set("y", 1);
Expand Down
111 changes: 111 additions & 0 deletions src/adjoint/DAInput/DAInputField.C
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/*---------------------------------------------------------------------------*\
DAFoam : Discrete Adjoint with OpenFOAM
Version : v4
\*---------------------------------------------------------------------------*/

#include "DAInputField.H"

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

namespace Foam
{

defineTypeNameAndDebug(DAInputField, 0);
addToRunTimeSelectionTable(DAInput, DAInputField, dictionary);
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //

DAInputField::DAInputField(
const word inputName,
const word inputType,
fvMesh& mesh,
const DAOption& daOption,
const DAModel& daModel,
const DAIndex& daIndex)
: DAInput(
inputName,
inputType,
mesh,
daOption,
daModel,
daIndex)
{
fieldName_ = daOption_.getAllOptions().subDict("inputInfo").subDict(inputName).getWord("fieldName");
fieldType_ = daOption_.getAllOptions().subDict("inputInfo").subDict(inputName).getWord("fieldType");
}

void DAInputField::run(const scalarList& input)
{
/*
Description:
Assign the input array to OF's field variables. Note that we need different treatment for distributed and
non-distributed field inputs
*/

if (fieldType_ == "scalar")
{
volScalarField& field = const_cast<volScalarField&>(mesh_.thisDb().lookupObject<volScalarField>(fieldName_));
if (this->distributed())
{
forAll(field, cellI)
{
field[cellI] = input[cellI];
}
}
else
{
for (label globalCellI = 0; globalCellI < daIndex_.nGlobalCells; globalCellI++)
{
if (daIndex_.globalCellNumbering.isLocal(globalCellI))
{
label localCellI = daIndex_.globalCellNumbering.toLocal(globalCellI);
field[localCellI] = input[globalCellI];
}
}
}
field.correctBoundaryConditions();
}
else if (fieldType_ == "vector")
{
volVectorField& field = const_cast<volVectorField&>(mesh_.thisDb().lookupObject<volVectorField>(fieldName_));
if (this->distributed())
{
label counterI = 0;
forAll(field, cellI)
{
for (label i = 0; i < 3; i++)
{
field[cellI][i] = input[counterI];
counterI++;
}
}
}
else
{
for (label globalCellI = 0; globalCellI < daIndex_.nGlobalCells; globalCellI++)
{
if (daIndex_.globalCellNumbering.isLocal(globalCellI))
{
label localCellI = daIndex_.globalCellNumbering.toLocal(globalCellI);
for (label comp = 0; comp < 3; comp++)
{
label inputIdx = globalCellI * 3 + comp;
field[localCellI][comp] = input[inputIdx];
}
}
}
}
field.correctBoundaryConditions();
}
else
{
FatalErrorIn("DAInputField::run") << exit(FatalError);
}
}

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

} // End namespace Foam

// ************************************************************************* //
102 changes: 102 additions & 0 deletions src/adjoint/DAInput/DAInputField.H
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/*---------------------------------------------------------------------------*\
DAFoam : Discrete Adjoint with OpenFOAM
Version : v4
Description:
Child class for field variable input
\*---------------------------------------------------------------------------*/

#ifndef DAInputField_H
#define DAInputField_H

#include "DAInput.H"
#include "addToRunTimeSelectionTable.H"
#include "mixedFvPatchFields.H"
#include "DAGlobalVar.H"

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

namespace Foam
{

/*---------------------------------------------------------------------------*\
Class DAInputField Declaration
\*---------------------------------------------------------------------------*/

class DAInputField
: public DAInput
{

protected:
word fieldName_;
word fieldType_;

public:
TypeName("field");
// Constructors

//- Construct from components
DAInputField(
const word inputName,
const word inputType,
fvMesh& mesh,
const DAOption& daOption,
const DAModel& daModel,
const DAIndex& daIndex);

//- Destructor
virtual ~DAInputField()
{
}

virtual void run(const scalarList& input);

virtual label size()
{
if (fieldType_ == "scalar")
{
if (this->distributed())
{
return daIndex_.nLocalCells;
}
else
{
return daIndex_.nGlobalCells;
}
}
else if (fieldType_ == "vector")
{
if (this->distributed())
{
return daIndex_.nLocalCells * 3;
}
else
{
return daIndex_.nGlobalCells * 3;
}
}
else
{
FatalErrorIn("DAInputField::size") << "fieldType not valid" << exit(FatalError);
return -1;
}
}

virtual label distributed()
{
label distributed = daOption_.getAllOptions().subDict("inputInfo").subDict(inputName_).getLabel("distributed");
return distributed;
}
};

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

} // End namespace Foam

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

#endif

// ************************************************************************* //
Loading

0 comments on commit 1389913

Please sign in to comment.