Graph-based SLAM: pose optimization, loop closure and robust estimation
Optimize the entire trajectory with factor graphs, nonlinear least squares, sparse Gauss–Newton, loop closures, robust kernels and incremental smoothing such as iSAM2.
After this lesson you can
- Build a pose graph from odometry and loop closures with information matrices.
- Derive and numerically check relative-pose factor Jacobians in SE(2) and SE(3).
- Solve the graph with Gauss–Newton and Levenberg–Marquardt on manifolds using sparse linear algebra.
- Explain how elimination ordering determines Cholesky fill-in.
- Make SLAM robust to false loop closures with Huber or Cauchy kernels.
Before you start
Correcting the past too
A filter retains a summary of its history and normally corrects only the current state. Pose-graph SLAM retains variables for past poses and relative factors between them; observing a previously visited place can redistribute drift across the whole trajectory. A smoother can also operate on landmarks, velocities, or biases. Neither filtering nor optimization alone corrects a wrong association or guarantees calibrated uncertainty.
In a factor graph, the product connects each factor to the variables it needs. If measurement has independent Gaussian noise with covariance , maximizing the posterior is equivalent, up to state-independent constants, to minimizing
An information matrix must be symmetric positive definite in the measured space. For a residual on a manifold, use a local convention and covariance expressed in that same frame. If factors are correlated, multiplying independent Gaussians is an incorrect model. A robust loss modifies the objective and is no longer exactly the Gaussian MAP above.
Relative residual and Jacobians
Let be poses and a relative measurement. One convention uses and , with tangent vector ordered translation then rotation. With right perturbations, and , we obtain
and are the left and right exponential Jacobians, . This expression holds in SE(2) and SE(3) with the appropriate adjoint and dimension, away from singularities of the logarithmic chart. The next cell constructs the group exponential and computes using a block matrix exponential; it checks both Jacobians with central differences. Left and right perturbations are not mixed.
To see where the adjoint comes from, substitute the perturbed poses: . Insert after the first exponential and use . The differential of Log transforms the left increment via and the right via . In SE(3), the adjoint is a matrix mixing translation and rotation; copying two rotations onto the diagonal is insufficient. Near the angular branch cut at , a finite difference can jump branches and cease to measure the local derivative.
import numpy as np
from scipy.linalg import expm
from scipy.spatial.transform import Rotation
def hat(v):
x,y,z=v;return np.array([[0.,-z,y],[z,0.,-x],[-y,x,0.]])
def exp_lie(x):
n=len(x)//2 if len(x)==6 else 2
T=np.eye(n+1)
if n==2:
v=x[:2];w=x[2];J=np.array([[0.,-1.],[1.,0.]])
R=np.eye(2)*np.cos(w)+J*np.sin(w)
V=np.eye(2)*(np.sin(w)/w if abs(w)>1e-4 else 1-w*w/6)+J*((1-np.cos(w))/w if abs(w)>1e-4 else w/2-w**3/24)
else:
v=x[:3];w=x[3:];a=np.linalg.norm(w);W=hat(w);R=Rotation.from_rotvec(w).as_matrix()
V=np.eye(3)+(.5 if a<1e-8 else (1-np.cos(a))/a**2)*W+(1/6 if a<1e-8 else (a-np.sin(a))/a**3)*(W@W)
T[:n,:n]=R;T[:n,n]=V@v;return T
def log_lie(T):
n=T.shape[0]-1;R=T[:n,:n];t=T[:n,n]
if n==2:
w=np.arctan2(R[1,0],R[0,0]);J=np.array([[0.,-1.],[1.,0.]])
V=np.eye(2)*(np.sin(w)/w if abs(w)>1e-4 else 1-w*w/6)+J*((1-np.cos(w))/w if abs(w)>1e-4 else w/2-w**3/24)
return np.r_[np.linalg.solve(V,t),w]
w=Rotation.from_matrix(R).as_rotvec();a=np.linalg.norm(w);W=hat(w)
V=np.eye(3)+(.5 if a<1e-8 else (1-np.cos(a))/a**2)*W+(1/6 if a<1e-8 else (a-np.sin(a))/a**3)*(W@W)
return np.r_[np.linalg.solve(V,t),w]
def adjoint(T):
n=T.shape[0]-1;R=T[:n,:n];t=T[:n,n]
if n==2:
A=np.eye(3);A[:2,:2]=R;A[:2,2]=-np.array([[0.,-1.],[1.,0.]])@t;return A
A=np.zeros((6,6));A[:3,:3]=R;A[:3,3:]=hat(t)@R;A[3:,3:]=R;return A
def ad(x):
if len(x)==3:
J=np.array([[0.,-1.],[1.,0.]]);A=np.zeros((3,3));A[:2,:2]=x[2]*J;A[:2,2]=-J@x[:2];return A
A=np.zeros((6,6));A[:3,:3]=hat(x[3:]);A[:3,3:]=hat(x[:3]);A[3:,3:]=hat(x[3:]);return A
def left_jacobian(x):
# The upper-right block of this exponential is integral exp(t ad_x) dt.
n=len(x);block=np.zeros((2*n,2*n));block[:n,:n]=ad(x);block[:n,n:]=np.eye(n)
return expm(block)[:n,n:]
def residual(X,Y,Z): return log_lie(np.linalg.inv(Z)@np.linalg.inv(X)@Y)
def jacobians(X,Y,Z):
r=residual(X,Y,Z)
return -np.linalg.solve(left_jacobian(r),adjoint(np.linalg.inv(Z))),np.linalg.inv(left_jacobian(-r))
def check(dim):
rng=np.random.default_rng(13+dim); X=exp_lie(rng.normal(0,.3,dim));Y=exp_lie(rng.normal(0,.3,dim));Z=exp_lie(rng.normal(0,.3,dim))
A,B=jacobians(X,Y,Z);h=1e-6;errors=[]
for which,analytic in enumerate([A,B]):
numeric=np.empty((dim,dim))
for k in range(dim):
d=np.eye(dim)[k]*h
if which==0:plus=residual(X@exp_lie(d),Y,Z);minus=residual(X@exp_lie(-d),Y,Z)
else:plus=residual(X,Y@exp_lie(d),Z);minus=residual(X,Y@exp_lie(-d),Z)
numeric[:,k]=(plus-minus)/(2*h)
errors.append(np.max(np.abs(numeric-analytic)))
return errors
print('errores máximos SE2:',check(3))
print('errores máximos SE3:',check(6))The optimizer below uses another chart common in g2o files: the vector formed by ‘s translation and wrapped angle, not the full . It updates coordinates locally and additively, wraps the angle, and derives analytic Jacobians for that chart. File information matrices are interpreted in that convention. This distinction matters: replacing only the residual or only its Jacobian changes the problem.
Solving a sparse system
At each iteration, linearize and solve . Gauss–Newton uses that equation; Levenberg–Marquardt adds damping, evaluates actual cost, and adjusts the parameter depending on whether the step is accepted or rejected. The code uses scalar damping and accepts only objective reductions in LM mode. It does not guarantee the global minimum: incorrect closures, poor initializations, and robust functions can create local minima.
For a factor between poses and , its two Jacobians contribute blocks , , and to , and , to the right-hand side. Assembling only those blocks avoids allocating a dense matrix of all possible pairs. A rejected LM step retains the previous trajectory and increases damping; an accepted one reduces it. One linear solve without evaluating the objective does not ensure the nonlinear step improves.
Without a prior, translating and rotating all poses preserves relative measurements: there are three gauge degrees of freedom in SE(2), six in SE(3). The normal matrix is singular. Fixing the first pose removes that gauge in a connected graph; a disconnected graph needs a reference per component. Numerical damping does not add physical information and must not hide a disconnected component.
Each factor connects few poses, so the normal matrix contains blocks only at neighboring nodes. The elimination order can create new edges between neighbors of an eliminated variable: that fill determines Cholesky memory and work. Reordering changes neither objective nor exact solution, but does change the factorization and rounding errors. A chain graph of 1000 poses with 20 closures between distinct pairs absent from the chain has 1000 diagonal blocks and off-diagonal blocks: 3038 structural blocks, not 3038 scalars.
Eliminating a landmark observed from several poses first connects those poses in the reduced system; eliminating a pose observing many landmarks can connect those landmarks. There is therefore no universally optimal order: visibility pattern and closures matter. COLAMD is a structure-based heuristic, not a promise of minimum time. The nonzero count in the small figure is the actual calculated factorization result; the large example measures real LU and its time in a separate run.
Loop closures and robust losses
Loop-closure detection searches for previously seen places using visual descriptors, geometry, or other signals; an appearance score is a proposal. Verify geometrically with correspondences and RANSAC or registration such as ICP, check overlap and degeneracy, and retain estimation uncertainty. A repetitive corridor can produce a false visual match and a plausible local geometric solution; verification reduces risk but does not eliminate it.
Robust kernels reduce the influence of large residuals. For , Huber uses if and outside; Cauchy uses . In iteratively reweighted least squares the factor uses : Huber outside the threshold, Cauchy . Scale applies to whitened residuals. A correct but initially distant closure can also be underweighted; robust loss does not replace association or guarantee the true solution.
Scale has a concrete interpretation: increasing a factor’s declared uncertainty makes the same physical difference less surprising in whitened units. A threshold set in meters and also applied to angles mixes units. Nor should one claim Cauchy is always better because it works in the figure: its loss may have local valleys and depends on initialization, the proportion of false closures, and other constraints. Inspect which factors receive small weights and verify that the proposed trajectory remains geometrically coherent.
Incremental smoothing reuses factorization as measurements are added; iSAM2 organizes dependencies in a Bayes tree and relinearizes affected parts according to its criteria. An update can propagate changes to old variables: it does not imply constant cost or that every variable is relinearized at every step. Extensive closures can cause more work. Implementation times depend on ordering, tolerances, hardware, and factor grouping; measure batch and incremental methods on the same input and separate initialization from updating.
The Bayes tree groups eliminated variables into cliques and represents dependencies among them. When a factor connects separate regions, part of the tree must be rebuilt and cliques and order can change. An incremental run with a high relinearization threshold often saves work but may retain an approximation farther from the batch solution. Comparing times alone without final cost or checking gauge can reward a solution that solved a different problem less accurately.
Lab: optimizer from scratch
The implementation below builds as a sparse matrix, fixes initial pose, and checks its chart’s analytic Jacobians with finite differences. Losses apply to the factor’s full Mahalanobis norm; printed cost sums without the in the initial definition. The square experiment uses one seed and synthetic truth: with a correct closure, cost falls from 443.49 to 4.89 and odometry RMS from 0.471 to 0.152 m. An EKF correcting only the last pose retains RMS 0.461 m in the stored trajectory, although final error is 0.005 m. Do not extrapolate that comparison to every filter or trajectory.
import numpy as np
from scipy.sparse import coo_matrix,eye
from scipy.sparse.linalg import spsolve
def wrap(a): return (a+np.pi)%(2*np.pi)-np.pi
def rot(a): return np.array([[np.cos(a),-np.sin(a)],[np.sin(a),np.cos(a)]])
J=np.array([[0.,-1.],[1.,0.]])
def factor(xi,xj,z):
Ri=rot(xi[2]);Rz=rot(z[2]);q=Ri.T@(xj[:2]-xi[:2]);Rt=Rz.T@Ri.T
residual=np.r_[Rz.T@(q-z[:2]),wrap(xj[2]-xi[2]-z[2])]
A=np.zeros((3,3));B=np.zeros((3,3));A[:2,:2]=-Rt;B[:2,:2]=Rt
A[:2,2]=Rz.T@(-J@q);A[2,2]=-1;B[2,2]=1
return residual,A,B
def parse_g2o(text):
vertices={};raw=[]
for line in text.splitlines():
p=line.split()
if not p or p[0].startswith('#'):continue
if p[0]=='VERTEX_SE2':vertices[int(p[1])]=np.array(list(map(float,p[2:5])))
elif p[0]=='EDGE_SE2':
i,j=map(int,p[1:3]);z=np.array(list(map(float,p[3:6])));v=list(map(float,p[6:12]))
O=np.array([[v[0],v[1],v[2]],[v[1],v[3],v[4]],[v[2],v[4],v[5]]]);raw.append((i,j,z,O))
ids=sorted(vertices);index={v:i for i,v in enumerate(ids)}
if not ids:raise ValueError('No hay vértices SE2')
x=np.stack([vertices[v] for v in ids]);edges=[(index[i],index[j],z,O) for i,j,z,O in raw]
return x,edges
def rho(s,loss='quadratic',scale=1.):
if loss=='quadratic':return s,1.
if loss=='huber':
if s<=scale**2:return s,1.
return 2*scale*np.sqrt(s)-scale**2,scale/np.sqrt(s)
if loss=='cauchy':return scale**2*np.log1p(s/scale**2),1/(1+s/scale**2)
raise ValueError('pérdida desconocida')
def objective(x,edges,loss='quadratic',scale=1.):
return sum(rho(float((r:=factor(x[i],x[j],z)[0])@O@r),loss,scale)[0] for i,j,z,O in edges)
def normal_equations(x,edges,loss='quadratic',scale=1.):
n=len(x);N=3*(n-1);rows=[];cols=[];values=[];b=np.zeros(N)
for i,j,z,O in edges:
r,A,B=factor(x[i],x[j],z);_,w=rho(float(r@O@r),loss,scale);Om=O*w
for k,D in ((i,A),(j,B)):
if k==0:continue
ks=slice(3*(k-1),3*k);b[ks]-=D.T@Om@r
for l,E in ((i,A),(j,B)):
if l==0:continue
block=D.T@Om@E
for p in range(3):
for q in range(3):rows.append(3*(k-1)+p);cols.append(3*(l-1)+q);values.append(block[p,q])
return coo_matrix((values,(rows,cols)),shape=(N,N)).tocsr(),b
def optimize(x,edges,iterations=10,loss='quadratic',scale=1.,method='lm'):
x=x.copy();lam=1e-3; costs=[objective(x,edges,loss,scale)];history=[x.copy()]
for _ in range(iterations):
H,b=normal_equations(x,edges,loss,scale)
if method=='lm':H=H+lam*eye(H.shape[0],format='csr')
step=spsolve(H,b);proposal=x.copy();proposal[1:]+=step.reshape(-1,3);proposal[:,2]=wrap(proposal[:,2])
c=objective(proposal,edges,loss,scale)
if method=='gn' or c<costs[-1]:x=proposal;costs.append(c);history.append(x.copy());lam=max(lam/3,1e-9)
else:costs.append(costs[-1]);history.append(x.copy());lam=min(lam*10,1e9)
return x,np.array(costs),history
def jacobian_check():
xi=np.array([1.1,-.4,.3]);xj=np.array([2.2,.5,-.2]);z=np.array([.7,.2,.4]);r,A,B=factor(xi,xj,z);h=1e-6
for var,analytic in ((0,A),(1,B)):
numeric=np.empty((3,3))
for k in range(3):
d=np.eye(3)[k]*h
plus=factor(xi+d if var==0 else xi,xj+d if var==1 else xj,z)[0]
minus=factor(xi-d if var==0 else xi,xj-d if var==1 else xj,z)[0]
numeric[:,k]=(plus-minus)/(2*h)
assert np.max(np.abs(numeric-analytic))<1e-8
return True
print('Jacobianos de carta correctos:',jacobian_check())import numpy as np
def between(a,b):return np.r_[rot(a[2]).T@(b[:2]-a[:2]),wrap(b[2]-a[2])]
def synthetic(seed=19):
rng=np.random.default_rng(seed);side=3.;n=10;truth=[]
for sideid in range(4):
for j in range(n):
q=side*j/n
pos=([q,0],[side,q],[side-q,side],[0,side-q])[sideid]
truth.append([*pos,sideid*np.pi/2])
truth.append([0.,0.,0.]);truth=np.array(truth)
O=np.diag(1/np.array([.05,.05,.025])**2);edges=[];initial=[truth[0].copy()]
for i in range(len(truth)-1):
z=between(truth[i],truth[i+1])+rng.normal(0,[.05,.05,.025]);z[2]=wrap(z[2]);edges.append((i,i+1,z,O))
p=initial[-1];initial.append(np.r_[p[:2]+rot(p[2])@z[:2],wrap(p[2]+z[2])])
initial=np.array(initial);loop=(0,len(truth)-1,between(truth[0],truth[-1]),np.diag(1/np.array([.03,.03,.03])**2))
bad=(0,20,np.array([0.,0.,0.]),np.diag(1/np.array([.05,.05,.05])**2))
return truth,initial,edges,loop,bad
def filter_once(initial,edges,loop):
# Odometry EKF only keeps current covariance; the last loop corrects the last pose.
x=initial[0].copy();P=np.eye(3)*1e-9;path=[x.copy()]
for _,_,z,O in edges:
theta=x[2];v=z[:2];R=rot(theta);F=np.eye(3);F[:2,2]=R@J@v
G=np.zeros((3,3));G[:2,:2]=R;G[2,2]=1
x[:2]+=R@v;x[2]=wrap(x[2]+z[2]);P=F@P@F.T+G@np.linalg.inv(O)@G.T;path.append(x.copy())
_,_,z,O=loop;r,_,H=factor(initial[0],x,z);V=np.linalg.inv(O);S=H@P@H.T+V
K=np.linalg.solve(S,H@P).T;x=x-K@r;x[2]=wrap(x[2]);A=np.eye(3)-K@H;P=A@P@A.T+K@V@K.T
path[-1]=x;return np.array(path),P
truth,initial,edges,loop,bad=synthetic()
solution,costs,history=optimize(initial,edges+[loop],iterations=12)
filtered,P=filter_once(initial,edges,loop)
rms=lambda x:float(np.sqrt(np.mean(np.sum((x[:,:2]-truth[:,:2])**2,axis=1))))
print('cierre correcto coste:',round(costs[0],2),round(costs[-1],2),'RMS odometría/grafo/filtro:',round(rms(initial),3),round(rms(solution),3),round(rms(filtered),3))
for mode in ('quadratic','huber','cauchy'):
sol,cost,_=optimize(initial,edges+[loop,bad],iterations=30,loss=mode,scale=2.)
r=factor(sol[bad[0]],sol[bad[1]],bad[2])[0]
print(mode,'RMS:',round(rms(sol),3),'peso falso:',round(rho(float(r@bad[3]@r),mode,2.)[1],5))With the false closure and same seed, RMS was 2.218 m with quadratic loss, 0.471 m with Huber and 0.151 m with Cauchy; false-factor weights were 1, 0.02168 and 0.00035. These are results for this scene, scale, and initialization. The robust objective changes across losses, so its values are not directly comparable as evidence of accuracy.
The following g2o files are the pinned distribution from the DPGO research repository. This Intel variant has 1728 poses and 2512 factors; M3500 has 3500 and 5453. Other conversions with different counts exist. Intel comes from a real environment; M3500 is a simulated graph. These files contain no trajectory ground truth: cost is reported, not absolute error. The download is checked with SHA-256 and read in the browser.
To solve both full graphs without repeated Python loops per factor, this cell vectorizes residuals, Jacobians, and normal-system blocks for quadratic loss. It retains the previous code’s chart, gauge fixing, and LM acceptance. Matrices and right-hand sides were checked against the scalar implementation on both graphs and perturbed states; maximum differences were in and on the right-hand side. Final trajectories after eight steps agreed to or better in that test.
def prepare_fast(edges):
i=np.array([e[0] for e in edges],dtype=int);j=np.array([e[1] for e in edges],dtype=int)
z=np.stack([e[2] for e in edges]);O=np.stack([e[3] for e in edges]);return i,j,z,O
def fast_factors(x,graph):
i,j,z,O=graph;angle=x[i,2];c=np.cos(angle);s=np.sin(angle);cz=np.cos(z[:,2]);sz=np.sin(z[:,2])
dp=x[j,:2]-x[i,:2];qx=c*dp[:,0]+s*dp[:,1];qy=-s*dp[:,0]+c*dp[:,1]
dx=qx-z[:,0];dy=qy-z[:,1];r=np.stack([cz*dx+sz*dy,-sz*dx+cz*dy,wrap(x[j,2]-x[i,2]-z[:,2])],axis=1)
C=np.empty((len(i),2,2));C[:,0,0]=cz*c-sz*s;C[:,0,1]=cz*s+sz*c;C[:,1,0]=-sz*c-cz*s;C[:,1,1]=-sz*s+cz*c
A=np.zeros((len(i),3,3));B=np.zeros_like(A);A[:,:2,:2]=-C;B[:,:2,:2]=C
A[:,0,2]=cz*qy-sz*qx;A[:,1,2]=-sz*qy-cz*qx;A[:,2,2]=-1;B[:,2,2]=1
return r,A,B
def fast_cost(x,graph):
r,_,_=fast_factors(x,graph);return float(np.einsum('ei,eij,ej->',r,graph[3],r))
def fast_normal(x,graph):
i,j,z,O=graph;r,A,B=fast_factors(x,graph);N=3*(len(x)-1);rhs=np.zeros(N);rows=[];cols=[];values=[];d=np.arange(3)
for index,D in ((i,A),(j,B)):
valid=index>0;ix=3*(index[valid]-1)[:,None]+d
rhs+=np.bincount(ix.ravel(),weights=-np.einsum('eji,ejk,ek->ei',D[valid],O[valid],r[valid]).ravel(),minlength=N)
for other,E in ((i,A),(j,B)):
mask=valid&(other>0);ii=3*(index[mask]-1)[:,None]+d;jj=3*(other[mask]-1)[:,None]+d
block=np.einsum('eji,ejk,ekl->eil',D[mask],O[mask],E[mask])
rows.append(np.broadcast_to(ii[:,:,None],block.shape).ravel());cols.append(np.broadcast_to(jj[:,None,:],block.shape).ravel());values.append(block.ravel())
return coo_matrix((np.concatenate(values),(np.concatenate(rows),np.concatenate(cols))),shape=(N,N)).tocsr(),rhs
def optimize_fast(x,edges,iterations=8):
graph=prepare_fast(edges);x=x.copy();lam=1e-3;cost=[fast_cost(x,graph)]
for _ in range(iterations):
H,b=fast_normal(x,graph);step=spsolve(H+lam*eye(H.shape[0],format='csr'),b)
proposal=x.copy();proposal[1:]+=step.reshape(-1,3);proposal[:,2]=wrap(proposal[:,2]);c=fast_cost(proposal,graph)
if c<cost[-1]:x=proposal;cost.append(c);lam=max(lam/3,1e-9)
else:cost.append(cost[-1]);lam=min(lam*10,1e9)
return x,np.array(cost)
from pyodide.http import pyfetch
import hashlib
base='https://raw.githubusercontent.com/MurpheyLab/DPGO/da0157f09ab23ad92a3361ac95336e416d8588df/dataset/'
files=[('intel.g2o','3e0724c048e0ba524be9dd268a8b78e19a2497043143584cbb61310638b15c4b'),
('M3500.g2o','1883593980e602b11bd0ba95799c969e59ee8a6892bdb2a3a48f495459efe9d8')]
for name,digest in files:
response=await pyfetch(base+name)
if response.status!=200: raise RuntimeError(f'Descarga {name}: HTTP {response.status}')
raw=await response.bytes()
assert hashlib.sha256(raw).hexdigest()==digest, 'El hash no coincide'
x,edges=parse_g2o(raw.decode('utf8'))
sol,cost=optimize_fast(x,edges,iterations=8)
print(name,'poses:',len(x),'factores:',len(edges),'coste inicial/final:',round(cost[0],2),round(cost[-1],2))In one native eight-iteration run, Intel reduced cost from 551.74 to 45.00 and M3500 from 2 566 667.66 to 137.91, under this chart and cost function. The figures are not directly comparable with chordal objectives or other dataset conversions.
This optional cell uses the M3500 normal matrix loaded above and compares three SuperLU orderings, not Cholesky. The system has 10 497 free variables and the native run recorded 129 591 stored entries in H, including possible explicit zeros. NATURAL produced 9 519 846 stored entries in L and U in 1.915 s; COLAMD, 633 856 in 0.030 s; MMD_AT_PLUS_A, 371 368 in 0.053 s. These are measurements from one machine and run, not algorithmic constants. The order with least fill was not fastest in that test. It can use substantial memory and take time in the browser.
from scipy.sparse.linalg import splu
import time
H,b=normal_equations(x,edges)
print('H:',H.shape,'entradas:',H.nnz)
for order in ('NATURAL','COLAMD','MMD_AT_PLUS_A'):
start=time.perf_counter()
lu=splu(H.tocsc(),permc_spec=order,diag_pivot_thresh=0)
print(order,'no ceros L+U:',lu.L.nnz+lu.U.nnz,'segundos:',round(time.perf_counter()-start,3))Local lab: GTSAM in 3D
GTSAM 4.3 needs an installation compatible with your system. On this machine it was checked in Python 3.12 within Ubuntu WSL. For example, in a compatible Linux virtual environment install it with python -m pip install gtsam==4.3.0 numpy; select that interpreter as the local runtime. The first cell checks a minimal Pose3 graph. The second downloads sphere2500.g2o and checks its hash, reproduces the 2D loop, compares batch Gauss–Newton with iSAM2 on the 3D graph, and adds a landmark with four synthetic observations generated from dataset initialization. These are not original sensor measurements. Optional environment parameter SLAM_N_POSES permits a short test; by default it uses all 2500 poses. Mean incremental time includes updates, three refinements, and estimate extraction, but not loading or cost evaluation; batch time measures optimization only. Difference between solutions is not error against ground truth. GTSAM costs include the factor 1/2 omitted by the custom code.
import numpy as np
import gtsam
G=gtsam.NonlinearFactorGraph();values=gtsam.Values()
noise=gtsam.noiseModel.Diagonal.Sigmas(np.ones(6)*.1)
origin=gtsam.Pose3();target=gtsam.Pose3(gtsam.Rot3(),np.array([1.,0.,0.]))
G.add(gtsam.PriorFactorPose3(0,origin,noise));G.add(gtsam.BetweenFactorPose3(0,1,target,noise))
values.insert(0,origin);values.insert(1,gtsam.Pose3(gtsam.Rot3(),np.array([.8,0.,0.])))
result=gtsam.GaussNewtonOptimizer(G,values).optimize()
print('coste inicial/final:',round(G.error(values),6),round(G.error(result),6),'x:',round(float(result.atPose3(1).x()),6))npm run lab and open the connection link.import hashlib, os, tempfile, time
from urllib.request import urlopen
from pathlib import Path
import numpy as np
import gtsam
# A small square with the same seeded odometry as the preceding 2D lab.
rng=np.random.default_rng(19);truth=[];side=3.;n=10
for k in range(4):
for j in range(n):
q=side*j/n;pos=([q,0],[side,q],[side-q,side],[0,side-q])[k]
truth.append(gtsam.Pose2(*pos,k*np.pi/2))
truth.append(gtsam.Pose2(0.,0.,0.));initial=gtsam.Values();graph=gtsam.NonlinearFactorGraph()
anchor=gtsam.noiseModel.Diagonal.Sigmas(np.array([1e-6,1e-6,1e-6]))
odom=gtsam.noiseModel.Diagonal.Sigmas(np.array([.05,.05,.025]))
close=gtsam.noiseModel.Diagonal.Sigmas(np.array([.03,.03,.03]))
graph.add(gtsam.PriorFactorPose2(0,truth[0],anchor));initial.insert(0,truth[0]);current=truth[0]
for i in range(40):
z=truth[i].between(truth[i+1]);noise=rng.normal(0,[.05,.05,.025]);z=gtsam.Pose2(z.x()+noise[0],z.y()+noise[1],z.theta()+noise[2])
graph.add(gtsam.BetweenFactorPose2(i,i+1,z,odom));current=current.compose(z);initial.insert(i+1,current)
graph.add(gtsam.BetweenFactorPose2(0,40,truth[0].between(truth[40]),close))
params=gtsam.GaussNewtonParams();params.setMaxIterations(40)
solution=gtsam.GaussNewtonOptimizer(graph,initial,params).optimize()
rmse=np.sqrt(np.mean([np.sum((solution.atPose2(i).translation()-truth[i].translation())**2) for i in range(41)]))
print('2D GTSAM: coste inicial/final',round(graph.error(initial),4),round(graph.error(solution),4),'RMS',round(float(rmse),4))
# Public 3D pose graph. Hash pins the exact snapshot, not a claim of physical ground truth.
url='https://raw.githubusercontent.com/MurpheyLab/DPGO/da0157f09ab23ad92a3361ac95336e416d8588df/dataset/sphere2500.g2o'
raw=urlopen(url,timeout=90).read()
assert hashlib.sha256(raw).hexdigest()=='104ab57593394f24351d9f692f3b923f8b98fff1eb638c64356cf5049e06cf3c'
with tempfile.TemporaryDirectory() as temp:
path=Path(temp)/'sphere2500.g2o';path.write_bytes(raw)
all_graph,all_values=gtsam.readG2o(str(path),True)
limit=int(os.environ.get('SLAM_N_POSES','2500'));N=min(limit,all_values.size())
values=gtsam.Values();full=gtsam.NonlinearFactorGraph();groups=[[] for _ in range(N)]
for k in range(N): values.insert(k,all_values.atPose3(k))
for i in range(all_graph.size()):
f=all_graph.at(i);keys=list(f.keys())
if max(keys)<N: full.add(f);groups[max(keys)].append(f)
prior=gtsam.PriorFactorPose3(0,values.atPose3(0),gtsam.noiseModel.Diagonal.Sigmas(np.full(6,1e-5)))
full.add(prior);groups[0].append(prior)
# Synthetic point and four bearing/range observations generated from initial poses.
# These are added demonstrations, not sensor readings from sphere2500.
landmark=gtsam.symbol('l',0); point=np.array([4.,-2.,3.]);values.insert(landmark,point+np.array([.2,-.1,.1]))
noise=gtsam.noiseModel.Diagonal.Sigmas(np.array([.02,.02,.1]))
for k in sorted(set([0,N//3,2*N//3,N-1])):
local=values.atPose3(k).transformTo(point)
f=gtsam.BearingRangeFactor3D(k,landmark,gtsam.Unit3(local),float(np.linalg.norm(local)),noise)
full.add(f);groups[k].append(f)
params=gtsam.GaussNewtonParams();params.setMaxIterations(30)
t0=time.perf_counter();batch=gtsam.GaussNewtonOptimizer(full,values,params).optimize();batch_time=time.perf_counter()-t0
settings=gtsam.ISAM2Params();settings.setRelinearizeThreshold(.01);settings.relinearizeSkip=1;isam=gtsam.ISAM2(settings)
t0=time.perf_counter()
for k in range(N):
factors=gtsam.NonlinearFactorGraph()
for f in groups[k]:factors.add(f)
init=gtsam.Values();init.insert(k,values.atPose3(k))
if k==0:init.insert(landmark,values.atPoint3(landmark))
isam.update(factors,init)
for _ in range(3):isam.update()
incremental=isam.calculateEstimate();incremental_time=time.perf_counter()-t0
diff=np.array([gtsam.Pose3.Logmap(batch.atPose3(k).between(incremental.atPose3(k))) for k in range(N)])
print('3D poses/factores/landmark:',N,full.size(),1)
print('coste inicial/lotes/iSAM2:',round(full.error(values),3),round(full.error(batch),3),round(full.error(incremental),3))
print('tiempo lotes/iSAM2 (s):',round(batch_time,3),round(incremental_time,3),'tiempo incremental medio:',round(incremental_time/N,6))
print('RMS diferencia lotes-iSAM2 giro (rad), traslación (m):',round(float(np.sqrt(np.mean(np.sum(diff[:,:3]**2,axis=1)))),6),round(float(np.sqrt(np.mean(np.sum(diff[:,3:]**2,axis=1)))),6))npm run lab and open the connection link.In one GTSAM 4.3 WSL run, the 2D loop reduced cost from 221.9693 to 2.4428 with RMS 0.1525 m; cost is half that printed by the custom code, which omits the factor. In the full 3D graph with 2500 poses and 4954 factors, including the prior and four synthetic landmark factors, initial, batch and incremental costs were 1 305 664.642, 2042.878 and 4158.250. Times were 2.306 s and 243.266 s respectively, with 2500 individual updates and three refinements. RMS difference between solutions was 0.050452 rad and 2.061116 m, calculated from rotational and translational tangent components of Log; it is not simply Euclidean distance between centers. In this configuration iSAM2 did not reach the batch solution. These are costs and differences from one run, not accuracy against truth or a general ranking of methods.
Exercises
Step 1 of 3. What form does each likelihood take?
Step 1 of 3. How does the Ti perturbation appear in E?
import numpy as np
from scipy.sparse import coo_matrix
def build_normal_equations(graph, x):
passSources: Grisetti and colleagues, graph SLAM tutorial, Dellaert and Kaess, factor graphs, Kaess and colleagues, iSAM2, Kümmerle and colleagues, g2o and Cadena and colleagues, SLAM review.