# The highest elevation mask at which each candidate site keeps at least `min_visible` satellites
# in view for `share` of a day. Run with:
#   program_run {project, name: "Highest mask per site", inputs: {fleet: <movers layer>, sites: <points layer>},
#                source: <this file>}
# One propagation, then one visibility per mask: 10 Engine calls, no model turn per step.
# Units: masks in deg, duration and step in s, times UTC. Positions come from the Engine, never from here.
import math

p = dk.params(
    model="j2",  # use sgp4 for a catalogue GP set
    min_visible=2,  # satellites that must be in view
    share=0.99,  # of the samples, 0 to 1
    masks=[0, 5, 10, 15, 20, 25, 30, 35, 40],  # deg, tried in order
    duration=86400,  # s
    step=120,  # s, at least; a gap shorter than the step is not seen
)
fleet, sites = dk.layer("fleet"), dk.layer("sites")

# A propagation holds at most 5,000,000 samples (satellites x instants) and each visibility at most 50,000,000 tests
# (sites x satellites x instants), its counts included (describe {topic:"limits"}): the step must fit both. A 50 million
# test visibility took about 15 s of Engine CPU on one core, inside the 30 s a program's Engine call may run, so the
# 9 masks stay inside Pro's 300 s of Engine time a run.
SAMPLES_MAX, TESTS_MAX = 5_000_000, 50_000_000
n, s = fleet.rows, sites.rows
if n * s >= TESTS_MAX:
    raise ValueError(f"{n} satellites x {s} sites exceed {TESTS_MAX:,} tests at a single instant: declare fewer sites")
step = max(p["step"], math.ceil(p["duration"] * n / (SAMPLES_MAX - n)),
           math.ceil(p["duration"] * n * s / (TESTS_MAX - n * s)))

# dk.clock: the project clock captured when source, params or refresh was last sent, never wall time.
# Select SGP4 for a GP set, J2 for a design: a declared layer handed to a function directly would get SGP4.
eph = dk.engine.propagate(fleet, start=dk.clock.start, duration=p["duration"], step=step, model=p["model"])

best = {}
for mask in p["masks"]:
    vis = dk.engine.visibility(eph, stations=sites, min_elevation=mask)  # radio refraction, the default
    v = vis.visibility.df()  # station_id, time, visible (a count); no pair limit, but the 50 million tests above
    ok = (v.visible >= p["min_visible"]).groupby(v.station_id).mean() >= p["share"]
    best.update({station: mask for station in ok[ok].index})

table = sites.df()
table["mask"] = table.site_id.map(best).fillna(-1)  # -1: not even the lowest mask holds

dk.emit.points(table, key="site_id", color_by="mask", name="Highest mask")
dk.emit.table(table[["site_id", "mask"]], slot="table", title="Highest mask per site", units={"mask": "deg"})
dk.emit.chart(slot="table", x="site_id", y=["mask"], kind="bar")
dk.result({
    "best": table.nlargest(3, "mask").site_id.tolist(),
    "none": int((table["mask"] < 0).sum()),
    "criterion": f">= {p['min_visible']} in view for {p['share']:.0%} of {p['duration']} s at a {step} s step, radio refraction",
})
print("sites", len(table), "with a mask", int((table["mask"] >= 0).sum()))
