- 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.
For example, with some HashTable or Map container of models
{ model0 => 1, model1 => 4, model2 => 5, model3 => 12, model4 => 15, }
specify the remapping
Map<label> mapper({{1, 3}, {2, 6}, {3, 12}, {5, 8}});
inplaceMapValue(mapper, models) then yields
{ model0 => 3, model1 => 4, model2 => 8, model3 => 12, model4 => 15, }
--
ENH: extend bitSet::count() to optionally count unset bits instead.
--
ENH: BitOps compatibility methods for boolList.
- These ease coding that uses a boolList instead of bitSet and use
short-circuit logic when possible.
Eg, when 'bitset' and 'bools' contain the same information
bitset.count() <-> BitOps::count(bools)
bitset.all() <-> BitOps::all(bools)
bitset.any() <-> BitOps::any(bools)
bitset.none() <-> BitOps::none(bools)
These methods can then be used directly in parameters or in logic.
Eg,
returnReduce(bitset.any(), orOp<bool>());
returnReduce(BitOps::any(bools), orOp<bool>());
if (BitOps::any(bools)) ...
- flags the following type of problems:
* mismatches:
keyword mismatch ( set of { brackets ) in the } entry;
* underflow (too many closing brackets:
keyword too many ( set of ) brackets ) in ) entry;
- a missing semi-colon
dict
{
keyword entry with missing semi-colon
}
will be flagged as 'underflow', since it parses through the '}' but
did not open with it.
Max monitoring depth is 60 levels of nesting, to avoid incurring any
memory allocation.
- In addition to the traditional Flex-based parser, added a Ragel-based
parser and a handwritten one.
Some representative timings for reading 5874387 points (1958129 tris):
Flex Ragel Manual
5.2s 4.8s 6.7s total reading time
3.8s 3.4s 5.3s without point merging
- the expansions were previously required as slash to follow, but
now either are possible.
"<case>", "<case>/" both yield the same as "$FOAM_CASE" and
will not have a trailing slash in the result. The expansion of
"$FOAM_CASE/" will however have a trailing slash.
- adjust additional files using these expansions
Support the following expansions when they occur at the start of a
string:
Short-form Equivalent
========= ===========
<etc>/ ~OpenFOAM/ (as per foamEtcFile)
<case>/ $FOAM_CASE/
<constant>/ $FOAM_CASE/constant/
<system>/ $FOAM_CASE/system/
These can be used in fileName expansions to improve clarity and reduce
some typing
"<constant>/reactions" vs "$FOAM_CASE/constant/reactions"
- this removes an OS-specific dependency (eg, drand48_r is not POSIX)
and allows easier use of other random number generators.
The Rand48 generator has identical behaviour and period as the
lrand48() library routine, but holds its own seed and state
(which makes it re-entrant) and can be combined with other
random distributions.
However, when using the modified form to obtain scalar values
they will not be identical to what drand48() yields.
This is because drand48() uses the raw 48-bit values to directly
set the mantissa of an IEEE double where as the newer distribution
normalizes based on the 32-bit value.
STYLE: simplify code in Random::shuffle and use Swap
- when constructing dimensioned fields that are to be zero-initialized,
it is preferrable to use a form such as
dimensionedScalar(dims, Zero)
dimensionedVector(dims, Zero)
rather than
dimensionedScalar("0", dims, 0)
dimensionedVector("zero", dims, vector::zero)
This reduces clutter and also avoids any suggestion that the name of
the dimensioned quantity has any influence on the field's name.
An even shorter version is possible. Eg,
dimensionedScalar(dims)
but reduces the clarity of meaning.
- NB: UniformDimensionedField is an exception to these style changes
since it does use the name of the dimensioned type (instead of the
regIOobject).
- improve internal handling to permit deriving resizable containers
(eg, PtrDynList).
- include '->' iterator dereferencing
- Only append/set non-const autoPtr references. This doesn't break
existing code, but makes the intention more transparent.
- also ensure fewer side-effects from inplaceReorder
- provide ListOps::reorder especially for PackedList and PackedBoolList
since they behave differently from regular lists.
- eliminate iterators from PackedList since they were unused, had
lower performance than direct access and added unneeded complexity.
- eliminate auto-vivify for the PackedList '[] operator.
The set() method provides any required auto-vivification and
removing this ability from the '[]' operator allows for a lower
when accessing the values. Replaced the previous cascade of iterators
with simpler reference class.
PackedBoolList:
- (temporarily) eliminate logic and addition operators since
these contained partially unclear semantics.
- the new test() method tests the value of a single bit position and
returns a bool without any ambiguity caused by the return type
(like the get() method), nor the const/non-const access (like
operator[] has). The name corresponds to what std::bitset uses.
- more consistent use of PackedBoolList test(), set(), unset() methods
for fewer operation and clearer code. Eg,
if (list.test(index)) ... | if (list[index]) ...
if (!list.test(index)) ... | if (list[index] == 0u) ...
list.set(index); | list[index] = 1u;
list.unset(index); | list[index] = 0u;
- deleted the operator=(const labelUList&) and replaced with a setMany()
method for more clarity about the intended operation and to avoid any
potential inadvertent behaviour.
- clockValue class for managing the clock values only, with a null
constructor that does not query the system clock (can defer to later).
Can also be used directly for +/- operations.
- refactor clockTime, cpuTime, clock to reduce storage.
- The bitSet class replaces the old PackedBoolList class.
The redesign provides better block-wise access and reduced method
calls. This helps both in cases where the bitSet may be relatively
sparse, and in cases where advantage of contiguous operations can be
made. This makes it easier to work with a bitSet as top-level object.
In addition to the previously available count() method to determine
if a bitSet is being used, now have simpler queries:
- all() - true if all bits in the addressable range are empty
- any() - true if any bits are set at all.
- none() - true if no bits are set.
These are faster than count() and allow early termination.
The new test() method tests the value of a single bit position and
returns a bool without any ambiguity caused by the return type
(like the get() method), nor the const/non-const access (like
operator[] has). The name corresponds to what std::bitset uses.
The new find_first(), find_last(), find_next() methods provide a faster
means of searching for bits that are set.
This can be especially useful when using a bitSet to control an
conditional:
OLD (with macro):
forAll(selected, celli)
{
if (selected[celli])
{
sumVol += mesh_.cellVolumes()[celli];
}
}
NEW (with const_iterator):
for (const label celli : selected)
{
sumVol += mesh_.cellVolumes()[celli];
}
or manually
for
(
label celli = selected.find_first();
celli != -1;
celli = selected.find_next()
)
{
sumVol += mesh_.cellVolumes()[celli];
}
- When marking up contiguous parts of a bitset, an interval can be
represented more efficiently as a labelRange of start/size.
For example,
OLD:
if (isA<processorPolyPatch>(pp))
{
forAll(pp, i)
{
ignoreFaces.set(i);
}
}
NEW:
if (isA<processorPolyPatch>(pp))
{
ignoreFaces.set(pp.range());
}
This class is largely a pre-C++11 holdover. It is now possible to
simply use move construct/assignment directly.
In a few rare cases (eg, polyMesh::resetPrimitives) it has been
replaced by an autoPtr.
Improve alignment of its behaviour with std::shared_ptr
- element_type typedef
- swap, reset methods
* additional reference access methods:
cref()
returns a const reference, synonymous with operator().
This provides a more verbose alternative to using the '()' operator
when that is desired.
Mnemonic: a const form of 'ref()'
constCast()
returns a non-const reference, regardless if the underlying object
itself is a managed pointer or a const object.
This is similar to ref(), but more permissive.
Mnemonic: const_cast<>
Using the constCast() method greatly reduces the amount of typing
and reading. And since the data type is already defined via the tmp
template parameter, the type deduction is automatically known.
Previously,
const tmp<volScalarField>& tfld;
const_cast<volScalarField&>(tfld()).rename("name");
volScalarField& fld = const_cast<volScalarField&>(tfld());
Now,
tfld.constCast().rename("name");
auto& fld = tfld.constCast();
--
BUG: attempts to move tmp value that may still be shared.
- old code simply checked isTmp() to decide if the contents could be
transfered. However, this means that the content of a shared tmp
would be removed, leaving other instances without content.
* movable() method checks that for a non-null temporary that is
unique (not shared).
Improve alignment of its behaviour with std::unique_ptr
- element_type typedef
- release() method - identical to ptr() method
- get() method to get the pointer without checking and without releasing it.
- operator*() for dereferencing
Method name changes
- renamed rawPtr() to get()
- renamed rawRef() to ref(), removed unused const version.
Removed methods/operators
- assignment from a raw pointer was deleted (was rarely used).
Can be convenient, but uncontrolled and potentially unsafe.
Do allow assignment from a literal nullptr though, since this
can never leak (and also corresponds to the unique_ptr API).
Additional methods
- clone() method: forwards to the clone() method of the underlying
data object with argument forwarding.
- reset(autoPtr&&) as an alternative to operator=(autoPtr&&)
STYLE: avoid implicit conversion from autoPtr to object type in many places
- existing implementation has the following:
operator const T&() const { return operator*(); }
which means that the following code works:
autoPtr<mapPolyMesh> map = ...;
updateMesh(*map); // OK: explicit dereferencing
updateMesh(map()); // OK: explicit dereferencing
updateMesh(map); // OK: implicit dereferencing
for clarity it may preferable to avoid the implicit dereferencing
- prefer operator* to operator() when deferenced a return value
so it is clearer that a pointer is involve and not a function call
etc Eg, return *meshPtr_; vs. return meshPtr_();
- relocated HashSetPlusEqOp and HashTablePlusEqOp to
HashSetOps::plusEqOp and HashTableOps::plusEqOp, respectively
- additional functions for converting between a labelHashSet
and a PackedBoolList or List<bool>:
From lists selections to labelHashSet indices:
HashSetOps::used(const PackedBoolList&);
HashSetOps::used(const UList<bool>&);
From labelHashSet to list forms:
PackedBoolList bitset(const labelHashSet&);
List<bool> bools(const labelHashSet&);
- relocated ListAppendEqOp and ListUniqueEqOp to ListOps::appendEqOp
and ListOps::UniqueEqOp, respectively for better code isolation and
documentation of purpose.
- relocated setValues to ListOps::setValue() with many more
alternative selectors possible
- relocated createWithValues to ListOps::createWithValue
for better code isolation. The default initialization value is itself
now a default parameter, which allow for less typing.
Negative indices in the locations to set are now silently ignored,
which makes it possible to use an oldToNew mapping that includes
negative indices.
- additional ListOps::createWithValue taking a single position to set,
available both in copy assign and move assign versions.
Since a negative index is ignored, it is possible to combine with
the output of List::find() etc.
STYLE: changes for PackedList
- code simplication in the PackedList iterators, including dropping
the unused operator() on iterators, which is not available in plain
list versions either.
- improved sizing for PackedBoolList creation from a labelUList.
ENH: additional List constructors, for handling single element list.
- can assist in reducing constructor ambiguity, but can also helps
memory optimization when creating a single element list.
For example,
labelListList labels(one(), identity(mesh.nFaces()));
- This class is largely a pre-C++11 holdover, prior to having movable
references.
- align internals with autoPtr instead of always unconditionally
allocating memory. The valid() method can be used to check for a null
pointer.
- Consolidate into a single file, in anticipation of future removal.
- rvalue() is a (transitional) means of converting Xfer content to a
reference for move construct, move assign semantics.
- valid() method for consistency with autoPtr and tmp classes
- simplify structure, removed unused constuctors.
- transfer from base objects via '=' assignment removed as being too
non-transparent
- add New factory method with perfect forwarding.
- the transfer method was previously a copy
- use std::reverse_iterator adaptors in FixedList
This greatly reduces the amount of code and now avoids the array-bounds
warning for FixedList::rend()
- use pointer arithmetic instead of dereferencing the internal array
- without these will use the normal move construct + move assign.
This is similarly efficient, but avoids the inadvertently having the
incorrect Swap being used for derived classes.
STYLE: remove unused xfer methods for HashTable, HashSet
- unneeded since move construct and move assignment are possible
- can stop producing content when the target number of entries has
been reached.
- change return type to labelList instead an Xfer container.
This allows return-value-optimization and avoids a surrounding
allocation. This potentially breaks existing code.
- make PackedList and PackedBoolList moveable. Drop xfer wrappers.
- support move construct/assignment for linked-lists themselves
and when moving into a 'normal' list
- better consistency with begin/end signatures and the various
iterators.
- for indirect linked-lists, provide iterator access to the underlying
data element address: iter.get() vs &(iter())
- add standard '->' indirection for iterators (as per normal STL
definitions)
* For most cases, this conversion would be largely unintentional
and also less efficient. If the regex is desirable, the caller
should invoke it explicitly.
For example,
findStrings(regExp(str), listOfStrings);
Or use one of the keyType, wordRe, wordRes variants instead.
If string is to be used as a plain (non-regex) matcher,
this can be directly invoked
findMatchingStrings(str, listOfStrings);
or using the ListOps instead:
findIndices(listOfStrings, str);
* provide function interfaces for keyType.
- subsetList, inplaceSubsetList with optional inverted logic.
- use moveable elements where possible.
- allow optional starting offset for the identity global function.
Eg, 'identity(10, start)' vs 'identity(10) + start'
- Eg instead of using labelHashSet, used HashSet<label> which uses
the string::hash for hashing. Other places inadvertently using the
string::hash instead of Hash<label> for hashing.
STYLE: use Map<..> instead of HashTable<.., label, Hash<label>>
- reduces clutter
- add copy construct from UList
- remove copy construct from dissimilar types.
This templated constructor was too generous in what it accepted.
For the special cases where a copy constructor is required with
a change in the data type, now use the createList factory method,
which accepts a unary operator. Eg,
auto scalars = scalarList::createList
(
labels,
[](const label& val){ return 1.5*val; }
);
- this currently just strips off the leading parent directory name
"/this/path/and/subdirs/name"
relative("/this/path") -> "and/subdirs/name"
relative("/this") -> "path/and/subdirs/name"
- simplify structure.
- protect against nullptr when resetting memory streams
- make UIListStream swappable
- add uiliststream as an example of using a plain std::istream
- define regExp::results_type using SubStrings container for handling
groups. This makes a later shift to std::smatch easier, but changes
the regExp API for matching with groups. Previously had list element
0 for regex group 1, now list element 0 is the entire match and list
element 1 is regex group 1.
Old:
List<std::string> mat;
if (re.match(text, mat)) Info<< "group 1: " << mat[0] << nl;
New:
regExp::results_type mat;
if (re.match(text, mat)) Info<< "group 1: " << mat.str(1) << nl;
- can be used to handle when options become redundant, but it is
undesirable to treat its presence as an error. Can now tag it as
being ignored.
argList::ignoreOptionCompat({"oldOption", 1706}, true);
argList::ignoreOptionCompat({"oldBoolOpttion", 1706}, false);
command -oldOption xyz -oldBoolOpttion
- use succincter method names that more closely resemble dictionary
and HashTable method names. This improves method name consistency
between classes and also requires less typing effort:
args.found(optName) vs. args.optionFound(optName)
args.readIfPresent(..) vs. args.optionReadIfPresent(..)
...
args.opt<scalar>(optName) vs. args.optionRead<scalar>(optName)
args.read<scalar>(index) vs. args.argRead<scalar>(index)
- the older method names forms have been retained for code compatibility,
but are now deprecated
- now avoid Istream and token mechanism in favour of a simpler string
parser. This makes the code clearer, smaller, robuster.
- provide convenience ge/gt/le/lt static constructors for scalarRange
for using bounds directly with specifying via a string parameter.
- scalarRange, scalarRanges now follow the unary predicate pattern
(using an operator() for testing). This allows their reuse in
other contexts. Eg, for filtering operations:
myHash.filterValues(scalarRange::ge(100));
- remove unused scalarRanges methods that were specific to handling
lists of time values. These were superseded by timeSelector methods
several versions ago.
- required if there is no system openmp and libomp or libgomp are
only found in the clang hierarchy
STYLE: add some notes in the openmp rules.
- the _OPENMP macro is now used in low-level testing files
- The -rotate-angle option allows convenient specification of a
rotation about an arbitrary axis. Eg, -rotate-angle '((1 1 1) 45)'
- The -origin option can be used to temporarily shift the origin
for the rotation operations. For example,
-origin '(0 0 1)' -rotate-angle '((1 0 0) 180)'
for mirroring.
- the vector normalise() method modifies the object inplace,
the normalised function returns a copy.
vector vec1(1,2,3);
vec1.normalise();
vs
vector vec1(1,2,3);
vec1 /= mag(vec1) + VSMALL;
For const usage, can use either of these
const vector vec2a(normalised(vector(1,2,3)));
const vector vec2b(vector(1,2,3).normalise());
- relocate some standard functionality to TimePaths to allow a lighter
means of managing time directories without using the entire Time
mechanism.
- optional enableLibs for Time construction (default is on)
and a corresponding argList::noLibs() and "-no-libs" option
STYLE:
- mark Time::outputTime() as deprecated MAY-2016
- use pre-increment for runTime, although there is no difference in
behaviour or performance.
- include amount of free system memory in profiling, which can give an
indication of when swapping is about to start
- profilingSummary utility to collect profiling from parallel
calculations. Collects profiling information from processor
directories and summarize the time spent and number of calls as (max
avg min) values.
- split now optionally retains empty substrings.
Added split on fixed field width.
- Foam::name() now formats directly into string buffer, which a
removes one layer of copying and also avoids using a non-constexpr
in the temporary.
STYLE: explicit type narrowing on zero-padded output for ensight
- this makes them applicable to Foam::string, Foam::word etc
ENH: improvements to CStringList
- add strings() sublist variant which can be useful when handling
command arguments separately
- add construct from SubStrings.
- this provides a better typesafe means of locating predefined cell
models than relying on strings. The lookup is now ptr() or ref()
directly. The lookup functions behave like on-demand singletons when
loading "etc/cellModels".
Functionality is now located entirely in cellModel but a forwarding
version of cellModeller is provided for API (but not ABI) compatibility
with older existing user code.
STYLE: use constexpr for cellMatcher constants
- when dictionary keywords change between versions, the programmer
can use these compatibility methods to help with migration.
* csearchCompat, foundCompat, lookupEntryPtrCompat, lookupEntryCompat,
lookupCompat, lookupOrDefaultCompat, readIfPresentCompat, ...
They behave like their similarly named base versions, but accept an
additional list of older keyword names augmented by a version number.
For example,
dict.readIfPresentCompat
(
"key", {{"olderName", 1612}, {"veryOld", 240}},
myscalar
);
where 1612=OpenFOAM-v1612, 240=OpenFOAM-v2.4.x, etc.
- If the entry could be directly inserted: a pointer to the inserted entry.
- If a dictionary merge was required: a pointer to the dictionary that
received the entry.
- Return nullptr on any type of insertion failure.
This change is code compatible with existing code since it only alters
a bool return value to be a pointer return value.
- improved memory alignment reduces overhead for Int32 compilation
- added move/swap semantics
- made the type() readonly in favour of setVariant() to allow change
of variant within a particular storage representation.
Eg, STRING -> VERBATIMSTRING.
- start/end values were underrepresented due to rounding.
Now extend the range to include -0.5 and +0.5 beyond the usual
range to ensure the same number density.
- the zero::null and one::null sub-classes add an additional null
output adapter.
The function of the nil class (special-purpose class only used for
HashSet) is now taken by zero::null.
- consistent with C++ STL conventions, the reverse iterators should
use operator++ to transit the list from rbegin() to rend().
The previous implementation used raw pointers, which meant that they
had the opposite behaviour: operator-- to transit from rbegin() to
rend().
The updated version only has operator++ defined, thus the compiler
should catch any possible instances where people were using the old
(incorrect) versions.
- updated forAllReverseIters() and forAllConstReverseIters() macros to
be consistent with new implementation and with C++ STL conventions.
- Instead of relying on #inputMode to effect a global change it is now
possible (and recommended) to a temporary change in the inputMode
for the following entry.
#default : provide default value if entry is not already defined
#overwrite : silently remove a previously existing entry
#warn : warn about duplicate entries
#error : error if any duplicate entries occur
#merge : merge sub-dictionaries when possible (the default mode)
This is generally less cumbersome than the switching the global
inputMode. For example to provide a set of fallback values.
#includeIfPresent "user-files"
...
#default value uniform 10;
vs.
#includeIfPresent "user-files"
#inputMode protect
...
value uniform 10;
#inputMode merge // _Assuming_ we actually had this before
These directives can also be used to suppress the normal dictionary
merge semantics:
#overwrite dict { entry val; ... }
- patterns only supported for the final element.
To create an element as a pattern instead of a word, an embedded
string quote (single or double) is used for that element.
Any of the following examples:
"/top/sub/dict/'(p|U).*" 100;
"/top/sub/dict/'(p|U).*'" 100;
"/top/sub/dict/\"(p|U).*" 100;
"/top/sub/dict/\"(p|U).*\"" 100;
are equivalent to the longer form:
top
{
sub
{
dict
{
"(p|U).*" 100;
}
}
}
It is not currently possible to auto-vivify intermediate
dictionaries with patterns.
NOK "/nonexistent.*/value" 100;
OK "/existing.*/value" 100;
- full scoping also works for the #remove directive
#remove "/dict1/subdict2/entry1"
The absolute value of the the time has been added to the rigid body
model state. This value is not directly necessary for calculating the
evolution of the rigid body system, it just facilitates the
implementation of sub-models which are in some way time-dependent.
- this increases the flexibility of the interface
- Add stringOps 'natural' string sorting comparison.
Digits are sorted in their natural order, which means that
(file10.txt file05.txt file2.txt)
are sorted as
(file2.txt file05.txt file10.txt)
STYLE: consistent naming of template parameters for comparators
- Compare for normal binary predicates
- ListComparePredicate for list compare binary predicates
- similar to word::validate to allow stripping of invalid characters
without triggering a FatalError.
- use this validated fileName in Foam::readDir to avoid problems when
a directory contains files with invalid characters in their names
- adjust rmDir to handle filenames with invalid characters
- fileName::equals() static method to compare strings while ignoring
any differences that are solely due to duplicate slashes
- more consistent naming:
* Versions that hold and manage their own memory:
IListStream, OListStream
* Versions that reference a fixed size external memory:
UIListStream, UOListStream
- use List storage instead of DynamicList within OListStream.
Avoids duplicate bookkeeping, more direct handling of resizing.
- The problem occurs when using atof to parse values such as "1e-39"
since this is out of range for a float and _can_ set errno to
ERANGE.
Similar to parsing of integers, now parse with the longest floating
point representation "long double" via strtold (guaranteed to be
part of C++11) and verify against the respective VGREAT values for
overflow. Treat anything smaller than VSMALL to be zero.
- these provide a similar functionality to string-streams, but operate
on a externally provided memory buffer which can be used to reduce
the amount of copying.
- classes were previously staged as part of the ADIOS community
repository.
- for convenience and symmetry with OStringStream
STYLE: void return value for stream rewind() methods
- this makes it easier to design bidirectional streams
- low-level beginRaw(), writeRaw(), endRaw() methods.
These can be used to directly add '()' decorators for serial output
or prepare/cleanup parallel buffers.
Used, for example, when outputting indirect lists in binary to avoid.
- used in various places to test if the input can be parsed as a
label/scalar, so warnings tend to flood the output.
- be more explicit when encountering range errors
- improve functional compatibility with DynList (remove methods)
* eg, remove an element from any position in a DynamicList
* reduce the number of template parameters
* remove/subset regions of DynamicList
- propagate Swap template specializations for lists, hashtables
- move construct/assignment to various containers.
- add find/found methods for FixedList and UList for a more succinct
(and clearer?) usage than the equivalent global findIndex() function.
- simplify List_FOR_ALL loops
Previously:
- bad command-line input such as -label 1234xyz would parse as a
label (with value 1234) and the trailing junk would be silently
ignored. This may or may not be appropriate. If the trailing junk
looked like this '100E' or '1000E-' (ie, forgot to type the
exponent), the incorrectly parsed values can be quite bad:
label = 32684
scalar = 6.93556e-310
Now:
- use the updated readLabel/readScalar routines that trigger a
FatalIOError on bad input:
--> FOAM FATAL IO ERROR:
Trailing content found parsing '1234xyz'
--> FOAM FATAL IO ERROR:
Trailing content found parsing '100E'
This traps erroneous command-line input immediately.
- Any trailing whitespace when parsing from strings or character buffers
is ignored rather than being treated as an error. This is consistent
with behaviour when reading from an Istream and with leading whitespace
being ignored in the underlying atof/atod, strtof/strtod... functions.
- Allow parsing directly from a std::string instead of just from a 'char*'.
This reflects the C++11 addition of std::stod to complement the C
functions strtod. This also makes it easier to parse string directly
without using an IStringStream.
- Two-parameter parsing methods return success/failure.
Eg,
if (readInt32(str, &int32Val)) ...
- One-parameter parsing methods return the value on success or
emit a FatalIOError.
Eg,
const char* buf;
int32Val = readInt32(buf, &);
- Improved consistency when parsing unsigned ints.
Use strtoimax and strtoumax throughout.
- Rename readDoubleScalar -> readDouble, readFloatScalar -> readFloat.
Using the primitive name directly instead of the Foam typedef for
better consistency with readInt32 etc.
- Clean/improve parseNasScalar.
Handle normal numbers directly, reduce some operations.
Original commit message:
------------------------
Parallel IO: New collated file format
When an OpenFOAM simulation runs in parallel, the data for decomposed fields and
mesh(es) has historically been stored in multiple files within separate
directories for each processor. Processor directories are named 'processorN',
where N is the processor number.
This commit introduces an alternative "collated" file format where the data for
each decomposed field (and mesh) is collated into a single file, which is
written and read on the master processor. The files are stored in a single
directory named 'processors'.
The new format produces significantly fewer files - one per field, instead of N
per field. For large parallel cases, this avoids the restriction on the number
of open files imposed by the operating system limits.
The file writing can be threaded allowing the simulation to continue running
while the data is being written to file. NFS (Network File System) is not
needed when using the the collated format and additionally, there is an option
to run without NFS with the original uncollated approach, known as
"masterUncollated".
The controls for the file handling are in the OptimisationSwitches of
etc/controlDict:
OptimisationSwitches
{
...
//- Parallel IO file handler
// uncollated (default), collated or masterUncollated
fileHandler uncollated;
//- collated: thread buffer size for queued file writes.
// If set to 0 or not sufficient for the file size threading is not used.
// Default: 2e9
maxThreadFileBufferSize 2e9;
//- masterUncollated: non-blocking buffer size.
// If the file exceeds this buffer size scheduled transfer is used.
// Default: 2e9
maxMasterFileBufferSize 2e9;
}
When using the collated file handling, memory is allocated for the data in the
thread. maxThreadFileBufferSize sets the maximum size of memory in bytes that
is allocated. If the data exceeds this size, the write does not use threading.
When using the masterUncollated file handling, non-blocking MPI communication
requires a sufficiently large memory buffer on the master node.
maxMasterFileBufferSize sets the maximum size in bytes of the buffer. If the
data exceeds this size, the system uses scheduled communication.
The installation defaults for the fileHandler choice, maxThreadFileBufferSize
and maxMasterFileBufferSize (set in etc/controlDict) can be over-ridden within
the case controlDict file, like other parameters. Additionally the fileHandler
can be set by:
- the "-fileHandler" command line argument;
- a FOAM_FILEHANDLER environment variable.
A foamFormatConvert utility allows users to convert files between the collated
and uncollated formats, e.g.
mpirun -np 2 foamFormatConvert -parallel -fileHandler uncollated
An example case demonstrating the file handling methods is provided in:
$FOAM_TUTORIALS/IO/fileHandling
The work was undertaken by Mattijs Janssens, in collaboration with Henry Weller.
now possible with level-sets as well as planes. Removed tetPoints class
as this wasn't really used anywhere except for the old tet-cutting
routines. Restored tetPointRef.H to be consistent with other primitive
shapes. Re-wrote tet-overlap mapping in terms of the new cutting.
- The logic for switching input-mode was previously completely
encapsulated within the #inputMode directive, but without any
programming equivalent. Furthermore, the encapsulation in inputMode
made the logic less clear in other places.
Exposing the inputMode as an enum with direct access from entry
simplifies things a fair bit.
- eliminate one level of else/if nesting in entryIO.C for clearer logic
- for dictionary function entries, simply use
addNamedToMemberFunctionSelectionTable() and avoid defining a type()
as a static. For most function entries the information is only used
to get a name for the selection table lookup anyhow.
- consolidate word::validated() into word::validate() and also allow
as short form for string::validate<word>(). Also less confusing than
having similarly named methods that essentially do the same thing.
- more consistent const access when iterating over strings
- add valid(char) for keyType and wordRe
- error::throwExceptions(bool) returning the previous state makes it
easier to set and restore states.
- throwing() method to query the current handling (if required).
- the normal error::throwExceptions() and error::dontThrowExceptions()
also return the previous state, to make it easier to restore later.
- resets the output buffer completely - implementing what rewind was
likely meant to have accomplished for many use cases.
STYLE: OSHA1stream reset() for symmetry. Deprecate rewind().
- use allocator class to wrap the stream pointers instead of passing
them into ISstream, OSstream and using a dynamic cast to delete
then. This is especially important if we will have a bidirectional
stream (can't delete twice!).
STYLE:
- file stream constructors with std::string (C++11)
- for rewind, explicit about in|out direction. This is not currently
important, but avoids surprises with any future bidirectional access.
- combined string streams in StringStream.H header.
Similar to <sstream> include that has both input and output string
streams.
- This provides a mechanism for moving mesh patches based on external
input (eg, from an external structures solver). The patch points are
influenced by the position and rotation of the lumped points.
BC: lumpedPointDisplacementPointPatchVectorField
Controlling mechanisms:
- externalCoupler
for coordinating the master/slave
- lumpedPointMovement
manages the patch-points motion, but also for extracting forces/moments
- lumpedPointState
represents the positions/rotations of the controlling points
Utils:
- lumpedPointZones
diagnostic for visualizing the correspondence between controlling
points and patch faces
- lumpedPointMovement
Test that the patch motion is as desired without invoking moveMesh.
With the -slave option, return items from a precalculated table
for the lumpedPointDisplacementPointPatchVectorField BC.
Adds overset discretisation to selected physics:
- diffusion : overLaplacianDyMFoam
- incompressible steady : overSimpleFoam
- incompressible transient : overPimpleDyMFoam
- compressible transient: overRhoPimpleDyMFoam
- two-phase VOF: overInterDyMFoam
The overset method chosen is a parallel, fully implicit implementation
whereby the interpolation (from donor to acceptor) is inserted as an
adapted discretisation on the donor cells, such that the resulting matrix
can be solved using the standard linear solvers.
Above solvers come with a set of tutorials, showing how to create and set-up
simple simulations from scratch.
- the heuristic for matching unresolved intersections is a relatively
simple matching scheme that seems to be more robust than attempting to walk
the geometry or the cuts.
- avoid false positives for self intersection
- adjust for updates in 'develop'
- change surfaceIntersection constructor to take a dictionary of
options.
tolerance | Edge-length tolerance | scalar | 1e-3
allowEdgeHits | Edge-end cuts another edge | bool | true
avoidDuplicates | Reduce the number of duplicate points | bool | true
warnDegenerate | Number of warnings about degenerate edges | label | 0
- the NamedEnum wrapper is somewhate too rigid.
* All enumerated values are contiguous, starting as zero.
* The implicit one-to-one mapping precludes using it for aliases.
* For example, perhaps we want to support alternative lookup names for an
enumeration, or manage an enumeration lookup for a sub-range.
- Remove the unused enums() method since it delivers wholly unreliable
results. It is not guaranteed to cover the full enumeration range,
but only the listed names.
- Remove the unused strings() method.
Duplicated functionality of the words(), but was never used.
- Change access of words() method from static to object.
Better code isolation. Permits the constructor to take over
as the single point of failure for bad input.
- Add values() method
- do not expose internal (HashTable) lookup since it makes it more
difficult to enforce constness and the implementation detail should
not be exposed. However leave toc() and sortedToc() for the interface.
STYLE: relocated NamedEnum under primitives (was containers)
- internal typedef as 'value_type' for some consistency with STL conventions
- The unset() method never auto-vivifies, whereas the set() method
always auto-vivifies. In the case where set() is called with a zero
for its argument - eg, set(index, 0) - this should behave
identically to an unset() and not auto-vivify out-of-range entries.
- provides a summary hash of classes used and their associated object names.
The HashTable representation allows us to leverage various HashTable
methods. This hashed summary view can be useful when querying
particular aspects, but is most useful when reducing the objects in
consideration to a particular subset. For example,
const wordHashSet interestingTypes
{
volScalarField::typeName,
volVectorField::typeName
};
IOobjectList objects(runTime, runTime.timeName());
HashTable<wordHashSet> classes = objects.classes();
classes.retain(interestingTypes);
// Or do just the opposite:
classes.erase(unsupportedTypes);
Can also use the underlying HashTable filter methods
STYLE: use templated internals to avoid findString() when matching subsets
- Generalized means over filtering table entries based on their keys,
values, or both. Either filter (retain), or optionally prune elements
that satisfy the specified predicate.
filterKeys and filterValues:
- Take a unary predicate with the signature
bool operator()(const Key& k);
- filterEntries:
Takes a binary predicate with the signature
bool operator()(const Key& k, const T& v);
==
The predicates can be normal class methods, or provide on-the-fly
using a C++ lambda. For example,
wordRes goodFields = ...;
allFieldNames.filterKeys
(
[&goodFields](const word& k){ return goodFields.match(k); }
);
Note that all classes that can match a string (eg, regExp, keyType,
wordRe, wordRes) or that are derived from a Foam::string (eg, fileName,
word) are provided with a corresponding
bool operator()(const std::string&)
that either performs a regular expression or a literal match.
This allows such objects to be used directly as a unary predicate
when filtering any string hash keys.
Note that HashSet and hashedWordList both have the proper
operator() methods that also allow them to be used as a unary
predicate.
- Similar predicate selection with the following:
* tocKeys, tocValues, tocEntries
* countKeys, countValues, countEntries
except that instead of pruning, there is a simple logic inversion.
- predicates::always and predicates::never returning true and false,
respectively. These simple classes make it easier when writing
templated code.
As well as unary and binary predicate forms, they also contain a
match(std::string) method for compatibility with regex-based classes.
STYLE: write bool and direction as primitive 'int' not as 'label'.
- ensure that the string-related classes have consistently similar
matching methods. Use operator()(const std::string) as an entry
point for the match() method, which makes it easier to use for
filters and predicates. In some cases this will also permit using
a HashSet as a match predicate.
regExp
====
- the set method now returns a bool to signal that the requested
pattern was compiled.
wordRe
====
- have separate constructors with the compilation option (was previously
a default parameter). This leaves the single parameter constructor
explicit, but the two parameter version is now non-explicit, which
makes it easier to use when building lists.
- renamed compile-option from REGEX (to REGEXP) for consistency with
with the <regex.h>, <regex> header names etc.
wordRes
====
- renamed from wordReListMatcher -> wordRes. For reduced typing and
since it behaves as an entity only slightly related to its underlying
list nature.
- Provide old name as typedef and include for code transition.
- pass through some list methods into wordRes
hashedWordList
====
- hashedWordList[const word& name] now returns a -1 if the name is is
not found in the list of indices. That has been a pending change
ever since hashedWordList was generalized out of speciesTable
(Oct-2010).
- add operator()(const word& name) for easy use as a predicate
STYLE: adjust parameter names in stringListOps
- reflect if the parameter is being used as a primary matcher, or the
matcher will be derived from the parameter.
For example,
(const char* re), which first creates a regExp
versus (const regExp& matcher) which is used directly.
- inherit from std::iterator to obtain the full STL typedefs, meaning
that std::distance works and the following is now possible:
labelRange range(100, 1500);
scalarList list(range.begin(), range.end());
--
Note that this does not work (mismatched data-types):
scalarList list = identity(12345);
But this does, since the *iter promotes label to scalar:
labelList ident = identity(12345);
scalarList list(ident.begin(), ident.end());
It is however more than slightly wasteful to create a labelList
just for initializing a scalarList. An alternative could be a
a labelRange for the same purpose.
labelRange ident = labelRange::identity(12345);
scalarList list(ident.begin(), ident.end());
Or this
scalarList list
(
labelRange::null.begin(),
labelRange::identity(12345).end()
);
- provides const/non-const access to the underlying list, but the
iterator access itself is const.
- provide linked-list iterator 'found()' method for symmetry with
hash-table iterators. Use nullptr for more clarity.
- lookup(): with a default value (const access)
For example,
Map<label> something;
value = something.lookup(key, -1);
being equivalent to the following:
Map<label> something;
value = -1; // bad value
if (something.found(key))
{
value = something[key];
}
except that lookup also makes it convenient to handle const references.
Eg,
const labelList& ids = someHash.lookup(key, labelList());
- For consistency, provide a two parameter HashTable '()' operator.
The lookup() method is, however, normally preferable when
const-only access is to be ensured.
- retain(): the counterpart to erase(), it only retains entries
corresponding to the listed keys.
For example,
HashTable<someType> largeCache;
wordHashSet preserve = ...;
largeCache.retain(preserve);
being roughly equivalent to the following two-stage process,
but with reduced overhead and typing, and fewer potential mistakes.
HashTable<someType> largeCache;
wordHashSet preserve = ...;
{
wordHashSet cull(largeCache.toc()); // all keys
cull.erase(preserve); // except those to preserve
largeCache.erase(cull); //
}
The HashSet &= operator and retain() are functionally equivalent,
but retain() also works with dissimilar value types.
- provide key_iterator/const_key_iterator for all hashes,
reuse directly for HashSet as iterator/const_iterator, respectively.
- additional keys() method for HashTable that returns a wrapped to
a pair of begin/end const_iterators with additional size/empty
information that allows these to be used directly by anything else
expecting things with begin/end/size. Unfortunately does not yet
work with std::distance().
Example,
for (auto& k : labelHashTable.keys())
{
...
}
- previously had a mismash of const/non-const attributes on iterators
that were confused with the attributes of the object being accessed.
- use the iterator keys() and object() methods consistently for all
internal access of the HashTable iterators. This makes the intention
clearer, the code easier to maintain, and protects against any
possible changes in the definition of the operators.
- 'operator*': The standard form expected by STL libraries.
However, for the std::map, this dereferences to a <key,value> pair,
whereas OpenFOAM dereferences simply to <value>.
- 'operator()': OpenFOAM treats this like the 'operator*'
- adjusted the values of end() and cend() to reinterpret from nullObject
instead of returning a static iteratorEnd() object.
This means that C++ templates can now correctly deduce and match
the return types from begin() and end() consistently.
So that range-based now works.
Eg,
HashTable<label> table1 = ...;
for (auto i : table1)
{
Info<< i << endl;
}
Since the 'operator*' returns hash table values, this prints all the
values in the table.
This uses a concept similar to what std::valarray and std::slice do.
A labelRange provides a convenient container for holding start/size
and lends itself to addressing 'sliced' views of lists.
For safety, the operations and constructors restricts the given input range
to a valid addressible region of the underlying list, while the labelRange
itself precludes negative sizes.
The SubList version is useful for patches or other things that have a
SubList as its parameter. Otherwise the UList [] operator will be the
more natural solution. The slices can be done with a labelRange, or
a {start,size} pair.
Examples,
labelList list1 = identity(20);
list1[labelRange(18,10)] = -1;
list1[{-20,25}] = -2;
list1[{1000,5}] = -3;
const labelList list2 = identity(20);
list2[{5,10}] = -3; // ERROR: cannot assign to const!
- some functionality similar to what the standary library <iterator>
provides.
* stdFoam::begin() and stdFoam::end() do type deduction,
which means that many cases it is possible to manage these types
of changes.
For example, when managing a number of indices:
Map<labelHashSet> lookup;
1) Longhand:
for
(
Map<labelHashSet>::const_iterator iter = lookup.begin();
iter != lookup.end();
++iter
)
{ .... }
1b) The same, but wrapped via a macro:
forAllConstIter(Map<labelHashSet>, lookup, iter)
{ .... }
2) Using stdFoam begin/end templates directly
for
(
auto iter = stdFoam::begin(lookup);
iter != stdFoam::end(lookup);
++iter
)
{ .... }
2b) The same, but wrapped via a macro:
forAllConstIters(lookup, iter)
{ .... }
Note that in many cases it is possible to simply use a range-based for.
Eg,
labelList myList;
for (auto val : myList)
{ ... }
for (const auto& val : myList)
{ ... }
These however will not work with any of the OpenFOAM hash-tables,
since the standard C++ concept of an iterator would return a key,value
pair when deferencing the *iter.
The deduction methods also exhibits some slightly odd behaviour with
some PtrLists (needs some more investigation).
- make construct from UList explicit and provide corresponding
assignment operator.
- add construct,insert,set,assignment from FixedList.
This is convenient when dealing with things like edges or triFaces.
- explicitly mention the value-initialized status for the operator().
This means that the following code will properly use an initialized
zero.
HashTable<label> regionCount;
if (...)
regionCount("region1")++;
... and also this;
if (regionCount("something") > 0)
{
...
}
Note that the OpenFOAM HashTable uses operator[] to provide read and
write access to *existing* entries and will provoke a FatalError if
the entry does not exist.
The operator() provides write access to *existing* entries or will
create the new entry as required.
The STL hashes use operator[] for this purpose.
- more hash-like methods.
Eg, insert/erase via lists, clear(), empty(),...
- minVertex(), maxVertex() to return the smallest/largest label used
- improved documentation, more clarification about where/how negative
point labels are treated.
- cannot use comparison of list sizes. Okay for UList, but not here.
STYLE:
- don't need two iterators for the '<' comparison, can just access
internal storage directly
- The existing ':' anchor works for rvalue substitutions
(Eg, ${:subdict.name}), but fails for lvalues, since it is
a punctuation token and parse stops there.
- support edge-ordering on construction, and additional methods:
- sort(), sorted(), unitVec(), collapse()
- null constructor initializes with -1, for consistency with face,
triFace and since it is generally much more useful that way.
- add some methods that allow edges to used somewhat more like hashes.
- count(), found(), insert(), erase()
Here is possible way to use that:
edge someEdge; // initializes with '-1' for both entries
if (someEdge.insert(pt1))
{
// added a new point label
}
... later
// unmark point on edge
someEdge.erase(pt2);
--
STYLE:
- use UList<point> instead of pointField for edge methods for flexibility.
The pointField include is retained, however, since many other routines
may be relying on it being included via edge.H
- This can be used as a convenient alternative to comparing against end().
Eg,
dictionaryConstructorTable::iterator cstrIter =
dictionaryConstructorTablePtr_->find(methodType);
if (cstrIter.found())
{
...
}
vs.
if (cstrIter != dictionaryConstructorTablePtr_->end())
{
...
}
- ensure proper and sensible handling of empty names.
Eg, isDir(""), isFile("") are no-ops, and avoid file-stat
- rmDir:
* optional 'silent' option to suppress messages.
* removes all possible sub-entries, instead of just giving up on
the first problem encountered.
- reduced code duplication in etcFiles
ENH: provide WM_USER_RESOURCE_DIRNAME define (in foamVersion.H)
- this is still a hard-coded value, but at least centrally available