The core of InsightCAE consists of a number of libraries. There is a core library (libtoolkit) which contains the basic functions. Other, optional features are found in a number of other libraries which differ in their build dependencies.
Overview over the component libraries:
toolkit (depends on VTK, Boost, Armadillo, GSL)
i.e. depends only on the basic dependencies (including VTK)
insightcad (depends on toolkit, OpenCASCADE, DXFlib)
i.e. depends on the basic features plus CAD kernel
Provides all the CAD functions but excluding CAD-related GUI classes.
tookit_remote (depends on toolkit, Wt)
Contains classes for remote execution client that require Wt
tookit_cad (depends on toolkit, insightcad)
Contains extensions to basic classes that require CAD (e.g. visualization of block mesh templates) but not GUI-related classes.
toolkit_gui (depends on toolkit, toolkit_cad, insightcad, toolkit_remote, Qt)
Extends all the above with Qt-GUI support.
Since InsightCAE is a toolbox for the creation of custom workflows, it is therefore very natural to use its API in own extensions.
There are different developer perspectives:
Creating extensions (own workflow modules).
To write own workflow modules, just a plain binary installation of InsightCAE is required. It brings header files for its libraries and a CMake configuration which enables the developer to build his own extensions. It is recommended to create a custom library containing the additions (plug-in). See section 1 for a guide.
Modifying and extending the InsightCAE base project itself.
Since InsightCAE is free and open software, it is perfectly possible to take it and apply extensions or corrections or any other modification or improvement. Please note that silentdynamics GmbH develops InsightCAE primarily with its own applications in mind so there are almost certainly features missing in the API which third party users might need. If you implement something which might be of public interest, please think about sharing it with us and the rest of the community. We are very open to integrate foreign contributions into the project.
Now, modifying the InsightCAE project requires to build the project from its sources. Please see section 2 for a guide to set up a self-built working copy of the sources.
The InsightCAE toolkit requires a number of dependencies. Not all versions have been tested, of course. The following list contains the major dependencies along with the versions, which are currently utilized in binary packages:
boost, http://www.boost.org, 1.65.0
python, 3.6
gsl
armadillo
OpenCASCADE
dxflib
Gmsh
Qt, 5.
Wt
OpenFOAM
Code_Aster
The InsightCAE sources are prepared to be built in a Posix environment. The developers use Ubuntu Linux in the latest LTS version. The Windows version is cross-compiled using the MXE cross compiling suite.
Some prerequisites:
GCC 10 should be used. Newer version were found to have buggy optimizers.
For Ubuntu, there is a package containing all the important dependencies. Install it by
$ sudo apt install insightcae-dependencies
An out-of-source build is recommended. If the aforementioned dependencies package is used, the following variables need to be added to the CMake configuration:
Once configured, the project is built either by
$ make
or
$ ninja
depending on the chosen generator.
Once built, the InsightCAE programs can be executed directly from the build folder, provided that the environment is set.
To setup the environment, add the appropriate script to the beginning of the /.bashrc file:
source /path/to/build/directory/bin/insight_setenv.sh
The Windows version so far has only been created using a cross compiler.
First, an installation of MXE is required. There is Ubuntu installation package in the InsightCAE development repository (see section 3). It contains all the required dependencies plus some additional packages (i.e. dxflib and python 3.6) and a number of patches. It can be installed using:
$ sudo apt install mxe
On other Linux distributions, MXE probably needs to be built from its sources. The following command should do the build of all required packages:
$ make -j10 MXE_TARGETS=i686-w64-mingw32.shared MXE_PLUGIN_DIRS="plugins/gcc10 plugins/boost_1_66_0" pe-util cgal gettext gcc glew glfw3 mesa harfbuzz armadillo boost dxflib freetype libgcrypt glib gsl hdf5 libiconv libidn libidn2 vtk oce openssl jpeg qt5 cryptopp poppler libntlm openssl wt tiff libgsasl
First, edit the “Kit” settings in QtCreator and create a Kit for MXE. Therefore, add:
GCC compiler “GCC MXE32 shared”, select /opt/mxe/usr/bin/i686-w64-mingw32.shared-gcc
C++ compiler “GCC MXE32 shared”, select /opt/mxe/usr/bin/i686-w64-mingw32.shared-g++
Qt installation “Qt MXE32 shared”, select /opt/mxe/usr/i686-w64-mingw32.shared/qt5/bin/ qmake
In section “CMake”, add “CMake MXE shared”, select /opt/mxe/usr/bin/i686-w64-mingw32.shared-cmake
Finally add a Kit “Desktop MXE32 shared” and select all the previously added entities
Some variables need to be added to the CMake configuration:
PYTHON_INCLUDE_DIRS=/opt/mxe/usr/i686-w64-mingw32.shared/python36/include
PYTHON_INCLUDE_DIR=/opt/mxe/usr/i686-w64-mingw32.shared/python36/include
PYTHON_LIBRARIES=/opt/mxe/usr/i686-w64-mingw32.shared/python36/python36.dll
PYTHON_LIBRARY=/opt/mxe/usr/i686-w64-mingw32.shared/python36/python36.dll
VTK_ONSCREEN_DIR=/opt/mxe/usr/i686-w64-mingw32.shared/lib/cmake/vtk-8.2
CMAKE_WRAPPER=/opt/mxe/usr/bin/i686-w64-mingw32.shared-cmake
INSIGHT_BUILD_MEDREADER:BOOL=OFF
With these variables manually added, it should be possible to build the project with QtCreator.
Install a SAMBA server and export the following paths as shares:
Make sure to include the option acl allow execute always = True for the share. Otherwise there will be an error 0xc0000022 when it is attempted to execute an EXE file from the share.
Prepare a windows machine with the following steps:
install python3.6.8rc1.exe (32bit version is required!)
Make sure to enable the option “add Python executable to PATH”!
map the share “insightwin” → drive I:
Set the following environment variables:
INSIGHT_GLOBALSHAREDDIRS=i:\share\insight
append to PATH:
i:\bin
i:\lib
Once this is done, it should be possible to execute the EXE files directly from the network drive I:\bin
To run flow simulations or finite element analyses, the Windows installation needs a linux environment since the backend tools are mostly only available for Linux. Therefore, a WSL container is required with an InsightCAE linux version inside. For development purposes, it is beneficial to have the InsightCAE linux build from the same source available inside the WSL container as was used to create the Windows version. The following steps can be made to achieve this goal:
Export the build folder (when QtCreator is used, it may be named like “build-insight-Desktop_superbuild-Debug”) of the Linux build as an additional share by the Samba server (e.g. named “insightlin”).
Create an Ubuntu WSL container, e.g. execute in a Power Shell:
> wsl.exe --install --distribution=Ubuntu-22.04
Launch a shell in the newly created container:
> wsl.exe
and install the insightcae-dependencies package (compare section 3.1).
The following commands at the WSL containers bash prompt are required:
$ sudo apt-key adv --fetch-keys http://downloads.silentdynamics.de/SD_REPOSITORIES_PUBLIC_KEY.gpg
$ sudo add-apt-repository http://downloads.silentdynamics.de/ubuntu_dev
$ sudo apt-get update
$ sudo apt-get install insightcae-dependencies
Then mount the share and add the environment setup script to the users’ bashrc file:
$ sudo mkdir -p /opt/build-insightcae
$ echo '\\<server>\insightlin /opt/build-insightcae drvfs defaults 0 0' | sudo tee /etc/fstab
$ sudo mount -a
$ sed -i '1i source /opt/build-insightcae/bin/insight_setenv.sh' ~/.bashrc
$ sed -i '1i source /opt/insightcae/bin/insight_setthirdpartyenv.sh' ~/.bashrc
Note: File I/O from within the WSL container is slowed down considerably by the Windows Defender Services. To improve performance, consider to disable this service and/or add exceptions where possible.
Move into the build directory and execute CPack, e.g.:
$ cd ~/Projekte/build-insight-Desktop_superbuild-Debug
$ cpack -G TGZ
The resulting archive has to be copied to the target and unpacked. For example:
$ tar xzf insightcae_5.0.139-gf41a2d2c~ubuntu24.04_amd64.tar.gz
Then change the path to the environment setup script in $HOME/.bashrc:
source <UNPACK PATH>/insightcae_5.0.139-gf41a2d2c~ubuntu24.04_amd64/usr/local/bin/insight_setenv.sh
(Replace <UNPACK PATH> with the path, in which the tar xzf command was executed. Also the version number in the archive will be different)
A new shell needs to be opened to apply the changes.
There is a script for creating the MSI installer which also copied the required dependencies from the MXE installation. It is intended to be executed from the build directory. For example:
cd ~/Projekte/build-insight-Desktop_MXE32_shared-Release
../insight/generateInsightCAEWindowsMSI.py -s ../insight -v 5.0.139
(The correct version number should be inserted after “-v”)
This will yield an installation package “insightcae.msi”.
The resulting MSI package has to be copied to the target and installed using the Windows tools (double click in the explorer window on the file).
An analysis (insight::Analysis, base/analysis.h) is the basic container of InsightCAE. It takes a set of parameters and computes a set of results (a ResultSet) from them. Each analysis has a working directory (the execution path) for intermediate files and result data.
Analyses are not called directly by type. They are registered in factory tables under their type name, and all front ends instantiate them through these tables:
analyze,base/parameterstudy.h), which run an analysis repeatedly with modified parameters,Running an analysis has three steps:
ParameterSet is created, usually from the default parameters of the analysis type (Analysis::defaultParameters()(typeName)), then modified by the user or loaded from an input file.Analysis::supplementedInputDatas()). It holds the quantities that are derived from the parameters before the run (see Computing Supplemented Input Data (SID)). The GUI also creates this object without running the analysis, for the parameter visualization.Analysis::analyses()) and executed by its call operator. The result is a ResultSet, which can be rendered as a PDF report or saved as an ISR file.In code (simplified from src/toolkit/base/analysisthread.cpp):
auto ps = Analysis::defaultParameters()(analysisName);
// ... modify *ps ...
std::shared_ptr<supplementedInputDataBase> sid =
Analysis::supplementedInputDatas()(
analysisName,
ParameterSetInput(*ps),
executionPath,
*progress.forkNewAction(99, "Processing input data") );
auto analysis = Analysis::analyses()(analysisName, sid);
ResultSetPtr results = (*analysis)(progress);
The constructor of Analysis calls throwIfIncomplete() on the SID: all deferred quantities are computed, and the analysis is not created if any of them failed. An analysis therefore never runs on incomplete input data.
Concrete analyses do not derive from Analysis directly but from AnalysisWithParameters. It adds a Parameters struct (with the userInformation subset) and the accessors p() and spPBase().
An analysis class contains:
| Member | Purpose |
|---|---|
PDL block PARAMETERSET>>> ... <<<PARAMETERSET |
definition of the parameters. The PDL generator produces a Parameters struct from it. Parameters of the base class are included with inherits Base::Parameters. |
struct supplementedInputData |
the SID class. Can be a plain typedef supplementedInputDataDerived<Parameters> supplementedInputData;, if nothing has to be derived from the parameters. |
addParameterMembers_SupplementedInputData(Class::Parameters) |
defines p() (the typed parameters) and sp() (the typed SID) |
declareType("Name") |
the type name, which is the key in the factory tables |
constructor taking const std::shared_ptr<supplementedInputDataBase>& |
called by the factory. Usually just inherited: using AnalysisWithParameters::AnalysisWithParameters; |
ResultSetPtr operator()(ProgressDisplayer&) |
performs the analysis and returns the results |
The following static functions are optional. They hide the defaults of Analysis and are registered together with the analysis:
| Function | Default | Purpose |
|---|---|---|
static AnalysisDescription description() |
empty | name and short description for the GUI and the report |
static std::string category() |
"Uncategorized" |
category in the analysis selection gallery, e.g. "Generic Analyses" |
static int galleryOrder() |
500 | position in the gallery; low values are placed on top |
static OperatingSystemSet compatibleOperatingSystems() |
Windows and Linux | operating systems on which the analysis can be executed |
static std::unique_ptr<ParameterSet> getPropositionsForParameter(path, currentValues) |
none | proposed values for a parameter, offered in the parameter editor |
A minimal analysis, following src/addons/insight-dummies/dummyanalysis.h:
#include "base/analysis.h"
#include "myanalysis_pdl.h"
namespace insight {
class MyAnalysis
: public AnalysisWithParameters
{
public:
#include MYANALYSIS_PDL_MyAnalysis
/*
PARAMETERSET>>>
L = double 1.0 "[m] some length"
n = int 10 "number of steps"
<<<PARAMETERSET
*/
struct supplementedInputData
: public supplementedInputDataDerived<Parameters>
{
supplementedInputData(
ParameterSetInput ip,
const boost::filesystem::path& workDir,
ActionProgress& progress );
Supplemented<double> dx_;
};
addParameterMembers_SupplementedInputData(MyAnalysis::Parameters);
public:
declareType("My Analysis");
using AnalysisWithParameters::AnalysisWithParameters;
ResultSetPtr operator()(ProgressDisplayer& progress) override;
static std::string category() { return "Generic Analyses"; }
static AnalysisDescription description()
{ return { "My Analysis", "Computes something from L and n" }; }
};
}
#include "myanalysis.h"
#include "base/resultelements/scalarresult.h"
namespace insight {
defineType(MyAnalysis);
Analysis::Add<MyAnalysis> addMyAnalysis; // registration in all factory tables
MyAnalysis::supplementedInputData::supplementedInputData(
ParameterSetInput ip,
const boost::filesystem::path& workDir,
ActionProgress& ap )
: supplementedInputDataDerived<Parameters>( ip.forward<Parameters>(), workDir, ap )
{
dx_ = deferred("dx", [this]() { return p().L/double(p().n); });
}
ResultSetPtr MyAnalysis::operator()(ProgressDisplayer& progress)
{
auto ap = progress.forkNewAction(1, "Computing");
auto results = createResultSet(); // contains the input parameters and the description
results->insert<ScalarResult>("dx", sp().dx_, "step size", "", "m");
++*ap;
return results;
}
}
Notes:
Analysis::Add<T> registers the factory and all static functions listed above. Its instance must be defined at namespace scope in the library which contains the analysis.myanalysis_pdl.h, macro MYANALYSIS_PDL_MyAnalysis) is generated during the build. The library target has to call target_add_PDL(<target>) in its CMakeLists.txt.createResultSet() creates a result set, which already contains the input parameters and the analysis description.operator(), files are written to executionPath().ProgressDisplayer to report progress (forkNewAction(), message(), ++) and solver convergence (update()).boost::thread_interrupted, so that they can be cancelled from the GUI.analyze --list-analyses shows all available types.Most CFD analyses in InsightCAE follow the same sequence: create a mesh, set up an OpenFOAM case, initialize and run the solver, evaluate the results. This sequence is implemented once in the class template OpenFOAMAnalysisTemplate<Base> (openfoam/openfoamanalysis.h). A concrete analysis only implements the case-specific steps.
OpenFOAMAnalysisTemplate<Base> derives from Base and adds:
Base::Parameters):
run/OFEname: the OpenFOAM installation to use,run/np: number of processors,run/mapFrom: case to map an initial solution from,run/potentialinit, run/evaluateonly, run/preprocessonly,mesh/linkmesh: link the mesh of another case instead of creating one,eval/reportdicts, eval/skipmeshquality,operator(), which runs the steps below,np(), reportIntermediateParameter(), installConvergenceAnalysis().Base has to be an analysis class with Parameters and supplementedInputData types, i.e. AnalysisWithParameters or a class derived from it. The usual case is the typedef
typedef OpenFOAMAnalysisTemplate<AnalysisWithParameters> OpenFOAMAnalysis;
Using the template with another base allows combining the OpenFOAM workflow with an existing non-CFD analysis, which contributes its own parameters and supplemented input data. Example from src/addons/insight-fmu/buildingventilationforcedflow.h, where BuildingVentilation defines the building model and BuildingVentilationCFDMesh adds the meshing on top:
typedef
BuildingVentilationCFDMesh<
OpenFOAMAnalysisTemplate<
BuildingVentilation<ForcedFlowVentilationZone> > >
BuildingVentilationForcedFlowBase;
The SID type of the template is supplementedInputDataDerived<Parameters, Base::supplementedInputData>, so the SID of Base is retained.
OpenFOAM analyses run only on Linux (compatibleOperatingSystems() returns LinuxOS).
operator() calls the following virtual functions in this order. Functions marked pure have to be implemented by the derived class; all others have default implementations which can be overridden. Overrides usually call the base implementation.
| Step | Function | Default behaviour |
|---|---|---|
| 1 | prepareCaseCreation(progress) |
nothing. Hook for actions before the case setup, e.g. running a preliminary solver to obtain settings. |
| 2 | createCaseOnDisk(runCase, progress) |
runs steps 2a–2g |
| 2a | calcDerivedInputData(progress) |
nothing. Typically reports derived quantities by reportIntermediateParameter(). They appear in the section “Derived Input Data” of the report. |
| 2b | createMesh(meshCase, progress) |
pure. Creates the mesh in executionPath(). Skipped if a mesh is already present or mesh/linkmesh is set. |
| 2c | createCase(runCase, progress) |
pure. Inserts the case elements (numerics, transport properties, boundary conditions, turbulence model, function objects) into runCase. |
| 2d | createDictsInMemory(runCase, dicts) |
creates the OpenFOAM dictionaries from the case elements |
| 2e | applyCustomOptions(runCase, dicts) |
checks the number of subdomains in decomposeParDict against np(). Hook for modifying dictionaries before they are written. |
| 2f | writeDictsToDisk(runCase, dicts) |
writes the case to disk. Skipped, if output time directories are already present. |
| 2g | applyCustomPreprocessing(runCase, progress) |
nothing. Hook for modifications of the case on disk, e.g. running setFields. |
| 3 | initializeSolverRun(progress, runCase) |
maps the solution from run/mapFrom, runs decomposePar for parallel runs, optionally potentialFoam. Skipped if run/evaluateonly. |
| 4 | runSolver(progress, runCase) |
runs the application from system/controlDict until endTime. Solver output is analysed for progress and convergence. Skipped if run/evaluateonly or run/preprocessonly. |
| 5 | finalizeSolverRun(runCase, progress) |
runs reconstructPar for the latest time step if needed |
| 6 | evaluateResults(runCase, progress) |
creates the result set: input parameters, mesh quality report, optionally the dictionaries, derived input data. Derived classes add their own evaluation. |
Because existing meshes, case files and output times are detected and not overwritten, an interrupted analysis can be restarted in the same execution directory, and run/evaluateonly re-evaluates an existing case.
The structure is the same as for any analysis (see Creating an Analysis). The differences:
OpenFOAMAnalysis (or from OpenFOAMAnalysisTemplate<YourBase>),inherits OpenFOAMAnalysis::Parameters. Sets with the same name (e.g. mesh, run, eval) are merged with the inherited ones,operator(); implement createMesh() and createCase() instead, and override evaluateResults() and the other hooks as needed.Example, condensed from src/modules/generic/numericalwindtunnel.h:
#include "openfoam/openfoamanalysis.h"
#include "numericalwindtunnel_pdl.h"
namespace insight {
class NumericalWindtunnel
: public OpenFOAMAnalysis
{
public:
#include NUMERICALWINDTUNNEL_PDL_NumericalWindtunnel
/*
PARAMETERSET>>>
inherits OpenFOAMAnalysis::Parameters
geometry = set { ... } "Geometry"
mesh = set { ... } "Properties of the computational mesh"
fluid = set {
turbulenceModel = dynamicclassparameters "insight::turbulenceModel" default "kOmegaSST" "Turbulence model"
} "Parameters of the fluid"
eval = set { ... } "Parameters for evaluation after solver run"
<<<PARAMETERSET
*/
struct supplementedInputData
: public supplementedInputDataDerived<Parameters>
{
supplementedInputData(
ParameterSetInput ip,
const boost::filesystem::path& workDir,
ActionProgress& progress );
Supplemented<double> Lref_;
// ... domain dimensions, geometry, blocking
};
addParameterMembers_SupplementedInputData(NumericalWindtunnel::Parameters);
public:
declareType("Numerical Wind Tunnel");
NumericalWindtunnel(const std::shared_ptr<supplementedInputDataBase>& sp)
: OpenFOAMAnalysis(sp) {}
void calcDerivedInputData(ProgressDisplayer& progress) override;
void createMesh(OpenFOAMCase& cm, ProgressDisplayer& progress) override;
void createCase(OpenFOAMCase& cm, ProgressDisplayer& progress) override;
ResultSetPtr evaluateResults(OpenFOAMCase& cm, ProgressDisplayer& progress) override;
static std::string category() { return "Generic Analyses"; }
static AnalysisDescription description() { return {"Numerical Wind Tunnel", ""}; }
};
}
The implementation (condensed from numericalwindtunnel.cpp and numericalwindtunnel_eval.cpp):
defineType(NumericalWindtunnel);
Analysis::Add<NumericalWindtunnel> addNumericalWindtunnel;
void NumericalWindtunnel::calcDerivedInputData(ProgressDisplayer&)
{
reportIntermediateParameter("Lref", sp().Lref_,
"reference length of object (bounding box diagonal)", "m");
}
void NumericalWindtunnel::createMesh(OpenFOAMCase& cm, ProgressDisplayer& progress)
{
// e.g. blockMesh followed by snappyHexMesh, written into executionPath()
}
void NumericalWindtunnel::createCase(OpenFOAMCase& cm, ProgressDisplayer&)
{
path dir = executionPath();
OFDictData::dict boundaryDict;
cm.parseBoundaryDict(dir, boundaryDict); // patches of the mesh created before
cm.insert(new steadyIncompressibleNumerics(cm, steadyIncompressibleNumerics::Parameters()
.set_endTime(1000.0) ));
cm.insert(new singlePhaseTransportProperties(cm, singlePhaseTransportProperties::Parameters()
.set_nu(p().fluid.nu) ));
cm.insert(new forces(cm, forces::Parameters()
.set_rhoInf(p().fluid.rho)
.set_patches(patchList)
.set_name("forces") ));
cm.insert(new PressureOutletBC(cm, "side1", boundaryDict));
// ... further boundary conditions
cm.addRemainingBCs<WallBC>(boundaryDict, WallBC::Parameters());
insertTurbulenceModel(cm, p().fluid.turbulenceModel);
}
ResultSetPtr NumericalWindtunnel::evaluateResults(OpenFOAMCase& cm, ProgressDisplayer& pp)
{
// mesh quality, derived input data etc. from the template
auto results = OpenFOAMAnalysis::evaluateResults(cm, pp);
double Re = p().operation.v*sp().Lref_/p().fluid.nu;
results->insert<ScalarResult>("Re", Re, "Reynolds number", "", "");
// ... force coefficients, plots, renderings
return results;
}
Guidelines:
createMesh() or createCase(). Then they are computed in parallel, checked before the run starts, and available to the parameter visualization in the GUI.createMesh() gets its own OpenFOAMCase object. Case elements needed only for meshing (e.g. meshingNumerics) are inserted there, not into the run case.createCase(), read the patches of the existing mesh with parseBoundaryDict(), insert the boundary conditions of the known patches and finish with addRemainingBCs<...>(), so that every patch has a boundary condition.np(), not from p().run.np directly: np() resolves values < 1 to the number of available processors.ConvergenceAnalysisDisplayer objects with installConvergenceAnalysis() (e.g. in createCase()). The solver is stopped, once all of them report convergence.evaluateResults() by calling the template implementation first and adding to the returned result set.
A supplemented input data (SID) object holds the quantities that an analysis derives from its parameters before the actual run, e.g. geometry bounding boxes, domain sizes, cell counts or CAD features. It is a class named supplementedInputData inside the analysis class, derived from supplementedInputDataDerived<Parameters> (base/supplementedinputdata.h).
The derived quantities are not computed eagerly in the SID constructor. Instead, each one is declared as a deferred computation. This has three advantages:
The building blocks are Supplemented<T> and deferred().
| Type / function | Meaning |
|---|---|
deferred(name, f) |
called in the SID constructor; registers the function f as a deferred computation and returns a Supplemented<T> handle. T is the return type of f. |
Supplemented<T> |
handle to a deferred quantity of type T. Used as SID member in place of a plain T member. |
SupplementedQuantity<T> |
the computation itself (state, stored value or error). Normally not used directly. |
SupplementedQuantityError |
thrown on access to a quantity whose computation failed. Refers to the quantity in which the error originally occurred. |
The headers are base/supplementedinputdata.h and base/supplementedquantity.h.
The members are declared as Supplemented<T> and assigned in the constructor using deferred(). The constructor only defines how each value is computed; nothing is computed there. Example from src/modules/generic/internalpressureloss_supplementedinputdata.cpp:
// header: members of InternalPressureLossBase::supplementedInputData
Supplemented<BoundingBox> bb_;
Supplemented<arma::mat> L_;
Supplemented<int> nx_, ny_, nz_;
// constructor
std::vector<Supplemented<arma::mat> > geomBBs; // one per geometry file
for (auto &w: p().geometry)
{
const auto label=w.first;
geomBBs.push_back(deferred("geometry/"+label, [this,label]() -> arma::mat
{
auto file = p().geometry.at(label).file;
if (file->isValid())
return file->geometry()->modelBndBox();
return arma::mat();
}));
}
bb_ = deferred("bounding box", [geomBBs]() // waits for all geometry files
{
BoundingBox bb;
for (const auto& tbb: geomBBs)
if (tbb->n_elem>0) bb.extend(tbb);
return bb;
});
L_ = deferred("model size", [this]() -> arma::mat
{
arma::mat L=bb_->col(1)-bb_->col(0);
if (L(0)<1e-12)
throw insight::Exception("model size in x direction is zero!");
// ...
return L;
});
nx_=deferred("nx", [this]() { return std::max(1, int(ceil(L_(0)/p().mesh.size))); });
Here, the bounding boxes of the geometry files are computed in parallel. bb_ captures the vector of handles by value (handles are cheap shared-pointer copies). nx_, ny_ and nz_ are independent of each other and all depend on L_.
Notes on deferred():
ActionProgress&, if it wants to report progress:
geometry_ = deferred("geometry", [this](ActionProgress& ap) { ...; return g; } );
Supplemented<T> member exactly. Specify the return type explicitly (e.g. -> arma::mat) if the expression would otherwise yield an expression template or a different type.Supplemented<T> is constructible from a plain T.Accessing a value means: compute it now, or wait for it. If the quantity is still pending, the accessing thread computes it itself. If another thread is computing it, the accessing thread blocks until that computation has finished. Each computation is executed at most once.
Dependencies therefore resolve themselves and are never declared explicitly: deferred functions simply read other Supplemented members.
Supplemented<T> is designed such that existing code that read plain members keeps compiling:
const T& (e.g. arithmetic: 2.*sp().L_), and get()operator* and operator->: the value itself or, if T is a std::shared_ptr, the pointee (so *sp().blocking or sp().feature_->... keep their meaning)operator(), e.g. element access of matrices: sp().L_(0)begin()/end() for range-based for loops over containersThe state can be queried without throwing:
| Function | Behaviour |
|---|---|
ok() |
computes if necessary (blocking); true, if a value is available |
status() |
non-blocking; Pending, Running, Done or Failed |
error() |
non-blocking; the stored exception, if failed, null otherwise |
isDefined() |
true, if a computation or a value has been assigned |
The supplementedInputDataBase provides these functions to run all registered computations:
| Function | Behaviour |
|---|---|
launchAll(progress) |
starts up to hardware_concurrency worker threads and returns immediately. Each worker walks through all pending quantities and computes whatever is not yet claimed by another thread. |
computeAll(progress) |
launchAll(), then waits until all quantities (including those registered after the launch) are finished. Does not throw on failures. |
throwIfIncomplete(progress) |
computeAll(), then throws an exception listing all errors, if any computation failed. |
cancelDeferredComputations() |
interrupts all background computations and waits for the threads to end. Unfinished quantities are marked as failed (“computation was cancelled”). |
complete() |
non-blocking; true, if all quantities have been computed successfully. |
After launchAll(), the caller has to ensure that either computeAll() or cancelDeferredComputations() is called before the SID object is destroyed.
Analysis::resetParameters() calls throwIfIncomplete(), so an analysis run still requires a complete and valid SID.
The GUI parameter visualizer (src/toolkit_gui/cadparametersetvisualizer.cpp) uses the deferred computation as follows:
launchAll(), then the partially filled SID is displayed immediately.computeAll() completes the remaining quantities. Then the table of reported quantities and the error list are updated.If a deferred function throws, the exception is stored and rethrown (wrapped in a SupplementedQuantityError) on every access. Only the failing quantity and the quantities depending on it fail; all independent quantities remain available. The error of a dependent quantity refers to the original cause, e.g.:
supplemented quantity "nx" is unavailable, since "model size" could not be computed: model size in x direction is zero!
SupplementedQuantityError provides quantity(), rootQuantity(), rootMessage(), rootCause() and isDependencyFailure().
On the SID level:
errors() lists all failed quantities, including those which failed because of failed dependencies,rootErrors() lists only the quantities in which the errors originally occurred,issues() returns the recorded warnings together with the root errors, for display. Warnings issued during a deferred computation are recorded automatically and attributed to that quantity. Further warnings can be added with recordWarning().reportSupplementQuantity() has an overload taking a Supplemented<T>:
reportSupplementQuantity("Lref", Lref_, "reference length", "m");
It stores a reporter instead of a value. When the table of reported quantities is requested (reportedSupplementQuantities()), the value is inserted if it is available, the error message if the computation failed, or “(computing…)” otherwise. Reporting never waits for a computation.
Supplemented<T> and assign them with deferred(). Compute values eagerly in the constructor only if they are cheap and cannot fail.this or copies of handles in the lambdas, never local variables by reference: the function runs later, possibly in another thread, after the constructor has returned.p() and other Supplemented members is fine; modifying shared state requires explicit locking.Points and vectors are traditionally passed around as bare arma::mat objects (3x1 column vectors, e.g. created by vec3(x,y,z)). Nothing in such a variable tells in which coordinate system (frame of reference) its components are expressed. Errors from combining coordinates of different frames, or from transforming a direction vector like a point (i.e. including the translation), are easy to make and hard to find.
The header base/framedvector.h therefore provides frame-tagged point and vector types. Similar to how boost::units ties a unit to a number, these types tie a frame to the coordinates. The frame is a compile-time tag, so that:
The tagged types are thin wrappers around arma::mat and SpatialTransformation; there is no runtime overhead. The untagged API of SpatialTransformation and CoordinateSystem remains available, so tagged and untagged code can be mixed and existing code can be migrated gradually.
| Type | Meaning |
|---|---|
GlobalFrame |
predefined tag for the global coordinate system |
INSIGHT_DECLARE_FRAME(Tag) |
macro to declare a new frame tag (at namespace scope) |
PointIn<F> |
a location, expressed in frame F. Affected by translation. |
VectorIn<F> |
a direction or displacement, expressed in frame F. Not affected by translation. |
FrameTransformation<From,To> |
maps points and vectors from frame From into frame To. Wraps a SpatialTransformation. |
The untagged base classes are:
SpatialTransformation (base/spatialtransformation.h): translation, rotation and scaling, applied in this order. trsfPt() transforms points, trsfVec() transforms vectors (without translation).CoordinateSystem (same header): a coordinate system given by its origin and the axes ex, ey, ez. localToGlobal() and globalToLocal() return the corresponding SpatialTransformation.A frame tag is an empty struct. It only names the role of a coordinate system in the code, e.g. “the local beam coordinate system” or “the CAD model coordinate system”. The actual position and orientation of the frame is usually known only at runtime (e.g. from analysis parameters). It is bound to the tag by creating a FrameTransformation (see below).
#include "base/framedvector.h"
using namespace insight;
INSIGHT_DECLARE_FRAME(BeamLocal);
INSIGHT_DECLARE_FRAME(SensorFrame);
PointIn<GlobalFrame> p1(1, 2, 3), p2(4, 6, 3);
VectorIn<GlobalFrame> ex(1, 0, 0);
VectorIn<GlobalFrame> d = p2 - p1; // point - point -> vector
PointIn<GlobalFrame> p3 = p1 + 0.5*d; // point + vector -> point
PointIn<GlobalFrame> p4 = p2 - ex; // point - vector -> point
double l = norm(d); // 5
double s = distance(p1, p2); // 5
VectorIn<GlobalFrame> n = normalized(cross(d, ex));
double c = dot(n, ex);
double x = p1.x(); // components: x(), y(), z() or p1(0), ...
The following does not compile:
PointIn<BeamLocal> pl(0, 0, 1);
auto e1 = p1 - pl; // error: points/vectors are expressed in different frames
auto e2 = p1 + p2; // error: adding two points is not meaningful
auto e3 = 2.*p1; // error: scaling a point is not meaningful
Untagged arma::mat data is tagged with the explicit constructors. The constructor checks that the input has three components; row vectors are accepted and stored as columns. The untagged components are returned by raw():
arma::mat legacyPoint = vec3(1, 2, 3);
PointIn<GlobalFrame> p(legacyPoint); // tag explicitly
// PointIn<GlobalFrame> q = legacyPoint; // does not compile: implicit tagging is not allowed
someLegacyFunction( p.raw() ); // const arma::mat& (3x1)
The explicit tagging is deliberate. Every place where untagged data enters the tagged world is visible in the code and states which frame the data is assumed to be in.
A FrameTransformation<From,To> is created from a SpatialTransformation. It applies the translation to points, but not to vectors:
FrameTransformation<SensorFrame,BeamLocal> sensorToBeam(
SpatialTransformation(
vec3(0, 3, 0), // translation
vec3(-45, 0, 90) // roll, pitch, yaw in degrees
) );
PointIn<SensorFrame> ps(0.3, -1, 4);
VectorIn<SensorFrame> vs(1, 1, 0);
PointIn<BeamLocal> pb = sensorToBeam(ps); // uses trsfPt
VectorIn<BeamLocal> vb = sensorToBeam(vs); // uses trsfVec (no translation)
// auto e = sensorToBeam(pb); // error: point is not expressed in the source frame of this transformation
Transformations can be inverted and chained. The chain is checked at compile time: FrameTransformation<B,C> * FrameTransformation<A,B> yields FrameTransformation<A,C>. As with matrices, the right operand is applied first:
FrameTransformation<BeamLocal,SensorFrame> beamToSensor = sensorToBeam.inverted();
FrameTransformation<BeamLocal,GlobalFrame> beamToGlobal = /* ... */;
FrameTransformation<SensorFrame,GlobalFrame> sensorToGlobal = beamToGlobal * sensorToBeam;
// auto e = sensorToBeam * beamToGlobal; // error: cannot compose transformations
The underlying untagged transformation is available through spatialTransformation(), e.g. to pass it to VTK or OpenFOAM utilities.
Note: if the SpatialTransformation contains a scale factor other than 1, vectors are scaled too, i.e. unit vectors do not remain unit vectors.
Coordinate systems are typically constructed at runtime as a CoordinateSystem, e.g. from parameters like origin, X- and Z-direction. The functions localToParent<Local,Parent> and parentToLocal<Local,Parent> create the typed transformations from it. Parent is the frame in which the CoordinateSystem itself is defined; it defaults to GlobalFrame. The functions originOf, exOf, eyOf and ezOf return its origin and axes as tagged quantities in the parent frame.
// beam axis along global Y, starting at (1,2,3)
CoordinateSystem beamCS( vec3(1, 2, 3), vec3(0, 1, 0), vec3(0, 0, 1) );
auto beamToGlobal = localToParent<BeamLocal>(beamCS); // FrameTransformation<BeamLocal,GlobalFrame>
auto globalToBeam = parentToLocal<BeamLocal>(beamCS); // FrameTransformation<GlobalFrame,BeamLocal>
PointIn<BeamLocal> pTip(L, 0, 0); // tip of a beam of length L
PointIn<GlobalFrame> pTipGlobal = beamToGlobal(pTip); // == (1, 2+L, 3)
VectorIn<GlobalFrame> r = pTipGlobal - originOf<GlobalFrame>(beamCS);
VectorIn<GlobalFrame> axis = exOf<GlobalFrame>(beamCS);
// a force given in global coordinates, expressed in the beam CS
VectorIn<GlobalFrame> F(0, 0, -1000);
VectorIn<BeamLocal> Fbeam = globalToBeam(F);
PointIn/VectorIn in interfaces (function arguments, return values, class members) where the frame matters. Inside numerical inner loops, plain arma::mat may still be used.VectorIn, a location is a PointIn.raw() and the explicit constructors at the boundaries to untagged code.The tagged types are currently not wrapped for Python.