# Programs

A program is your Python, sent with `program_run`, that runs next to the Engine and calls its functions directly. Use one for a loop, a sweep, more than 3 dependent computes, or your own algorithm over Engine results. It is saved in the project as a computation: the person sees its code, inputs, outputs and every run, and can run it again.

## The shape of a program

```python
p = dk.params(min_visible=2, masks=[0, 10, 20, 30])    # defaults; they become the form a person edits
fleet, sites = dk.layer("fleet"), dk.layer("sites")    # the inputs named in program_run {inputs}
eph = dk.engine.propagate(fleet, start=dk.clock.start, duration=86400, step=120, model="sgp4")  # GP set; use j2 for a design
best = {}
for mask in p["masks"]:
    vis = dk.engine.visibility(eph, stations=sites, min_elevation=mask)
    v = vis.visibility.df()                            # columns station_id, time, visible
    ...
table = sites.df()
table["mask"] = table.site_id.map(best).fillna(-1)        # best: your highest passing mask per site
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": [...]})                             # a small JSON for you, returned inside `untrusted`
print("done")                                          # the run log
```

## The library

| Name | What it is |
|---|---|
| `dk.params(**defaults)` | The run's parameters: the defaults, overridden by `program_run {params}` |
| `dk.layer(name)` | A declared input as a data handle. Only inputs named in `program_run {inputs}` exist |
| `dk.clock.start`, `dk.clock.end`, `dk.clock.time` | The project clock (UTC) captured when `source`, `params` or `refresh` was last sent, never wall time; a plain rerun keeps it |
| `dk.engine.<fn>(...)` | A Dynamik function, the same names, arguments and units as `compute`. Returns its outputs as handles, by output name (`vis.visibility`); a function with one output is that output |
| Data handle | `.schema` (columns and units), `.rows`, `.df()` (pandas), `.table()` (Arrow), `.numpy(column)`. A points layer's `.df()` has `site_id` and `location = [lon, lat, alt]`, accepted by `emit.points`. Reading bytes counts against your read budget; a handle you only pass on costs nothing |
| `dk.emit.points / features / cells / movers / links / table` | Draw a result. `slot` names `table`, `table_2` or `table_3` for tables. At most 8 slots and 200,000 rows a slot |
| `dk.emit.chart(slot, x, y, kind)` | A chart over a table slot, linked to the clock and selection |
| `dk.result(obj)` | Up to a few KB of JSON for the caller |
| `print(...)` | The run log; its tail comes back in the answer |

## Rules

- **Python 3.12** with numpy, scipy, pandas, pyarrow, shapely, h3, pyproj and networkx. The import allow-list is an advisory first check of import roots. Allowed libraries can expose other modules through attributes; the check is not a security boundary.
- **Confinement.** Production gVisor runsc, outer and child seccomp, no network, a read-only container filesystem, a per-run chroot with a private PROJ copy, dropped privileges and resource limits enforce the boundary. Only the run's private scratch is writable: the working directory, also `TMPDIR` (there is no `/tmp`), at most 64 MB a file. Bring data first with `data_put`, then declare it in `inputs`.
- **No positions in code.** Propagation, visibility, coverage and links come from `dk.engine`; there is no orbit library in the sandbox on purpose.
- **No writes.** A program reads its inputs and emits its outputs; the platform writes them as one step, attributed to whoever ran it.
- **Deterministic.** The clock is captured when the source, params or refresh is sent; `random` and `numpy.random` are seeded from the program's identity. The same source, params and inputs give the same outputs.
- **Assurance.** An Engine result emitted as it is, from checked inputs, stays "Dynamik, checked". Anything your code builds, or computed from custom data such as an uploaded CSV, is "custom". The platform decides this from the call trace; your code cannot set it.

## Running

Optional: `program_run {project, name, inputs, source, check:true}` only parses the source in one call: syntax with line and column, imports outside the set, the slots you emit, your parameter defaults, your limits. It does not execute the source or write anything.

Put values you want to report into `dk.result`, rather than printing them.

1. `program_run {project, name, inputs, source}`: saves the program and runs it. The call waits up to 25 s; a longer run continues, `state:"running"`, read with `project_open {project, run}`.
2. `program_run {project, program, params}`: run again with new parameters. `{program, source}`: new code for the same program. `{program, refresh:true}`: inputs declared as a catalogue `{ref}` move to their latest release and the clock is captured again, then run; an input given as a layer id keeps its data.
3. `program_failed`: `hints` names the line (`/source:<line>`) when there is one, `details.kind` what failed (`exception`, or a limit such as `cpu_time`, `memory` or `blocked_syscall`). The program and its failed run stay in the project; fix them or `undo {project}`.

<!-- Generated by `pnpm registry build` (tools/registry/skill.ts). Do not edit below: the header above is tools/registry/skill-program.md: change the source it names. -->

## `dk.engine` functions

- `dk.engine.visibility(of, *, stations, horizon=None, min_elevation=10, refraction="radio", site_keys=None, frequency=0, start=dk.clock.start, duration=7200, step=60, model=None, **model_args)` returns outputs `.visibility` (station_id, time, visible; plus the function's values, see .schema), `.pairs` (station_id, station_name, sat_id, satellite_name, time, azimuth_deg, azimuth_defined, elevation_deg, apparent_elevation_deg, range_km, visible, sample_valid; plus the function's values, see .schema), `.passes` (station_id, station_name, sat_id, satellite_name, rise, set, max_elevation_deg, max_time, duration_s, range_at_max_km, rise_clipped, set_clipped, step_s, rise_unknown, set_unknown; plus the function's values, see .schema)
- `dk.engine.footprint(satellites, *, pattern, grid=None, levels=[-3, -6, -10], beam=0, every=1, gain_every=1, at=None, model=None, **model_args)` returns outputs `.footprint` (sat_id, time, beam, level_db, geometry), `.gain` (cell; plus the function's values, see .schema), `.gain_series` (cell, time; plus the function's values, see .schema)
- `dk.engine.beam_pattern(file=None, *, peak_gain=0, model=None, **model_args)` returns outputs `.pattern` (beam, az_deg, el_deg, gain_db, contour, order; plus the function's values, see .schema)
- `dk.engine.walker(*, total=24, planes=6, raan_spread=360, phasing=1, altitude=550, inclination=53, epoch=dk.clock.time, model=None, **model_args)` returns outputs `.elements` (sat_id, semi_major_axis, eccentricity, inclination, raan, arg_perigee, mean_anomaly; plus the function's values, see .schema)
- `dk.engine.coverage_summary(of, *, min_satellites=1, model=None, **model_args)` returns outputs `.coverage` (station_id, coverage_fraction, longest_gap, mean_visible)
- `dk.engine.grid_count(grid, *, of, model=None, **model_args)` returns outputs `.cells` (cell; plus the function's values, see .schema)
- `dk.engine.grid_coverage(of, *, grid, criterion="elevation", min_elevation=10, min_satellites=1, refraction="radio", start=dk.clock.start, duration=86400, step=60, model=None, **model_args)` returns outputs `.cells` (cell; plus the function's values, see .schema)
- `dk.engine.grid_revisit(of, *, grid, criterion="elevation", min_elevation=10, cluster="none", min_satellites=1, refraction="radio", start=dk.clock.start, duration=86400, step=60, model=None, **model_args)` returns outputs `.passes` (cell, start, end; plus the function's values, see .schema)
- `dk.engine.ascent(*, liftoff, latitude, longitude, altitude=0, inclination=51.6, northbound=True, target_altitude=300, duration=540, step=5, name="vehicle", model=None, **model_args)` returns outputs `.ephemeris` (sat_id, time, x, y, z; plus the function's values, see .schema)
- `dk.engine.links(of=None, *, stations=None, horizon=None, start=dk.clock.start, duration=7200, step=60, site_keys=None, clearance=None, refraction=None, links_per_site=None, hysteresis=None, hold=None, neighbours=None, model=None, **model_args)` returns outputs `.links` (time, a, b, range_km; plus the function's values, see .schema)
- `dk.engine.network(features, *, snap_m=450, stitch_km=6, landing_km=150, model=None, **model_args)` returns outputs `.network` (link_id, a, b, km, kind, name, geometry, properties; plus the function's values, see .schema)
- `dk.engine.path(stations, *, ground, links=None, instant=dk.clock.time, origin, destination, processing_ms=0, route_stretch=1, fibre_speed_km_s=200000, model=None, **model_args)` returns outputs `.path` (segment, time, status, cause, a, b, kind, range_km, delay_ms, total_ms, round_trip_ms, hop_count, geodesic_km, fibre_km, fibre_ms, processing_ms, route_stretch, fibre_speed_km_s, fibre_round_trip_ms, a_kind, b_kind; plus the function's values, see .schema)
- `dk.engine.propagate(of, *, start=dk.clock.start, duration=86400, step=60, model=None, **model_args)` returns outputs `.ephemeris` (sat_id, time, x, y, z; plus the function's values, see .schema)
- `dk.engine.horizon(stations, *, terrain="ground", site_keys=None, model=None, **model_args)` returns outputs `.horizon` (station_id, azimuth_deg, elevation_deg, station_height_m, ground_m, raised)
- `dk.engine.sunlight(of, *, start=dk.clock.start, duration=86400, step=60, model=None, **model_args)` returns outputs `.intervals` (sat_id, satellite_name, state, start, end, duration_s, min_sun_fraction, start_clipped, end_clipped; plus the function's values, see .schema), `.series` (sat_id, time, sun_fraction, lighting, beta_deg; plus the function's values, see .schema)
- `dk.engine.trajectory(*, start=dk.clock.start, duration=432000, step=60, center="earth", orbit=None, state=None, burns=[], name="spacecraft", model=None, **model_args)` returns outputs `.ephemeris` (sat_id, time, x, y, z; plus the function's values, see .schema), `.moon` (sat_id, time, x, y, z; plus the function's values, see .schema), `.events` (event, kind, time, elapsed_s, about, altitude_km, speed_km_s, dv_m_s, dv_v_m_s, dv_n_m_s, dv_b_m_s, total_dv_m_s, periapsis_altitude_km, apoapsis_altitude_km, eccentricity, inclination_deg, c3_km2_s2, period_s, x_km, y_km, z_km, vx_km_s, vy_km_s, vz_km_s)
- `dk.engine.cloud_cover(sites, *, atmosphere=None, time_range, variables=["total_cloud_cover"], site_keys=None, model=None, **model_args)` returns outputs `.cloud_cover` (site_id, time, total_cloud_cover; plus the function's values, see .schema)

## Limits per run

| Limit | starter | pro |
|---|---|---|
| cpu s | 10 | 120 |
| wall s | 60 | 300 |
| memory mib | 512 | 1,024 |
| engine calls | 50 | 1,000 |
| engine s | 30 | 300 |
| read mb | 64 | 256 |
| slots | 8 | 8 |
| rows per slot | 200,000 | 200,000 |
| emit mb | 8 | 64 |
| source kb | 64 | 64 |
| params kb | 16 | 16 |
| log kb | 256 | 256 |
| log tail kb | 4 | 4 |
| daily cpu s | 120 | 3,600 |
| concurrency | 1 | 1 |
| runs per hour | 10 | 60 |

Passing a limit ends the run as `program_failed` with the limit named; nothing it emitted is kept. `describe {topic:"limits"}` gives yours and what is left today.
