#!/usr/bin/env python3
"""Common jumps of the satellite clocks of a clock RINEX file, per system.

usage: clkjumps.py <clock RINEX file> [threshold_m]   (default 0.1 m)

For each satellite the change between consecutive epochs is reduced by the
median change of the neighbouring epochs (clock drift); the median of these
reduced changes over the satellites of a system is the common jump of the
epoch. Epochs with a common jump above the threshold are listed, e.g. a shift
of all BDS clocks of a combination when the set of combined satellites
changes (test case combi_bds_level).
"""
import sys, collections, statistics

C = 299792458.0


def main():
    path = sys.argv[1]
    thr = float(sys.argv[2]) if len(sys.argv) > 2 else 0.1
    clk = collections.defaultdict(dict)  # prn -> {epoch seconds: clock [m]}
    for line in open(path):
        if not line.startswith('AS '):
            continue
        p = line.split()
        h, m, s = int(p[5]), int(p[6]), float(p[7])
        clk[p[1]][int(p[4]) * 86400 + h * 3600 + m * 60 + s] = float(p[9]) * C

    reduced = collections.defaultdict(list)  # (system, epoch) -> reduced changes
    for prn, d in clk.items():
        ts = sorted(d)
        steps = [(b, d[b] - d[a]) for a, b in zip(ts, ts[1:]) if 0.0 < b - a <= 30.0]
        for i, (t, v) in enumerate(steps):
            window = [x for _, x in steps[max(0, i - 6):i + 7]]
            reduced[(prn[0], t)].append(v - statistics.median(window))

    found = False
    for (sysc, t), values in sorted(reduced.items()):
        if len(values) < 5:
            continue
        jump = statistics.median(values)
        if abs(jump) > thr:
            found = True
            t = int(round(t)) % 86400
            print('%s %02d:%02d:%02d common jump %+.2f m (%d satellites)'
                  % (sysc, t // 3600, t % 3600 // 60, t % 60, jump, len(values)))
    if not found:
        print('no common clock jumps > %.2f m' % thr)


if __name__ == '__main__':
    main()
