"""Why a phone needs 4 satellites, and the relativity numbers.
Run: python gps-fix.py   (standard library only)
"""
import math

C = 299_792_458.0          # speed of light, m/s
R_EARTH = 6_371_000.0      # m
R_ORBIT = 26_561_750.0     # m, GPS orbit radius (Ashby 2003)

def unit(lat, lon):
    la, lo = math.radians(lat), math.radians(lon)
    return (math.cos(la) * math.cos(lo), math.cos(la) * math.sin(lo), math.sin(la))

# Four made-up satellites, placed by the point on Earth they are above.
sats = [tuple(R_ORBIT * u for u in unit(la, lo))
        for la, lo in [(10, 5), (50, 20), (-30, 40), (20, -45)]]

me = (R_EARTH, 0.0, 0.0)              # true receiver position
clock_error = 2e-3                    # phone clock is 2 ms off (cheap clock)

def dist(a, b):
    return math.sqrt(sum((p - q) ** 2 for p, q in zip(a, b)))

# What the phone measures: true distance plus clock error times c.
pseudo = [dist(s, me) + C * clock_error for s in sats]

def solve(sats, pseudo, with_clock):
    x = [0.0, 0.0, 0.0, 0.0]          # start at Earth's centre, clock 0
    for _ in range(12):
        rows, res = [], []
        for s, p in zip(sats, pseudo):
            d = dist(s, x[:3])
            rows.append([(x[i] - s[i]) / d for i in range(3)] + [1.0])
            res.append(p - (d + (x[3] if with_clock else 0.0)))
        n = 4 if with_clock else 3
        # normal equations A^T A dx = A^T r, solved by Gaussian elimination
        A = [[sum(r[i] * r[j] for r in rows) for j in range(n)] for i in range(n)]
        b = [sum(r[i] * e for r, e in zip(rows, res)) for i in range(n)]
        for i in range(n):
            piv = max(range(i, n), key=lambda k: abs(A[k][i]))
            A[i], A[piv], b[i], b[piv] = A[piv], A[i], b[piv], b[i]
            for k in range(i + 1, n):
                f = A[k][i] / A[i][i]
                A[k] = [a - f * c for a, c in zip(A[k], A[i])]
                b[k] -= f * b[i]
        dx = [0.0] * n
        for i in reversed(range(n)):
            dx[i] = (b[i] - sum(A[i][j] * dx[j] for j in range(i + 1, n))) / A[i][i]
        for i in range(n):
            x[i] += dx[i]
    return x

x3 = solve(sats[:4], pseudo, with_clock=False)
x4 = solve(sats[:4], pseudo, with_clock=True)
print("ignore the clock: off by %.0f km" % (dist(x3[:3], me) / 1000))
print("solve clock too : off by %.4f m, clock found = %.6f ms" % (dist(x4[:3], me), x4[3] / C * 1000))
print("1 microsecond of clock error = %.0f m of range" % (C * 1e-6))
print("1 nanosecond = %.2f m" % (C * 1e-9))
print("38 microseconds = %.1f km" % (C * 38e-6 / 1000))
print("one-way flight, straight overhead: %.1f ms" % ((R_ORBIT - R_EARTH) / C * 1000))
print("one-way flight, at horizon (approx): %.1f ms" % ((math.sqrt(R_ORBIT**2 - R_EARTH**2)) / C * 1000))

# Relativity (my arithmetic from textbook formulas, per day)
GM = 3.986004418e14
c2 = C * C
R_GEOID = 6_378_137.0
v = math.sqrt(GM / R_ORBIT)
grav = GM / c2 * (1 / R_GEOID - 1 / R_ORBIT)           # satellite clock runs fast
vel = -(v * v) / (2 * c2)                               # satellite clock runs slow
rot = -(7.2921151467e-5 * R_GEOID) ** 2 / (2 * c2)      # ground clock moves with Earth rotation
day = 86400e6
print("orbit speed %.0f m/s" % v)
print("gravity: +%.1f us/day" % (grav * day))
print("speed  : %.1f us/day" % (vel * day))
print("net (with ground rotation): %.1f us/day" % ((grav + vel - rot) * day))
print("net fractional %.4e" % (grav + vel - rot))
print("uncorrected 38.4 us -> %.1f km per day" % (C * 38.4e-6 / 1000))
# signal power
p = 10 ** (-158.5 / 10)
print("-158.5 dBW = %.2e W" % p)
print("a 100 W bulb is %.1e times stronger" % (100 / p))
