Module contents
Lesson 19 of 33Advanced 120 min

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 p(X∣Z)∝∏kfk(Xk)p(X\mid Z)\propto\prod_k f_k(X_k) connects each factor to the variables it needs. If measurement zk=hk(Xk)+ϵkz_k=h_k(X_k)+\epsilon_k has independent Gaussian noise with covariance Σk\Sigma_k, maximizing the posterior is equivalent, up to state-independent constants, to minimizing

F(X)=12∑krk(Xk)⊤Ωkrk(Xk),rk=zk−hk(Xk),Ωk=Σk−1.F(X)=\frac12\sum_k r_k(X_k)^\top\Omega_k r_k(X_k),\qquad r_k=z_k-h_k(X_k),\quad \Omega_k=\Sigma_k^{-1}.

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 Ti,TjT_i,T_j be poses and ZijZ_{ij} a relative measurement. One convention uses E=Zij−1Ti−1TjE=Z_{ij}^{-1}T_i^{-1}T_j and r=Log⁡(E)r=\operatorname{Log}(E), with tangent vector ordered translation then rotation. With right perturbations, Ti′=TiExp⁡(δi)T_i'=T_i\operatorname{Exp}(\delta_i) and Tj′=TjExp⁡(δj)T_j'=T_j\operatorname{Exp}(\delta_j), we obtain

E′=Exp⁡(−Ad⁡Z−1δi) E Exp⁡(δj),Ji=−Jl(r)−1Ad⁡Z−1,Jj=Jr(r)−1.E'=\operatorname{Exp}(-\operatorname{Ad}_{Z^{-1}}\delta_i)\,E\,\operatorname{Exp}(\delta_j),\qquad J_i=-J_l(r)^{-1}\operatorname{Ad}_{Z^{-1}},\quad J_j=J_r(r)^{-1}.

JlJ_l and JrJ_r are the left and right exponential Jacobians, Jr(r)=Jl(−r)J_r(r)=J_l(-r). 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 Jl=∫01exp⁡(sad⁡r)dsJ_l=\int_0^1\exp(s\operatorname{ad}_r)ds 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: E′=Z−1Exp⁡(−δi)Ti−1TjExp⁡(δj)E'=Z^{-1}\operatorname{Exp}(-\delta_i)T_i^{-1}T_j\operatorname{Exp}(\delta_j). Insert ZZ−1ZZ^{-1} after the first exponential and use Z−1Exp⁡(−δi)Z=Exp⁡(−Ad⁡Z−1δi)Z^{-1}\operatorname{Exp}(-\delta_i)Z=\operatorname{Exp}(-\operatorname{Ad}_{Z^{-1}}\delta_i). The differential of Log transforms the left increment via Jl−1J_l^{-1} and the right via Jr−1J_r^{-1}. In SE(3), the adjoint is a 6×66\times6 matrix mixing translation and rotation; copying two 3×33\times3 rotations onto the diagonal is insufficient. Near the angular branch cut at π\pi, a finite difference can jump branches and cease to measure the local derivative.

[ ]Log Jacobians in SE(2) and SE(3)Browser
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 EE‘s translation and wrapped angle, not the full Log⁡(E)\operatorname{Log}(E). It updates coordinates (x,y,θ)(x,y,\theta) 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 r(X⊞δ)≈r+Jδr(X\boxplus\delta)\approx r+J\delta and solve (J⊤ΩJ)δ=−J⊤Ωr(J^\top\Omega J)\delta=-J^\top\Omega r. 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 ii and jj, its two Jacobians Ji,JjJ_i,J_j contribute blocks Ji⊤ΩJiJ_i^\top\Omega J_i, Ji⊤ΩJjJ_i^\top\Omega J_j, Jj⊤ΩJiJ_j^\top\Omega J_i and Jj⊤ΩJjJ_j^\top\Omega J_j to HH, and −Ji⊤Ωr-J_i^\top\Omega r, −Jj⊤Ωr-J_j^\top\Omega r 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.

InteractiveThe graph relaxes

━ Graph · ━ Filter · dashed line: truth. The correct closure is included from the first iteration.

iteration 0
Weighted cost443.49
Trajectory RMS0.471 m
A synthetic loop with noisy odometry and a true closure; LM iterations were calculated before drawing. The EKF uses the same factors and corrects only the current pose at the end; it retains past estimates. RMS against truth is available only in this simulation.

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 2(999+20)2(999+20) 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.

InteractiveOrder changes fill

Original information

Cholesky L in selected order

Blue: nonzero element. The example counts nonzeros in a small problem; it does not measure time or predict improvement for all graphs.

Elimination order
Nonzeros in L127
Synthetic SPD matrix for 12 poses and 8 landmarks: Cholesky factorizations are calculated for four orders and LL⊤LL^\top is checked after permutation. COLAMD is the SuperLU column permutation applied before Cholesky. Nonzeros are counted; timings are not inferred.

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 s=r⊤Ωrs=r^\top\Omega r, Huber uses ρ(s)=s\rho(s)=s if s≤c2s\le c^2 and 2cs−c22c\sqrt{s}-c^2 outside; Cauchy uses c2log⁡(1+s/c2)c^2\log(1+s/c^2). In iteratively reweighted least squares the factor uses w=ρ′(s)w=\rho'(s): Huber c/sc/\sqrt{s} outside the threshold, Cauchy 1/(1+s/c2)1/(1+s/c^2). Scale cc 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.

InteractiveA false loop closure

━ Estimate · gray dashed line: truth · ━ false closure. Costs of different losses are not comparable without a common scale.

Loss
Trajectory RMS2.218 m
False closure weight1.0000
The synthetic loop adds an incorrect factor between the start and midpoint of the path. It is optimized from the same initialization using quadratic, Huber, or Cauchy loss and scale 2. Truth is available only because the experiment is simulated; the displayed weight is the loss derivative at the false closure.

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 HH 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 ρ(s)\rho(s) without the 1/21/2 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.

[ ]Sparse normal systemBrowser
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]);[email protected]
    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())
[ ]True and false loop closuresBrowser
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@[email protected][email protected](O)@G.T;path.append(x.copy())
    _,_,z,O=loop;r,_,H=factor(initial[0],x,z);V=np.linalg.inv(O);S=H@[email protected]+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@[email protected]+K@[email protected]
    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 1.46⋅10−111.46\cdot10^{-11} in HH and 2.28⋅10−122.28\cdot10^{-12} on the right-hand side. Final trajectories after eight steps agreed to 4.63⋅10−124.63\cdot10^{-12} or better in that test.

[ ]Full Intel and M3500 graphsBrowser
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.

[ ]Fill and time on M3500Browser
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.

[ ]Checking GTSAM with Pose3Local GPU
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))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Batch and iSAM2 in SE(3)Local GPU
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))
This cell needs the local lab (PyTorch with your GPU). Start it with 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 1/21/2 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

ProofFrom MAP to least squares
Prove: Derive the MAP objective for independent Gaussian factors and nonlinear measurement models.
0
Each factor has fixed positive-definite covariance.

Step 1 of 3. What form does each likelihood take?

ProofPerturbing a relative factor
Prove: Derive the Jacobians of Log(Z⁻¹ Ti⁻¹ Tj) for right perturbations.
0
Write E = Z⁻¹ Ti⁻¹ Tj and use the adjoint and exponential Jacobians.

Step 1 of 3. How does the Ti perturbation appear in E?

Numeric
A connected graph of 1000 poses has a chain of 999 edges and 20 closures between distinct pairs, none already present in the chain. How many structural nonzero blocks does the symmetric normal matrix have, counting the diagonal and both halves?
CodeAssemble the normal system
Implement build_normal_equations(graph, x), where graph is a list of (i,j,z,Omega), x is an array of poses (N,3), and factor(xi,xj,z) comes from the lab. Fix pose 0 and return sparse H and b from H δ = b for the other poses, with quadratic loss.
import numpy as np
from scipy.sparse import coo_matrix
def build_normal_equations(graph, x):
  pass
Shift+Enter to run
Quiz
What distinguishes graph smoothing from an EKF that retains only current state?
Key idea
A closure adds a constraint that propagates through the graph, but its value depends on association, geometric convention, fixed reference, and uncertainty model.

Sources: 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.