* Support default values for format/compress enum lookups.
- Avoids situations where the preferred default format is not ASCII.
For example, with dictionary input:
format binar;
The typing mistake would previously have caused formatEnum to
default to ASCII. We can now properly control its behaviour.
IOstream::formatEnum
(
dict.get<word>("format"), IOstream::BINARY
);
Allowing us to switch ascii/binary, using BINARY by default even in
the case of spelling mistakes. The mistakes are flagged, but the
return value can be non-ASCII.
* The format/compression lookup behave as pass-through if the lookup
string is empty.
- Allows the following to work without complaint
IOstream::formatEnum
(
dict.getOrDefault("format", word::null), IOstream::BINARY
);
- Or use constructor-like failsafe method
IOstream::formatEnum("format", dict, IOstream::BINARY);
- Apply the same behaviour with setting stream format/compression
from a word.
is.format("binar");
will emit a warning, but leave the stream format UNCHANGED
* Rationalize versionNumber construction
- constexpr constructors where possible.
Default construct is the "currentVersion"
- Construct from token to shift the burden to versionNumber.
Support token as argument to version().
Now:
is.version(headerDict.get<token>("version"));
or failsafe constructor method
is.version
(
IOstreamOption::versionNumber("version", headerDict)
);
Before (controlled input):
is.version
(
IOstreamOption::versionNumber
(
headerDict.get<float>("version")
)
);
Old, uncontrolled input - has been removed:
is.version(headerDict.lookup("version"));
* improve consistency, default behaviour for IOstreamOption construct
- constexpr constructors where possible
- add copy construct with change of format.
- construct IOstreamOption from streamFormat is now non-explicit.
This is a commonly expected result with no ill-effects
- renamed 'core/' -> 'base/' to avoid gitignore masking when re-adding
files
- rename 'nas/' to 'nastran/' for more clarity
- relocated OBJstream from surfMesh to fileFormats
STYLE: remove unused parseNASCoord. Was deprecated 2017-09
- `tensor` and `tensor2D` returns complex eigenvalues/vectors
- `symmTensor` and `symmTensor2D` returns real eigenvalues/vectors
- adds new test routines for eigendecompositions
- improves numerical stability by:
- using new robust algorithms,
- reordering the conditional branches in root-type selection
- ensures each Tensor-container operates for the following base types:
- floatScalar
- doubleScalar
- complex
- adds/improves test applications for each container and base type:
- constructors
- member functions
- global functions
- global operators
- misc:
- silently removes `invariantIII()` for `tensor2D` and `symmTensor2D`
since the 3rd invariant does not exist for 2x2 matrices
- fixes `invariantII()` algorithm for `tensor2D` and `symmTensor2D`
- adds `Cmpt` multiplication to `Vector2D` and `Vector`
- adds missing access funcs for symmetric containers
- improves func/header documentations
- provides an indirect access to a sub-section of a list that is
somewhat less efficient than a Foam::SubList, but supports the
following:
* adjustment of its addressing range after construction
* recovery of the original, underlying list at any time
This can be more convenient for some coding cases.
For example,
template<class Addr>
void renumberFaces(IndirectListBase<face, Addr>& faces, ...);
which can be called for
* Specific faces:
UIndirectList<face>(mesh.faces(), facesToChange)
* A sub-range of faces:
IndirectSubList<face>(mesh.faces(), pp.range())
* All faces:
IndirectSubList<face>(mesh.faces())
CONFIG: added IndirectListsFwd.H with some common forwarding
- now use debug 2 for scanner and debug 4 for parser.
Provided better feedback about what is being parsed (debug mode)
- relocate debug application to applications/tools/foamExprParserInfo
- follows the principle of least surprise if the expansion behaviour
for #eval and expressions (eg, exprFixedValue) are the same. This
is possible now that we harness the regular stringOps::expand()
within exprString::expand()
- reuse more of stringOps expansions to reduce code and improve the
syntax flexiblity.
We can now embed "pre-calculated" values into an expression.
For example,
angle 35;
valueExpr "vector(${{cos(degToRad($angle))}}, 2, 3)";
and the ${{..}} will be evaluated with the regular string evaluation
and used to build the entire expression for boundary condition
evaluation.
Could also use for fairly wild indirect referencing:
axis1 (1 0 0);
axis2 (0 1 0);
axis3 (0 0 1);
index 100;
expr "$[(vector) axis${{ ($index % 3) +1 }}] / ${{max(1,$index)}}";
QRMatrix (i.e. QR decomposition, QR factorisation or orthogonal-triangular
decomposition) decomposes a scalar/complex matrix \c A into the following
matrix product:
\verbatim
A = Q*R,
\endverbatim
where
\c Q is a unitary similarity matrix,
\c R is an upper triangular matrix.
Usage
Input types:
- \c A can be a \c SquareMatrix<Type> or \c RectangularMatrix<Type>
Output types:
- \c Q is always of the type of the matrix \c A
- \c R is always of the type of the matrix \c A
Options for the output forms of \c QRMatrix (for an (m-by-n) input matrix
\c A with k = min(m, n)):
- outputTypes::FULL_R: computes only \c R (m-by-n)
- outputTypes::FULL_QR: computes both \c R and \c Q (m-by-m)
- outputTypes::REDUCED_R: computes only reduced \c R (k-by-n)
Options where to store \c R:
- storeMethods::IN_PLACE: replaces input matrix content with \c R
- storeMethods::OUT_OF_PLACE: creates new object of \c R
Options for the computation of column pivoting:
- colPivoting::FALSE: switches off column pivoting
- colPivoting::TRUE: switches on column pivoting
Direct solution of linear systems A x = b is possible by solve() alongside
the following limitations:
- \c A = a scalar square matrix
- output type = outputTypes::FULL_QR
- store method = storeMethods::IN_PLACE
Notes
- QR decomposition is not unique if \c R is not positive diagonal \c R.
- The option combination:
- outputTypes::REDUCED_R
- storeMethods::IN_PLACE
will not modify the rows of input matrix \c A after its nth row.
- Both FULL_R and REDUCED_R QR decompositions execute the same number of
operations. Yet REDUCED_R QR decomposition returns only the first n rows
of \c R if m > n for an input m-by-n matrix \c A.
- For m <= n, FULL_R and REDUCED_R will produce the same matrices
COMP: delay evaluation of fieldToken enumeration types
- lazy evaluation at runTime instead of compile-time to make the code
independent of initialization order.
Otherwise triggers problems on gcc-4.8.5 on some systems where
glibc is the same age, or older.
- replace stringOps::toScalar with a more generic stringOps::evaluate
method that handles scalars, vectors etc.
- improve #eval to handle various mathematical operations.
Previously only handled scalars. Now produce vectors, tensors etc
for the entries. These tokens are streamed directly into the entry.
- ITstream append() would previously have used the append from the
underlying tokenList, which leaves the tokenIndex untouched and
renders the freshly appended tokens effectively invisible if
interspersed with primitiveEntry::read() that itself uses tokenIndex
when building the list.
The new append() method makes this hidden ITstream bi-directionality
easier to manage. For efficiency, we only append lists
(not individual tokens) and support a 'lazy' resizing that allows
the final resizing to occur later when all tokens have been appended.
- The new ITstream seek() method provides a conveniently means to move
to the end of the list or reposition to the middle.
Using rewind() and using seek(0) are identical.
ENH: added OTstream to output directly to a list of tokens
---
BUG: List::newElem resized incorrectly
- had a simple doubling of the List size without checking that this
would indeed be sufficient for the requested index.
Bug was not triggered since primitiveEntry was the only class using
this call, and it added the tokens sequentially.
- allows use of Enum in more situations where a tiny Map/HashTable
replacement is desirable. The new methods can be combined with
null constructed for to have a simple low-weight caching system
for words/integers instead of fitting in a HashTable.
- silently deprecate 'startsWith', 'endsWith' methods
(added in 2016: 2b14360662), in favour of
'starts_with', 'ends_with' methods, corresponding to C++20 and
allowing us to cull then in a few years.
- handle single character versions of starts_with, ends_with.
- add single character version of removeEnd and silently deprecate
removeTrailing which did the same thing.
- drop the const versions of removeRepeated, removeTrailing.
Unused and with potential confusion.
STYLE: use shrink_to_fit(), erase()
- Now accept '/' when reading variables without requiring
a surrounding '{}'
- fix some degenerate parsing cases when the first character is
already bad.
Eg, $"abc" would have previously parsed as a <$"> variable, even
although a double quote is not a valid variable character.
Now emits a warning and parses as a '$' token and a string token.
- add toScalar evaluation, embedded as "${{EXPR}}".
For example,
"repeat ${{5 * 7}} times or ${{ pow(3, 10) }}"
- use direct string concatenation if primitive entry is only a string
type. This prevents spurious quotes from appearing in the expansion.
radius "(2+4)";
angle "3*15";
#eval "$radius*sin(degToRad($angle))";
We want to have
'(2+4)*sin(degToRad(3*15))'
and not
'"(2+4)"*sin(degToRad("3*15"))'
ENH: code refactoring
- refactored expansion code with low-level service routines now
belonging to file-scope. All expansion routines use a common
multi-parameter backend to handle with/without dictionary etc.
This removes a large amount of code duplication.
- add floor/ceil/round methods
- support evaluation of sub-strings
STYLE: add blockMeshDict1.calc, blockMeshDict1.eval test dictionaries
- useful for testing and simple demonstration of equivalence
- SubField and SubList assign from zero
- SubField +=, -=, *=, /= operators
- SubList construct from UList (as per SubField)
Note: constructing an anonymous SubField or SubList with a single
parameter should use '{} instead of '()' to avoid compiler
ambiguities.
- the #eval directive is similar to the #calc directive, but for evaluating
string expressions into scalar values. It uses an internal parser for
the evaluation instead of dynamic code compilation. This can make it
more suitable for 'quick' evaluations.
The evaluation supports the following:
- operations: - + * /
- functions: exp, log, log10, pow, sqrt, cbrt, sqr, mag, magSqr
- trigonometric: sin, cos, tan, asin, acos, atan, atan2, hypot
- hyperbolic: sinh, cosh, tanh
- conversions: degToRad, radToDeg
- constants: pi()
- misc: rand(), rand(seed)
- this largely reverts 3f0f218d88 and 4ee65d12c4.
Consistent addressing with support for wrapped pointer types (eg,
autoPtr, std::unique_ptr) has proven to be less robust than desired.
Thus rescind HashTable iterator '->' dereferencing (from APR-2019).
- relax casting rules
* down-cast of labelToken to boolToken
* up-cast of wordToken to stringToken.
Can use isStringType() test for word or string types
- simplify constructors, move construct etc.
- expose reset() method as public, which resets to UNDEFINED and
clears allocated storage etc.
DEFEATURE: remove assign from word or string pointer.
- This was deprecated 2017-11 and now removed.
For this type of content transfer, move assignment should be used
instead of stealing pointers.
- change contiguous from a series of global functions to separate
templated traits classes:
- is_contiguous
- is_contiguous_label
- is_contiguous_scalar
The static constexpr 'value' and a constexpr conversion operator
allow use in template expressions. The change also makes it much
easier to define general traits and to inherit from them.
The is_contiguous_label and is_contiguous_scalar are special traits
for handling data of homogeneous components of the respective types.
- this is principally for cases where reduced indentation is desired,
such as when streaming to a memory location. If the indentation size
is zero or one, only a single space will be used to separate the
key/value.
This change does not affect the stream allocation size, since the
extra data falls within the padding.
ENH: relocate label/scalar sizes from Istream to IOstream.
- could allow future use for output streams as well?
Due to padding, reorganization has no effect on allocated size
of output streams.
STYLE: add read/write name qualifier to beginRaw, endRaw
- removes ambiguity for bi-directional streams
STYLE: fix inconsistent 'const' qualifier on std::streamsize
- base Ostream was without const, some derived streams with const
- allows full recovery of allocated space, not just addressable range.
This can be particularly useful for code patterns that repeatedly
reuse the same buffer space. For example,
DynamicList<char> buf(1024);
// some loop
{
OListStream os(std::move(buf));
os << ...
os.swap(buf);
}
Can read back from this buffer as a second operation:
{
UIListStream is(buf);
is >> ...
}
- the behaviour of std::rename with overwriting an existing file is
implementation dependent:
- POSIX: it overwrites.
- Windows: it does not overwrite.
- for Windows need to use the ::MoveFileEx() routine for overwriting.
More investigation is needed for proper handling of very long names.
- unfriend HashSet, HashTable IO operators
- global min(), max(), minMax() functions taking a labelHashSet and an
optional limit. For example,
labelHashSet set = ...;
Info<< "min is " << min(set) << nl;
Info<< "max (non-negative) " << max(set, 0) << nl;
- make HashTable iterator '->' dereferencing more consistent by also
supporting non-pointer types as well.
- read HashTable values in-situ to avoid copying
ENH: define addition/subtraction operations for scalar and complex
- required since construct complex from scalar is explicit
- additional tests in Test-complex
- forces c++DBUG='-DFULLDEBUG -g -O0' for the compilation, to allow
localized debugging during development without file editing and
while retaining the WM_COMPILE_OPTION (eg, Opt)
Note that switching between 'wmake' and 'wmake -debug' will not
cause existing targets to be rebuilt. As before, these are driven by
the dependencies. An intermediate wclean may thus be required.
- generalize identity matrix constructors for non-scalar types
- add constructors using labelPair for the row/column sizing information.
For a SquareMatrix, this provides an unambiguous parameter resolution.
- reuse assignment operators
STYLE: adjust matrix comments
- add iterators, begin/end, empty() methods for STL behaviour.
Use standard algorithms where possible
* std::fill, std::copy
* std::min_element, std::max_element
- access methods consistent with other OpenFOAM containers:
* data(), cdata(), uniform()
- Use ListPolicy to impose output line breaks
- Can recover matrix storage for re-use elsewhere.
For example, to populate values with 2D i-j addressing and later
release it as flat linear storage.
- construct/assign moveable
- added minMax() function for Matrix
- additional inplace +=, -=, *=, /= operations
- add named methods at() and rowData() to Matrix.
Allows a better distinction between linear and row-based addressing
- low-level matrix solve on List/UList instead of Field
- can be used to check the validity of input values.
Example:
dict.getCheck<label>("nIters", greaterOp1<label>(0));
dict.getCheck<scalar>("relax", scalarMinMax::zero_one());
- use 'get' prefix for more regular dictionary methods.
Eg, getOrDefault() as alternative to lookupOrDefault()
- additional ops for convenient construction of predicates
ENH: make dictionary writeOptionalEntries integer
- allow triggering of Fatal if default values are used
ENH: additional scalarRange static methods: ge0, gt0, zero_one
- use GREAT instead of VGREAT for internal placeholders
- additional MinMax static methods: gt, le
- adjust naming of quaternion 'rotationSequence' to be 'eulerOrder'
to reflect its purpose.
- provide rotation matrices directly for these rotation orders in
coordinateRotations::euler for case in which the rotation tensor
is required but not a quaternion.
- support move insert/set and emplace insertion.
These adjustments can be used for improved memory efficiency, and
allow hash tables of non-copyable objects (eg, std::unique_ptr).
- extend special HashTable output treatment to include pointer-like
objects such as autoPtr and unique_ptr.
ENH: HashTable::at() method with checking. Fatal if entry does not exist.
All remote contributions to interpolation stencils now
get added as 'processor' type lduInterfaces. This guarantees
a consistent matrix, e.g. initial residual is normalised to 1.
Second change is the normalisation of the interpolation discretisation
which uses the diagonal from the unmodified equation. This helps
GAMG.
- previously would have different SHA1 depending on whether the
string was a C-string, a C++-string or if the SHA1 was calculated
directly or via the OSHA1stream.
- SHA1("string")
- OSHA1stream << "string";
- OSHA1stream << string("string");
By avoiding string quoting on output, they now all deliver the same
result. This also means that the following will no longer change the SHA1
content, since it does not add anything:
osha<< string() << string() << string() << string();
This would have previously add a pair of double quotes each time!
- Eg, with surface writers now in surfMesh, there are fewer libraries
depending on conversion and sampling.
COMP: regularize linkage ordering and avoid some implicit linkage (#1238)
- extracts values from the arch "LSB;label=32;scalar=64" header entry
to provision for managing dissimilar primitive sizes.
Compensate for the additional IOobject members by narrowing the types
for the (objectState, readOption, writeOption) enumerations
- use an IndirectListBase class for various indirect list types.
- new SortList type
In some places the SortList can be used as a lightweight alternative
to SortableList to have the convenience of bundling data and sort
indices together, but while operating on existing data lists.
In other situations, it can be useful as an alternative to
sortedOrder. For example,
pointField points = ...;
labelList order;
sortedOrder(points, order);
forAll(order, i)
{
points[order[i]] = ...;
}
Can be replaced with the following (with the same memory overhead)
pointField points = ...;
SortList<point> sortedPoints(points);
for (point& pt : sortedPoints)
{
pt = ...;
}
- new SliceList type (#1220), which can be used for stride-based
addressing into existing lists
- this is somewhat like labelRange, but with a stride.
Can be used to define slices (of lists, fields, ..) or as a range specifier
for a for-loop. For example,
for (label i : sliceRange(0, 10, 3))
{
...
}
- this adds support for various STL operations including
* sorting, filling, find min/max element etc.
* for-range iteration
STYLE: use constexpr for VectorSpace rank
- having whitespace in fileName can be somewhat fragile since it means
that the fileName components do not necessarily correspond to a
'Foam::word'. But in many cases it will work provided that spaces
are not present in the final portion of the simulation directory
itself.
InfoSwitches
{
// Allow space character in fileName (use with caution)
allowSpaceInFileName 0;
}
- now use doClean=true as default for fileName::validate(). Was false.
Unlike fileName::clean() this requires no internal string rewrite
since the characters are being copied. Also handle any path
separator transformations (ie, backslash => forward slash) at the
same time. This makes it resemble the std::filesystem a bit more.
- operators are still incomplete, as are dimensioned fields,
field-fields etc.
- split complexFields into separate complexField, complexVectorField files
- add construction from and conversion to std::complex, which allows
easier wrapping of functions
- add Foam:: functions for complex versions of sin, cos, ...
- was historically defined as (1 1), but it is more consistent with
the concept of one to have a real component only.
Now defined as (1 0): 1+0i
STYLE: remove obscure '!' operator for complex conjugate
- either use the member function or the '~' operator
- These are not defined in the C++ standard for cmath, so allow for
compilation without them. Will need to provide replacements in the
future or rework.
- new regExpCxx wrapper for C++11 regex support with drop-in
compatibility with existing code.
- regExpPosix (was regExp), for future phase out in favour of regExpCxx.
- The regExp header will continue to be used for defining an
appropriate typedef corresponding to the preferred implementation.
- PtrDynList support for move append list:
can be used to concatenate pointer lists into a single one
- include resize in PtrDynList squeezeNull as being a natural
combination
- support sorting operations for pointer lists (PtrListOps)
- remove writeGeometry() in favour of write() and make it pure virtual
so that all writers must explicitly deal with it.
- establish proxy extension at construction time and treated as an
invariant thereafter. This avoids potentially surprising changes in
behaviour when writing.
- this is a simple container for fields with i-j-k addressing.
It does not support field operations directly, but is primarily
intended to be used when assembling field information with i-j-k
logic. After assembly, the field can be transferred to a regular
field for normal operations. Eg,
IjkField<scalar> assemble({15, 16, 200});
// .. fill in i-j-k fields
Field<scalar> final(std::move(assemble));
assemble.clear(); // be pedantic
...
- While a rectilinear mesh can be created with blockMesh, not every mesh
created with blockMesh will satisfy the requirements for being a
rectilinear mesh.
This alternative to blockMesh uses a single block that is aligned
with the xy-z directions and specifications of the control points,
mesh divisions and expansion ratios. For example,
x
{
points ( -13.28 -0.10 6.0 19.19 );
nCells ( 10 12 10 );
ratios ( 0.2 1 5 );
}
y { ... }
z { ... }
With only one block, the boundary patch definition is simple and the
canonical face number is used directly. For example,
inlet
{
type patch;
faces ( 0 );
}
outlet
{
type patch;
faces ( 1 );
}
sides
{
type patch;
faces ( 2 3 );
}
...
- After a mesh is defined, it is trivial to retrieve mesh-related
information such as cell-volume, cell-centres for any i-j-k location
without an actual polyMesh.
STYLE: remove -noFunctionObjects from blockMesh
- no time loop, so function objects cannot be triggered anyhow.
- PtrList::release() method.
Similar to autoPtr and unique_ptr and clearer in purpose than
using set(i,nullptr)
- Construct from List of pointers, taking ownership.
Useful when upgrading code. Eg,
List<polyPatch*> oldList = ...;
PtrList<polyPatch> newList(oldList);
...
BUG: incorrect resizing method names (PtrDynList) in previously unused code
- previously just removed duplicate literals, but now remove any
duplicates.
- Replace previous wordHashSet implementation with a linear search
instead. The lists are normally fairly small and mostly just have
unique entries anyhow. This reduces the overall overhead.
- previously had a single pointer/value zeros (8 bytes), this meant
that the reinterpret cast to a List would yield a reference that
could be unsafe under certain conditions.
Eg,
const labelList& myList = labelList::null();
Info<< myList.size() << nl; // OK since size is the first parameter
SubList<label>(myList, 0); // Unsafe
The SubList usage is unsafe since it passes in pointer and size into
the underlying UList. However, the pointer from the labelList::null()
will be whatever happens to be around in memory immediately after the
NullObject singleton. This is mostly not a problem if the List size
is always checked, but does mean that the data pointer is rather
dubious.
- Increase the size of the nullObject singleton to 32 bytes of zeros
to ensure that most reinterpret casting will not result in objects
that reference arbitrary memory.
The 32-byte data size is rather arbitrary, but covers most basic
containers.
- Global functions are unary or combining binary functions, which are
defined in MinMax.H (MinMaxOps.H).
There are also global reduction functions (gMinMax, gMinMaxMag)
as well as supporting 'Op' classes:
- minMaxOp, minMaxEqOp, minMaxMagOp, minMaxMagEqOp
Since the result of the functions represents a content reduction
into a single MinMax<T> value (a min/max pair), field operations
returning a field simply do not make sense.
- Implemented for lists, fields, field-fields, DimensionedField,
GeometricField (parallel reducing, with boundaries).
- Since the minMax evaluates during its operation, this makes it more
efficient for cases where both min/max values are required since it
avoids looping twice through the data.
* Changed GeometricField writeMinMax accordingly.
ENH: clip as field function
- clipping provides a more efficient, single-pass operation to apply
lower/upper limits on single or multiple values.
Examples,
scalarMinMax limiter(0, 1);
limiter.clip(value)
-> returns a const-ref to the value if within the range, or else
returns the appropriate lower/upper limit
limiter.inplaceClip(value)
-> Modifies the value if necessary to be within lower/upper limit
Function calls
clip(value, limiter)
-> returns a copy after applying lower/upper limit
clip(values, limiter)
-> returns a tmp<Field> of clipped values
- in some circumstances we need to pass a bool value upwards to the
caller and know if the true/false value was set based on real input
or is a default value.
Eg, in the object::read() we might normally have
enabled_(dict.readIfPresent(key, true));
but would lose information about why the value is true/false.
We can change that by using
enabled_(dict.readIfPresent<Switch>(key, Switch::DEFAULT_ON));
After which we can use this information is testing.
if
(
child.enabled().nonDefault()
? child.enabled()
: parent.enabled()
)
{ ... }
And thus enable output if the parent requested it explicitly or by
default and it has not been explicitly disabled in the child.
No difference when testing as a bool and the text representation
of DEFAULT_ON / DEFAULT_OFF will simply be "true" / "false".
ENH: add construction of Switch from dictionary (similar to Enum)
- introduced a ListPolicy details to make the transition between
a short list (space separated) and a long list (newline separated)
more configurable.
We suppress line breaks for commonly used types that often have
short content: (word, wordRes, keyType).
- a valid() method (same as !empty() call) for consistency with other
containers and data types
- a centre() method (same as midpoint() method) for consistency with
other OpenFOAM geometric entities
- provide a lookupOrDefault constructor form, since this is a fairly
commonly used requirement and simplifies the calling sequence.
Before
dimensionedScalar rhoMax
(
dimensionedScalar::lookupOrDefault
(
"rhoMax",
pimple.dict(),
dimDensity,
GREAT
)
);
After
dimensionedScalar rhoMax("rhoMax", dimDensity, GREAT, pimple.dict());
- read, readIfPresent methods with alternative lookup names.
- Mark the Istream related constructors with compile-time deprecated
warnings.
BUG: read, readIfPresent methods not handling optional dimensions (#1148)
- can be used as a more natural test on the iterator.
For example, with
HashTable<..> table;
auto iter = table.find(...);
Following are now all equivalent:
1. if (iter != table.end()) ...
2. if (iter.found()) ...
3. if (iter) ...
- similar to autoPtr and unique_ptr. Returns the pointer value without
any checks. This provides a simple way for use to use either
an autoPtr or a tmp for local memory management without accidentally
stealing the pointer.
Eg,
volVectorField* ptr;
tmp<volVectorField> tempField;
if (someField.valid())
{
ptr = someField.get();
}
else
{
tempField.reset(new volVectorField(....));
ptr = tmpField.get();
}
const volVectorField& withField = *ptr;
STYLE: make more tmp methods noexcept
- provide relativePath() for argList and for Time.
These are relative to the case globalPath().
Eg,
Info<< "output: " << runTime.relativePath(outputFile) << nl;
- makes the intent clearer and avoids the need for additional
constructor casting. Eg,
labelList(10, Zero) vs. labelList(10, 0)
scalarField(10, Zero) vs. scalarField(10, scalar(0))
vectorField(10, Zero) vs. vectorField(10, vector::zero)
- for some special cases we wish to mark command-line arguments as
being optional, in order to do our own treatment. For example,
when an arbitrary number of arguments should be allowed.
Now tag this situation with argList::noMandatoryArgs().
The argList::argsMandatory() query can then be used in any further
logic, including the standard default argument checking.
- with the new default check, can consolidate the special-purpose
"setRootCaseNonMandatoryArgs.H"
into the regular
"setRootCase.H"
- revert to a simple "setRootCase.H" and move all the listing related
bits to a "setRootCaseLists.H" file. This leaves the information
available for solvers, or whoever else wishes, without being
introduced everywhere.
- add include guards and scoping to the listing files and rename to
something less generic.
listOptions.H -> setRootCaseListOptions.H
listOutput.H -> setRootCaseListOutput.H
- similar to the foamEtcFile script -mode=... option, the specific
search location (user/group/other) can now also specified for
string expansions and as a numerical value for etcFile()
For example, if searching for group or other (project) controlDict,
but not wishing to see the user controlDict:
1. foamEtcFile -mode=go controlDict
2. fileName dictFile("<etc:go>/controlDict");
dictFile.expand();
3. etcFile(controlDict, false, 0077);
The default behaviour for searching all contexts is unchanged.
1. foamEtcFile controlDict
2. fileName dictFile("<etc>/controlDict");
dictFile.expand();
3. etcFile(controlDict);
- prefer this to using the OPENFOAM define since this improves the
internal consistency with the build information.
The API information could change between builds without the
etcFiles.C being recompiled whereas the value of
Foam::foamVersion::api is force updated during the build (triggers
recompilation of globals.Cver)
- provide default WM_DIR if not already set, to improve robustness if a
reduced environment is used
- add etc/ to WM_PROJECT_SITE search. This makes the site directory
structure consistent with the OpenFOAM structure.
Eg,
WM_PROJECT_SITE/etc/..
WM_PROJECT_SITE/bin/..
WM_PROJECT_SITE/platforms/..
- Don't set/export WM_OSTYPE. The default is POSIX and is properly
defaulted throughout, including in CMakeLists-OpenFOAM.txt (also for
Catalyst)
- cfindObject() for const pointer access.
- getObject() for mutable non-const pointer access, similar to the
objectRegistry::getObjectPtr()
- cfindObject(), findObject(), getObject() with template type access
to also check the headerClassName.
For example,
cfindObject("U") -> good
cfindObject<volVectorField>("U") -> good
cfindObject<volScalarField>("U") -> nullptr
This allows inversion of looping logic.
1) Obtain the names for a particular Type
for (const word& objName : objs.sortedNames<Type>())
{
const IOobject* io = objs[objName];
...
}
2) Use previously obtained names and apply to a particular Type
for (const word& objName : someListOfNames)
{
const IOobject* io = objs.cfindObject<Type>(objName);
if (io)
{
...
}
}
- Provides a means of accumulating file entries for generating vtm
by accumulate blocks, datasets and writing them later.
Only a single block depth is currently supported and the methods
are kept fairly simple.
- Within strings it is preferable to use the "<etc>" instead.
Most use cases for the old "~OpenFOAM" expansion have been obsoleted
by the #includeEtc directive.
- use std::string instead of c-string for the string constants
- centralize some definitions of resources into foamVersion.H
Now expose some of the hard-coded values used in foamEtcFiles()
so that they can be known or even overridden as required.
Relocate to src/OpenFOAM/include as a constant location.
- uses wmake, without OpenFOAM libraries.
The application and libray serve as a minimal test case for wmake,
but can also be used to generate a minimal library/executable pair
target for testing of packaging etc.
- For compatibility, access to the old global names is provided via
macros
#define FOAMversion foamVersion::version
#define FOAMbuild foamVersion::build
#define FOAMbuildArch foamVersion::buildArch
- this isolation makes it easier to provide additional scoped methods
for dealing with version related information. Eg, printBuildInfo()
- 'unfriend' operators on dimensionSet, since they operate without
requiring access to non-public members.
- add missing invTransform() function for dimensionSet.
- make inv(const dimensionSet&) available as
operator~(const dimensionSet&), which can be used instead
of (dimless/ds).
- writing of dictionary entry with the name of the dimensionedType
suppressed if it is identical to the keyword.
This corresponds to the input requirements.
- deprecate dimensionedType constructors using an Istream in favour of
versions accepting a keyword and a dictionary.
Dictionary entries are almost the exclusive means of read
constructing a dimensionedType. By construct from the dictionary
entry instead of doing a lookup() first, we can detect possible
input errors such as too many tokens as a result of a input syntax
error.
Constructing a dimensionedType from a dictionary entry now has
two forms.
1. dimensionedType(key, dims, dict);
This is the constructor that will normally be used.
It accepts entries with optional leading names and/or
dimensions. If the entry contains dimensions, they are
verified against the expected dimensions and an IOError is
raised if they do not correspond. On conclusion, checks the
token stream for any trailing rubbish.
2. dimensionedType(key, dict);
This constructor is used less frequently.
Similar to the previous description, except that it is initially
dimensionless. If entry contains dimensions, they are used
without further verification. The constructor also includes a
token stream check.
This constructor is useful when the dimensions are entirely
defined from the dictionary input, but also when handling
transition code where the input dimensions are not obvious from
the source.
This constructor can also be handy when obtaining values from
a dictionary without needing to worry about the input dimensions.
For example,
Info<< "rho: " << dimensionedScalar("rho", dict).value() << nl;
This will accept a large range of inputs without hassle.
ENH: consistent handling of dimensionedType for inputs (#1083)
BUG: incorrect Omega dimensions (fixes#2084)
- this seems to be the only reliable means of obtaining the values.
Using typeName_() yields the wrong value.
Using the typeName causes initialization issues
(segfault when executing on some systems).
- support name filtering by class based on <Type> or predicates.
Eg,
objects.sortedNames<volScalarField>(namePattern);
vs objects.sortedNames(volScalarField::typeName, namePattern);
These can also be used directly for untyped name matching.
Eg,
objects.sortedNames<void>(namePattern);
Can also use a predicate:
objects.sortedNames(wordRe("vol.*Field"), namePattern);
objects.sortedNames
(
[](const word& clsName){ return clsName.startsWith("vol"); },
namePattern
);
- naming similar to objectRegistry, with unambiguous resolution.
The lookup() methods have different return types depending on the
calling parameter.
STYLE: use IOobjectListTemplates.C for implementations
- previously included as local definition within IOobjectList.C,
but will be adding more templated methods soon.
- adjust parameters (eg, matchName instead of matcher) to show their
function
ENH: handle objectRegistry::names<void>(...)
- this is equivalent to no Type restriction, and can be used when
filtering names. Eg,
obr.names<void>(wordRe..);
- as part of the cleanup of dictionary access methods (c6520033c9)
made the dictionary class single inheritance from IDLList<entry>.
This eliminates any ambiguities for iterators and allows
for simple use of range-for looping.
Eg,
for (const entry& e : topDict))
{
Info<< "entry:" << e.keyword() << " is dict:" << e.isDict() << nl;
}
vs
forAllConstIter(dictionary, topDict, iter))
{
Info<< "entry:" << iter().keyword()
<< " is dict:" << iter().isDict() << nl;
}
- more dictionary-like methods, enforce keyType::LITERAL for all
lookups to avoid any spurious keyword matching.
- new readEntry, readIfPresent methods
- The get() method replaces the now deprecate lookup() method.
- Deprecate lookupOrFailsafe()
Failsafe behaviour is now an optional parameter for lookupOrDefault,
which makes it easier to tailor behaviour at runtime.
- output of the names is now always flatted without line-breaks.
Thus,
os << flatOutput(someEnumNames.names()) << nl;
os << someEnumNames << nl;
both generate the same output.
- Constructor now uses C-string (const char*) directly instead of
Foam::word in its initializer_list.
- Remove special enum + initializer_list constructor form since
it can create unbounded lookup indices.
- Removd old hasEnum, hasName forms that were provided during initial
transition from NamedEnum.
- Added static_assert on Enum contents to restrict to enum or
integral values. Should not likely be using this class to enumerate
other things since it internally uses an 'int' for its values.
Changed volumeType accordingly to enumerate on its type (enum),
not the class itself.
- these currently only with bool parameters, but the return value should
nonetheless always be a bool value:
andOp(), orOp(), lessOp(), lessEqOp(), greaterOp(), greaterEqOp()
- renamed the unused eqEqOp() to equalOp() for naming consistency with
the equal() global function.
ENH: equalOp() specialization for scalars
- function object version of the equal() function.
The default constructor uses the same tolerance (VSMALL),
but can also supply an alternative tolerance on construction.
- with the 'cwd' optimization switch it is possible to select the
preferred behaviour for the cwd() function.
A value of 0 causes cwd() to return the physical directory,
which is what getcwd() and `pwd -P` return.
Until now, this was always the standard behaviour.
With a value of 1, cwd() instead returns the logical directory,
which what $PWD contains and `pwd -L` returns.
If any of the sanity checks fail (eg, PWD points to something other
than ".", etc), a warning is emitted and the physical cwd() is
returned instead.
Apart from the optical difference in the output, this additional
control helps workaround file systems with whitespace or other
characters in the directory that normally cause OpenFOAM to balk.
Using a cleaner symlink elsewhere should skirt this issue.
Eg,
cd $HOME
ln -s "/mounted volume/user/workdir" workdir
cd workdir
# start working with OpenFOAM
- use keyType::option enum to consolidate searching options.
These enumeration names should be more intuitive to use
and improve code readability.
Eg, lookupEntry(key, keyType::REGEX);
vs lookupEntry(key, false, true);
or
Eg, lookupEntry(key, keyType::LITERAL_RECURSIVE);
vs lookupEntry(key, true, false);
- new findEntry(), findDict(), findScoped() methods with consolidated
search options for shorter naming and access names more closely
aligned with other components. Behave simliarly to the
methods lookupEntryPtr(), subDictPtr(), lookupScopedEntryPtr(),
respectively. Default search parameters consistent with lookupEntry().
Eg, const entry* e = dict.findEntry(key);
vs const entry* e = dict.lookupEntryPtr(key, false, true);
- added '*' and '->' dereference operators to dictionary searchers.
- use the dictionary 'get' methods instead of readScalar for
additional checking
Unchecked: readScalar(dict.lookup("key"));
Checked: dict.get<scalar>("key");
- In templated classes that also inherit from a dictionary, an additional
'template' keyword will be required. Eg,
this->coeffsDict().template get<scalar>("key");
For this common use case, the predefined getXXX shortcuts may be
useful. Eg,
this->coeffsDict().getScalar("key");
Previously the coordinate system functionality was split between
coordinateSystem and coordinateRotation. The coordinateRotation stored
the rotation tensor and handled all tensor transformations.
The functionality has now been revised and consolidated into the
coordinateSystem classes. The sole purpose of coordinateRotation
is now just to provide a selectable mechanism of how to define the
rotation tensor (eg, axis-angle, euler angles, local axes) for user
input, but after providing the appropriate rotation tensor it has
no further influence on the transformations.
--
The coordinateSystem class now contains an origin and a base rotation
tensor directly and various transformation methods.
- The origin represents the "shift" for a local coordinate system.
- The base rotation tensor represents the "tilt" or orientation
of the local coordinate system in general (eg, for mapping
positions), but may require position-dependent tensors when
transforming vectors and tensors.
For some coordinate systems (currently the cylindrical coordinate system),
the rotation tensor required for rotating a vector or tensor is
position-dependent.
The new coordinateSystem and its derivates (cartesian, cylindrical,
indirect) now provide a uniform() method to define if the rotation
tensor is position dependent/independent.
The coordinateSystem transform and invTransform methods are now
available in two-parameter forms for obtaining position-dependent
rotation tensors. Eg,
... = cs.transform(globalPt, someVector);
In some cases it can be useful to use query uniform() to avoid
storage of redundant values.
if (cs.uniform())
{
vector xx = cs.transform(someVector);
}
else
{
List<vector> xx = cs.transform(manyPoints, someVector);
}
Support transform/invTransform for common data types:
(scalar, vector, sphericalTensor, symmTensor, tensor).
====================
Breaking Changes
====================
- These changes to coordinate systems and rotations may represent
a breaking change for existing user coding.
- Relocating the rotation tensor into coordinateSystem itself means
that the coordinate system 'R()' method now returns the rotation
directly instead of the coordinateRotation. The method name 'R()'
was chosen for consistency with other low-level entities (eg,
quaternion).
The following changes will be needed in coding:
Old: tensor rot = cs.R().R();
New: tensor rot = cs.R();
Old: cs.R().transform(...);
New: cs.transform(...);
Accessing the runTime selectable coordinateRotation
has moved to the rotation() method:
Old: Info<< "Rotation input: " << cs.R() << nl;
New: Info<< "Rotation input: " << cs.rotation() << nl;
- Naming consistency changes may also cause code to break.
Old: transformVector()
New: transformPrincipal()
The old method name transformTensor() now simply becomes transform().
====================
New methods
====================
For operations requiring caching of the coordinate rotations, the
'R()' method can be used with multiple input points:
tensorField rots(cs.R(somePoints));
and later
Foam::transformList(rots, someVectors);
The rotation() method can also be used to change the rotation tensor
via a new coordinateRotation definition (issue #879).
The new methods transformPoint/invTransformPoint provide
transformations with an origin offset using Cartesian for both local
and global points. These can be used to determine the local position
based on the origin/rotation without interpreting it as a r-theta-z
value, for example.
================
Input format
================
- Streamline dictionary input requirements
* The default type is cartesian.
* The default rotation type is the commonly used axes rotation
specification (with e1/e2/3), which is assumed if the 'rotation'
sub-dictionary does not exist.
Example,
Compact specification:
coordinateSystem
{
origin (0 0 0);
e2 (0 1 0);
e3 (0.5 0 0.866025);
}
Full specification (also accepts the longer 'coordinateRotation'
sub-dictionary name):
coordinateSystem
{
type cartesian;
origin (0 0 0);
rotation
{
type axes;
e2 (0 1 0);
e3 (0.5 0 0.866025);
}
}
This simplifies the input for many cases.
- Additional rotation specification 'none' (an identity rotation):
coordinateSystem
{
origin (0 0 0);
rotation { type none; }
}
- Additional rotation specification 'axisAngle', which is similar
to the -rotate-angle option for transforming points (issue #660).
For some cases this can be more intuitive.
For example,
rotation
{
type axisAngle;
axis (0 1 0);
angle 30;
}
vs.
rotation
{
type axes;
e2 (0 1 0);
e3 (0.5 0 0.866025);
}
- shorter names (or older longer names) for the coordinate rotation
specification.
euler EulerRotation
starcd STARCDRotation
axes axesRotation
================
Coding Style
================
- use Foam::coordSystem namespace for categories of coordinate systems
(cartesian, cylindrical, indirect). This reduces potential name
clashes and makes a clearer declaration. Eg,
coordSystem::cartesian csys_;
The older names (eg, cartesianCS, etc) remain available via typedefs.
- added coordinateRotations namespace for better organization and
reduce potential name clashes.
- the opposite problem from issue #762. Now we also test if the input
token stream had any tokens at all.
- called by the dictionary get<> and readEntry() methods.
- Can now retrieve or set a column/row of a tensor.
Either compile-time or run-time checks.
Get
t.col<1>(); t.col(1);
t.row<1>(); t.row(1);
Set
t.col<1>(vec); t.col(1,vec);
t.row<1>(vec); t.row(1,vec);
The templated versions are compile-time checked
t.col<3>();
t.col<3>(vec);
The parameter versions are run-time checked
t.col(3);
t.col(3,vec);
ENH: provide named access to tensor/tensor inner product as inner()
- nBoundaryFaces() is often used and is identical to
(nFaces() - nInternalFaces()).
- forward the mesh nInternalFaces() and nBoundaryFaces() to
polyBoundaryMesh as nFaces() and start() respectively,
for use when operating on a polyBoundaryMesh.
STYLE:
- use identity() function with starting offset when creating boundary maps.
labelList map
(
identity(mesh.nBoundaryFaces(), mesh.nInternalFaces())
);
vs.
labelList map(mesh.nBoundaryFaces());
forAll(map, i)
{
map[i] = mesh.nInternalFaces() + i;
}
Also extended the cubic equation test routine and modified the error
methods so that they more accurately generate the round of error of
evaluation.
This resolves bug report https://bugs.openfoam.org/view.php?id=3015
- functionObjectLibs -> libs
- redirectType -> name
- change deprecated writeCompression flags types to Switch.
- cleanup some trailing ';;' from some dictionaries
- there were previously no hashing mechanisms for lists so they
would fall back to the definition for primitives and hash the
memory location of the allocated List object.
- provide a UList::Hash<> sub-class for inheritance, and also a global
specialization for UList<T>, List<T> such that the hash value for
List<List<T>> cascades properly.
- provide similar function in triFace to ensure that it remains
similar in behaviour to face.
- added SymmHash to Pair, for use when order is unimportant.
STYLE: use string::hash() more consistently
- no particular reason to use Hash<word>() which forwards to
string::hash() anyhow
- With argList::noFunctionObjects() we use the logic added in
4b93333292 (issue #352)
By removing the '-noFunctionObjects' option, we automatically
suppress the creation of function-objects via Time (with argList
as a parameter).
There is generally no need in these cases for an additional
runTime.functionObjects().off() statement
Use the argList::noFunctionObjects() for more direct configuration
and reduce unnecessary clutter in the -help information.
In previous versions, the -noFunctionObjects would have been redundant
anyhow, so we can also just ignore it now instead.
- allows use with any container with begin(), end() and where the
"*iterator" dereference returns a label, which is used for indexing
into the list of points.
This container could be labelUList, bitSet, labelHashSet, etc
- allows for simpler unpacking of a full list, or list range into any
sufficiently large integral type.
For example,
processorPolyPatch pp = ...;
UOPstream toNbr(pp.neighbProcNo(), pBufs);
toNbr << faceValues.unpack<char>(pp.range());
- behaves the same as the valid() method, but can be queried directly
like a normal raw pointer and as per std::unique_ptr.
Eg,
autoPtr<T> ptr = ...
if (ptr) ...
- improves backward compatibility and more naming consistency.
Retain setMany(iter1, iter2) to avoid ambiguity with the
PackedList::set(index, value) method.
- disallow insert() of raw pointers, since a failed insertion
(ie, entry already existed) results in an unmanaged pointer.
Either insert using an autoPtr, or set() with raw pointers or autoPtr.
- IOobjectList::add() now takes an autoPtr instead of an object reference
- IOobjectList::remove() now returns an autoPtr instead of a raw pointer
- controlled by the the 'printExecutionFormat' InfoSwitch in
etc/controlDict
// Style for "ExecutionTime = " output
// - 0 = seconds (with trailing 's')
// - 1 = day-hh:mm:ss
ExecutionTime = 112135.2 s ClockTime = 113017 s
ExecutionTime = 1-07:08:55.20 ClockTime = 1-07:23:37
- Callable via the new Time::printExecutionTime() method,
which also helps to reduce clutter in the applications.
Eg,
runTime.printExecutionTime(Info);
vs
Info<< "ExecutionTime = " << runTime.elapsedCpuTime() << " s"
<< " ClockTime = " << runTime.elapsedClockTime() << " s"
<< nl << endl;
--
ENH: return elapsedClockTime() and clockTimeIncrement as double
- previously returned as time_t, which is less portable.