Index: trunk/BNC/src/orbComp/sp3Comp.cpp
===================================================================
--- trunk/BNC/src/orbComp/sp3Comp.cpp	(revision 11158)
+++ trunk/BNC/src/orbComp/sp3Comp.cpp	(revision 11228)
@@ -35,5 +35,7 @@
  * Created:    24-Nov-2014
  *
- * Changes:
+ * Changes:    26-Nov-2026: optional clock RINEX files (sp3CompClkFile): clocks
+ *                           and SIS at the epochs of the clock files, orbits
+ *                           interpolated between the SP3 epochs
  *
  * -----------------------------------------------------------------------*/
@@ -41,5 +43,7 @@
 #include <QRegularExpression>
 #include <iostream>
+#include <fstream>
 #include <iomanip>
+#include <algorithm>
 #include "sp3Comp.h"
 #include "bnccore.h"
@@ -58,4 +62,17 @@
   for (int ii = 0; ii < _sp3FileNames.size(); ii++) {
     expandEnvVar(_sp3FileNames[ii]);
+  }
+  // Clock RINEX files, in the order of the SP3 files; one name refers to
+  // SP3 file 1, an empty entry or "-" to no clock file
+  QString clkFiles = settings.value("sp3CompClkFile").toString().trimmed();
+  if (!clkFiles.isEmpty()) {
+    _clkFileNames = clkFiles.split(",", Qt::KeepEmptyParts);
+    for (int ii = 0; ii < _clkFileNames.size(); ii++) {
+      _clkFileNames[ii] = _clkFileNames[ii].trimmed();
+      if (_clkFileNames[ii] == "-") {
+        _clkFileNames[ii].clear();
+      }
+      expandEnvVar(_clkFileNames[ii]);
+    }
   }
   _logFileName = settings.value("sp3CompOutLogFile").toString(); expandEnvVar(_logFileName);
@@ -94,6 +111,15 @@
     *_log << "! SP3 File " << ii+1 << ": " << _sp3FileNames[ii] << "\n";
   }
+  for (int ii = 0; ii < _clkFileNames.size(); ii++) {
+    if (!_clkFileNames[ii].isEmpty()) {
+      *_log << "! CLK File " << ii+1 << ": " << _clkFileNames[ii] << "\n";
+    }
+  }
   if (_sp3FileNames.size() != 2) {
     *_log << "ERROR: sp3Comp requires two input SP3 files" << "\n";
+    goto end;
+  }
+  if (_clkFileNames.size() > 2) {
+    *_log << "ERROR: sp3Comp accepts at most two clock RINEX files" << "\n";
     goto end;
   }
@@ -280,36 +306,47 @@
 void t_sp3Comp::compare(ostringstream& out) const {
 
-  // Synchronize reading of two sp3 files
-  // ------------------------------------
-  bncSP3 in1(_sp3FileNames[0]); in1.nextEpoch();
-  bncSP3 in2(_sp3FileNames[1]); in2.nextEpoch();
+  // Read the SP3 files (and clock RINEX files)
+  // -------------------------------------------
+  t_sp3Data sp3[2];
+  map<bncTime, map<t_prn, double> > clk[2];
+  bool withClkFiles = false;
+  for (int ii = 0; ii < 2; ii++) {
+    readSp3(_sp3FileNames[ii], sp3[ii]);
+    if (ii < _clkFileNames.size() && !_clkFileNames[ii].isEmpty()) {
+      readClk(_clkFileNames[ii], clk[ii]);
+      withClkFiles = true;
+      if (clk[ii].empty()) {
+        throw "t_sp3Comp: no clocks in clock RINEX file " + string(_clkFileNames[ii].toLatin1().data());
+      }
+    }
+    else {
+      clk[ii] = sp3[ii]._clk;
+    }
+  }
 
   vector<t_epoch*> epochs;
-  while (in1.currEpoch() && in2.currEpoch()) {
-    bncTime t1 = in1.currEpoch()->_tt;
-    bncTime t2 = in2.currEpoch()->_tt;
-    if      (t1 < t2) {
-      in1.nextEpoch();
-    }
-    else if (t1 > t2) {
-      in2.nextEpoch();
-    }
-    else if (t1 == t2) {
-      t_epoch* epo = new t_epoch; epo->_tt = t1;
-      bool epochOK = false;
-      for (int i1 = 0; i1 < in1.currEpoch()->_sp3Sat.size(); i1++) {
-        bncSP3::t_sp3Sat* sat1 = in1.currEpoch()->_sp3Sat[i1];
-        for (int i2 = 0; i2 < in2.currEpoch()->_sp3Sat.size(); i2++) {
-          bncSP3::t_sp3Sat* sat2 = in2.currEpoch()->_sp3Sat[i2];
-          if (sat1->_prn == sat2->_prn &&
-              sat1->_clkValid && sat2->_clkValid) {
-            epochOK = true;
-            epo->_dr[sat1->_prn]  = sat1->_xyz - sat2->_xyz;
-            epo->_xyz[sat1->_prn] = sat1->_xyz;
-            epo->_dc[sat1->_prn]  = sat1->_clk - sat2->_clk;
-          }
-        }
-      }
-      if (epochOK) {
+  if (!withClkFiles) {
+    // Common epochs of the two SP3 files, satellites with valid clocks in both
+    // -------------------------------------------------------------------------
+    map<bncTime, map<t_prn, ColumnVector> >::const_iterator it1;
+    for (it1 = sp3[0]._xyz.begin(); it1 != sp3[0]._xyz.end(); it1++) {
+      const bncTime& tt = it1->first;
+      map<bncTime, map<t_prn, ColumnVector> >::const_iterator it2 = sp3[1]._xyz.find(tt);
+      if (it2 == sp3[1]._xyz.end()) {
+        continue;
+      }
+      const map<t_prn, double>& c1 = clk[0][tt];
+      const map<t_prn, double>& c2 = clk[1][tt];
+      t_epoch* epo = new t_epoch; epo->_tt = tt;
+      for (map<t_prn, ColumnVector>::const_iterator is = it1->second.begin(); is != it1->second.end(); is++) {
+        const t_prn& prn = is->first;
+        map<t_prn, ColumnVector>::const_iterator jj = it2->second.find(prn);
+        if (jj != it2->second.end() && c1.find(prn) != c1.end() && c2.find(prn) != c2.end()) {
+          epo->_dr[prn]  = is->second - jj->second;
+          epo->_xyz[prn] = is->second;
+          epo->_dc[prn]  = c1.find(prn)->second - c2.find(prn)->second;
+        }
+      }
+      if (epo->_dc.size() > 0) {
         epochs.push_back(epo);
       }
@@ -317,6 +354,43 @@
         delete epo;
       }
-      in1.nextEpoch();
-      in2.nextEpoch();
+    }
+  }
+  else {
+    // Common epochs of the two clock sources; the orbits are interpolated
+    // between the SP3 epochs where necessary and then used for the clock
+    // comparison and the SIS only (orbit statistics: common SP3 epochs)
+    // ---------------------------------------------------------------------
+    map<bncTime, map<t_prn, double> >::const_iterator it1;
+    for (it1 = clk[0].begin(); it1 != clk[0].end(); it1++) {
+      const bncTime& tt = it1->first;
+      map<bncTime, map<t_prn, double> >::const_iterator it2 = clk[1].find(tt);
+      if (it2 == clk[1].end()) {
+        continue;
+      }
+      t_epoch* epo = new t_epoch; epo->_tt = tt;
+      for (map<t_prn, double>::const_iterator is = it1->second.begin(); is != it1->second.end(); is++) {
+        const t_prn& prn = is->first;
+        map<t_prn, double>::const_iterator jj = it2->second.find(prn);
+        if (jj == it2->second.end()) {
+          continue;
+        }
+        ColumnVector xyz1, xyz2;
+        bool interp1, interp2;
+        if (!orbit(sp3[0], prn, tt, xyz1, interp1) || !orbit(sp3[1], prn, tt, xyz2, interp2)) {
+          continue;
+        }
+        epo->_dr[prn]  = xyz1 - xyz2;
+        epo->_xyz[prn] = xyz1;
+        epo->_dc[prn]  = is->second - jj->second;
+        if (interp1 || interp2) {
+          epo->_orbInterp.insert(prn);
+        }
+      }
+      if (epo->_dc.size() > 0) {
+        epochs.push_back(epo);
+      }
+      else {
+        delete epo;
+      }
     }
   }
@@ -413,8 +487,10 @@
               << setw(7) << setprecision(4) << rao[2] << "    ";
         }
-        stat[prn.toString()]._rao += SP(rao, rao); // Schur product
-        stat[all.str()     ]._rao += SP(rao, rao);
-        stat[prn.toString()]._nr  += 1;
-        stat[all.str()     ]._nr  += 1;
+        if (epo->_orbInterp.find(prn) == epo->_orbInterp.end()) {
+          stat[prn.toString()]._rao += SP(rao, rao); // Schur product
+          stat[all.str()     ]._rao += SP(rao, rao);
+          stat[prn.toString()]._nr  += 1;
+          stat[all.str()     ]._nr  += 1;
+        }
         if (dc.find(prn) != dc.end() && dcRed.find(prn) != dc.end()) {
           double clkRes    = dc.find(prn)->second;
@@ -482,9 +558,11 @@
     char sys = prn[0];
     stringstream all; all << sys << 99;
-    if (stat._nr > 0) {
-      stat._rao[0] = sqrt(stat._rao[0] / stat._nr);
-      stat._rao[1] = sqrt(stat._rao[1] / stat._nr);
-      stat._rao[2] = sqrt(stat._rao[2] / stat._nr);
-      stat._rao3DRMS = stat._rao.NormFrobenius();
+    if (stat._nr > 0 || stat._nc > 0) {
+      if (stat._nr > 0) {
+        stat._rao[0] = sqrt(stat._rao[0] / stat._nr);
+        stat._rao[1] = sqrt(stat._rao[1] / stat._nr);
+        stat._rao[2] = sqrt(stat._rao[2] / stat._nr);
+        stat._rao3DRMS = stat._rao.NormFrobenius();
+      }
       // orbit values in millimeter
       if (prn != all.str()) {
@@ -529,4 +607,139 @@
 }
 
+// Read an SP3 file (positions, valid clocks, orbit series per satellite)
+////////////////////////////////////////////////////////////////////////////
+void t_sp3Comp::readSp3(const QString& fileName, t_sp3Data& data) const {
+  bncSP3 in(fileName);
+  bncTime lastTime;
+  while (const bncSP3::t_sp3Epoch* epo = in.nextEpoch()) {
+    const bncTime& tt = epo->_tt;
+    if (lastTime.valid()) {
+      double dt = tt - lastTime;
+      if (dt > 0.0 && (data._sampl == 0.0 || dt < data._sampl)) {
+        data._sampl = dt;
+      }
+    }
+    lastTime = tt;
+    map<t_prn, ColumnVector>& xyz = data._xyz[tt];
+    for (int ii = 0; ii < epo->_sp3Sat.size(); ii++) {
+      const bncSP3::t_sp3Sat* sat = epo->_sp3Sat[ii];
+      xyz[sat->_prn] = sat->_xyz;
+      if (sat->_clkValid) {
+        data._clk[tt][sat->_prn] = sat->_clk;
+      }
+    }
+  }
+  map<bncTime, map<t_prn, ColumnVector> >::const_iterator it;
+  for (it = data._xyz.begin(); it != data._xyz.end(); it++) {
+    map<t_prn, ColumnVector>::const_iterator is;
+    for (is = it->second.begin(); is != it->second.end(); is++) {
+      t_orbSeries& series = data._series[is->first];
+      series._tt.push_back(it->first);
+      series._xyz.push_back(is->second);
+    }
+  }
+}
+
+// Read the satellite clocks (AS records) of a clock RINEX file [m]
+////////////////////////////////////////////////////////////////////////////
+void t_sp3Comp::readClk(const QString& fileName,
+                        map<bncTime, map<t_prn, double> >& clk) const {
+  ifstream in(fileName.toLocal8Bit().data());
+  if (!in.good()) {
+    throw "t_sp3Comp: cannot open clock RINEX file " + string(fileName.toLatin1().data());
+  }
+  string line;
+  bool header = true;
+  while (getline(in, line)) {
+    if (header) {
+      if (line.find("END OF HEADER") != string::npos) {
+        header = false;
+      }
+      continue;
+    }
+    if (line.compare(0, 3, "AS ") != 0) {   // other records, continuation lines
+      continue;
+    }
+    replace(line.begin(), line.end(), 'D', 'E');   // Fortran exponent
+    replace(line.begin(), line.end(), 'd', 'E');
+    istringstream inLine(line.substr(3));
+    string prnStr;
+    int    YY, MM, DD, hh, mm, numValues;
+    double ss, value;
+    inLine >> prnStr >> YY >> MM >> DD >> hh >> mm >> ss >> numValues >> value;
+    if (inLine.fail() || numValues < 1 || prnStr.size() < 3) {
+      continue;
+    }
+    t_prn prn;
+    try {
+      prn.set(prnStr);
+    }
+    catch (...) {        // satellite system not supported
+      continue;
+    }
+    if (prn.number() == 0) {
+      continue;
+    }
+    bncTime tt; tt.set(YY, MM, DD, hh, mm, ss);
+    clk[tt][prn] = value * t_CST::c;
+  }
+}
+
+// Satellite position at epoch tt: the SP3 position if tt is an SP3 epoch,
+// otherwise Lagrange interpolation with 10 consecutive SP3 epochs around tt
+// (no extrapolation, no data gaps longer than 1.5 sampling intervals)
+////////////////////////////////////////////////////////////////////////////
+bool t_sp3Comp::orbit(const t_sp3Data& data, const t_prn& prn, const bncTime& tt,
+                      ColumnVector& xyz, bool& interpolated) const {
+  const unsigned NUMNODES = 10;
+  interpolated = false;
+  map<t_prn, t_orbSeries>::const_iterator itS = data._series.find(prn);
+  if (itS == data._series.end()) {
+    return false;
+  }
+  const t_orbSeries& series = itS->second;
+  const vector<bncTime>& times = series._tt;
+  vector<bncTime>::const_iterator it = lower_bound(times.begin(), times.end(), tt);
+  if (it != times.end() && *it == tt) {
+    xyz = series._xyz[it - times.begin()];
+    return true;
+  }
+  if (it == times.begin() || it == times.end() || data._sampl <= 0.0) {
+    return false;
+  }
+  const double maxGap = 1.5 * data._sampl;
+  int lo = (it - times.begin()) - 1;
+  int hi = lo + 1;
+  if (times[hi] - times[lo] > maxGap) {
+    return false;
+  }
+  // extend the window alternately to both sides
+  while (unsigned(hi - lo + 1) < NUMNODES) {
+    bool left  = (lo > 0 && times[lo] - times[lo-1] <= maxGap);
+    bool right = (hi < int(times.size()) - 1 && times[hi+1] - times[hi] <= maxGap);
+    if (!left && !right) {
+      return false;
+    }
+    if (left && (!right || (tt - times[lo]) <= (times[hi] - tt))) {
+      --lo;
+    }
+    else {
+      ++hi;
+    }
+  }
+  xyz.ReSize(3); xyz = 0.0;
+  for (int ii = lo; ii <= hi; ii++) {
+    double weight = 1.0;
+    for (int jj = lo; jj <= hi; jj++) {
+      if (jj != ii) {
+        weight *= (tt - times[jj]) / (times[ii] - times[jj]);
+      }
+    }
+    xyz += weight * series._xyz[ii];
+  }
+  interpolated = true;
+  return true;
+}
+
 //
 ////////////////////////////////////////////////////////////////////////////
