File: instrumentAccelerometerEstimateParameters.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 (625 lines) | stat: -rw-r--r-- 25,365 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
/***********************************************/
/**
* @file instrumentAccelerometerEstimateParameters.cpp
*
* @brief Estimate parameters from accelerometer data.
*
* @author Andreas Kvas
* @date 2022-07-27
*/
/***********************************************/

// Latex documentation
#define DOCSTRING docstring
static const char *docstring = R"(
This program estimates calibration parameters for acceleration data given given an optional reference acceleration.
Specifically, the program solves the equation
\begin{equation}
  \mathbf{a} - \mathbf{a}_\text{ref} = \mathbf{f}(\mathbf{x}) + \mathbf{e}
\end{equation}
for the unknown parameters $\mathbf{x}$, where $\mathbf{a}$ is given in \configFile{inputfileAccelerometer}{instrument} and
$\mathbf{a}_\text{ref}$ is given in  \configFile{inputfileAccelerometerReference}{instrument}.
The parametrization of $\mathbf{x}$ can be set via \configClass{parametrizationAcceleration}{parametrizationAccelerationType}.
Optionally, the empirical covariance functions for the accelerations $\mathbf{a}$ can be estimated by enabling \config{estimateCovarianceFunctions}.

The estimated parameters are written to the file \configFile{outputfileSolution}{matrix} and can be used by
\program{InstrumentAccelerometerApplyEstimatedParameters} to calibrate accelerometer measurements.
)";

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

#include "programs/program.h"
#include "files/fileMatrix.h"
#include "files/fileInstrument.h"
#include "files/fileSatelliteModel.h"
#include "files/fileParameterName.h"
#include "classes/earthRotation/earthRotation.h"
#include "classes/ephemerides/ephemerides.h"
#include "classes/parametrizationAcceleration/parametrizationAcceleration.h"
#include "misc/varianceComponentEstimation.h"

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

/** @brief  Estimate parameters from accelerometer data.
* @ingroup programsGroup */
class InstrumentAccelerometerEstimateParameters
{
  InstrumentFile                 accFile, accFileSim, orbitFile, starCameraFile;
  EarthRotationPtr               earthRotation;
  EphemeridesPtr                 ephemerides;
  ParametrizationAccelerationPtr parameterAcceleration;
  SatelliteModelPtr              satellite;

  Matrix N;        // normal equation matrix
  Vector n;        // right hand sides
  Vector x;        // solution
  Matrix Wz;       // monte carlo vector for redundancy computation
  Double lPl;      // =l'Pl, weighted norm of the observations
  UInt   obsCount; // number of observations

  Bool   estimateCovarianceFunctionVCE;
  Bool   estimateArcSigmas;
  Bool   estimateEpochSigmas;

  Double sampling;
  Matrix covFunc, CosTransform, Psd;
  Vector arcSigmas, arcSigmasNew;
  Matrix ePe, redundancy;  // one row for each frequency, one column for each component
  std::vector<ObservationSigmaArc> arcListEpochSigma;

  class ObservationEquationArc
  {
    public:
      std::vector<Time> times;
      Vector l;
      Matrix A, B;
      Vector xArc; // arc wise parameters
  };

  std::vector<ObservationEquationArc> observationEquations;

  void computeObservationEquation(UInt arcNo);
  void decorrelate(const std::vector<Time> &times, Double sigmaArc, const ObservationSigmaArc &sigmaEpoch, std::vector<Matrix> &W, const std::list<MatrixSlice> &A);
  void buildNormals(UInt arcNo);
  void computeRedundancies(UInt arcNo);
  ObservationSigmaArc computeEpochSigmas(UInt arcNo);

public:
  void run(Config &config, Parallel::CommunicatorPtr comm);
};

GROOPS_REGISTER_PROGRAM(InstrumentAccelerometerEstimateParameters, PARALLEL, "estimate accelerometer parameters.", Instrument)

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

void InstrumentAccelerometerEstimateParameters::run(Config &config, Parallel::CommunicatorPtr comm)
{
  try
  {
    estimateCovarianceFunctionVCE = estimateArcSigmas = estimateEpochSigmas = FALSE;

    FileName fileNameOutSolution, fileNameOutParameterName;
    FileName fileNameOutCovFunc, fileNameOutArcSigmas, fileNameOutEpochSigmas;
    FileName fileNameInAccelerometer,  fileNameInAccelerometerReference, fileNameInOrbit, fileNameInStarCamera, fileNameInSatelliteModel;
    Double   sigmaX, sigmaY, sigmaZ;
    UInt     maxIter;

    readConfig(config, "outputfileSolution",              fileNameOutSolution,        Config::MUSTSET,  "",     "values for estimated parameters");
    readConfig(config, "outputfileParameterNames",        fileNameOutParameterName,   Config::OPTIONAL, "",     "names of the estimated parameters");
    if(readConfigSequence(config, "estimateArcSigmas", Config::OPTIONAL, "", ""))
    {
      estimateArcSigmas = TRUE;
      readConfig(config, "outputfileArcSigmas",           fileNameOutArcSigmas,   Config::OPTIONAL, "", "accuracies of each arc");
      endSequence(config);
    }
    if(readConfigSequence(config, "estimateEpochSigmas", Config::OPTIONAL, "", ""))
    {
      estimateEpochSigmas = TRUE;
      readConfig(config, "outputfileEpochSigmas",         fileNameOutEpochSigmas, Config::OPTIONAL, "", "estimated epoch-wise sigmas");
      endSequence(config);
    }
    if(readConfigSequence(config, "estimateCovarianceFunctions", Config::OPTIONAL, "", ""))
    {
      estimateCovarianceFunctionVCE = TRUE;
      readConfig(config, "outputfileCovarianceFunction",  fileNameOutCovFunc,     Config::OPTIONAL, "", "covariance functions for x, y, z direction");
      endSequence(config);
    }
    readConfig(config, "inputfileAccelerometer",          fileNameInAccelerometer,          Config::MUSTSET,  "",      "");
    readConfig(config, "inputfileAccelerometerReference", fileNameInAccelerometerReference, Config::OPTIONAL, "",      "if not given, reference acceleration is assumed zero");
    readConfig(config, "inputfileOrbit",                  fileNameInOrbit,                  Config::OPTIONAL, "",      "may be needed by parametrizationAcceleration");
    readConfig(config, "inputfileStarCamera",             fileNameInStarCamera,             Config::OPTIONAL, "",      "may be needed by parametrizationAcceleration");
    readConfig(config, "inputfileSatelliteModel",         fileNameInSatelliteModel,         Config::OPTIONAL, "{groopsDataDir}/satelliteModel/", "satellite macro model (may be needed by parametrizationAcceleration)");
    readConfig(config, "earthRotation",                   earthRotation,                    Config::OPTIONAL, "file",  "may be needed by parametrizationAcceleration");
    readConfig(config, "ephemerides",                     ephemerides,                      Config::OPTIONAL, "jpl",   "may be needed by parametrizationAcceleration");
    readConfig(config, "parametrizationAcceleration",     parameterAcceleration,            Config::MUSTSET,  "",      "");
    readConfig(config, "sigmaX",                          sigmaX,                           Config::DEFAULT,  "1e-9",  "apriori accuracy in x-axis");
    readConfig(config, "sigmaY",                          sigmaY,                           Config::DEFAULT,  "10e-9", "apriori accuracy in y-axis");
    readConfig(config, "sigmaZ",                          sigmaZ,                           Config::DEFAULT,  "1e-9",  "apriori accuracy in z-axis");
    readConfig(config, "iterationCount",                  maxIter,                          Config::DEFAULT,  "5",     "iteration count for determining the covariance function");
    if(isCreateSchema(config)) return;

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

    // init instrument files + satellite model
    // ---------------------------------------
    logStatus<<"read instrument data <"<<fileNameInAccelerometer<<">"<<Log::endl;
    logStatus<<"read reference data <"<<fileNameInAccelerometerReference<<">"<<Log::endl;
    accFile.open(fileNameInAccelerometer);
    accFileSim.open(fileNameInAccelerometerReference);
    orbitFile.open(fileNameInOrbit);
    starCameraFile.open(fileNameInStarCamera);
    InstrumentFile::checkArcCount({accFile, accFileSim, orbitFile, starCameraFile});
    const UInt arcCount = accFile.arcCount();

    if(!fileNameInSatelliteModel.empty())
    {
      logStatus<<"read satellite model <"<<fileNameInSatelliteModel<<">"<<Log::endl;
      readFileSatelliteModel(fileNameInSatelliteModel, satellite);
    }

    if(Parallel::isMaster(comm) && !fileNameOutParameterName.empty())
    {
      logStatus<<"write parameter names to <"<<fileNameOutParameterName<<">"<<Log::endl;
      std::vector<ParameterName> names, nameArc;
      parameterAcceleration->parameterName(names);
      parameterAcceleration->parameterNameArc(nameArc);
      for(UInt arcNo=0; arcNo<arcCount; arcNo++)
      {
        const std::string str = "arc"+arcNo%"%i"s+".";
        for(UInt i=0; i<nameArc.size(); i++)
        {
          ParameterName param = nameArc.at(i);
          param.type = str+param.type;
          names.push_back(param);
        }
      }
      writeFileParameterName(fileNameOutParameterName, names);
    }

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

    // setup observation equations
    // ---------------------------
    logStatus<<"compute observation equations"<<Log::endl;
    observationEquations.resize(arcCount);
    const std::vector<UInt> processNo = Parallel::forEach(arcCount, [&](UInt arcNo) {computeObservationEquation(arcNo);}, comm);

    // determine sampling
    sampling  = 0.;
    for(const auto &arc : observationEquations)
      if(arc.times.size())
        sampling += medianSampling(arc.times).seconds();
    Parallel::reduceSum(sampling, 0, comm);
    Parallel::broadCast(sampling, 0, comm);
    sampling /= arcCount;

    // Determine max. length of ovariance functions
    UInt covLength = 0;
    for(const auto &arc : observationEquations)
      if(arc.times.size())
        covLength = std::max(covLength, static_cast<UInt>(std::round((arc.times.back()-arc.times.front()).seconds()/sampling)+1));
    Parallel::reduceMax(covLength, 0, comm);
    Parallel::broadCast(covLength, 0, comm);

    logInfo<<"  length of covariance function: "<<covLength<<" epochs with a sampling of "<<sampling<<" seconds"<<Log::endl;

    // init arc sigmas and covariance function
    // ---------------------------------------
    arcSigmas    = Vector(arcCount, 1.0);
    CosTransform = Vce::cosTransform(covLength);
    covFunc = Vce::readCovarianceFunction(FileName(), covLength, 3, sampling);
    covFunc.column(1)  *= std::pow(sigmaX, 2);
    covFunc.column(2)  *= std::pow(sigmaY, 2);
    covFunc.column(3)  *= std::pow(sigmaZ, 2);
    Psd = CosTransform * covFunc.column(1, 3);

    // init epoch sigmas
    // -----------------
    arcListEpochSigma.resize(arcCount);
    Parallel::forEachProcess(arcCount, [this](UInt arcNo)
    {
      const auto &times = observationEquations.at(arcNo).times;
      arcListEpochSigma.at(arcNo) = Arc(times, Matrix(times.size(), 2), Epoch::OBSERVATIONSIGMA);
    }, processNo, comm, FALSE/*timing*/);

    // start iteration
    // ---------------
    const UInt countParameter = parameterAcceleration->parameterCount();
    for(UInt iter=0; iter<maxIter; iter++)
    {
      if(maxIter>1) logStatus<<"starting iteration "<<iter+1<<Log::endl;

      // solve normal equations
      // ----------------------
      if(countParameter)
      {
        logStatus<<"accumulate system of normal equations"<<Log::endl;
        N        = Matrix(countParameter, Matrix::SYMMETRIC);
        n        = Vector(countParameter);
        lPl      = 0;
        obsCount = 0;
        Parallel::forEachProcess(arcCount, [this](UInt arcNo) {buildNormals(arcNo);}, processNo, comm);
        Parallel::reduceSum(N,        0, comm);
        Parallel::reduceSum(n,        0, comm);
        Parallel::reduceSum(obsCount, 0, comm);
        Parallel::reduceSum(lPl,      0, comm);

        logStatus<<"solve system of normal equations"<<Log::endl;
        if(Parallel::isMaster(comm))
        {
          // regularize unused parameters
          UInt countUnused = 0;
          for(UInt k=0; k<N.rows(); k++)
            if(N(k, k) == 0.0)
            {
              N(k, k) = 1.0;
              countUnused++;
            }
          obsCount += countUnused;
          if(countUnused)
            logInfo<<"  "<<countUnused<<" parameters unused -> set to zero"<<Log::endl;

          x = solve(N, n);
          logInfo<<"  aposteriori sigma = "<<std::sqrt((lPl-inner(x, n))/(obsCount-x.rows()))<<Log::endl;

          Wz = Vce::monteCarlo(x.rows(), 100); // monte carlo vector for VCE
          triangularSolve(1., N, Wz);
        }
        Parallel::broadCast(x,  0, comm);
        Parallel::broadCast(Wz, 0, comm);
      }
      Parallel::barrier(comm);

      // compute redundancies
      // --------------------
      logStatus<<"compute arc parameters and redundancies"<<Log::endl;
      arcSigmasNew = Vector(arcCount);
      ePe = redundancy = Matrix(covLength, 3);
      Parallel::forEachProcess(arcCount, [this](UInt arcNo) {computeRedundancies(arcNo);}, processNo, comm);
      Parallel::barrier(comm);

      // write parameter vector
      // ----------------------
      if(!fileNameOutSolution.empty())
      {
        // collect solution vector
        std::vector<Vector> solutions(arcCount);
        Parallel::forEachProcess(solutions, [this](UInt arcNo) {return observationEquations.at(arcNo).xArc;}, processNo, comm, FALSE/*timing*/);

        if(Parallel::isMaster(comm))
        {
          // copy global and arc parameters to one vector
          solutions.insert(solutions.begin(), x); // global parametes
          const UInt count = std::accumulate(solutions.begin(), solutions.end(), UInt(0), [](UInt c, const Vector &x) {return c+x.size();});

          Vector xOut(count);
          UInt   idx = 0;
          for(const Vector &solution : solutions)
          {
            copy(solution, xOut.row(idx, solution.rows()));
            idx += solution.rows();
          }

          logStatus<<"write solution to <"<<fileNameOutSolution<<">"<<Log::endl;
          writeFileMatrix(fileNameOutSolution, xOut);
        }
      }

      // sigmas per arc
      // --------------
      if(estimateArcSigmas)
      {
        Parallel::reduceSum(arcSigmasNew, 0, comm);
        if(Parallel::isMaster(comm))
        {
          arcSigmas = arcSigmasNew;
          const Double sigma0 = Vce::meanSigma(arcSigmas);
          arcSigmas *= 1./sigma0;
          logInfo<<"  sigma per arc (median): "<<sigma0<<Log::endl;

          if(!fileNameOutArcSigmas.empty())
          {
            logStatus<<"write arc sigma file <"<<fileNameOutArcSigmas<<">"<<Log::endl;
            writeFileMatrix(fileNameOutArcSigmas, arcSigmas);
          }
        }
        Parallel::broadCast(arcSigmas, 0, comm);
      }

      // sigmas per epoch
      // --------------
      if(estimateEpochSigmas)
      {
        Parallel::forEachProcess(arcListEpochSigma, [this](UInt arcNo) {return computeEpochSigmas(arcNo);}, processNo, comm, FALSE/*timing*/);
        if(Parallel::isMaster(comm))
        {
          UInt count = std::accumulate(arcListEpochSigma.begin(), arcListEpochSigma.end(), UInt(0), [](UInt c, auto &arc) {return c+arc.size();});
          UInt countOutlier = 0;
          for(auto &arc : arcListEpochSigma)
            countOutlier += std::count_if(arc.begin(), arc.end(), [](const ObservationSigmaEpoch &e) {return (e.sigma > 0);});
          logInfo<<"  "<<countOutlier<<" of "<<count<<" outliers ("<<100.*countOutlier/count%"%.2f%%)"s<<Log::endl;
        }
        if(Parallel::isMaster(comm) && !fileNameOutEpochSigmas.empty())
        {
          logStatus<<"write epoch sigma file <"<<fileNameOutEpochSigmas<<">"<<Log::endl;
          InstrumentFile::write(fileNameOutEpochSigmas, arcListEpochSigma);
        }
      }

      // estimate new PSD through variance component estimation
      // ------------------------------------------------------
      if(estimateCovarianceFunctionVCE)
      {
        logStatus<<"compute psd through variance component estimation"<<Log::endl;
        Parallel::reduceSum(ePe, 0, comm);
        Parallel::reduceSum(redundancy, 0, comm);
        if(Parallel::isMaster(comm))
        {
          Double maxFactor = 0;
          Vce::estimatePsd(ePe, redundancy, Psd, maxFactor);
          logInfo<<"  max. PSD adjustment factor: "<<maxFactor<<Log::endl;
        }
        Parallel::broadCast(Psd, 0, comm);
        copy(CosTransform*Psd, covFunc.column(1, Psd.columns())); // compute new covariance function

        if(Parallel::isMaster(comm) && !fileNameOutCovFunc.empty())
        {
          logStatus<<"write covariance function file <"<<fileNameOutCovFunc<<">"<<Log::endl;
          writeFileMatrix(fileNameOutCovFunc, covFunc);
        }
      }
    } // for(iter)
  }
  catch(std::exception &e)
  {
    GROOPS_RETHROW(e)
  }
}

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

void InstrumentAccelerometerEstimateParameters::computeObservationEquation(UInt arcNo)
{
  try
  {
    AccelerometerArc acc        = accFile.readArc(arcNo);
    AccelerometerArc accSim     = accFileSim.readArc(arcNo);
    OrbitArc         orbit      = orbitFile.readArc(arcNo);
    StarCameraArc    starCamera = starCameraFile.readArc(arcNo);
    Arc::checkSynchronized({acc, accSim, orbit, starCamera});

    const std::vector<Time> times = acc.times();
    parameterAcceleration->setIntervalArc(times.front(), times.back()+medianSampling(times));

    const UInt epochCount = acc.size();
    Vector l(3*epochCount);
    Matrix A(3*epochCount, parameterAcceleration->parameterCount());
    Matrix B(3*epochCount, parameterAcceleration->parameterCountArc());

    for(UInt i=0; i<epochCount; i++)
    {
      Rotary3d rotEarth, rotSat;
      Vector3d position, velocity;
      if(earthRotation)     rotEarth = earthRotation->rotaryMatrix(acc.at(i).time);
      if(starCamera.size()) rotSat   = starCamera.at(i).rotary;
      if(orbit.size())      position = orbit.at(i).position;
      if(orbit.size())      velocity = orbit.at(i).velocity;

      Vector lk = acc.at(i).acceleration.vector();
      if(accSim.size())
        lk -= accSim.at(i).acceleration.vector();
      Matrix Ak(3, parameterAcceleration->parameterCount());
      Matrix Bk(3, parameterAcceleration->parameterCountArc());
      parameterAcceleration->compute(satellite, acc.at(i).time, position, velocity, rotSat, rotEarth, ephemerides, Ak, Bk);

      const Matrix R = (rotEarth*rotSat).matrix();  // rotate into accelerometer frame
      l(i)              = lk(0);
      l(i+epochCount)   = lk(1);
      l(i+2*epochCount) = lk(2);
      if(A.size())
      {
        Ak = R.trans() * Ak;
        copy(Ak.row(0), A.row(i));
        copy(Ak.row(1), A.row(i+epochCount));
        copy(Ak.row(2), A.row(i+2*epochCount));
      }
      if(B.size())
      {
        Bk = R.trans() * Bk;
        copy(Bk.row(0), B.row(i));
        copy(Bk.row(1), B.row(i+epochCount));
        copy(Bk.row(2), B.row(i+2*epochCount));
      }
    }

    observationEquations.at(arcNo).l = l;
    observationEquations.at(arcNo).A = A;
    observationEquations.at(arcNo).B = B;
    observationEquations.at(arcNo).times = times;
  }
  catch(std::exception &e)
  {
    GROOPS_RETHROW(e)
  }
}

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

void InstrumentAccelerometerEstimateParameters::decorrelate(const std::vector<Time> &times, Double sigmaArc, const ObservationSigmaArc &sigmaEpoch,
                                                            std::vector<Matrix> &W, const std::list<MatrixSlice> &A)
{
  try
  {
    std::vector<UInt> index;
    for(const Time &t : times)
      index.push_back(static_cast<UInt>(std::round((t-times.front()).seconds()/sampling)));

    W = std::vector<Matrix>(3, Matrix(times.size(), Matrix::SYMMETRIC, Matrix::UPPER));
    for(UInt idAxis=0; idAxis<3; idAxis++)
    {
      for(UInt i=0; i<times.size(); i++)
        for(UInt k=i; k<times.size(); k++)
          W.at(idAxis)(i, k) = sigmaArc*sigmaArc * covFunc(index.at(k-i), idAxis+1);

      if(sigmaEpoch.size())
        for(UInt i=0; i<times.size(); i++)
            W.at(idAxis)(i, i) += std::pow(sigmaEpoch.at(i).sigma, 2);

      cholesky(W.at(idAxis));
      for(MatrixSliceRef WA : A)
        if(WA.size())
          triangularSolve(1., W.at(idAxis).trans(), WA.row(idAxis*times.size(), times.size()));
    }
  }
  catch(std::exception &e)
  {
    GROOPS_RETHROW(e)
  }
}

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

void InstrumentAccelerometerEstimateParameters::buildNormals(UInt arcNo)
{
  try
  {
    // decorrelate
    Vector Wl = observationEquations.at(arcNo).l;
    Matrix WA = observationEquations.at(arcNo).A;
    Matrix WB = observationEquations.at(arcNo).B;
    std::vector<Matrix> W;
    decorrelate(observationEquations.at(arcNo).times, arcSigmas(arcNo), arcListEpochSigma.at(arcNo), W, {Wl, WA, WB});

    // estimate arc dependent parameters
    Vector tau;
    if(WB.size())
    {
      tau = QR_decomposition(WB);
      QTransMult(WB, tau, Wl); // transform observations: l:= Q'l
      QTransMult(WB, tau, WA); // transform design matrix A:=Q'A
    }
    // use only nullspace of design matrix WB
    MatrixSlice A_bar( WA.row(WB.columns(), WA.rows()-WB.columns()) );
    MatrixSlice l_bar( Wl.row(WB.columns(), Wl.rows()-WB.columns()) );

    // build normals
    this->lPl      += quadsum(l_bar);
    this->obsCount += l_bar.rows();
    matMult(1., A_bar.trans(), l_bar, n);
    rankKUpdate(1., A_bar, N);
  }
  catch(std::exception &e)
  {
    GROOPS_RETHROW(e)
  }
}

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

void InstrumentAccelerometerEstimateParameters::computeRedundancies(UInt arcNo)
{
  try
  {
    Vector We = observationEquations.at(arcNo).l;
    Matrix WA = observationEquations.at(arcNo).A;
    Matrix WB = observationEquations.at(arcNo).B;
    if(WA.size())
      matMult(-1., WA,  x, We);

    std::vector<Matrix> W;
    decorrelate(observationEquations.at(arcNo).times, arcSigmas(arcNo), arcListEpochSigma.at(arcNo), W, {We, WA, WB});

    // estimate & eliminate arc dependent parameters
    // ---------------------------------------------
    if(WB.size())
    {
      Vector tau = QR_decomposition(WB);
      QTransMult(WB, tau, We);           // transform observations: l:= Q'l
      observationEquations.at(arcNo).xArc = We.row(0, tau.rows());
      triangularSolve(1., WB.row(0, tau.rows()), observationEquations.at(arcNo).xArc);
      We.row(0, WB.columns()).setNull(); // residuals: remove WB*x
      QMult(WB, tau, We);                // back transformation

      if(WA.size())
      {
        QTransMult(WB, tau, WA);           // transform design matrix A:=Q'A
        WA.row(0, WB.columns()).setNull(); // residuals: remove WB*x
        QMult(WB, tau, WA);                // back transformation
      }

      generateQ(WB, tau);
      WB.setType(Matrix::GENERAL);
    }

    if(!estimateArcSigmas && !estimateCovarianceFunctionVCE)
      return;

    // Without variance component estimation
    // -------------------------------------
    Matrix WAz(We.rows(), Wz.columns());
    if(WA.size())
      matMult( 1., WA, Wz, WAz);
    if(!estimateCovarianceFunctionVCE)
    {
      const Double redundancy = We.rows() - quadsum(WAz) - quadsum(WB);
      arcSigmasNew(arcNo) = std::sqrt(quadsum(We)/redundancy) * arcSigmas(arcNo);
      return;
    }

    // Variance component estimation
    // -----------------------------
    std::vector<UInt> index;
    for(const Time &t : observationEquations.at(arcNo).times)
      index.push_back(static_cast<UInt>(std::round((t-observationEquations.at(arcNo).times.front()).seconds()/sampling)));
    const UInt countEpoch = observationEquations.at(arcNo).times.size();
    Double ePeSum=0, redundancySum=0;

    for(UInt idAxis=0; idAxis<Psd.columns(); idAxis++)
    {
      Matrix R;
      Vector WWe;
      Vce::redundancy(W.at(idAxis), We.row(idAxis*countEpoch, countEpoch), WAz.row(idAxis*countEpoch, countEpoch), WB.row(idAxis*countEpoch, countEpoch), R, WWe);
      Vce::psd(R, WWe, index, arcSigmas(arcNo), CosTransform, Psd.column(idAxis),
               ePe.column(idAxis), redundancy.column(idAxis), ePeSum, redundancySum);
    }
    arcSigmasNew(arcNo) = std::sqrt(ePeSum/redundancySum) * arcSigmas(arcNo);
  }
  catch(std::exception &e)
  {
    GROOPS_RETHROW(e)
  }
}

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

ObservationSigmaArc InstrumentAccelerometerEstimateParameters::computeEpochSigmas(UInt arcNo)
{
  try
  {
    const Double huber = 2.5;
    const Double threshold2 = std::pow(huber * arcSigmas(arcNo), 2) * sum(covFunc.slice(0, 1, 1, 3));
    const UInt   epochCount = observationEquations.at(arcNo).times.size();

    Vector e = observationEquations.at(arcNo).l;
    if(observationEquations.at(arcNo).A.size())
      matMult(-1.0, observationEquations.at(arcNo).A, x, e);
    if(observationEquations.at(arcNo).B.size())
      matMult(-1, observationEquations.at(arcNo).B, observationEquations.at(arcNo).xArc, e);

    for(UInt i=0; i<epochCount; i++)
    {
      const Double e2 = quadsum(Vector({e(i), e(epochCount+i), e(2*epochCount+i)}));
      arcListEpochSigma.at(arcNo).at(i).sigma = 0.;
      if(e2 > threshold2)
        arcListEpochSigma.at(arcNo).at(i).sigma = std::sqrt((e2-threshold2)/3);
    }

    return arcListEpochSigma.at(arcNo);
  }
  catch(std::exception &e)
  {
    GROOPS_RETHROW(e)
  }
}

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