The TooN library is a set of C++ header files which provide basic numerics facilities:
It provides classes for statically- (known at compile time) and dynamically- (unknown at compile time) sized vectors and matrices and it can delegate advanced functions (like large SVD or multiplication of large matrices) to LAPACK and BLAS (this means you will need libblas and liblapack).
The library makes substantial internal use of templates to achieve run-time speed efficiency whilst retaining a clear programming syntax.
Why use this library?
This section is arranged as a FAQ. Most answers include code fragments. Assume
using namespace TooN;.
To get the code from cvs use: cvs -z3 -d:pserver:email@example.com:/cvsroot/toon co TooN The home page for the library with a version of this documentation is at: http://mi.eng.cam.ac.uk/~er258/cvd/toon.html The code will work as-is, and comes with a default configuration, which should work on any system. On a unix system, <code>./configure && make install </code> will install TooN to the correct place. Note there is no code to be compiled, but the configure script performs some basic checks. On non-unix systems, e.g. Windows and embedded systems, you may wish to configure the library manually. See \ref sManualConfiguration.
To begin, just in include the right file:
Everything lives in the
Then, make sure the directory containing TooN is in your compiler's search path. If you use any decompositions, you will need to link against LAPACK, BLAS and any required support libraries. On a modern unix system, linking against LAPACK will do this automatically.
If you get errors compiling code that uses TooN, look for the macro TOON_TYPEOF in the messages. Most likely the file <code>internal/config.hh</code> is clobbered. Open it and remove all the defines present there. Also see @ref sManualConfiguration for more details on configuring TooN, and @ref sConfigLapack, if you want to use LAPACK and BLAS. Define the macro in <code>internal/config.hh</code>.
Vectors can be statically sized or dynamically sized.
Matrices can be statically sized or dynamically sized.
To write a function taking a local copy of a vector:
To write a function taking any type of vector by reference:
Slices are strange types. If you want to write a function which uniformly accepts <code>const</code> whole objects as well as slices, you need to template on the precision. Note that constness in C++ is tricky (see \ref sConst). If you write the function to accept <code> Vector<3, double, B>& </code>, then you will not be able to pass it slices from <code> const Vector</code>s. If, however you write it to accept <code> Vector<3, const double, B>& </code>, then the only way to pass in a <code>Vector<3></code> is to use the <code>.as_slice()</code> method. See also \ref sGenericCode
In TooN, the behaviour of a Vector or Matrix is controlled by the third template parameter. With one parameter, it owns the data, with another parameter, it is a slice. A static sized object uses the variable:
to hold the data. A slice object uses:
When a Vector is made
const, C++ inserts
const in to those types. The
const it inserts it top level, so these become (respectively):
Now the types behave very differently. In the first case
my_data is immutable. In the second case,
my_data is immutable, but
my_data is mutable.
Therefore a slice
const Vector behaves like an immutable pointer to mutable data. TooN attempts to make
const objects behave as much like pointers to immutable data as possible.
The semantics that TooN tries to enforce can be bypassed with sufficient steps:
Assignments are performed using <code>=</code>. See also \ref sNoResize. These operators apply to vectors or matrices and scalars. The operator is applied to every element with the scalar.
Vector and vectors or matrices and matrices:
Matrix multiplying a column vector:
Row vector multiplying a matrix:
3x3 Vector cross product:
All the functions listed below return slices. The slices are simply references to the original data and can be used as lvalues.
Getting the transpose of a matrix:
Turning vectors in to matrices:
Slicing with a start position and size:
Like other features of TooN, mixed static/dynamic slicing is allowed. For example:
See also What are slices?
Vectors and matrices start off uninitialized (filled with random garbage). They can be easily filled with zeros, or ones (see also TooN::Ones):
Vectors can be filled with makeVector:
Matrices can be initialized to the identity matrix:
note that you need to specify the size in the dynamic case.
Matrices can be filled from data in row-major order:
A less general, but visually more pleasing syntax can also be used:
Note that underfilling is a run-time check, since it can not be detected at compile time.
They can also be initialized with data from another source. See also I have a pointer to a bunch of data. How do I turn it in to a vector/matrix without copying?.
Addition to every element is not an elementary operation in the same way as multiplication by a scalar. It is supported throught the ::Ones object:
It is supported the same way on Matrix and slices.
Vectors are not generic containers, and dynamic vectors have been designed to have the same semantics as static vectors where possible. Therefore trying to assign a vector of length 2 to a vector of length 3 is an error, so it fails. See also \ref sResize
As C++ does not yet support move semantics, you can only safely store static and resizable Vectors in STL containers.
Do you really want to? If you do, then you have to declare it:
The policy behind the design of TooN is that it is a linear algebra library, not a generic container library, so resizable Vectors are only created on request. They provide fewer guarantees than other vectors, so errors are likely to be more subtle and harder to track down. One of the main purposes is to be able to store Dynamic vectors of various sizes in STL containers.
Assigning vectors of mismatched sizes will cause an automatic resize. Likewise assigning from entities like Ones with a size specified will cause a resize. Assigning from an entities like Ones with no size specified will not cause a resize.
They can also be resized with an explicit call to .resize(). Resizing is efficient since it is implemented internally with
std::vector. Note that upon resize, existing data elements are retained but new data elements are uninitialized.
Currently, resizable matrices are unimplemented. If you want a resizable matrix, you may consider using a
std::vector, and accessing it as a TooN object when appropriate. See I have a pointer to a bunch of data. How do I turn it in to a vector/matrix without copying?. Also, the speed and complexity of resizable matrices depends on the memory layout, so you may wish to use column major matrices as opposed to the default row major layout.
By default, everything which is checked at compile time in the static case is checked at run-time in the dynamic case (with some additions). Checks can be disabled with various macros. Note that the optimizer will usually remove run-time checks on static objects if the test passes. Bounds are not checked by default. Bounds checking can be enabled by defining the macro \c TOON_CHECK_BOUNDS. None of these macros change the interface, so debugging code can be freely mixed with optimized code. The debugging checks can be disabled by defining either of the following macros: - \c TOON_NDEBUG - \c NDEBUG Additionally, individual checks can be disabled with the following macros: - Static/Dynamic mismatch - Statically determined functions accept and ignore dynamically specified sizes. Nevertheless, it is an error if they do not match. - Disable with \c TOON_NDEBUG_MISMATCH - Slices - Disable with \c TOON_NDEBUG_SLICE - Size checks (for assignment) - Disable with \c TOON_NDEBUG_SIZE - overfilling using Fill - Disable with \c TOON_NDEBUG_FILL - underfilling using Fill (run-time check) - Disable with \c TOON_NDEBUG_FILL Errors are manifested to a call to <code>std::abort()</code>. TooN does not initialize data in a Vector or Matrix. For debugging purposes the following macros can be defined: - \c TOON_INITIALIZE_QNAN or \c TOON_INITIALIZE_NAN Sets every element of newly defined Vectors or Matrixs to quiet NaN, if it exists, and 0 otherwise. Your code will not compile if you have made a Vector or Matrix of a type which cannot be constructed from a number. - \c TOON_INITIALIZE_SNAN Sets every element of newly defined Vectors or Matrixs to signalling NaN, if it exists, and 0 otherwise. - \c TOON_INITIALIZE_VAL Sets every element of newly defined Vectors or Matrixs to the expansion of this macro. - \c TOON_INITIALIZE_RANDOM Fills up newly defined Vectors and Matrixs with random bytes, to trigger non repeatable behaviour. The random number generator is automatically seeded with a granularity of 1 second. Your code will not compile if you have a Vector or Matrix of a non-POD type.
Slices are references to data belonging to another vector or matrix. Modifying the data in a slice modifies the original object. Likewise, if the original object changes, the change will be reflected in the slice. Slices can be used as lvalues. For example:
Slices are usually strange types. See How do I write a function taking a vector?
Likewise for matrix. By default, TooN supports all builtin types and std::complex. Using custom types requires some work. If the custom type understands +,-,*,/ with builtin types, then specialize TooN::IsField on the types.
If the type only understands +,-,*,/ with itself, then specialize TooN::Field on the type.
Note that this is required so that TooN can follow the C++ promotion rules. The result of multiplying a
Matrix<double> by a
Vector<float> is a
If you are using C++11, returning slices is now easy:
If not, some tricks are required. Each vector has a
SliceBase type indicating the type of a slice.
They can be slightly tricky to use:
You use the decomposition objects (see \ref sDecompos "below"), for example to solve Ax=b:
Similarly for the other decomposition objects
For 2x2 matrices, the TooN::inv function can be used.
For general size matrices (not necessarily square) there are: @link TooN::LU LU @endlink, @link TooN::SVD SVD @endlink, @link TooN::QR QR@endlink, @link TooN::QR_Lapack LAPACK's QR@endlink and gauss_jordan() For square symmetric matrices there are: @link TooN::SymEigen SymEigen @endlink and @link TooN::Cholesky Cholesky @endlink If all you want to do is solve a single Ax=b then you may want gaussian_elimination()
Look at the @link modules modules @endlink.
See @link gLinAlg here @endlink.
TooN has buildin support for <a href="http://www.fadbad.com/fadbad.html">FADBAD++</a>. Just do:
Then create matrices and vectors of FADBAD types. See functions/fadbad.h for available functions and parameterisations.
TooN is type generic and so can work on any reasonable types including AD types if a small amount of interfacing is performed. See .
Consider the function:
It can accept a
Vector<3> by reference, and operate on it in place. A
Vector<3> is a type which allocates memory on the stack. A slice merely references memory, and is a subtly different type. To write a function taking any kind of vector (including slices) you can write:
A slice is a temporary object, and according to the rules of C++, you can't pass a temporary to a function as a non-const reference. TooN provides the
.ref() method to escape from this restriction, by returning a reference as a non-temporary. You would then have to write:
to get func to accept the slice.
You may also wish to consider writing functions that do not modify structures in place. The
unit function of TooN computes a unit vector given an input vector. In the following context, the code:
produces exactly the same compiler output as the hypothetical
Normalize(v) which operates in place (for static vectors). Consult the ChangeLog entries dated
Wed 25 Mar, 2009 20:18:16'' andWed 1 Apr, 2009 16:48:45'' for further discussion.
To create a vector use:
Or, a functional form can be used:
To crate a matrix use
The constructors for TooN objects are very permissive in that they accept run-time size arguments for statically sized objects, and then discard the values, This allows you to easily write generic code which works for both static and dynamic inputs. Here is a function which mixes up a vector with a random matrix:
Writing functions which safely accept multiple objects requires assertions on the sizes since they may be either static or dynamic. TooN's built in size check will fail at compile time if mismatched static sizes are given, and at run-time if mismatched dynamic sizes are given:
For issues relating to constness, see and
TooN compiles cleanly under C++ 11, but does not require it. It can also make use of some C++11 features where present. Internally, it will make use of \c decltype if a C++11 compiler is present and no overriding configuration has been set. See \ref stypeof for more information.
Create two vectors and work out their inner (dot), outer and cross products
Create a vector and a matrix and multiply the two together
One aspect that makes this library efficient is that when you declare a 3-vector, all you get are 3 doubles - there's no metadata. So
sizeof(Vector<3>) is 24. This means that when you write
Vector<3> v; the data for
v is allocated on the stack and hence
free) overhead is avoided. However, for large vectors and matrices, this would be a Bad Thing since
Vector<1000000> v; would result in an object of 8 megabytes being allocated on the stack and potentially overflowing it. TooN gets around that problem by having a cutoff at which statically sized vectors are allocated on the heap. This is completely transparent to the programmer, the objects' behaviour is unchanged and you still get the type safety offered by statically sized vectors and matrices. The cutoff size at which the library changes the representation is defined in
TooN.h as the
const int TooN::Internal::max_bytes_on_stack=1000;.
When you apply the subscript operator to a
Matrix<3,3> and the function simply returns a vector which points to the the apropriate hunk of memory as a reference (i.e. it basically does no work apart from moving around a pointer). This avoids copying and also allows the resulting vector to be used as an l-value. Similarly the transpose operation applied to a matrix returns a matrix which referes to the same memory but with the opposite layout which also means the transpose can be used as an l-value so
M1 = M2.T(); and
M1.T() = M2; do exactly the same thing.
Warning: This also means that
M = M.T(); does the wrong thing. However, since .T() essentially costs nothing, it should be very rare that you need to do this.
These are implemented in the obvious way using metadata with the rule that the object that allocated on the heap also deallocates. Other objects may reference the data (e.g. when you subscript a matrix and get a vector).
When you write
v1 = M * v2; a naive implementation will compute
M * v2 and store the result in a temporary object. It will then copy this temporary object into
v1. A method often advanced to avoid this is to have
M * v2 simply return an special object
O which contains references to
v2. When the compiler then resolves
v1 = O, the special object computes
M*v2 directly into
v1. This approach is often called lazy evaluation and the special objects lazy vectors or lazy matrices. Stroustrup (The C++ programming language Chapter 22) refers to them as composition closure objects or compositors.
The killer is this: What if v1 is just another name for v2? i.e. you write something like
v = M * v;. In this case the semantics have been broken because the values of
v are being overwritten as the computation progresses and then the remainder of the computation is using the new values. In this library
v1 in the expression could equally well alias part of
M, thus you can't even solve the problem by having a clever check for aliasing between
v2. This aliasing problem means that the only time the compiler can assume it's safe to omit the temporary is when
v1 is being constructed (and thus cannot alias anything else) i.e.
Vector<3> v1 = M * v2;.
TooN provides this optimisation by providing the compiler with the opportunity to use a return value optimisation. It does this by making
M * v2 call a special constructor for
v2 as arguments. Since nothing is happening between the construction of the temporary and the copy construction of
v1 from the temporary (which is then destroyed), the compiler is permitted to optimise the construction of the return value directly into
Because a naive implemenation of this strategy would result in the vector and matrix classes having a very large number of constructors, these classes are provided with template constructors that take a standard form. The code that does this, declared in the header of class
This documentation is generated from a cleaned-up version of the interface, hiding the implementation that allows all of the magic to work. If you want to know more and can understand idioms like:
then take a look at the source code ...
TooN needs a mechanism to determine the type of the result of an expression. One of the following macros can be defined to control the behaviour:
typeofextension. Only works with GCC and will fail with -pedantic
typeofextension. Only works with GCC and will work with -pedantic
Under Win32, the builtin typeof needs to be used. Comment out all the TOON_TYPEOF_ defines to use it.
If no configuration is present and C++11 is detected, then
decltype will be used.
Some functions use internal implementations for small sizes and may switch over to LAPACK for larger sizes. In all cases, an equivalent method is used in terms of accuracy (eg Gaussian elimination versus LU decomposition). If the following macro is defined:
TOON_USE_LAPACKthen LAPACK will be used for large systems, where optional. The individual functions are:
Note that these macros do not affect classes that are currently only wrappers around LAPACK.