Reviewing Factor Graphs and GTSAM by the GTSAM project to learn key concepts for working with factor graphs.
This is an updated version of the 2012 tech-report Factor Graphs and GTSAM: A Hands-on Introduction by Frank Dellaert. A more thorough introduction to the use of factor graphs in robotics is the 2017 article Factor graphs for robot perception by Frank Dellaert and Michael Kaess.
Related Papers: More of this application layer:
- Factor Graphs for Navigation Applications: A Tutorial
- Factor Graphs for Robot Perception
- Nister et al 2004 → Visual Odometry → Nistér, D., Naroditsky, O., and Bergen, J., "Visual Odometry", in IEEE Conf. on Computer Vision and Pattern Recognition (CVPR) vol. 1, (2004), pp. 652-659.
- Davison 2003 → Visual SLAM → Davison, A.J., "Real-Time Simultaneous Localisation and Mapping with a Single Camera", in Intl. Conf. on Computer Vision (ICCV) (2003), pp. 1403-1410.
Related Papers: Adjacent Ideas:
- TinyMPC: Model-Predictive Control on Resource-Constrained Microcontrollers, tick tock iteration
- On-Manifold Preintegration for Real-Time Visual Inertial Odometry
Related Papers: Digging Deeper
- The Levenberg-Marquardt algorithm for nonlinear least squares curve-fitting problems -Covariance Recovery from a Square Root Information Matrix for Data Association
Section 1: Overview¶
Key idea:
A factor graph, however, is a bipartite graph consisting of factors connected to variables. The variables represent the unknown random variables in the estimation problem, whereas the factors represent probabilistic constraints on those variables, derived from measurements or prior knowledge.
Q: how to represent physical motion constraints / time system evolution model?
- A: Odometry Binary Factors + noise
Q: how to represent sensor models, sensor constraints? Some bytes/float from sensor implies some projection to a state [unknown random variables]
- A: Sensor Unary Factors + noise, where the specific factor is partially evaluated with the given sensor reading
Q: How does uncertainty models play a role here? e.g. expecting that there’s noisy motion evolution over time and sensor data is only probably approximate
- A: Each factor has a noise model (inverse confidence weighting)
- sub Q: How do you do this for gaussian noise? What if you have some other distribution (e.g. binary)
- A: There's at least ConcentratedGaussian as alternative distributions, but it may be that everything is based on a Gaussian noise of some sort
- sub Q: How can you do uncertain associations? e.g. did you see the same place for loop closure, or did you see the same
- A: This isn't covered, but I think you could do some sort of decision variable to probabilistically weight one of two or one of N associations as the correct one and then optimize the decision variable which would in turn constrain the optimization to adjust the bundle towards one association or the other (or the joint probability of multiple)
GTSAM exploits sparsity to be computationally efficient. Typically measurements only provide information on the relationship between a handful of variables, and hence the resulting factor graph will be sparsely connected.
Starting mental model: some unknown process from an unknown starting state evolves over time. At each time, the state generates a measurement based only on the state at that time. This is the Bayes Network.
We then observe the measurements and want to find the most probable sequence of states that generated those measurements.
Setup: Markov chain of 3 hidden states and 3 measurements generates 6 factors:
- initial condition
- 2 transitions (state X1 to X2, X2 to X3)
- 3 measurements (from Z1 to X1, etc), “likelihood factors”
Q: what are the variables then?
- A: the variables are the unknown states X1, X2, X3
Objective / Minimization / Maximization: Maximize the value of the graph. The value is the product of all factors f of their associated variables.
Section 2 - Modeling Robot Motion¶
Simple example, linear chain:
- f0(x1) encoding initially known information (prior), “unary factor”
- f1(x1, x2; o1) “binary factor” of the transition from x1 to x2 given an odometry measurement o1
- f2(x2, x3; o2) “binary factor” of the transition from x2 to x3 given an odometry measurement o2
Q: Are these odometry measurements treated as “given” or “global”? I’m not quite putting my wording right for the question I’m trying to ask. Are these pre-integrated terms (based on my mental model of pre-integration and maybe not the actual paper)?
- A: Yes, this would be motion from wheel encoders, etc. See also The Preintegrated IMU Factor
Note: explicit typing for a prior that is known ahead of time and constrains a single state PriorFactor
Note: It seems like the variables are just represented as integers? Yes, and there are helpers to track nicer names for the integers
Neat: They use shared pointers to do an approximation of common subexpression elimination: For example: if you re-use the same noise model for multiple factors, then you can point them all at the same noise model shared pointer and not have to reallocate it, etc.
Section 2.3 Factor Graphs vs Values¶
At this point it is instructive to emphasize two important design ideas underlying GTSAM:
- The factor graph and its embodiment in code specify the joint probability distribution P(X|Z) over the entire trajectory X = {x_1, x_2, x_3} of the robot, rather than just the last pose. This smoothing view of the world gives GTSAM its name: “smoothing and mapping”. Later in this document we will talk about how we can also use GTSAM to do filtering (which you often do not want to do) or incremental inference (which we do all the time).
- A factor graph in GTSAM is just the specification of the probability density P(X|Z) , and the corresponding FactorGraph class and its derived classes do not ever contain a “solution”. Rather, there is a separate type Values that is used to specify specific values for (in this case) x1, x2, x3, which can then be used to evaluate the probability (or, more commonly, the error) associated with particular values.
Q: What's their take on why not filtering?
Neat: Incremental Inference sounds just up my alley
[W]hen designing GTSAM we took a functional approach of classes corresponding to mathematical objects, which are usually immutable.
Example optimization pseudocode/ideal loop:
- Set up
FactorGraphdata structure with probability distribution - Set up
Valuesdata structure with initial guess - Optimize, given a graph
- Get a new
Valuesresult
Example optimization algorithm: Levenberg-Marquardt
Nice: the optimization algorithm is plug-and-play instead of assuming one algorithm. The optimization algorithm is also immutable-functional (given the values and graph, run through an optimizer function and get a new set of optimized values)
Section 2.5 Full Posterior Inference¶
GTSAM can also be used to calculate [an approximate] covariance matrix for each pose after incorporating the information from all measurements
Nice 🙂
GTSAM only computes a Gaussian approximation to the true underlying posterior.
Code: Marginals marginals(graph, result);
Q: This calculation is done by running a function on the graph and the result. What is the algorithm to recover the marginals?
An important fact to note when interpreting these numbers is that covariance matrices are given in relative coordinates, not absolute coordinates. This is because internally GTSAM optimizes for a change with respect to a linearization point, as do all nonlinear optimization libraries.
A nice result that you see with the odometry-only example is that uncertainty Maringals grows over time
Section 3 Robot Localization¶
Use Unary Measurement Factors to introduce external measurements
Q: why not use measurements for odometry?
- A: I guess you have to use something for odometry, be it measured with a clock (dt) + a motion model or measured with a wheel encoder, etc
Unary measurement factors depend only on the current state/pose of the robot: GPS readings, correlation of laser-range finder to existing map
Q: can you optimize non-gaussian noise models?
- A: I haven't been able to find documentation for this. Perhaps if you can represent things as a projection to Gaussians and factor error models then you can approximate it as a non-Gaussian distribution.
Construct noise model by partially evaluating a likelihood function of the measurement m and the unknown variable q. Internally it includes the measurement model h(q) and then you partially evaluate/compile in the measurement to get a function that calculates the likelihood based on the unknown variable q. By default this seems like it’s doing least squares minimizing error squared.
Q: I don’t fully get the example that’s being worked here. It is populating a H matrix if it’s provided,
- A: Perhaps this is providing a Hessian matrix of partial derivatives to aid in the optimization calculation if the structure of the optimization at the current linearization point is known. This would be the Hessian for the measurement model
h, I think?
Real Answer (that lines up with my guess):
Importantly, because we want to use this factor for nonlinear optimization (see e.g., Dellaert and Kaess 2006 for details), whenever the optional argument H is provided, a Matrix reference, the function should assign the Jacobian of h(q) to it, evaluated at the provided value for q
Q: I don’t understand their note about the exponential map
Important Note Many of our users, when attempting to create a custom factor, are initially surprised at the Jacobian matrix not agreeing with their intuition. For example, above you might simply expect a 2×3 diagonal matrix. This would be true for variables belonging to a vector space. However, in GTSAM we define the Jacobian more generally to be the matrix H such that h(qeξˆ)≈h(q)+Hξ where ξ=(δx,δy,δθ) is an incremental update and expξˆ is the exponential map for the variable we want to update, In this case q∈SE(2) , where SE(2) is the group of 2D rigid transforms, implemented by Pose2.
First order understanding is that it’s something like “all the partial derivatives”, maybe this is what I was already doing with sympy without recognizing the language for it?
Note: also in the boost::make_shared world, I wonder if it is compatible with the new standard shared_ptr
Section 4 PoseSLAM¶
The simplest instantiation of a SLAM problem is PoseSLAM, which avoids building an explicit map of the environment.
Model: odometry and then 2D lidar, which constrains pose to pose motion (lidar odometry) and loop closure (place recognition)
Section 5: Landmark-based SLAM¶
Map observed landmarks as variables
Robot poses connect to an initial condition and each other via odometry. Landmarks are observed from one or more robot poses which adds binary factors.
The end result gives you uncertainty bounds for the robot poses and landmark poses.
The connections from robot pose to landmarks are bearing/distance estimates, which could also be distance-only or bearing-only?
Section 6: Structure From Motion¶
Treat images as unordered, then use a specific reprojection-error factor and a [optionally?] known camera intrinsics K to estimate a camera position and orientation
Note: GTSAM explicitly excludes the data association problem
Note: GTSAM explicitly excludes the initialization problem
Section 7: iSAM Incremental Smoothing and Mapping¶
New interface for incremental update
Reminder to be careful with initial conditions / initial setup
Section 8: More Applications¶
8.2 Visual Odometry
A gentle introduction to vision-based sensing is Visual Odometry (abbreviated VO, see e.g. Nistér et al. (2004)), which provides pose constraints between successive robot poses by tracking or associating visual features in successive images taken by a camera mounted rigidly on the robot. GTSAM includes both C++ and MATLAB example code, as well as VO-specific factors to help you on the way.
8.3 Visual SLAM
Visual SLAM (see e.g., Davison (2003)) is a SLAM variant where 3D points are observed by a camera as the camera moves through space, either mounted on a robot or moved around by hand. GTSAM, and particularly iSAM (see below), can easily be adapted to be used as the back-end optimizer in such a scenario.
Papers to find:
- Introduction to Visual Odometry: Nister et al 2004 → Visual Odometry → Nistér, D., Naroditsky, O., and Bergen, J., "Visual Odometry", in IEEE Conf. on Computer Vision and Pattern Recognition (CVPR) vol. 1, (2004), pp. 652-659.
- Davison 2003 → Visual SLAM → Davison, A.J., "Real-Time Simultaneous Localisation and Mapping with a Single Camera", in Intl. Conf. on Computer Vision (ICCV) (2003), pp. 1403-1410.
8.4 Fixed-lag Smoothing and Filtering
GTSAM can easily perform recursive estimation, where only a subset of the poses are kept in the factor graph, while the remaining poses are marginalized out. In all examples above we explicitly optimize for all variables using all available measurements, which is called Smoothing because the trajectory is “smoothed” out, and this is where GTSAM got its name (GT Smoothing and Mapping). When instead only the last few poses are kept in the graph, one speaks of Fixed-lag Smoothing. Finally, when only the single most recent poses is kept, one speaks of Filtering, and indeed the original formulation of SLAM was filter-based (Smith et al., 1988).
Q: Where can I find an explanation of the marginalization of the poses?
8.5 Discrete Variables and HMMs
Finally, factor graphs are not limited to continuous variables: GTSAM can also be used to model and solve discrete optimization problems. For example, a Hidden Markov Model (HMM) has the same graphical model structure as the Robot Localization problem from Section 2, except that in an HMM the variables are discrete. GTSAM can optimize and perform inference for discrete models.
Q: Where can I find an example of GTSAM solving discrete optimization problems? It’d be nice to use this to play the probabilistic association game in a mixed continuous and discrete system
- A: Example from GTSAM documentation: HybridFactorGraph with worked Python example
Additional Interesting area from documentation: Certifiable optimization
Conclusion¶
Open Questions¶
Q: What's their take on why not filtering?
Q: I don’t understand their note about the exponential map
Q: How do you encode that the place recognition / loop closure might not be accurate? e.g. in a grid world without many unique features, you may only sometimes identify the correct loop closure.
Q: Where can I find an explanation of the marginalization of the poses?