GTSAM is a C++17 library for factor graphs and sensor fusion, with Python and MATLAB wrappers. Follow the existing code near your change and keep changes focused.
Consult ARCHITECTURE.md before adding functionality to
identify existing abstractions and appropriate extension points. Run
python3 scripts/check_code_quality.py for the automated source conventions.
For opt-in local Clang-Tidy checks, generate a compilation database with
cmake -S . -B build -DCMAKE_EXPORT_COMPILE_COMMANDS=ON, then run
clang-tidy -p build path/to/file.cpp on the affected translation units.
See the local setup and changed-line command
for the CI tool version and build options. To avoid discrepancies between local
runs and CI's clang-tidy job:
- Match the CI
clang-tidyversion pinned in.github/workflows/code-quality.yml(installed viapip install clang-tidy==23.1.4in a venv) rather than an older system or Homebrew LLVM, since newer releases catch additional patterns (for example,bugprone-float-loop-counteron multiplicative float loops). - Re-run
clang-tidy-diff.pyagainst the fullorigin/developmerge-base diff after the final refactor orclang-formatpass; any line touched by reformatting or cleanup enters CI's diff filter. - Account for Linux
libstdc++vs. macOSlibc++differences: CI runs on Ubuntu with GCClibstdc++, wherebugprone-throwing-static-initializationflags namespace-scope dynamic containers (such asconst KeyVectororstd::vectorwith initializer lists) even when macOSlibc++stays silent. Prefer small factory functions orconstexprdata over namespace-scope containers, use integer loop counters rather than floating-point induction variables, and prefer plain functions over namespace-scope lambdas captured by reference.
When fixing additional build problems discovered during a task, establish the concrete failure and explain why each fix is necessary. Keep independently useful API or infrastructure redesigns in separate PRs.
- All functions in header files should have Doxygen-style API documentation
using
/** */, except small functions such as getters, which can use a single-line///comment. There is no need for@brief,@param, or similar tags when the prose is already clear. - Use
///for single-line documentation comments rather than/** */. - Use meaningful variable names, for example
measurementrather thanmsm; avoid abbreviations. - On Windows, externally accessible library APIs must be explicitly exported.
When adding or modifying public classes or functions, review and follow
Using-GTSAM-EXPORT.md, including its template specialization and header-only rules.
- Use GTSAM's versioned deprecation mechanism rather than adding a standalone
[[deprecated]]attribute. For APIs deprecated since GTSAM 4.3, wrap their declarations, definitions, and any tests in#ifdef GTSAM_ALLOW_DEPRECATED_SINCE_V43. - Add a Doxygen
@deprecatedcomment that names the supported replacement or migration path. - Verify the normal configuration with deprecated APIs disabled. When changing
compatibility code itself, also verify a build with the corresponding
GTSAM_ALLOW_DEPRECATED_SINCE_*option enabled.
- When relocating functionality between directories, move every associated
.hand.cppfile withgit mv. This applies both to promotions fromgtsam_unstable/togtsam/and to moves between directories withingtsam/; do not copy the implementation to its destination while modifying the original headers in place. - When an old include path must remain available for backward compatibility,
first move the original header to its canonical destination with
git mv, then add a new forwarding header at the old path. Keep forwarding headers minimal: document the replacement, apply the appropriate versioned deprecation guard, and include the canonical header. - Update build manifests, internal includes, tests, wrappers, and documentation to use the canonical destination. The old path should remain only as the compatibility surface.
- When moving classes, also move their corresponding notebooks from the old
doc/directory to the destination'sdoc/directory withgit mv. Update the relevant documentation indices so they list and link to the notebooks at their canonical locations. Review path-dependent links inside each moved notebook as well: in particular, update its "Open in Colab" button and links to source files when their targets changed. - Review export directives whenever a move changes the library that owns the
functionality. Use the destination library's export macro consistently on
public declarations and any exported definitions; for example, replace
GTSAM_UNSTABLE_EXPORTwithGTSAM_EXPORTwhen promoting functionality fromgtsam_unstable/intogtsam/. FollowUsing-GTSAM-EXPORT.mdfor the applicable platform and template rules.
- Classes and types are
UpperCamelCase; methods and functions arelowerCamelCase. - Public fields in structs use plain names without a trailing underscore.
- Apart from those naming conventions, follow Google C++ style.
- Prefer concise, elegant examples. Use the fewest helpers needed and favor direct construction and small local functors or lambdas over adapter functions.
- When reviewing changes, flag overly complex or long functions and recommend breaking them into smaller functions.
Use fixed-size types such as Matrix3, Matrix23, and Vector6 when
dimensions are known at compile time, especially for OptionalJacobian
outputs. Fixed-size types store their coefficients inline and avoid unnecessary
dynamic allocation and fixed/dynamic conversions.
Use Matrix and Vector when dimensions are determined at runtime or when an
existing API explicitly requires a dynamic type.
When assigning to a fixed-size Jacobian, prefer writing directly to it or using a fixed-size temporary:
if (H) {
*H = Matrix3{{1.0, 0.0, 0.0},
{0.0, 1.0, 0.0},
{0.0, 0.0, 1.0}};
}Use flat initializer lists for vectors and nested initializer lists for matrices:
Vector3 vector{1.0, 2.0, 3.0};
Matrix23 matrix{{1.0, 2.0, 3.0},
{4.0, 5.0, 6.0}};- When a C++ function is exposed in a wrapper
.ifile, parameter names must match exactly between the header declaration and the.ideclaration. Update both whenever a wrapped parameter name changes. - For templated classes and factors in wrappers, prefer the normal
.itemplate mechanism over one handwritten wrapper class per instantiation. Let the wrapper generate names such asAttitudeFactorRot3fromtemplate<...> class AttitudeFactor. - Do not add or retain C++
usingortypedefaliases solely to manufacture wrapper names. Keep aliases only when they are useful in the C++ API. - The top-level
wrap/directory is a git subtree ofborglab/wrap, not a submodule. Make wrapper-generator contributions inborglab/wrap, then sync them into GTSAM with./update_wrap.sh [branch-or-tag], which defaults tomaster. Run the sync on a feature branch because it creates GTSAM commits, typically a squash followed by a merge commit. Do not editwrap/directly for changes that belong upstream. - Do not edit files under
gtsam/3rdparty/. These are vendored third-party libraries, including Eigen; direct changes make upstream updates difficult.
- Keep declarations for the same C++ API in shared
.ifiles. When an optional dependency controls availability, have both wrappers include the same interface conditionally. Use language-specific files only for genuinely language-specific APIs, such as MATLAB callbacks. - Before adding container bindings, inspect existing precedents such as
KeyVector, Point2Vector, and FixedLagSmootherKeyTimestampMap. Check the
Python ignore list and compatibility aliases as well as the
.ifiles. Shared declarations may produce MATLAB proxy classes while Python uses native lists and dictionaries. - Before proposing a wrapper-generator change, demonstrate why existing interface declarations and configuration cannot express the required binding. Distinguish missing functionality from a preferred conversion or naming convention. Keep broader generator improvements separate.
- Validate wrapper changes through actual calls in both languages. Successful generation or compilation alone does not establish that arguments, returned containers, or object lifetimes work. Exercise parameter maps, container access, repeated retrieval, and 64-bit keys where relevant. Check optional-dependency configurations too.
- When an investigation reveals a simpler supported approach, remove the superseded scaffolding and rewrite the PR description around the final implementation.
Place new wrapper declarations in the shared .i file for their logical
API group. Add methods, constructors, and overloads to the existing wrapped
class declaration in its current file. For new classes and free functions,
use the following split; inspect declarations rather than #include lines,
since sibling files also include headers for dependencies.
gtsam/slam/slam.i: between factors, planar and ordinary projection factors, and general SFM factors (BetweenFactor,PlanarProjectionFactor,GenericProjectionFactor,GeneralSFMFactor, andGeneralSFMFactor2).gtsam/slam/slam_smart_projection.i: smart projection factors, their parameters and base classes, and the linear-factor specializations they return (SmartFactorBase,SmartProjectionParams,SmartProjectionFactor,SmartProjectionPoseFactor,SmartProjectionRigFactor,RegularHessianFactor, andJacobianFactorQ).gtsam/slam/slam_synchronization.i: Lie-group synchronization, averaging, and initialization (FastSync,KarcherMeanFactor, Frobenius factors,WahbaFactor,RelativeTranslationFactor,InitializePose3, andlago); dataset I/O; and the smaller SLAM factors already grouped here (stereo, reference-frame, rotation, oriented-plane, pose translation/rotation priors, known-landmark, and triangulation factors). Extend each family here.gtsam/nonlinear/nonlinear.i: core nonlinear factor and graph APIs, marginals, linear-container factors, batch optimizers and their parameters, and incremental optimization (ISAM2andNonlinearISAM).gtsam/nonlinear/nonlinear_continuous_time.i: continuous-time Gaussian-process APIs (StateData,WnoaMotionFactor,WnoaInterpFactor, andWnoaFactorGraph, together with itsExpressionFactorGraphbase); prior factors (PriorFactor,ExtendedPriorFactor, andConcentratedGaussian),VectorNormFactor, fixed-lag smoothers and their supporting types, andExtendedKalmanFilter.gtsam/nonlinear/values.i:Valuesand its typed accessors.gtsam/nonlinear/custom.i:CustomFactor.gtsam/navigation/navigation.i: navigation state and IMU bias, preintegration and IMU/AHRS factors, navigation measurement factors (GPS, pseudorange, carrier phase, Doppler, attitude, barometric, constant velocity, and magnetic), and scenarios and scenario runners.gtsam/navigation/navigation_geometric.i: manifold, Lie-group, invariant, and equivariant filters (ManifoldEKF,LieGroupEKF,LeftLinearEKF,InvariantEKF, andAbcEquivariantFilter), specialized IMU EKFs (NavStateImuEKFandGal3ImuEKF), and legged estimators and their contact measurements and parameters, including the legged fixed-lag smoothers.
For APIs outside these groups, follow the existing shared .i file for that
subsystem. Keep related classes and functions together and use descriptive
topic names when a new logical group needs its own interface file. Keep each
file's required includes with its declarations, and preserve registration
order in python/CMakeLists.txt and matlab/CMakeLists.txt: a wrapped base
class belongs in the same file as its derived classes or in an earlier file.
- Run validation relevant to the files changed.
- Run C++ tests from
build/withmake -j6 testXXX.run, replacingtestXXXwith the relevant test target. - For Python commands in the standard local development environment, use the
py312conda environment. Run wrapper tests withcmake --build build --target python-testorcmake --build build --target python-test-unstable, as appropriate. - Documentation-only changes do not require unrelated C++ tests, but should
still pass applicable documentation checks and
git diff --check.
- Use the correctly spelled
IndeterminateSystemException. The formerIndeterminantLinearSystemExceptionname is available only through the GTSAM 4.3 deprecation machinery. - Treat
nearbyVariable()as the key where elimination detected the problem, not necessarily its source; the reported key depends on graph structure and elimination ordering. - Remember that the exception also protects against nearly indeterminate systems. A mathematically full-rank graph can trigger it when elimination produces a Cholesky pivot that is very small relative to its original diagonal entry. This test is invariant to diagonal changes of variable units but still depends on elimination ordering. For example, a very strong finite prior combined with much looser measurement noise can expose a weakly observed direction, although the raw weight ratio alone may only reflect different variable units and is not sufficient evidence.
- Preserve the failing nonlinear graph, values, and ordering. Linearize at those values, request the Jacobian with an explicit ordering, and inspect its singular spectrum and null space. Prefer Jacobian rank analysis over a determinant or Hessian rank analysis because forming the Hessian squares the condition number.
- Check for missing gauge constraints, unused or accidental keys, disconnected components, degenerate geometry or motion, lost observability after marginalization, inconsistent units or noise scales, and negative curvature introduced by custom Hessian factors.
- Use a temporary, physically meaningful prior to test an observability
hypothesis, then recompute rank. If the intended prior fixes a gauge exactly,
prefer a hard constraint such as
noiseModel::Constrained::All(dimension); it expresses that intent without choosing an arbitrary extreme finite weight. Do not present damping or a dense solve as a fix unless the model itself becomes observable and well conditioned. - See
gtsam/linear/doc/IndeterminateSystemException.ipynbfor a runnable Python example and a full diagnostic checklist.
-
Avoid one large anonymous namespace collecting every helper at the top of a test file. Prefer small, named fixture-style namespaces containing both the helpers and tests that use them.
-
Put at least one short
//comment immediately above everyTEST()explaining the behavior being verified. -
When using
/* ************************************************************************* */dividers, put one immediately before each fixture namespace and one immediately after it closes. Do not put dividers between tests in the same fixture namespace:/* ************************************************************************* */ namespace my_fixture { // Verifies the expected behavior. TEST(Suite, Case) {} } // namespace my_fixture /* ************************************************************************* */
-
Always prefer Plotly for charts and data visualizations, including reports, documentation pages, notebooks, and examples, so readers can inspect values and interact with the figures.
-
Always load Plotly JavaScript from its version-pinned CDN in HTML reports, documentation pages, and standalone downloads. Do not embed or vendor the Plotly runtime. State that interactive charts require an internet connection.
-
Write for a robotics audience, without assuming expertise in GTSAM internals or optimization solvers. Explain library-specific concepts, solver choices, and numerical metrics when they are needed to interpret an example or result.
-
Lead each paragraph with a concrete topic sentence stating its main point. Develop that point with the relevant explanation or evidence.
-
Use factual, descriptive headings. Avoid slogans, promotional language, and conversational headings such as "Meet the datasets."
-
State what a comparison measures and how to interpret it before presenting implementation details. Keep detailed numerical settings and provenance available without making them prerequisites for understanding the results.
Notebooks in */doc/*.ipynb and */examples/*.ipynb should use this preamble:
- Title and introductory Markdown cell.
- Copyright Markdown cell tagged
remove-cell. - Colab badge Markdown cell.
- Colab installation code cell tagged
remove-cell. - Imports and setup code cell.
Use the existing remove-cell metadata convention so documentation builds and
Colab behavior stay consistent.
Always prefer Plotly for graphs and other notebook visualizations so figures are interactive.