Non-Linear Least Squares: Sparse Schur Complement

As optimization problems get larger they also tend to be more sparse. A common problem with sparse systems is fill in. What fill in refers to are zero elements becoming non-zero as a linear system is solved. This will destroy your performance. What the Schur Complement does is allow you to solve the problem in separate components which are structured for efficiency.

Bundle Adjustment is a classic problem from computer vision which is made possible by the Schur Complement. What would take seconds when solved with the Schur Complement can literally take hours or days without it. This example demonstrates the Schur Comlpement in a 2D version of bundle adjustment.

The parameters which are optimized are camera and landmarks locations. Both are them are described by an (x,y) coordinate. Each camera can observe each landmark with a bearings measurement.

\[\theta_{ij} = \mbox{atan}\left( \frac{l^j_y-c^i_y}{l^j_x-c^i_x}\right)\]

where \(\theta_{ij}\) is camera i’s observation of landmark j, \((c_x,c_y)\) is a camera’s location, and \((l_x,l_y)\) is a landmark’s location.

The actual code is shown below. This is more complex than our previous examples so be sure to read the in code comments. How the Jacobian is formulated is also different from the regular least-squaers problem. It’s broken up into a left and right side.

ExampleSchurComplementLeastSquares.java

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
public static void main(String[] args)
{
    //------------------------------------------------------------------
    // Randomly generate the world
    //
    Random rand = new Random(0xDEADBEEF);
    final int numCameras = 10;
    final int numLandmarks = 40;

    // Cameras are placed along a line. This specifies the length of the line and how spread out the cameras
    // will be
    final double length = 10;

    // how far away the landmark line is from the camera line
    final double depth = 20;

    double[] observations = new double[numCameras*numLandmarks];

    double[] optimal = new double[2*(numCameras+numLandmarks)];
    double[] initial = new double[optimal.length];

    // Randomly create the world and observations
    List<Point2D> cameras = new ArrayList<>();
    List<Point2D> landmarks = new ArrayList<>();

    int index = 0;
    for (int i = 0; i < numCameras; i++) {
        double x = 2*(rand.nextDouble()-0.5)*length;
        cameras.add( new Point2D(0,x) );

        optimal[index++] = 0;
        optimal[index++] = x;
    }
    for (int i = 0; i < numLandmarks; i++) {
        double y = 2*(rand.nextDouble()-0.5)*length;
        landmarks.add( new Point2D(depth,y) );

        optimal[index++] = depth;
        optimal[index++] = y;
    }

    //------------------------------------------------------------------
    // Creating noisy initial estimate
    //
    for (int i = 0; i < optimal.length; i++) {
        initial[i] = optimal[i] + rand.nextGaussian()*5; // this is a lot of error!
    }

    //------------------------------------------------------------------
    // Creating perfect observations.
    //   Unrealistic, but we know if it hit the optimal solution or not
    index = 0;
    for (int i = 0; i < numCameras; i++) {
        Point2D c = cameras.get(i);
        for (int j = 0; j < numLandmarks; j++, index++) {
            Point2D l = landmarks.get(j);
            observations[index] = Math.atan((l.y-c.y)/(l.x-c.x));

            // sanity check
            if(UtilEjml.isUncountable(observations[index]))
                throw new RuntimeException("Egads");
        }
    }

    //------------------------------------------------------------------
    // Create the optimizer and optimize!
    //
    UnconstrainedLeastSquaresSchur<DMatrixSparseCSC> optimizer =
            FactoryOptimizationSparse.levenbergMarquardtSchur(null);

    // Send to standard out progress information
    optimizer.setVerbose(System.out,0);

    // For large sparse systems it's strongly recommended that you use an analytic Jacobian. While this might
    // change in the future after a redesign, there isn't a way to efficiently compute the numerical Jacobian
    FuncGradient funcGrad = new FuncGradient(numCameras,numLandmarks,observations);
    optimizer.setFunction(funcGrad,funcGrad);

    // provide it an extremely crude initial estimate of the line equation
    optimizer.initialize(initial,1e-12,1e-12);

    // iterate 500 times or until it converges.
    // Manually iteration is possible too if more control over is required
    UtilOptimize.process(optimizer,500);

    // see how accurately it found the solution. Optimally this value would be zero
    System.out.println("Final Error = "+optimizer.getFunctionValue());
}


/**
 * Implements the residual function and the gradient.
 */
public static class FuncGradient
        implements FunctionNtoM, SchurJacobian<DMatrixSparseCSC>
{
    int numCameras,numLandmarks;
    
    // observations of each landmark as seen from each camera as an angle measurement
    // 2D array. cameras = rows, landmarks = columns
    double observations[];
    
    List<Point2D> cameras = new ArrayList<>();
    List<Point2D> landmarks = new ArrayList<>();

    public FuncGradient(int numCameras, int numLandmarks,
                        double observations[] ) {
        this.numCameras = numCameras;
        this.numLandmarks = numLandmarks;
        this.observations = observations;
    }

    /**
     * The function.
     * 
     * @param input Parameters for input model.
     * @param output Storage for the output give the model.
     */
    @Override
    public void process(double[] input, double[] output) {
        decode(numCameras,numLandmarks,input,cameras, landmarks);

        int index = 0;
        for (int i = 0; i < cameras.size(); i++) {
            Point2D c = cameras.get(i);
            for (int j = 0; j < landmarks.size(); j++, index++) {
                Point2D l = landmarks.get(j);
                output[index] = Math.atan((l.y-c.y)/(l.x-c.x))-observations[index];

                if(UtilEjml.isUncountable(output[index]))
                    throw new RuntimeException("Egads");
            }
        }
    }

    @Override
    public int getNumOfInputsN() {
        return 2*numCameras + 2*numLandmarks;
    }

    @Override
    public int getNumOfOutputsM() {
        return numCameras*numLandmarks;
    }

    /**
     * The Jaoobian. Split in a left and right hand side for the Schur Complement.
     * 
     * @param input Vector with input parameters.
     * @param left (Output) left side of jacobian. Will be resized to fit.
     * @param right (Output) right side of jacobian. Will be resized to fit.
     */
    @Override
    public void process(double[] input, DMatrixSparseCSC left, DMatrixSparseCSC right) {
        decode(numCameras,numLandmarks,input,cameras, landmarks);

        int N = numCameras*numLandmarks;
        DMatrixSparseTriplet tripletLeft = new DMatrixSparseTriplet(N,2*numCameras,1);
        DMatrixSparseTriplet tripletRight = new DMatrixSparseTriplet(N,2*numLandmarks,1);

        int output = 0;
        for (int i = 0; i < numCameras; i++) {
            Point2D c = cameras.get(i);
            for (int j = 0; j < numLandmarks; j++, output++) {
                Point2D l = landmarks.get(j);
                double top = l.y-c.y;
                double bottom = l.x-c.x;
                double slope = top/bottom;

                double a = 1.0/(1.0+slope*slope);

                double dx = top/(bottom*bottom);
                double dy = -1.0/bottom;

                tripletLeft.addItemCheck(output,i*2+0,a*dx);
                tripletLeft.addItemCheck(output,i*2+1,a*dy);
            }
        }

        for (int i = 0; i < numLandmarks; i++) {
            Point2D l = landmarks.get(i);
            for (int j = 0; j < numCameras; j++) {
                Point2D c = cameras.get(j);
                double top = l.y-c.y;
                double bottom = l.x-c.x;
                double slope = top/bottom;

                double a = 1.0/(1.0+slope*slope);

                double dx = -top/(bottom*bottom);
                double dy = 1.0/bottom;

                output = j*numLandmarks + i;
                tripletRight.addItemCheck(output,i*2+0,a*dx);
                tripletRight.addItemCheck(output,i*2+1,a*dy);
            }
        }

        ConvertDMatrixStruct.convert(tripletLeft,left);
        ConvertDMatrixStruct.convert(tripletRight,right);
    }
}

protected static void decode( int numCameras , int numLandmarks, 
                              double[] input, List<Point2D> cameras , List<Point2D> landmarks ) {
    cameras.clear();
    landmarks.clear();
    int index = 0;
    for (int i = 0; i < numCameras; i++) {
        cameras.add( new Point2D(input[index++],input[index++]) );
    }
    for (int i = 0; i < numLandmarks; i++) {
        landmarks.add( new Point2D(input[index++],input[index++]) );
    }
}

static class Point2D {
    double x,y;

    public Point2D(double x, double y) {
        this.x = x;
        this.y = y;
    }
}

When you run this example you should see something like the following:

Steps     fx        change      |step|   f-test     g-test    tr-ratio  lambda
0     2.124E+01   0.000E+00  0.000E+00  0.000E+00  0.000E+00    0.00   1.00E-04
1     1.521E+00  -1.972E+01  4.268E+01  9.284E-01  2.749E-02   0.942   3.33E-05
2     2.505E-02  -1.496E+00  2.687E+01  9.835E-01  7.797E-03   0.991   1.11E-05
3     5.300E-05  -2.500E-02  6.227E+00  9.979E-01  1.886E-04   0.999   3.70E-06
4     9.786E-10  -5.300E-05  3.123E-01  1.000E+00  1.415E-05   1.000   1.23E-06
5     1.303E-18  -9.786E-10  1.413E-03  1.000E+00  1.244E-07   1.000   4.12E-07
6     1.280E-30  -1.303E-18  5.313E-08  1.000E+00  7.759E-12   1.000   1.37E-07
Converged g-test
Final Error = 1.2803435700834499E-30