# Recipe: which satellite serves each terminal

"These 200 terminals: which Starlink satellite serves each over the next 6 hours, with handovers."

This is the `links` function with model `ground` over a points layer. Never write one entity per terminal, and never compute the geometry yourself.

## 1. Bring the terminals and the constellation

```json
{"verb":"data_put","args":{"project":"P","items":[
  {"id":"terminals","content":"site_id,latitude,longitude\nt001,48.85,2.35\n...","format":"csv","columns":{"id":"site_id"}},
  {"id":"starlink","ref":{"kind":"satellite-set","id":"<from data_find>"}}]}}
```
`site_id` keys each terminal (`terminals/t001`). The answer lists the columns it read with their units. A terminal without an `altitude` column is placed at 0 m above sea level, not on the ground; give an `altitude` column in m above sea level for terminals on high ground. Terminals are custom data; the satellites are catalogue data. Say both.

## 2. Size it

Work is terminals x satellites x instants and must stay under the `links` limit (`describe {topic:"limits"}`, `ground_link_work`: 50,000,000 tests today). Read the satellite count from the starlink layer's `rows`.

- 200 x 6 x 361 (a 6-satellite set, 6 h at 60 s) = 433,200: one call (3a).
- 200 x 9,000 x 361 (a full Starlink set) = 650 million, 13 times the limit. A coarser step does not close the gap (600 s is still 67 million, and hides every handover). Send batches of terminals in a program (3b).

A program's Engine call stops after 30 s, and a run has 300 s of Engine time on Pro (`describe {topic:"limits"}`, `engine_s`). Measured on one core, `links` runs about 2 million tests a CPU second in calls of up to 5 million tests and slows sharply in bigger ones (15 x 9,000 x 361, 49 million, took 2 minutes). So keep each call to about 5 million tests and a run to about 300 million. 650 million does not fit one run; over 2 h at 60 s (121 instants) it is 218 million, in calls of 4 terminals (4.4 million each): that fits. Tell the person the window you could run.

## 3a. One call, when it fits

```json
{"verb":"compute","args":{"project":"P","fn":"links","model":"ground",
  "inputs":{"of":"starlink","stations":"terminals"},
  "args":{"duration":21600,"step":60,"min_elevation":10}}}
```
Give the GP set itself as `of`: Dynamik propagates it with SGP4 over the same window, so do not propagate first. The window starts at the clock range's start (`clock.range.start` in `project_open`) unless you give `start`. Rows are `time, a, b, range_km` with the terminal's `site_id` at `a` and the satellite at `b`. The model holds a link while the satellite stays above the mask, and hands over to a satellite more than `hysteresis` deg higher once a link has lasted `hold` s (see `describe {topic:"functions", name:"links"}` for the defaults).

Read one terminal's serving intervals without paging the whole table:

```json
{"verb":"data_read","args":{"project":"P","of":"output:<links id>.links","where":{"a":"t042"},"columns":["time","b","range_km"],"limit":1000}}
```
The answer's `summary.sites` already gives each terminal's `links`, `min_links`, `mean_links`, `max_links` and `handovers` (replacements between consecutive samples, outage reconnects not counted); `summary.omitted` counts the terminals past its 4 KB, which you read with `site_keys` or `data_read`.

## 3b. A program, when it does not fit

Run it with `program_run {project:"P", name:"Serving satellites", inputs:{"fleet":"starlink","terminals":"terminals"}, source:<the code below>}`; the code reads the GP set as `fleet`.

```python
import pandas as pd
p = dk.params(step=60, hours=2)
fleet, terminals = dk.layer("fleet"), dk.layer("terminals")
t = terminals.df()
instants = p["hours"] * 3600 // p["step"] + 1
batch = max(1, 5_000_000 // (fleet.rows * instants))                  # terminals per call: about 5 million tests, a few s
if len(t) * fleet.rows * instants > 300_000_000:                         # about a Pro run's 300 s of Engine time
    raise ValueError("Too much for one run: shorten hours, coarsen step or split the terminals")
eph = dk.engine.propagate(fleet, start=dk.clock.start, duration=p["hours"] * 3600, step=p["step"], model="sgp4")
keys, served = list(t.site_id), []
for i in range(0, len(keys), batch):
    links = dk.engine.links(eph, stations=terminals, site_keys=keys[i:i + batch], model="ground")
    served.append(links.links.df())
rows = pd.concat(served).sort_values(["a", "time"])
gap = rows.groupby("a").time.diff().dt.total_seconds().ne(p["step"])   # unserved in between
change = rows.b.ne(rows.groupby("a").b.shift()) | gap                   # a new serving satellite
rows["interval"] = change.cumsum()
intervals = rows.groupby(["a", "b", "interval"]).agg(start=("time", "min"), end=("time", "max"),
                                                      min_range_km=("range_km", "min")).reset_index().sort_values(["a", "start"])
dk.emit.table(intervals.drop(columns="interval"), slot="table", title="Serving satellite per terminal",
              units={"min_range_km": "km"})
handovers = intervals.groupby("a").b.apply(lambda b: int(b.ne(b.shift()).sum() - 1))
per_terminal = t[["site_id"]].assign(handovers=t.site_id.map(handovers).fillna(0).astype(int), served=t.site_id.isin(handovers.index))
dk.emit.table(per_terminal, slot="table_2", title=f"Handovers in {p['hours']} h")  # unserved terminals stay, served=False
dk.result({"terminals": len(t), "unserved": int((~per_terminal.served).sum()),
           "median_handovers": float(per_terminal.handovers.median())})
```
Emit intervals, not one row per step: per-step rows grow as terminals x instants (200 terminals for a day at 60 s is 288,200 rows, over the 200,000 a slot holds).

## 4. Check

- One serving interval at 550 km lasts minutes: at most about 8 above a 10 deg mask, 5 above 25 deg. Hours mean a wrong step or a stuck link.
- A terminal at a latitude the shell never reaches above its mask has no row at all. Report it as unserved; do not drop it.
- `render {project}` at a busy time: the links draw over the fleet, from the terminals to satellites overhead, and the answer's `drawn` lists the link set with a count above 0. Links are not a layer: never `layer_put` them.
