unitConversion: Unit conversions on all input parameters

The majority of input parameters now support automatic unit conversion.
Units are specified within square brackets, either before or after the
value. Primitive parameters (e.g., scalars, vectors, tensors, ...),
dimensioned types, fields, Function1-s and Function2-s all support unit
conversion in this way.

Unit conversion occurs on input only. OpenFOAM writes out all fields and
parameters in standard units. It is recommended to use '.orig' files in
the 0 directory to preserve user-readable input if those files are being
modified by pre-processing applications (e.g., setFields).

For example, to specify a volumetric flow rate inlet boundary in litres
per second [l/s], rather than metres-cubed per second [m^3/s], in 0/U:

    boundaryField
    {
        inlet
        {
            type            flowRateInletVelocity;
            volumetricFlowRate 0.1 [l/s];
            value           $internalField;
        }

        ...
    }

Or, to specify the pressure field in bar, in 0/p:

    internalField   uniform 1 [bar];

Or, to convert the parameters of an Arrhenius reaction rate from a
cm-mol-kcal unit system, in constant/chemistryProperties:

    reactions
    {
        methaneReaction
        {
            type    irreversibleArrhenius;
            reaction "CH4^0.2 + 2O2^1.3 = CO2 + 2H2O";
            A       6.7e12 [(mol/cm^3)^-0.5/s];
            beta    0;
            Ea      48.4 [kcal/mol];
        }
    }

Or, to define a time-varying outlet pressure using a CSV file in which
the pressure column is in mega-pascals [MPa], in 0/p:

    boundaryField
    {
        outlet
        {
            type            uniformFixedValue;
            value
            {
                type            table;
                format          csv;
                nHeaderLine     1;
                units           ([s] [MPa]); // <-- new units entry
                columns         (0 1);
                mergeSeparators no;
                file            "data/pressure.csv";
                outOfBounds     clamp;
                interpolationScheme linear;
            }
        }

        ...
    }

(Note also that a new 'columns' entry replaces the old 'refColumn' and
'componentColumns'. This is is considered to be more intuitive, and has
a consistent syntax with the new 'units' entry. 'columns' and
'componentColumns' have been retained for backwards compatibility and
will continue to work for the time being.)

Unit definitions can be added in the global or case controlDict files.
See UnitConversions in $WM_PROJECT_DIR/etc/controlDict for examples.
Currently available units include:

    Standard: kg m s K kmol A Cd

     Derived: Hz N Pa J W g um mm cm km l ml us ms min hr mol
              rpm bar atm kPa MPa cal kcal cSt cP % rad rot deg

A user-time unit is also provided if user-time is in operation. This
allows it to be specified locally whether a parameter relates to
real-time or to user-time. For example, to define a mass source that
ramps up from a given engine-time (in crank-angle-degrees [CAD]) over a
duration in real-time, in constant/fvModels:

    massSource1
    {
        type        massSource;
        points      ((1 2 3));
        massFlowRate
        {
            type        scale;
            scale       linearRamp;
            start       20 [CAD];
            duration    50 [ms];
            value       0.1 [g/s];
        }
    }

Specified units will be checked against the parameter's dimensions where
possible, and an error generated if they are not consistent. For the
dimensions to be available for this check, the code requires
modification, and work propagating this change across OpenFOAM is
ongoing. Unit conversions are still possible without these changes, but
the validity of such conversions will not be checked.

Units are no longer permitted in 'dimensions' entries in field files.
These 'dimensions' entries can now, instead, take the names of
dimensions. The names of the available dimensions are:

    Standard: mass length time temperature
              moles current luminousIntensity

     Derived: area volume rate velocity momentum acceleration density
              force energy power pressure kinematicPressure
              compressibility gasConstant specificHeatCapacity
              kinematicViscosity dynamicViscosity thermalConductivity
              volumetricFlux massFlux

So, for example, a 0/epsilon file might specify the dimensions as
follows:

    dimensions      [energy/mass/time];

And a 0/alphat file might have:

    dimensions      [thermalConductivity/specificHeatCapacity];

*** Development Notes ***

A unit conversion can construct trivially from a dimension set,
resulting in a "standard" unit with a conversion factor of one. This
means the functions which perform unit conversion on read can be
provided dimension sets or unit conversion objects interchangeably.

A basic `dict.lookup<vector>("Umean")` call will do unit conversion, but
it does not know the parameter's dimensions, so it cannot check the
validity of the supplied units. A corresponding lookup function has been
added in which the dimensions or units can be provided; in this case the
corresponding call would be `dict.lookup<vector>("Umean", dimVelocity)`.
This function enables additional checking and should be used wherever
possible.

Function1-s and Function2-s have had their constructors and selectors
changed so that dimensions/units must be specified by calling code. In
the case of Function1, two unit arguments must be given; one for the
x-axis and one for the value-axis. For Function2-s, three must be
provided.

In some cases, it is desirable (or at least established practice), that
a given non-standard unit be used in the absence of specific
user-defined units. Commonly this includes reading angles in degrees
(rather than radians) and reading times in user-time (rather than
real-time). The primitive lookup functions and Function1 and Function2
selectors both support specifying a non-standard default unit. For
example, `theta_ = dict.lookup<scalar>("theta", unitDegrees)` will read
an angle in degrees by default. If this is done within a model which
also supports writing then the write call must be modified accordingly
so that the data is also written out in degrees. Overloads of writeEntry
have been created for this purpose. In this case, the angle theta should
be written out with `writeEntry(os, "theta", unitDegrees, theta_)`.
Function1-s and Function2-s behave similarly, but with greater numbers
of dimensions/units arguments as before.

The non-standard user-time unit can be accessed by a `userUnits()`
method that has been added to Time. Use of this user-time unit in the
construction of Function1-s should prevent the need for explicit
user-time conversion in boundary conditions and sub-models and similar.

Some models might contain non-typed stream-based lookups of the form
`dict.lookup("p0") >> p0_` (e.g., in a re-read method), or
`Umean_(dict.lookup("Umean"))` (e.g., in an initialiser list). These
calls cannot facilitate unit conversion and are therefore discouraged.
They should be replaced with
`p0_ = dict.lookup<scalar>("p0", dimPressure)` and
`Umean_(dict.lookup<vector>("Umean", dimVelocity))` and similar whenever
they are found.
This commit is contained in:
Will Bainbridge
2024-04-19 11:44:41 +01:00
parent d21e75ac74
commit 476bb42b04
626 changed files with 8274 additions and 4300 deletions

View File

@ -53,7 +53,6 @@ Description
#include "removePoints.H"
#include "meshCheck.H"
#include "polyTopoChangeMap.H"
#include "unitConversion.H"
using namespace Foam;
@ -305,24 +304,25 @@ int main(int argc, char *argv[])
#include "createPolyMesh.H"
const word oldInstance = mesh.pointsInstance();
const scalar featureAngle = args.argRead<scalar>(1);
const scalar minCos = Foam::cos(degToRad(featureAngle));
const scalar featureAngle = degToRad(args.argRead<scalar>(1));
const scalar minCos = Foam::cos(featureAngle);
// Sin of angle between two consecutive edges on a face.
// If sin(angle) larger than this the face will be considered concave.
scalar concaveAngle = args.optionLookupOrDefault("concaveAngle", 30.0);
scalar concaveSin = Foam::sin(degToRad(concaveAngle));
const scalar concaveAngle =
degToRad(args.optionLookupOrDefault("concaveAngle", 30.0));
const scalar concaveSin = Foam::sin(concaveAngle);
const bool overwrite = args.optionFound("overwrite");
const bool meshQuality = args.optionFound("meshQuality");
Info<< "Merging all faces of a cell" << nl
<< " - which are on the same patch" << nl
<< " - which make an angle < " << featureAngle << " degrees"
<< nl
<< " - which make an angle < " << radToDeg(featureAngle)
<< " degrees" << nl
<< " (cos:" << minCos << ')' << nl
<< " - even when resulting face becomes concave by more than "
<< concaveAngle << " degrees" << nl
<< radToDeg(concaveAngle) << " degrees" << nl
<< " (sin:" << concaveSin << ')' << nl
<< endl;

View File

@ -50,7 +50,6 @@ Description
#include "cellSet.H"
#include "cellModeller.H"
#include "meshCutter.H"
#include "unitConversion.H"
#include "geomCellLooper.H"
#include "plane.H"
#include "edgeVertex.H"
@ -548,9 +547,9 @@ int main(int argc, char *argv[])
#include "createPolyMesh.H"
const word oldInstance = mesh.pointsInstance();
const scalar featureAngle = args.argRead<scalar>(1);
const scalar minCos = Foam::cos(degToRad(featureAngle));
const scalar minSin = Foam::sin(degToRad(featureAngle));
const scalar featureAngle = degToRad(args.argRead<scalar>(1));
const scalar minCos = Foam::cos(featureAngle);
const scalar minSin = Foam::sin(featureAngle);
const bool readSet = args.optionFound("set");
const bool geometry = args.optionFound("geometry");
@ -559,7 +558,7 @@ int main(int argc, char *argv[])
const scalar edgeTol = args.optionLookupOrDefault("tol", 0.2);
Info<< "Trying to split cells with internal angles > feature angle\n" << nl
<< "featureAngle : " << featureAngle << nl
<< "featureAngle : " << radToDeg(featureAngle) << nl
<< "edge snapping tol : " << edgeTol << nl;
if (readSet)
{

View File

@ -2,7 +2,7 @@
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2011-2021 OpenFOAM Foundation
\\ / A nd | Copyright (C) 2011-2024 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
@ -35,7 +35,6 @@ Description
#include "IFstream.H"
#include "OFstream.H"
#include "pointField.H"
#include "unitConversion.H"
using namespace Foam;

View File

@ -1429,7 +1429,11 @@ int main(int argc, char *argv[])
// Un-merge any merged cyclics
if (args.optionFound("includedAngle"))
{
polyMeshUnMergeCyclics(mesh, args.optionRead<scalar>("includedAngle"));
polyMeshUnMergeCyclics
(
mesh,
degToRad(args.optionRead<scalar>("includedAngle"))
);
}
else
{

View File

@ -43,7 +43,6 @@ Description
#include "wedgePolyPatch.H"
#include "mergedCyclicPolyPatch.H"
#include "polyMeshUnMergeCyclics.H"
#include "unitConversion.H"
using namespace Foam;

View File

@ -2,7 +2,7 @@
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2011-2023 OpenFOAM Foundation
\\ / A nd | Copyright (C) 2011-2024 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
@ -35,7 +35,6 @@ Description
#include "Time.H"
#include "repatchMesh.H"
#include "repatcher.H"
#include "unitConversion.H"
#include "OFstream.H"
#include "ListOps.H"
@ -84,12 +83,12 @@ int main(int argc, char *argv[])
<< " s\n" << endl << endl;
const scalar featureAngle = args.argRead<scalar>(1);
const scalar featureAngle = degToRad(args.argRead<scalar>(1));
const bool overwrite = args.optionFound("overwrite");
const scalar minCos = Foam::cos(degToRad(featureAngle));
const scalar minCos = Foam::cos(featureAngle);
Info<< "Feature:" << featureAngle << endl
Info<< "Feature:" << radToDeg(featureAngle) << endl
<< "minCos :" << minCos << endl
<< endl;

View File

@ -2,7 +2,7 @@
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2011-2023 OpenFOAM Foundation
\\ / A nd | Copyright (C) 2011-2024 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
@ -168,6 +168,7 @@ int main(int argc, char *argv[])
scalar nonOrthThreshold = 70;
args.optionReadIfPresent("nonOrthThreshold", nonOrthThreshold);
nonOrthThreshold = degToRad(nonOrthThreshold);
scalar skewThreshold = 4;
args.optionReadIfPresent("skewThreshold", skewThreshold);

View File

@ -61,7 +61,6 @@ Usage
#include "argList.H"
#include "Time.H"
#include "fvMesh.H"
#include "unitConversion.H"
#include "polyTopoChange.H"
#include "polyTopoChangeMap.H"
#include "PackedBoolList.H"
@ -90,7 +89,7 @@ void simpleMarkFeatures
labelList& multiCellFeaturePoints
)
{
scalar minCos = Foam::cos(degToRad(featureAngle));
const scalar minCos = Foam::cos(featureAngle);
const polyBoundaryMesh& patches = mesh.boundaryMesh();
@ -393,10 +392,10 @@ int main(int argc, char *argv[])
}
}
const scalar featureAngle = args.argRead<scalar>(1);
const scalar minCos = Foam::cos(degToRad(featureAngle));
const scalar featureAngle = degToRad(args.argRead<scalar>(1));
const scalar minCos = Foam::cos(featureAngle);
Info<< "Feature:" << featureAngle << endl
Info<< "Feature:" << radToDeg(featureAngle) << endl
<< "minCos :" << minCos << endl
<< endl;

View File

@ -75,7 +75,6 @@ See also
#include "pointSet.H"
#include "transformField.H"
#include "transformGeometricField.H"
#include "unitConversion.H"
using namespace Foam;

View File

@ -2,7 +2,7 @@
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2011-2023 OpenFOAM Foundation
\\ / A nd | Copyright (C) 2011-2024 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
@ -120,13 +120,10 @@ int main(int argc, char *argv[])
// Read field
volScalarField field(*iter(), mesh);
// lookup field from dictionary and convert field
label unitNumber;
if
(
foamDataToFluentDict.readIfPresent(field.name(), unitNumber)
&& unitNumber > 0
)
// Lookup field from dictionary and convert field
const label unitNumber =
foamDataToFluentDict.lookupOrDefault<label>(field.name(), 0);
if (unitNumber > 0)
{
Info<< " Converting field " << field.name() << endl;
writeFluentField(field, unitNumber, fluentDataFile);
@ -145,13 +142,10 @@ int main(int argc, char *argv[])
// Read field
volVectorField field(*iter(), mesh);
// lookup field from dictionary and convert field
label unitNumber;
if
(
foamDataToFluentDict.readIfPresent(field.name(), unitNumber)
&& unitNumber > 0
)
// Lookup field from dictionary and convert field
const label unitNumber =
foamDataToFluentDict.lookupOrDefault<label>(field.name(), 0);
if (unitNumber > 0)
{
Info<< " Converting field " << field.name() << endl;
writeFluentField(field, unitNumber, fluentDataFile);

View File

@ -2,7 +2,7 @@
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2011-2023 OpenFOAM Foundation
\\ / A nd | Copyright (C) 2011-2024 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
@ -45,8 +45,7 @@ Usage
{
file "pressureData";
nHeaderLine 1; // number of header lines
refColumn 0; // reference column index
componentColumns (1); // component column indices
columns (0 1); // column indices
separator " "; // optional (defaults to ",")
mergeSeparators no; // merge multiple separators
outOfBounds clamp; // optional out-of-bounds handling
@ -162,6 +161,7 @@ int main(int argc, char *argv[])
Function1s::Table<scalar> pData
(
"pressure",
{dimTime, dimPressure},
dict.subDict("pressureData")
);

View File

@ -2,7 +2,7 @@
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2013-2023 OpenFOAM Foundation
\\ / A nd | Copyright (C) 2013-2024 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
@ -46,8 +46,6 @@ void processField
return;
}
const word timeName(mesh.time().name());
IOobjectList fieldObjbjects(objects.lookupClass(VolField<Type>::typeName));
if (fieldObjbjects.lookup(fieldName) != nullptr)

View File

@ -36,7 +36,6 @@ Description
#include "Time.H"
#include "volFields.H"
#include "CompactListList.H"
#include "unitConversion.H"
#include "pairPatchAgglomeration.H"
#include "labelListIOList.H"
#include "syncTools.H"

View File

@ -2,7 +2,7 @@
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2023 OpenFOAM Foundation
\\ / A nd | Copyright (C) 2023-2024 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
@ -27,7 +27,6 @@ License
#include "dictionary.H"
#include "polyPatch.H"
#include "wallPolyPatch.H"
#include "unitConversion.H"
#include "blockMeshFunctions.H"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //

View File

@ -2,7 +2,7 @@
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2018-2022 OpenFOAM Foundation
\\ / A nd | Copyright (C) 2018-2024 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
@ -197,7 +197,8 @@ namespace Foam
// Either construct features from surface & featureAngle or read set.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const scalar includedAngle = dict.lookup<scalar>("includedAngle");
const scalar includedAngle =
dict.lookup<scalar>("includedAngle", unitDegrees);
autoPtr<surfaceFeatures> set
(
@ -451,7 +452,9 @@ namespace Foam
(
closenessDict.lookupOrDefault<scalar>
(
"internalAngleTolerance", 80
"internalAngleTolerance",
unitDegrees,
80
)
);
@ -459,7 +462,9 @@ namespace Foam
(
closenessDict.lookupOrDefault<scalar>
(
"externalAngleTolerance", 80
"externalAngleTolerance",
unitDegrees,
80
)
);

View File

@ -39,7 +39,6 @@ Usage
#include "indexedOctree.H"
#include "treeBoundBox.H"
#include "PackedBoolList.H"
#include "unitConversion.H"
#include "searchableSurfaces.H"
#include "systemDict.H"
@ -114,41 +113,6 @@ void greenRefine
}
//scalar checkEdgeAngle
//(
// const triSurface& surf,
// const label edgeIndex,
// const label pointIndex,
// const scalar& angle
//)
//{
// const edge& e = surf.edges()[edgeIndex];
// vector eVec = e.vec(surf.localPoints());
// eVec /= mag(eVec) + small;
// const labelList& pEdges = surf.pointEdges()[pointIndex];
//
// forAll(pEdges, eI)
// {
// const edge& nearE = surf.edges()[pEdges[eI]];
// vector nearEVec = nearE.vec(surf.localPoints());
// nearEVec /= mag(nearEVec) + small;
// const scalar dot = eVec & nearEVec;
// const scalar minCos = degToRad(angle);
// if (mag(dot) > minCos)
// {
// return false;
// }
// }
// return true;
//}
void createBoundaryEdgeTrees
(
const PtrList<triSurfaceMesh>& surfs,
@ -429,15 +393,6 @@ int main(int argc, char *argv[])
if (nearestHit.hit())
{
// bool rejectEdge =
// checkEdgeAngle
// (
// surf,
// nearestHit.index(),
// pointi,
// 30
// );
if (dist2 > Foam::sqr(dist))
{
nearestHit.setMiss();

View File

@ -60,7 +60,6 @@ See also
\*---------------------------------------------------------------------------*/
#include "argList.H"
#include "unitConversion.H"
#include "MeshedSurfaces.H"
using namespace Foam;

View File

@ -2,7 +2,7 @@
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2011-2023 OpenFOAM Foundation
\\ / A nd | Copyright (C) 2011-2024 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
@ -724,7 +724,6 @@ void Foam::chemkinReader::addReaction
(
Afactor*ArrheniusCoeffs[0],
ArrheniusCoeffs[1],
ArrheniusCoeffs[2]/RR,
FixedList<scalar, 4>(powerSeriesCoeffs)
)
);