File: kalmanBuildNormals.cpp

package info (click to toggle)
groops 0%2Bgit20250907%2Bds-1
  • links: PTS, VCS
  • area: non-free
  • in suites: forky, sid
  • size: 11,140 kB
  • sloc: cpp: 135,607; fortran: 1,603; makefile: 20
file content (299 lines) | stat: -rw-r--r-- 10,956 bytes parent folder | download | duplicates (2)
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/***********************************************/
/**
* @file kalmanBuildNormals.cpp
*
* @brief Accumulate normals for sub monthly data sets.
*
* @author Torsten Mayer-Guerr
* @author Andreas Kvas
* @date 2009-10-10
*/
/***********************************************/

// Latex documentation
#define DOCSTRING docstring
static const char *docstring = R"(
This program sets up normal equations based on \configClass{observation}{observationType}
for short-term gravity field variations.
It computes the normal equations based on the intervals $i \in \{1, ..., N\}$ given in the \configFile{arcList}{arcList}.
It sets up the least squares adjustment
\begin{equation}
    \begin{bmatrix}
    \mathbf{l}_1 \\
    \mathbf{l}_2 \\
    \vdots \\
    \mathbf{l}_N \\
  \end{bmatrix}
  =
  \begin{bmatrix}
    \mathbf{A}_1  &  & & \\
    & \mathbf{A}_2  & &\\
    &  & \ddots & \\
    & & & \mathbf{A}_N \\
  \end{bmatrix}
  \begin{bmatrix}
    \mathbf{x}^{(1)} \\
    \mathbf{x}^{(2)} \\
    \vdots \\
    \mathbf{x}^{(N)} \\
  \end{bmatrix}
  +
  \begin{bmatrix}
    \mathbf{e}_1 \\
    \mathbf{e}_2 \\
    \vdots \\
    \mathbf{e}_N \\
  \end{bmatrix},
\end{equation}
and subsequently computes the normal equations $\mathbf{N}_i, \mathbf{n}_i$ for each interval.
If \config{eliminateNonGravityParameters} is true, all non-gravity parameters are eliminated before the normals
are written to \configFile{outputfileNormalEquation}{normalEquation}.
For each time interval in \config{arcList} a single \file{normal equation file}{normalEquation} is written.

This program computes the input normals for \program{KalmanFilter} and \program{KalmanSmootherLeastSquares}.
)";

/***********************************************/

#include "programs/program.h"
#include "parser/dataVariables.h"
#include "files/fileArcList.h"
#include "files/fileNormalEquation.h"
#include "classes/observation/observation.h"

/***** CLASS ***********************************/

/** @brief Accumulate normals for sub monthly data sets.
* @ingroup programsGroup */
class KalmanBuildNormals
{
public:
  void run(Config &config, Parallel::CommunicatorPtr comm);

private:
  ObservationPtr    observation;
  std::vector<UInt> arcsInterval;
  std::vector<Time> timesInterval;

  // normal equation system (for each interval)
  std::vector<UInt>    obsCount;
  std::vector<Matrix>  N,  n;
  std::vector<Vector>  lPl;

  void computeArc(UInt arcNo);
};

GROOPS_REGISTER_PROGRAM(KalmanBuildNormals, PARALLEL, "accumulate normals for sub monthly data sets.", KalmanFilter, NormalEquation)

/***********************************************/

void KalmanBuildNormals::run(Config &config, Parallel::CommunicatorPtr comm)
{
  try
  {
    FileName      fileNameNormals;
    FileName      fileNameArcList;
    Bool          eliminatePararmeter;

    renameDeprecatedConfig(config, "inputfileNormalequation", "inputfileNormalEquation", date2time(2020, 6, 3));
    renameDeprecatedConfig(config, "arcList",                 "inputfileArcList",        date2time(2020, 7, 7));

    readConfig(config, "outputfileNormalEquation",      fileNameNormals,     Config::MUSTSET,  "normals/normals_{loopTime:%D}.dat", "outputfile for normal equations");
    readConfig(config, "observation",                   observation,         Config::MUSTSET,  "", "");
    readConfig(config, "inputfileArcList",              fileNameArcList,     Config::MUSTSET,  "",  "list to correspond points of time to arc numbers");
    readConfig(config, "eliminateNonGravityParameters", eliminatePararmeter, Config::DEFAULT,  "1", "eliminate additional parameters from normals, 0: all parameter are saved");
    if(isCreateSchema(config)) return;

    // =======================

    const UInt arcCount = observation->arcCount();

    // read arc list
    // -------------
    logStatus<<"read arc list <"<<fileNameArcList<<">"<<Log::endl;
    readFileArcList(fileNameArcList, arcsInterval, timesInterval);
    if(arcsInterval.back()>arcCount)
      throw(Exception("count of arcs differ in observation and arcList"));

    VariableList fileNameVariableList;
    addTimeVariables(fileNameVariableList);

    // =======================

    // setup observation equations
    // ---------------------------
    logStatus<<"set up observation equations"<<Log::endl;
    // init normals
    N.resize(arcsInterval.size()-1);
    n.resize(arcsInterval.size()-1);
    lPl.resize(arcsInterval.size()-1);
    obsCount.resize(arcsInterval.size()-1, 0);
    Parallel::forEachInterval(arcCount, arcsInterval, [this](UInt arcNo) {return computeArc(arcNo);}, comm);

    // =======================

    // collect system of normal equations
    // ----------------------------------
    if(Parallel::size(comm)>=3)
    {
      logStatus<<"collect system of normal equations"<<Log::endl;
      for(UInt idxInterval=0; idxInterval<timesInterval.size()-1; idxInterval++)
      {
        UInt color = MAX_UINT;
        if(N.at(idxInterval).size())
          color = idxInterval;

        Parallel::CommunicatorPtr commSplit= Parallel::splitCommunicator(color, Parallel::myRank(comm), comm);
        if(commSplit && (Parallel::size(commSplit)>1))
        {
          Parallel::reduceSum(N.at(idxInterval),        0, commSplit);
          Parallel::reduceSum(n.at(idxInterval),        0, commSplit);
          Parallel::reduceSum(lPl.at(idxInterval),      0, commSplit);
          Parallel::reduceSum(obsCount.at(idxInterval), 0, commSplit);
          if(Parallel::myRank(commSplit) != 0)
          {
            N.at(idxInterval) = Matrix();
            n.at(idxInterval) = Matrix();
            lPl.at(idxInterval) = Vector();
            obsCount.at(idxInterval) = 0;
          }
        }
      } // for(idxInterval)
    } // if(Parallel::size()>=3)

    // =======================

    logStatus<<"computing normals"<<Log::endl;
    for(UInt idxInterval=0; idxInterval<timesInterval.size()-1; idxInterval++)
      if(N.at(idxInterval).size())
      {
        NormalEquationInfo normalInfo;
        observation->parameterName(normalInfo.parameterName);

        // eliminate state parameters
        if(eliminatePararmeter && (observation->parameterCount() > observation->gravityParameterCount()))
        {
          // regularize not used parameters
          for(UInt i=observation->gravityParameterCount(); i<N.at(idxInterval).rows(); i++)
            if(N.at(idxInterval)(i,i)==0)
            {
              N.at(idxInterval)(i,i)   += 1.0;
              obsCount.at(idxInterval) += 1;
            }

          Double regul = 1;
          for(;;)
          {
            try
            {
              UInt startElim = observation->gravityParameterCount();
              UInt countElim = observation->parameterCount() - observation->gravityParameterCount();

              // solve for state parameters and update correlation block
              Matrix N22 = N.at(idxInterval).slice(startElim, startElim, countElim, countElim);
              cholesky(N22); // N22 = W^T*W
              triangularSolve(1.0, N22.trans(), N.at(idxInterval).slice(0, startElim, startElim, countElim).trans()); //N12*W^-1

              // update coefficient matrix
              rankKUpdate(-1.0, N.at(idxInterval).slice(0, startElim, startElim, countElim).trans(),
                                N.at(idxInterval).slice(0, 0, startElim, startElim)); // N = N11 - N12 (W^T W)^-1 N12^T

              // update right hand side
              triangularSolve(1.0, N22.trans(), n.at(idxInterval).row(startElim, countElim)); // W^-T * n2
              matMult(-1.0, N.at(idxInterval).slice(0, startElim, startElim, countElim),
                            n.at(idxInterval).row(startElim, countElim),
                            n.at(idxInterval).row(0, startElim)); // n = n1 - N12*W^-1 * W^-T*n2

              // update normals
              obsCount.at(idxInterval) -= countElim;
              for(UInt i=0; i<lPl.at(idxInterval).rows(); i++)
                lPl.at(idxInterval)(i) -= quadsum(n.at(idxInterval).slice(startElim, i, countElim, 1)); // lPl = lPl - n2^T N2^(-1) n2

              N.at(idxInterval) =  N.at(idxInterval).slice(0, 0, startElim, startElim);
              n.at(idxInterval) =  n.at(idxInterval).row(0, startElim);
              break;
            }
            catch(std::exception &e)
            {
              logError<<"error at "<<timesInterval.at(idxInterval).dateStr()<<": "<<e.what()<<" continue..."<<Log::endl;
              for(UInt i=observation->gravityParameterCount(); i<N.at(idxInterval).rows(); i++)
                N.at(idxInterval)(i,i) += regul;
              regul *= 10;
            }
          }

          normalInfo.parameterName.resize(observation->gravityParameterCount());
        }

        // save normals
        // ------------
        normalInfo.lPl = lPl.at(idxInterval);
        normalInfo.observationCount = obsCount.at(idxInterval);
        evaluateTimeVariables(idxInterval, timesInterval.at(idxInterval), timesInterval.at(idxInterval+1), fileNameVariableList);
        logStatus<<"write normal equations to <"<<fileNameNormals(fileNameVariableList)<<">"<<Log::endl;
        writeFileNormalEquation(fileNameNormals(fileNameVariableList), normalInfo, N.at(idxInterval), n.at(idxInterval));
      } // for(idxInterval)
  }
  catch(std::exception &e)
  {
    GROOPS_RETHROW(e)
  }
}

/***********************************************/

void KalmanBuildNormals::computeArc(UInt arcNo)
{
  try
  {
    // observation equations
    // ---------------------
    Matrix l,A,B;
    observation->observation(arcNo, l,A,B);
    if(l.rows()==0)
      return;

    // if equations are orthogonaly transformed
    // additional residuals are appended to l
    // ----------------------------------------
    Matrix l2;
    if(l.rows()>A.rows())
    {
      l2 = l.row(A.rows(), l.rows()-A.rows());
      l  = l.row(0, A.rows());
    }

    // eliminate arc related parameters
    // --------------------------------
    if(B.size()!=0)
      eliminationParameter(B,A,l);

    // search time interval
    // --------------------
    UInt idxInterval = 0;
    while(arcsInterval.at(idxInterval+1)<=arcNo)
      idxInterval++;

    // accumulate normal equation system
    // ---------------------------------
    obsCount.at(idxInterval) += l.rows() + l2.rows();
    if(lPl.at(idxInterval).size() == 0)
      lPl.at(idxInterval) = Vector(l.columns());
    for(UInt i=0; i<l.columns(); i++)
      lPl.at(idxInterval)(i) += quadsum(l.column(i)) + quadsum(l2.column(i));
    // right hand side
    if(n.at(idxInterval).size() == 0)
      n.at(idxInterval) = Matrix(A.columns(), l.columns());
    matMult(1., A.trans(), l, n.at(idxInterval));
    // normal matrix
    if(N.at(idxInterval).size() == 0)
      N.at(idxInterval) = Matrix(A.columns(), Matrix::SYMMETRIC);
    rankKUpdate(1., A, N.at(idxInterval));
  }
  catch(std::exception &e)
  {
    GROOPS_RETHROW(e)
  }
}

/***********************************************/