Index: trunk/BNC/src/combination/bnccomb.cpp
===================================================================
--- trunk/BNC/src/combination/bnccomb.cpp	(revision 11205)
+++ trunk/BNC/src/combination/bnccomb.cpp	(revision 11212)
@@ -1262,5 +1262,6 @@
   // Update and outlier detection loop
   // ---------------------------------
-  SymmetricMatrix QQ_sav = _QQ[sys];
+  SymmetricMatrix     QQ_sav = _QQ[sys];
+  QVector<t_datumObs> datumObs; // all corrections of the epoch, incl. outliers
   while (_running) {
 
@@ -1273,4 +1274,35 @@
     }
 
+    if (datumObs.isEmpty()) {
+      bool referredAC = false;
+      for (int ii = 0; ii < corrs(sys).size(); ii++) {
+        const cmbCorr* corr = corrs(sys)[ii];
+        t_datumObs dObs;
+        dObs.ac       = corr->_acName;
+        dObs.prn      = corr->_prn;
+        dObs.value    = ll(ii+1) + DotProduct(AA.Row(ii+1), x0);
+        dObs.iAC      = 0;
+        dObs.iSat     = 0;
+        dObs.referred = !_biasInconsistent.contains(corr->_acName + sys) && corr->_refBiasesOK;
+        dObs.rejected = false;
+        referredAC    = referredAC || dObs.referred;
+        for (int iPar = 1; iPar <= nPar; iPar++) {
+          const cmbParam* pp = _params[sys][iPar-1];
+          if      (pp->type == cmbParam::offACgnss && pp->AC == corr->_acName) {
+            dObs.iAC = iPar;
+          }
+          else if (pp->type == cmbParam::clkSat && pp->prn == corr->_prn) {
+            dObs.iSat = iPar;
+          }
+        }
+        datumObs.push_back(dObs);
+      }
+      if (!referredAC) { // as in createAmat: then all clocks define the datum
+        for (t_datumObs& dObs : datumObs) {
+          dObs.referred = true;
+        }
+      }
+    }
+
     dx.ReSize(nPar); dx = 0.0;
     kalman(AA, ll, PP, _QQ[sys], dx);
@@ -1278,6 +1310,7 @@
     ColumnVector vv = ll - AA * dx;
 
+    // outliers among the observations only (not the conditions)
     int     maxResIndex;
-    double  maxRes = vv.maximum_absolute_value1(maxResIndex);
+    double  maxRes = vv.Rows(1, corrs(sys).size()).maximum_absolute_value1(maxResIndex);
     out.setRealNumberNotation(QTextStream::FixedNotation);
     out.setRealNumberPrecision(3);
@@ -1300,4 +1333,10 @@
       _outlierStat[sys][corrs(sys)[maxResIndex-1]->_acName + ' ' +
                         corrs(sys)[maxResIndex-1]->_prn.mid(0,3)].residuals.push_back(maxRes);
+      for (t_datumObs& dObs : datumObs) {
+        if (dObs.ac  == corrs(sys)[maxResIndex-1]->_acName &&
+            dObs.prn == corrs(sys)[maxResIndex-1]->_prn) {
+          dObs.rejected = true;
+        }
+      }
       _QQ[sys] = QQ_sav;
       delete corrs(sys)[maxResIndex-1];
@@ -1317,4 +1356,5 @@
         out.setFieldWidth(0);
       }
+      updateDatum(epoTime, sys, out, datumObs, x0 + dx);
       break;
     }
@@ -1401,6 +1441,9 @@
     // exclusion the offsets are reset and not yet converged, so a single
     // passing check does not prove consistency; a borderline AC would
-    // otherwise change the clock datum every few minutes.
-    const int REINCLUDE_CHECKS = 12;
+    // otherwise change the clock datum every few minutes. Each change of the
+    // datum shifts the combined clocks of the system, so the number of
+    // passing checks required is doubled with each further exclusion of the
+    // AC (up to 16 hours).
+    const int REINCLUDE_CHECKS = 12 << std::min(4, std::max(0, _biasExclusions.value(key) - 1));
     if (spread < MIN_SPREAD || slope < MIN_SLOPE || corrCoeff < MIN_CORR) {
       if (_biasInconsistent.contains(key) && ++_biasConsistentChecks[key] < REINCLUDE_CHECKS) {
@@ -1433,4 +1476,5 @@
     if (!_biasInconsistent.contains(key)) {
       _biasInconsistent.insert(key);
+      ++_biasExclusions[key];
       msg += ", AC excluded from the clock datum";
       _biasCheckWarned.remove(key);
@@ -1515,11 +1559,166 @@
 }
 
+// Robust clock datum
+////////////////////////////////////////////////////////////////////////////
+// A persistent clock difference of one AC for a satellite cannot be absorbed
+// by its satellite offset as long as the offset is in the zero-sum condition
+// of the satellite: either it shifts the combined clock (accepted, e.g. at
+// the start of the filter) or the correction is rejected in every epoch
+// (outlier lock-in), depending on the history of the filter. Therefore, per
+// satellite, the satellite-specific clock difference of each AC referred to
+// the reference signals
+//   u = clock - AC offset - combined clock
+// (rejected corrections included) is compared with the median of the ACs.
+// An offset rejected as outlier for DATUM_OUT_SEC leaves the zero-sum
+// conditions (satellite and AC) and is re-initialized: it then absorbs the
+// constant difference, and the AC contributes to the variation of the
+// combined clock only. This applies to any number of ACs, as long as another
+// offset of the satellite stays in the datum (otherwise a rejected offset in
+// the datum would shift the combined clock). For satellites with at least
+// DATUM_MIN_AC ACs, an offset deviating by more than DATUM_OUT_DEV for
+// DATUM_OUT_SEC leaves as well, as long as a majority of the ACs stays in.
+// An offset rejoins the datum after a deviation below DATUM_IN_DEV (at most
+// half of the maximum residual) without rejection for DATUM_IN_SEC. ACs not
+// referred to the reference signals are excluded from the datum anyway and
+// not judged.
+////////////////////////////////////////////////////////////////////////////
+void bncComb::updateDatum(bncTime epoTime, char sys, QTextStream& out,
+                          const QVector<t_datumObs>& datumObs, const ColumnVector& xx) {
+
+  const int    DATUM_MIN_AC  = 3;
+  const double DATUM_OUT_DEV = std::min(0.5, _MAX_RES); // [m]
+  const double DATUM_OUT_SEC = 60.0;
+  const double DATUM_IN_DEV  = 0.5 * DATUM_OUT_DEV;       // [m]
+  const double DATUM_IN_SEC  = 600.0;
+  const double DATUM_FORGET  = 3600.0; // state of offsets not provided for this time is dropped
+
+  QMap<QString, t_datumState>& states = _datumState[sys];
+
+  // parameters observed by accepted corrections
+  QSet<int> observed;
+  for (const t_datumObs& dObs : datumObs) {
+    if (!dObs.rejected) {
+      observed << dObs.iAC << dObs.iSat;
+    }
+  }
+
+  // satellite-specific clock differences per satellite
+  QMap<QString, QVector<const t_datumObs*> > satObs;
+  QMap<QString, double> uu; // key "AC PRN"
+  for (const t_datumObs& dObs : datumObs) {
+    QString key = dObs.ac + ' ' + dObs.prn;
+    states[key].lastSeen = epoTime;
+    states[key].referred = dObs.referred;
+    if (dObs.referred && dObs.iAC && dObs.iSat &&
+        observed.contains(dObs.iAC) && observed.contains(dObs.iSat)) {
+      uu[key] = dObs.value - xx(dObs.iAC) - xx(dObs.iSat);
+      satObs[dObs.prn].push_back(&dObs);
+    }
+  }
+
+  QMapIterator<QString, QVector<const t_datumObs*> > itSat(satObs);
+  while (itSat.hasNext()) {
+    itSat.next();
+    const QVector<const t_datumObs*>& obs = itSat.value();
+    const bool robust = (obs.size() >= DATUM_MIN_AC); // median meaningful
+    QVector<double> uSat;
+    for (const t_datumObs* dObs : obs) {
+      uSat.push_back(uu[dObs->ac + ' ' + dObs->prn]);
+    }
+    std::sort(uSat.begin(), uSat.end());
+    int    nn     = uSat.size();
+    double median = (nn % 2) ? uSat[nn/2] : 0.5 * (uSat[nn/2-1] + uSat[nn/2]);
+
+    // a majority of the ACs stays in the datum (e.g. two groups of ACs with
+    // a clock difference: the median is not meaningful); the offsets with the
+    // largest deviations leave first
+    const int minIn  = std::max(2, (nn + 1) / 2);
+    int       numIn  = 0;
+    QVector<const t_datumObs*> order = obs;
+    for (const t_datumObs* dObs : obs) {
+      QString key = dObs->ac + ' ' + dObs->prn;
+      states[key].dev = uu[key] - median;
+      if (!states[key].out) {
+        ++numIn;
+      }
+    }
+    std::stable_sort(order.begin(), order.end(),
+                     [&states](const t_datumObs* aa, const t_datumObs* bb) {
+                       return fabs(states[aa->ac + ' ' + aa->prn].dev) >
+                              fabs(states[bb->ac + ' ' + bb->prn].dev);
+                     });
+
+    for (const t_datumObs* dObs : order) {
+      QString       key   = dObs->ac + ' ' + dObs->prn;
+      t_datumState& state = states[key];
+      bool change = state.out ? (fabs(state.dev) < DATUM_IN_DEV && !dObs->rejected)
+                              : (dObs->rejected || (robust && fabs(state.dev) > DATUM_OUT_DEV));
+      if (!change) {
+        state.since.reset();
+        continue;
+      }
+      if (!state.since.valid()) {
+        state.since = epoTime;
+      }
+      double duration = epoTime - state.since;
+      if (duration < (state.out ? DATUM_IN_SEC : DATUM_OUT_SEC)) {
+        continue;
+      }
+      // a rejected offset leaves as long as another one stays in, a deviating
+      // (accepted) one only as long as a majority stays in
+      if (!state.out && numIn - 1 < (dObs->rejected ? 1 : minIn)) {
+        continue;
+      }
+      QString msg;
+      if (!state.out) {
+        --numIn;
+        state.out      = true;
+        state.outSince = epoTime;
+        msg = QString("%1 %2 out of the clock datum: deviation %3 m from the median of %4 ACs%5")
+              .arg(dObs->ac).arg(dObs->prn.mid(0,3))
+              .arg(state.dev, 0, 'f', 2).arg(nn)
+              .arg(dObs->rejected ? QString(", rejected as outlier for %1 s").arg(duration, 0, 'f', 0) : QString());
+        // re-initialize the offset: it absorbs the difference from now on
+        for (int iPar = 1; iPar <= _params[sys].size(); iPar++) {
+          cmbParam* pp = _params[sys][iPar-1];
+          if (pp->type == cmbParam::offACSat && pp->AC == dObs->ac && pp->prn == dObs->prn) {
+            _QQ[sys].Row(iPar)    = 0.0;
+            _QQ[sys].Column(iPar) = 0.0;
+            _QQ[sys](iPar,iPar)   = pp->sig0 * pp->sig0;
+          }
+        }
+      }
+      else {
+        ++numIn;
+        state.out = false;
+        msg = QString("%1 %2 back in the clock datum: deviation %3 m from the median of %4 ACs "
+                      "(below %5 m for %6 s)")
+              .arg(dObs->ac).arg(dObs->prn.mid(0,3))
+              .arg(state.dev, 0, 'f', 2).arg(nn)
+              .arg(DATUM_IN_DEV, 0, 'f', 2).arg(duration, 0, 'f', 0);
+      }
+      state.since.reset();
+      out << epoTime.datestr().c_str() << " " << epoTime.timestr().c_str() << " " << msg << "\n";
+      emit newLogRecord(t_logRecord::message(t_logRecord::info, "bncComb: " + msg.toLatin1()), true);
+    }
+  }
+
+  // drop the state of offsets no longer provided
+  QMutableMapIterator<QString, t_datumState> itState(states);
+  while (itState.hasNext()) {
+    itState.next();
+    if (epoTime - itState.value().lastSeen > DATUM_FORGET) {
+      itState.remove();
+    }
+  }
+}
+
 // Report AC satellites rejected as outliers in most epochs
 ////////////////////////////////////////////////////////////////////////////
-// A persistent clock difference of one AC for a satellite cannot be absorbed
-// by its satellite offset, as the offsets of all ACs of the satellite sum up
-// to zero: the correction is rejected again in every epoch. Once per hour
-// and system, AC satellites rejected in at least half of their epochs are
-// reported.
+// Corrections of an AC for a satellite can still be rejected persistently,
+// e.g. for satellites with fewer than DATUM_MIN_AC ACs (see updateDatum) or
+// for noisy clocks. Once per hour and system, AC satellites rejected in at
+// least half of their epochs are reported, as well as the offsets out of
+// the clock datum.
 ////////////////////////////////////////////////////////////////////////////
 void bncComb::checkPersistentOutliers(bncTime epoTime, char sys, QTextStream& out) {
@@ -1552,4 +1751,21 @@
     out << epoTime.datestr().c_str() << " " << epoTime.timestr().c_str() << " " << msg << "\n";
     emit newLogRecord(t_logRecord::message(t_logRecord::warning, "bncComb: " + msg.toLatin1()), true);
+  }
+  QStringList outList;
+  QMapIterator<QString, t_datumState> itState(_datumState[sys]);
+  while (itState.hasNext()) {
+    itState.next();
+    const t_datumState& state = itState.value();
+    if (state.out) {
+      QStringList hlp = itState.key().split(' ');
+      outList << QString("%1 %2 (%3 m, since %4 %5)")
+                 .arg(hlp[0]).arg(hlp[1].mid(0,3)).arg(state.dev, 0, 'f', 2)
+                 .arg(state.outSince.datestr().c_str()).arg(state.outSince.timestr(0).c_str());
+    }
+  }
+  if (!outList.isEmpty()) {
+    QString msg = QString("%1 satellite offsets out of the clock datum: ").arg(sys) + outList.join(", ");
+    out << epoTime.datestr().c_str() << " " << epoTime.timestr().c_str() << " " << msg << "\n";
+    emit newLogRecord(t_logRecord::message(t_logRecord::info, "bncComb: " + msg.toLatin1()), true);
   }
   _outlierStat[sys].clear();
@@ -1870,4 +2086,23 @@
   }
 
+  // Offsets out of the robust clock datum (see updateDatum) and the nominal
+  // datum per satellite: offsets in the datum, provided within the last hour
+  QSet<QString>                outOfDatum;   // "AC PRN" (full PRN)
+  QMap<QString, QSet<QString> > nominalDatum; // PRN -> "AC PRN"
+  if (_method == filter) {
+    QMapIterator<QString, t_datumState> itState(_datumState[sys]);
+    while (itState.hasNext()) {
+      itState.next();
+      const t_datumState& state = itState.value();
+      if (state.out) {
+        outOfDatum.insert(itState.key());
+      }
+      else if (state.referred &&
+               !_biasInconsistent.contains(itState.key().section(' ', 0, 0) + sys)) {
+        nominalDatum[itState.key().section(' ', 1, 1)].insert(itState.key());
+      }
+    }
+  }
+
   // ACs of this epoch, each with a zero-sum condition of its satellite offsets
   QStringList epoACs;
@@ -1951,4 +2186,6 @@
    // }
     int iCond = 1;
+    QSet<int>     incrementRows; // conditions on the increments (continuity)
+    QSet<int>     offIncrement;  // offsets in satellite conditions on the increments
     QSet<int>     offExcluded; // offsets excluded from the zero-sum condition of their satellite
     QSet<int>     offInDatum;  // offsets in the zero-sum condition of their satellite
@@ -1960,5 +2197,6 @@
       ++iCond;
       PP(nObs+iCond) = Ph;
-      QList<int> offAll, offConsistent;
+      QList<int>    offAll, offConsistent, offRobust;
+      QSet<QString> robustKeys;
       for (int iPar = 1; iPar <= _params[sys].size(); iPar++) {
         cmbParam* pp = _params[sys][iPar-1];
@@ -1970,11 +2208,46 @@
           if (!excludedOff.contains(pp->AC + ' ' + pp->prn)) {
             offConsistent << iPar;
+            if (!outOfDatum.contains(pp->AC + ' ' + pp->prn)) {
+              offRobust << iPar;
+              robustKeys.insert(pp->AC + ' ' + pp->prn);
+            }
           }
         }
       }
-      // satellite observed by inconsistent ACs only: all its offsets are used
-      const QList<int>& offUsed = offConsistent.isEmpty() ? offAll : offConsistent;
+      // The condition refers to the values of the offsets (see below) only if
+      // all offsets of the nominal datum of the satellite are present. If one
+      // of them is missing in this epoch (data gap of the AC, correction
+      // rejected as outlier in this iteration), the sum of the present ones
+      // is kept (condition on the increments): otherwise the gap would shift
+      // the combined clock by the offsets of the remaining ACs.
+      const QSet<QString>& nominal = nominalDatum[prn];
+      bool complete = true;
+      for (const QString& key : nominal) {
+        if (!robustKeys.contains(key)) {
+          complete = false;
+          break;
+        }
+      }
+      if (!complete) {
+        incrementRows.insert(iCond);
+        for (int iPar : offRobust) {
+          offIncrement << iPar;
+        }
+      }
+      // satellite observed by inconsistent ACs only: all its offsets are used;
+      // all consistent offsets out of the robust datum: these are used. If
+      // the nominal datum of the satellite is missing completely, the offsets
+      // out of the datum only keep their sum (increments, see above) and are
+      // not used in the conditions of their ACs: they must not define the
+      // clock datum (their differences to the datum ACs are the reason for
+      // their exclusion).
+      const bool keepOnly = offRobust.isEmpty() && !nominal.isEmpty();
+      const QList<int>& offUsed = !offRobust.isEmpty()     ? offRobust     :
+                                  !offConsistent.isEmpty() ? offConsistent : offAll;
       for (int iPar : offAll) {
-        if (offUsed.contains(iPar)) {
+        if (keepOnly && offUsed.contains(iPar)) {
+          AA(nObs+iCond, iPar) = 1.0;
+        }
+        else if (offUsed.contains(iPar)) {
           AA(nObs+iCond, iPar) = 1.0;
           offInDatum << iPar;
@@ -2002,5 +2275,21 @@
         if (_params[sys][iPar-1]->AC == acName) {
           AA(nObs+iCond, iPar) = 1.0;
-        }
+          // an offset kept by its satellite condition (increments) cannot
+          // follow a condition of the AC on the values: both on the increments
+          if (offIncrement.contains(iPar)) {
+            incrementRows.insert(iCond);
+          }
+        }
+      }
+    }
+    // The conditions refer to the parameter values, not to their increments:
+    // with ll = 0, a sum would keep its value of the previous epoch, which
+    // differs from zero after a change of the offsets in the condition (an
+    // offset out of or back in the datum, a satellite no longer provided by
+    // an AC for more than an hour), leaving the datum to the history of the
+    // filter. Exception: incomplete nominal datum of a satellite (see above).
+    for (int iCon = 1; iCon <= nCon; iCon++) {
+      if (!incrementRows.contains(iCon)) {
+        ll(nObs+iCon) = -DotProduct(AA.Row(nObs+iCon), x0);
       }
     }
