source: git/src/matrix.c @ e83488d

stereo-2025
Last change on this file since e83488d was e83488d, checked in by Olly Betts <olly@…>, 9 months ago

Fix to build with DEBUG_MATRIX_BUILD set to 1

Reported by Eric C. Landgraf.

  • Property mode set to 100644
File size: 12.3 KB
Line 
1/* matrix.c
2 * Matrix building and solving routines
3 * Copyright (C) 1993-2003,2010,2013,2024 Olly Betts
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18 */
19
20/*#define SOR 1*/
21
22#if 0
23# define DEBUG_INVALID 1
24#endif
25
26#include <config.h>
27
28#include "debug.h"
29#include "cavern.h"
30#include "filename.h"
31#include "message.h"
32#include "netbits.h"
33#include "matrix.h"
34#include "out.h"
35
36#undef PRINT_MATRICES
37#define PRINT_MATRICES 0
38
39#undef DEBUG_MATRIX_BUILD
40#define DEBUG_MATRIX_BUILD 0
41
42#undef DEBUG_MATRIX
43#define DEBUG_MATRIX 0
44
45#if PRINT_MATRICES
46static void print_matrix(real *M, real *B, long n);
47#endif
48
49static void choleski(real *M, real *B, long n);
50
51#ifdef SOR
52static void sor(real *M, real *B, long n);
53#endif
54
55/* for M(row, col) col must be <= row, so Y <= X */
56# define M(X, Y) ((real *)M)[((((OSSIZE_T)(X)) * ((X) + 1)) >> 1) + (Y)]
57              /* +(Y>X?0*printf("row<col (line %d)\n",__LINE__):0) */
58/*#define M_(X, Y) ((real *)M)[((((OSSIZE_T)(Y)) * ((Y) + 1)) >> 1) + (X)]*/
59
60#define COLOUR_FIXED -1
61#define COLOUR_TODO -2
62
63static void set_row(node *stn, node *from, int row_number) {
64    // We store the matrix row/column index in stn->colour for quick and easy
65    // lookup when copying out the solved station coordinates.
66    stn->colour = row_number;
67    for (int d = 0; d < 3; d++) {
68        linkfor *leg = stn->leg[d];
69        if (!leg) break;
70        node *to = leg->l.to;
71        if (to == from || to->colour != COLOUR_TODO) {
72            continue;
73        }
74        if (fZeros(data_here(leg) ? &leg->v : &reverse_leg(leg)->v)) {
75            set_row(to, stn, row_number);
76        }
77    }
78}
79
80#ifdef NO_COVARIANCES
81# define FACTOR 1
82#else
83# define FACTOR 3
84#endif
85
86extern void
87solve_matrix(node *list)
88{
89   node *stn;
90   bool unfixed_stations = false;
91   FOR_EACH_STN(stn, list) {
92      if (!fixed(stn)) {
93          unfixed_stations = true;
94          stn->colour = COLOUR_TODO;
95      } else {
96          stn->colour = COLOUR_FIXED;
97      }
98   }
99   if (!unfixed_stations) {
100       return;
101   }
102
103   // Assign a matrix row/column index to each group of stations with the same
104   // pos.
105   long n = 0;
106   FOR_EACH_STN(stn, list) {
107      if (stn->colour == COLOUR_TODO) {
108          set_row(stn, NULL, n++);
109      }
110   }
111   SVX_ASSERT(n > 0);
112
113   // Array to map from row/column index to pos.  We fill this in as we build
114   // the matrix, and use it to know where to copy the solved station
115   // coordinates to.
116   pos **stn_tab = osmalloc((OSSIZE_T)(n * ossizeof(pos*)));
117
118   /* (OSSIZE_T) cast may be needed if n >= 181 */
119   real *M = osmalloc((OSSIZE_T)((((OSSIZE_T)n * FACTOR * (n * FACTOR + 1)) >> 1)) * ossizeof(real));
120   real *B = osmalloc((OSSIZE_T)(n * FACTOR * ossizeof(real)));
121
122   if (!fQuiet) {
123      if (n == 1)
124         out_current_action(msg(/*Solving one equation*/78));
125      else
126         out_current_action1(msg(/*Solving %d simultaneous equations*/75), n);
127   }
128
129#ifdef NO_COVARIANCES
130   int dim = 2;
131#else
132   int dim = 0; /* Collapse loop to a single iteration. */
133#endif
134   for ( ; dim >= 0; dim--) {
135      /* Initialise M and B to zero - zeroing "linearly" will minimise
136       * paging when the matrix is large */
137      {
138         int end = n * FACTOR;
139         for (int row = 0; row < end; row++) B[row] = (real)0.0;
140         end = ((OSSIZE_T)n * FACTOR * (n * FACTOR + 1)) >> 1;
141         for (int row = 0; row < end; row++) M[row] = (real)0.0;
142      }
143
144      /* Construct matrix by going through the stn list.
145       *
146       * All legs between two fixed stations can be ignored here.
147       *
148       * Other legs we want to add exactly once to M.  To achieve this we
149       * want to:
150       *
151       * - add forward legs between two unfixed stations,
152       *
153       * - add legs from unfixed stations to fixed stations (we do them from
154       *   the unfixed end so we don't need to detect when we're at a fixed
155       *   point cut line and determine which side we're currently dealing
156       *   with).
157       *
158       * To implement this, we only look at legs from unfixed stations and add
159       * a leg if to a fixed station, or to an unfixed station and it's a
160       * forward leg.
161       */
162      FOR_EACH_STN(stn, list) {
163         if (dim == 0) {
164             if (stn->colour != COLOUR_FIXED) {
165                 stn_tab[stn->colour] = stn->name->pos;
166             }
167         }
168
169#ifdef NO_COVARIANCES
170         real e;
171#else
172         svar e;
173         delta a;
174#endif
175#if DEBUG_MATRIX_BUILD
176         print_prefix(stn->name);
177         printf(" used: %d colour %ld\n",
178                (!!stn->leg[2]) << 2 | (!!stn -> leg[1]) << 1 | (!!stn->leg[0]),
179                stn->colour);
180
181         for (int dirn = 0; dirn <= 2 && stn->leg[dirn]; dirn++) {
182            printf("Leg %d, vx=%f, reverse=%d, to ", dirn,
183                   stn->leg[dirn]->v[0], stn->leg[dirn]->l.reverse);
184            print_prefix(stn->leg[dirn]->l.to->name);
185            putnl();
186         }
187         putnl();
188#endif /* DEBUG_MATRIX_BUILD */
189
190         int f = stn->colour;
191         if (f != COLOUR_FIXED) {
192            for (int dirn = 0; dirn <= 2 && stn->leg[dirn]; dirn++) {
193               linkfor *leg = stn->leg[dirn];
194               node *to = leg->l.to;
195               int t = to->colour;
196               if (t == COLOUR_FIXED) {
197                  bool fRev = !data_here(leg);
198                  if (fRev) leg = reverse_leg(leg);
199                  /* Ignore equated nodes */
200#ifdef NO_COVARIANCES
201                  e = leg->v[dim];
202                  if (e != (real)0.0) {
203                     e = ((real)1.0) / e;
204                     M(f,f) += e;
205                     B[f] += e * POS(to, dim);
206                     if (fRev) {
207                        B[f] += leg->d[dim];
208                     } else {
209                        B[f] -= leg->d[dim];
210                     }
211                  }
212#else
213                  if (invert_svar(&e, &leg->v)) {
214                     if (fRev) {
215                        adddd(&a, &POSD(to), &leg->d);
216                     } else {
217                        subdd(&a, &POSD(to), &leg->d);
218                     }
219                     delta b;
220                     mulsd(&b, &e, &a);
221                     for (int i = 0; i < 3; i++) {
222                        M(f * FACTOR + i, f * FACTOR + i) += e[i];
223                        B[f * FACTOR + i] += b[i];
224                     }
225                     M(f * FACTOR + 1, f * FACTOR) += e[3];
226                     M(f * FACTOR + 2, f * FACTOR) += e[4];
227                     M(f * FACTOR + 2, f * FACTOR + 1) += e[5];
228                  }
229#endif
230               } else if (data_here(leg)) {
231                  /* forward leg, unfixed -> unfixed */
232#if DEBUG_MATRIX
233                  printf("Leg %d to %d, var %f, delta %f\n", f, t, e,
234                         leg->d[dim]);
235#endif
236                  /* Ignore equated nodes & lollipops */
237#ifdef NO_COVARIANCES
238                  e = leg->v[dim];
239                  if (t != f && e != (real)0.0) {
240                     e = ((real)1.0) / e;
241                     M(f,f) += e;
242                     M(t,t) += e;
243                     if (f < t) M(t,f) -= e; else M(f,t) -= e;
244                     real a = e * leg->d[dim];
245                     B[f] -= a;
246                     B[t] += a;
247                  }
248#else
249                  if (t != f && invert_svar(&e, &leg->v)) {
250                     mulsd(&a, &e, &leg->d);
251                     for (int i = 0; i < 3; i++) {
252                        M(f * FACTOR + i, f * FACTOR + i) += e[i];
253                        M(t * FACTOR + i, t * FACTOR + i) += e[i];
254                        if (f < t)
255                           M(t * FACTOR + i, f * FACTOR + i) -= e[i];
256                        else
257                           M(f * FACTOR + i, t * FACTOR + i) -= e[i];
258                        B[f * FACTOR + i] -= a[i];
259                        B[t * FACTOR + i] += a[i];
260                     }
261                     M(f * FACTOR + 1, f * FACTOR) += e[3];
262                     M(t * FACTOR + 1, t * FACTOR) += e[3];
263                     M(f * FACTOR + 2, f * FACTOR) += e[4];
264                     M(t * FACTOR + 2, t * FACTOR) += e[4];
265                     M(f * FACTOR + 2, f * FACTOR + 1) += e[5];
266                     M(t * FACTOR + 2, t * FACTOR + 1) += e[5];
267                     if (f < t) {
268                        M(t * FACTOR + 1, f * FACTOR) -= e[3];
269                        M(t * FACTOR, f * FACTOR + 1) -= e[3];
270                        M(t * FACTOR + 2, f * FACTOR) -= e[4];
271                        M(t * FACTOR, f * FACTOR + 2) -= e[4];
272                        M(t * FACTOR + 2, f * FACTOR + 1) -= e[5];
273                        M(t * FACTOR + 1, f * FACTOR + 2) -= e[5];
274                     } else {
275                        M(f * FACTOR + 1, t * FACTOR) -= e[3];
276                        M(f * FACTOR, t * FACTOR + 1) -= e[3];
277                        M(f * FACTOR + 2, t * FACTOR) -= e[4];
278                        M(f * FACTOR, t * FACTOR + 2) -= e[4];
279                        M(f * FACTOR + 2, t * FACTOR + 1) -= e[5];
280                        M(f * FACTOR + 1, t * FACTOR + 2) -= e[5];
281                     }
282                  }
283#endif
284               }
285            }
286         }
287      }
288
289#if PRINT_MATRICES
290      print_matrix(M, B, n * FACTOR); /* 'ave a look! */
291#endif
292
293#ifdef SOR
294      /* defined in network.c, may be altered by -z<letters> on command line */
295      if (optimize & BITA('i'))
296         sor(M, B, n * FACTOR);
297      else
298#endif
299         choleski(M, B, n * FACTOR);
300
301      {
302         for (int m = (int)(n - 1); m >= 0; m--) {
303#ifdef NO_COVARIANCES
304            stn_tab[m]->p[dim] = B[m];
305# if !EXPLICIT_FIXED_FLAG
306            if (dim == 0) {
307               SVX_ASSERT2(pos_fixed(stn_tab[m]),
308                       "setting station coordinates didn't mark pos as fixed");
309            }
310# endif
311#else
312            for (int i = 0; i < 3; i++) {
313               stn_tab[m]->p[i] = B[m * FACTOR + i];
314            }
315# if !EXPLICIT_FIXED_FLAG
316            SVX_ASSERT2(pos_fixed(stn_tab[m]),
317                    "setting station coordinates didn't mark pos as fixed");
318# endif
319#endif
320#if EXPLICIT_FIXED_FLAG && !defined NO_COVARIANCES
321            fixpos(stn_tab[m]);
322#endif
323         }
324      }
325   }
326#if EXPLICIT_FIXED_FLAG && defined NO_COVARIANCES
327   for (int m = n - 1; m >= 0; m--) fixpos(stn_tab[m]);
328#endif
329   osfree(B);
330   osfree(M);
331   osfree(stn_tab);
332
333#if DEBUG_MATRIX
334   FOR_EACH_STN(stn, list) {
335      printf("(%8.2f, %8.2f, %8.2f ) ", POS(stn, 0), POS(stn, 1), POS(stn, 2));
336      print_prefix(stn->name);
337      putnl();
338   }
339#endif
340}
341
342/* Solve MX=B for X by Choleski factorisation - modified Choleski actually
343 * since we factor into LDL' while Choleski is just LL'
344 */
345/* Note M must be symmetric positive definite */
346/* routine is entitled to scribble on M and B if it wishes */
347static void
348choleski(real *M, real *B, long n)
349{
350   for (int j = 1; j < n; j++) {
351      real V;
352      for (int i = 0; i < j; i++) {
353         V = (real)0.0;
354         for (int k = 0; k < i; k++) V += M(i,k) * M(j,k) * M(k,k);
355         M(j,i) = (M(j,i) - V) / M(i,i);
356      }
357      V = (real)0.0;
358      for (int k = 0; k < j; k++) V += M(j,k) * M(j,k) * M(k,k);
359      M(j,j) -= V; /* may be best to add M() last for numerical reasons too */
360   }
361
362   /* Multiply x by L inverse */
363   for (int i = 0; i < n - 1; i++) {
364      for (int j = i + 1; j < n; j++) {
365         B[j] -= M(j,i) * B[i];
366      }
367   }
368
369   /* Multiply x by D inverse */
370   for (int i = 0; i < n; i++) {
371      B[i] /= M(i,i);
372   }
373
374   /* Multiply x by (L transpose) inverse */
375   for (int i = (int)(n - 1); i > 0; i--) {
376      for (int j = i - 1; j >= 0; j--) {
377         B[j] -= M(i,j) * B[i];
378      }
379   }
380
381   /* printf("\n%ld/%ld\n\n",flops,flopsTot); */
382}
383
384#ifdef SOR
385/* factor to use for SOR (must have 1 <= SOR_factor < 2) */
386#define SOR_factor 1.93 /* 1.95 */
387
388/* Solve MX=B for X by SOR of Gauss-Siedel */
389/* routine is entitled to scribble on M and B if it wishes */
390static void
391sor(real *M, real *B, long n)
392{
393   long it = 0;
394
395   real *X = osmalloc(n * ossizeof(real));
396
397   const real threshold = 0.00001;
398
399   printf("reciprocating diagonal\n"); /* TRANSLATE */
400
401   /* munge diagonal so we can multiply rather than divide */
402   for (int row = n - 1; row >= 0; row--) {
403      M(row,row) = 1 / M(row,row);
404      X[row] = 0;
405   }
406
407   printf("starting iteration\n"); /* TRANSLATE */
408
409   real t;
410   do {
411      /*printf("*");*/
412      it++;
413      t = 0.0;
414      for (int row = 0; row < n; row++) {
415         real x = B[row];
416         int col;
417         for (col = 0; col < row; col++) x -= M(row,col) * X[col];
418         for (col++; col < n; col++) x -= M(col,row) * X[col];
419         x *= M(row,row);
420         real sor_delta = (x - X[row]) * SOR_factor;
421         X[row] += sor_delta;
422         real t2 = fabs(sor_delta);
423         if (t2 > t) t = t2;
424      }
425      printf("% 6ld: %8.6f\n", it, t);
426   } while (t >= threshold && it < 100000);
427
428   if (t >= threshold) {
429      fprintf(stderr, "*not* converged after %ld iterations\n", it);
430      BUG("iteration stinks");
431   }
432
433   printf("%ld iterations\n", it); /* TRANSLATE */
434
435#if 0
436   putnl();
437   for (int row = n - 1; row >= 0; row--) {
438      t = 0.0;
439      for (int col = 0; col < row; col++) t += M(row, col) * X[col];
440      t += X[row] / M(row, row);
441      for (col = row + 1; col < n; col++)
442         t += M(col, row) * X[col];
443      printf("[ %f %f ]\n", t, B[row]);
444   }
445#endif
446
447   for (int row = n - 1; row >= 0; row--) B[row] = X[row];
448
449   osfree(X);
450   printf("\ndone\n"); /* TRANSLATE */
451}
452#endif
453
454#if PRINT_MATRICES
455static void
456print_matrix(real *M, real *B, long n)
457{
458   printf("Matrix, M and vector, B:\n");
459   for (long row = 0; row < n; row++) {
460      long col;
461      for (col = 0; col <= row; col++) printf("%6.2f\t", M(row, col));
462      for (; col <= n; col++) printf(" \t");
463      printf("\t%6.2f\n", B[row]);
464   }
465   putnl();
466   return;
467}
468#endif
Note: See TracBrowser for help on using the repository browser.