source: git/src/matrix.c @ 2d8d46d

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

Assign matrix rows more efficiently

  • Property mode set to 100644
File size: 12.5 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#ifdef NO_COVARIANCES
183            printf("Leg %d, vx=%f, reverse=%d, to ", dirn,
184                   stn->leg[dirn]->v[0], stn->leg[dirn]->l.reverse);
185#else
186            printf("Leg %d, vx=%f, reverse=%d, to ", dirn,
187                   stn->leg[dirn]->v[0][0], stn->leg[dirn]->l.reverse);
188#endif
189            print_prefix(stn->leg[dirn]->l.to->name);
190            putnl();
191         }
192         putnl();
193#endif /* DEBUG_MATRIX_BUILD */
194
195         int f = stn->colour;
196         if (f != COLOUR_FIXED) {
197            for (int dirn = 0; dirn <= 2 && stn->leg[dirn]; dirn++) {
198               linkfor *leg = stn->leg[dirn];
199               node *to = leg->l.to;
200               int t = to->colour;
201               if (t == COLOUR_FIXED) {
202                  bool fRev = !data_here(leg);
203                  if (fRev) leg = reverse_leg(leg);
204                  /* Ignore equated nodes */
205#ifdef NO_COVARIANCES
206                  e = leg->v[dim];
207                  if (e != (real)0.0) {
208                     e = ((real)1.0) / e;
209                     M(f,f) += e;
210                     B[f] += e * POS(to, dim);
211                     if (fRev) {
212                        B[f] += leg->d[dim];
213                     } else {
214                        B[f] -= leg->d[dim];
215                     }
216                  }
217#else
218                  if (invert_svar(&e, &leg->v)) {
219                     if (fRev) {
220                        adddd(&a, &POSD(to), &leg->d);
221                     } else {
222                        subdd(&a, &POSD(to), &leg->d);
223                     }
224                     delta b;
225                     mulsd(&b, &e, &a);
226                     for (int i = 0; i < 3; i++) {
227                        M(f * FACTOR + i, f * FACTOR + i) += e[i];
228                        B[f * FACTOR + i] += b[i];
229                     }
230                     M(f * FACTOR + 1, f * FACTOR) += e[3];
231                     M(f * FACTOR + 2, f * FACTOR) += e[4];
232                     M(f * FACTOR + 2, f * FACTOR + 1) += e[5];
233                  }
234#endif
235               } else if (data_here(leg)) {
236                  /* forward leg, unfixed -> unfixed */
237#if DEBUG_MATRIX
238                  printf("Leg %d to %d, var %f, delta %f\n", f, t, e,
239                         leg->d[dim]);
240#endif
241                  /* Ignore equated nodes & lollipops */
242#ifdef NO_COVARIANCES
243                  e = leg->v[dim];
244                  if (t != f && e != (real)0.0) {
245                     e = ((real)1.0) / e;
246                     M(f,f) += e;
247                     M(t,t) += e;
248                     if (f < t) M(t,f) -= e; else M(f,t) -= e;
249                     real a = e * leg->d[dim];
250                     B[f] -= a;
251                     B[t] += a;
252                  }
253#else
254                  if (t != f && invert_svar(&e, &leg->v)) {
255                     mulsd(&a, &e, &leg->d);
256                     for (int i = 0; i < 3; i++) {
257                        M(f * FACTOR + i, f * FACTOR + i) += e[i];
258                        M(t * FACTOR + i, t * FACTOR + i) += e[i];
259                        if (f < t)
260                           M(t * FACTOR + i, f * FACTOR + i) -= e[i];
261                        else
262                           M(f * FACTOR + i, t * FACTOR + i) -= e[i];
263                        B[f * FACTOR + i] -= a[i];
264                        B[t * FACTOR + i] += a[i];
265                     }
266                     M(f * FACTOR + 1, f * FACTOR) += e[3];
267                     M(t * FACTOR + 1, t * FACTOR) += e[3];
268                     M(f * FACTOR + 2, f * FACTOR) += e[4];
269                     M(t * FACTOR + 2, t * FACTOR) += e[4];
270                     M(f * FACTOR + 2, f * FACTOR + 1) += e[5];
271                     M(t * FACTOR + 2, t * FACTOR + 1) += e[5];
272                     if (f < t) {
273                        M(t * FACTOR + 1, f * FACTOR) -= e[3];
274                        M(t * FACTOR, f * FACTOR + 1) -= e[3];
275                        M(t * FACTOR + 2, f * FACTOR) -= e[4];
276                        M(t * FACTOR, f * FACTOR + 2) -= e[4];
277                        M(t * FACTOR + 2, f * FACTOR + 1) -= e[5];
278                        M(t * FACTOR + 1, f * FACTOR + 2) -= e[5];
279                     } else {
280                        M(f * FACTOR + 1, t * FACTOR) -= e[3];
281                        M(f * FACTOR, t * FACTOR + 1) -= e[3];
282                        M(f * FACTOR + 2, t * FACTOR) -= e[4];
283                        M(f * FACTOR, t * FACTOR + 2) -= e[4];
284                        M(f * FACTOR + 2, t * FACTOR + 1) -= e[5];
285                        M(f * FACTOR + 1, t * FACTOR + 2) -= e[5];
286                     }
287                  }
288#endif
289               }
290            }
291         }
292      }
293
294#if PRINT_MATRICES
295      print_matrix(M, B, n * FACTOR); /* 'ave a look! */
296#endif
297
298#ifdef SOR
299      /* defined in network.c, may be altered by -z<letters> on command line */
300      if (optimize & BITA('i'))
301         sor(M, B, n * FACTOR);
302      else
303#endif
304         choleski(M, B, n * FACTOR);
305
306      {
307         for (int m = (int)(n - 1); m >= 0; m--) {
308#ifdef NO_COVARIANCES
309            stn_tab[m]->p[dim] = B[m];
310# if !EXPLICIT_FIXED_FLAG
311            if (dim == 0) {
312               SVX_ASSERT2(pos_fixed(stn_tab[m]),
313                       "setting station coordinates didn't mark pos as fixed");
314            }
315# endif
316#else
317            for (int i = 0; i < 3; i++) {
318               stn_tab[m]->p[i] = B[m * FACTOR + i];
319            }
320# if !EXPLICIT_FIXED_FLAG
321            SVX_ASSERT2(pos_fixed(stn_tab[m]),
322                    "setting station coordinates didn't mark pos as fixed");
323# endif
324#endif
325#if EXPLICIT_FIXED_FLAG && !defined NO_COVARIANCES
326            fixpos(stn_tab[m]);
327#endif
328         }
329      }
330   }
331#if EXPLICIT_FIXED_FLAG && defined NO_COVARIANCES
332   for (int m = n - 1; m >= 0; m--) fixpos(stn_tab[m]);
333#endif
334   osfree(B);
335   osfree(M);
336   osfree(stn_tab);
337
338#if DEBUG_MATRIX
339   FOR_EACH_STN(stn, list) {
340      printf("(%8.2f, %8.2f, %8.2f ) ", POS(stn, 0), POS(stn, 1), POS(stn, 2));
341      print_prefix(stn->name);
342      putnl();
343   }
344#endif
345}
346
347/* Solve MX=B for X by Choleski factorisation - modified Choleski actually
348 * since we factor into LDL' while Choleski is just LL'
349 */
350/* Note M must be symmetric positive definite */
351/* routine is entitled to scribble on M and B if it wishes */
352static void
353choleski(real *M, real *B, long n)
354{
355   for (int j = 1; j < n; j++) {
356      real V;
357      for (int i = 0; i < j; i++) {
358         V = (real)0.0;
359         for (int k = 0; k < i; k++) V += M(i,k) * M(j,k) * M(k,k);
360         M(j,i) = (M(j,i) - V) / M(i,i);
361      }
362      V = (real)0.0;
363      for (int k = 0; k < j; k++) V += M(j,k) * M(j,k) * M(k,k);
364      M(j,j) -= V; /* may be best to add M() last for numerical reasons too */
365   }
366
367   /* Multiply x by L inverse */
368   for (int i = 0; i < n - 1; i++) {
369      for (int j = i + 1; j < n; j++) {
370         B[j] -= M(j,i) * B[i];
371      }
372   }
373
374   /* Multiply x by D inverse */
375   for (int i = 0; i < n; i++) {
376      B[i] /= M(i,i);
377   }
378
379   /* Multiply x by (L transpose) inverse */
380   for (int i = (int)(n - 1); i > 0; i--) {
381      for (int j = i - 1; j >= 0; j--) {
382         B[j] -= M(i,j) * B[i];
383      }
384   }
385
386   /* printf("\n%ld/%ld\n\n",flops,flopsTot); */
387}
388
389#ifdef SOR
390/* factor to use for SOR (must have 1 <= SOR_factor < 2) */
391#define SOR_factor 1.93 /* 1.95 */
392
393/* Solve MX=B for X by SOR of Gauss-Siedel */
394/* routine is entitled to scribble on M and B if it wishes */
395static void
396sor(real *M, real *B, long n)
397{
398   long it = 0;
399
400   real *X = osmalloc(n * ossizeof(real));
401
402   const real threshold = 0.00001;
403
404   printf("reciprocating diagonal\n"); /* TRANSLATE */
405
406   /* munge diagonal so we can multiply rather than divide */
407   for (int row = n - 1; row >= 0; row--) {
408      M(row,row) = 1 / M(row,row);
409      X[row] = 0;
410   }
411
412   printf("starting iteration\n"); /* TRANSLATE */
413
414   real t;
415   do {
416      /*printf("*");*/
417      it++;
418      t = 0.0;
419      for (int row = 0; row < n; row++) {
420         real x = B[row];
421         int col;
422         for (col = 0; col < row; col++) x -= M(row,col) * X[col];
423         for (col++; col < n; col++) x -= M(col,row) * X[col];
424         x *= M(row,row);
425         real sor_delta = (x - X[row]) * SOR_factor;
426         X[row] += sor_delta;
427         real t2 = fabs(sor_delta);
428         if (t2 > t) t = t2;
429      }
430      printf("% 6ld: %8.6f\n", it, t);
431   } while (t >= threshold && it < 100000);
432
433   if (t >= threshold) {
434      fprintf(stderr, "*not* converged after %ld iterations\n", it);
435      BUG("iteration stinks");
436   }
437
438   printf("%ld iterations\n", it); /* TRANSLATE */
439
440#if 0
441   putnl();
442   for (int row = n - 1; row >= 0; row--) {
443      t = 0.0;
444      for (int col = 0; col < row; col++) t += M(row, col) * X[col];
445      t += X[row] / M(row, row);
446      for (col = row + 1; col < n; col++)
447         t += M(col, row) * X[col];
448      printf("[ %f %f ]\n", t, B[row]);
449   }
450#endif
451
452   for (int row = n - 1; row >= 0; row--) B[row] = X[row];
453
454   osfree(X);
455   printf("\ndone\n"); /* TRANSLATE */
456}
457#endif
458
459#if PRINT_MATRICES
460static void
461print_matrix(real *M, real *B, long n)
462{
463   printf("Matrix, M and vector, B:\n");
464   for (long row = 0; row < n; row++) {
465      long col;
466      for (col = 0; col <= row; col++) printf("%6.2f\t", M(row, col));
467      for (; col <= n; col++) printf(" \t");
468      printf("\t%6.2f\n", B[row]);
469   }
470   putnl();
471   return;
472}
473#endif
Note: See TracBrowser for help on using the repository browser.