Metadata-Version: 2.5
Name: satimg
Version: 0.30.2
Summary: A uniform, tile-friendly wrapper over satellite imagery
Project-URL: Homepage, https://github.com/peachfuzz11/satimg
Project-URL: Repository, https://github.com/peachfuzz11/satimg
Project-URL: Issues, https://github.com/peachfuzz11/satimg/issues
Author-email: peachfuzz11 <pederh11@gmail.com>
License-Expression: MIT
License-File: LICENSE
Keywords: deep-zoom,geospatial,imagery,landsat,raster,remote-sensing,satellite,sentinel,tiling
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: GIS
Classifier: Topic :: Scientific/Engineering :: Image Recognition
Requires-Python: >=3.12
Requires-Dist: beautifulsoup4>=4.14.2
Requires-Dist: dask[array]>=2025.10.0
Requires-Dist: h5py>=3.16.0
Requires-Dist: numpy>=2.0.0
Requires-Dist: onnxruntime>=1.23.2
Requires-Dist: pillow>=12.0.0
Requires-Dist: pystac-client>=0.9.0
Requires-Dist: rasterio>=1.4.3
Requires-Dist: requests>=2.32.0
Requires-Dist: rioxarray>=0.19.0
Requires-Dist: roaring-landmask>=0.10.1
Requires-Dist: shapely>=2.0.0
Requires-Dist: xarray>=2025.10.1
Description-Content-Type: text/markdown

# satimg

A uniform, tile-friendly wrapper over satellite imagery. Point it at a product
directory and you get the same interface regardless of sensor: two views on the
pixels and one clean way to walk them in windows without ever losing track of
where a window came from.

Supported products: Sentinel-1 GRD (IW / EW), Sentinel-2 L1C, Landsat C2 L1,
NISAR L2 GCOV, VIIRS Day/Night Band L1B (NOAA-20 / NOAA-21, near-real-time),
MODIS 250 m L1B (Terra and Aqua), Sentinel-3 OLCI EFR, Umbra GEC,
Capella GEC and ICEYE GRD (metre-scale X-band SAR open data).

## Concepts

| Object | What it is |
| --- | --- |
| `Product` | A product directory or zip archive. Exposes `.raw`, `.visual` (DataArrays), `.patches(...)`, `.width/.height/.bands`, metadata. |
| `Window` | An immutable pixel rectangle (`col`, `row`, `width`, `height`). Pure geometry. |
| `Grid` | Lays `Window`s over an image with a step and an edge policy. |
| `Patch` | One window's `raw` / `visual` / `meta`, already sliced (lazy `DataArray`s / `PatchMeta`). |

`.raw` and `.visual` are plain lazy `xarray.DataArray`s, dims `(band, y, x)` —
use them with the full xarray API directly.

## Opening a product

`satimg.open` takes a product directory or a zip archive — detected by
content, not by extension — and returns the matching `Product` either way.

A **directory** gives you full access, same as ever:

```python
import satimg

product = satimg.open("/data/S2A_MSIL1C_20220114T103401_..._T33UUB_....SAFE")

product.raw                    # -> xarray.DataArray
for patch in product.patches(512):
    ...
```

A **zip archive** is read zip-native, straight off the archive — nothing is
ever extracted to disk, and there's no temp dir to release, so a `with`
block isn't needed just for a one-off read. Everything works, pixels
included: metadata files are read with `zipfile`, rasters by GDAL's
`/vsizip/`, which seeks inside the archive:

```python
product = satimg.open("/data/S2A_MSIL1C_20220114T103401_..._T33UUB_....SAFE.zip")

product.timestamp
product.metadata
for patch in product.patches(512):
    ...
```

Copernicus downloads, and the zips the Landsat connector writes, store their
rasters uncompressed (they are compressed already), and GDAL reads those at
plain file speed. A deflated archive works too, but every seek re-inflates from an
earlier point; for heavy pixel work on one, extract it first with
`satimg.open_zip`:

```python
with satimg.open_zip("/data/scene.zip") as product:
    for patch in product.patches(512):
        ...
```

This returns a directory-backed product exactly like `satimg.open` on a
directory would. It extracts to a temp dir that is removed — along with the
product's open rasters — when the block exits; read what you need inside
the block, since a lazy view can't be rebuilt afterwards. Pass `dest=` to
control where that temp dir is created.

A product's open rasters (and, for a zip-native one, its open archive) are
released when its `with` block exits, so use `with satimg.open(path) as
product:` — zipped or not — if you loop over many products, to release
handles promptly rather than waiting on garbage collection.

### Two views on the pixels

```python
import satimg

product = satimg.open("/data/S2A_MSIL1C_20220114T103401_..._T33UUB_....SAFE")

product.raw     # every native band, merged onto one grid, native dtype  -> xarray.DataArray
product.visual  # uint8 visualisation: 3-band true colour for optical    -> xarray.DataArray
                # sensors (Sentinel-2, Landsat), 1-band greyscale for SAR
                # (Sentinel-1, NISAR)
```

Both are lazy `DataArray`s over the **same grid**, so a `Window` means the same
thing in each.

`visual_overview(factor)` is the visual decimated `factor` times, read from the
overviews the product's own rasters carry (Sentinel-1 GRD COGs have 2x to 64x),
so a zoomed-out view or a thumbnail reads a fraction of the pixels.
`visual_overviews` lists the factors on offer, starting with 1 (`visual`
itself):

```python
product.visual_overviews       # e.g. [1, 2, 4, 8, 16, 32, 64]
product.visual_overview(64)    # the whole scene in a few hundred pixels a side
``` The `band` axis is labelled, so select by name:

```python
product.raw.sel(band="red")        # Landsat / (SWIR etc.)  ; "B04" for Sentinel-2, "VV" for Sentinel-1
product.raw.band.values            # e.g. ['coastal', 'blue', 'green', 'red', ...]
product.raw.wavelength_nm          # Sentinel-2 only: central wavelength per band
```

### Walking the image in patches

```python
for patch in product.patches(512, overlap=64):
    tile = patch.raw.values        # np.ndarray, (band, 512, 512), native dtype
    x0, y0 = patch.col, patch.row  # exact offset in the full image
    ...
```

`for patch in product` is shorthand for `product.patches()` (raw bands,
512 px, no overlap). Every patch from `product.patches()` / `patches_at()`
already carries `.raw` / `.visual` / `.meta` for that window (see
[Reading raw + visual + metadata together](#reading-raw--visual--metadata-together)) --
`product.patches()` / `patches_at()` are the only iterators in the library.

`product.patches()` opens `raw` and `visual` chunked to exactly the window
size before iterating, so each patch read decodes just the one tile it covers.
`patches_at()`, whose windows sit wherever the points are, reads them from the
default 1024 px chunks instead: one patch at a time, as a web request would,
costs a fraction of a second.

A product releases its rasters when its `with` block exits, so looping over
many products never leaks file handles:

```python
with satimg.open(path) as product:
    ...
```

### Edge handling

`product.patches(size, edge=...)` decides what happens at the right / bottom border:

| `edge` | behaviour | use for |
| --- | --- | --- |
| `"pad"` (default) | every patch is exactly `size`, overhang zero-filled | batched model inference |
| `"trim"` | last row/col of patches is smaller — you get exactly the pixels that exist | analysis, lossless re-assembly |
| `"skip"` | drop partial patches, keep only full interior tiles | training-set extraction |

Indices are always conserved: `patch.window` tells you where the tile belongs,
`patch.window.clip(product.width, product.height)` gives its valid region.

### Patches at specific points

When you already know where to look — detections, sample sites, a sparse set of
tiles — `patches_at` visits only those points instead of sweeping the whole
image. Each `(col, row)` is the **centre** of its patch, and every patch is
exactly `size` (overhang zero-filled, so points near an edge still work):

```python
points = [(4096, 2048), (10500, 512), (0, 0)]
for patch in product.patches_at(points, 512):
    tile = patch.raw.values         # (band, 512, 512), centred on the point
```

`satimg.windows_at(points, size)` gives the bare `Window`s if you don't need a
patch bound.

### Reading raw + visual + metadata together

Every patch from `product.patches()` / `product.patches_at()` already carries
its own window's raw, visual and metadata -- one window, every view.

```python
scene = product.metadata.attrs                 # scene-level scalars, constant per product
                                               # e.g. {"mean_sun_zenith": 77.5, ...}

for p in product.patches_at(points, 512):
    raw = p.raw                                # xarray.DataArray (band, 512, 512), band-labelled
    red = p.raw.sel(band="red").values         # np.ndarray (512, 512)   ("B04" on Sentinel-2)
    nir = p.raw.sel(band="nir08").values       #                          ("B08" on Sentinel-2)
    rgb = p.visual.values                       # np.ndarray (3, 512, 512) uint8, same window

    angles = p.meta.sample()                    # {"sun_zenith": 78.1, "view_zenith": 4.9, ...}
                                               #   -> per-pixel fields, bilinear at the patch centre
    sza_grid = p.meta["sun_zenith"].values      # np.ndarray (512, 512) — the field over the patch
```

### Mapping results back

```python
patch = next(iter(product.patches(1024)))
boxes = detect(patch.visual.values)     # boxes in patch pixels
boxes[:, [0, 2]] += patch.window.col    # -> full-image pixels
boxes[:, [1, 3]] += patch.window.row
latlon = product.transformer.rowcol_to_latlon(boxes[:, [1, 0]])
```

## Working with a single window

```python
from satimg import Window

win = Window(col=4096, row=2048, width=1024, height=1024)
chip = satimg.read_window(product.raw, win)   # lazy xarray.DataArray, (band, y, x)
chip.values                                   # numpy, zero-padded if the window overhangs
```

## Per-pixel metadata

Every sensor ships scene geometry that varies across the image — Sentinel-1's
incidence / elevation angles, Sentinel-2's and Landsat's sun / viewing angles —
stored on a coarse grid. `product.metadata` exposes those as named fields that
bilinearly interpolate to any pixel:

```python
m = product.metadata
m.fields                          # ['sun_zenith', 'sun_azimuth', 'view_zenith', ...]
m.sun_zenith.at((row, col))       # -> float, bilinear on the coarse grid
m.sample((row, col))              # -> {field: value} for every field
m.sun_zenith.corners()            # -> {'top_left', 'top_right', 'bottom_left', 'bottom_right', 'center'}
m.corners()                       # -> {field: {'top_left': ..., ..., 'center': ...}}  (whole grid)
m.attrs                           # scalar scene-level metadata (mean angles, ...)
```

| Product | Fields (all `degrees` unless noted) |
| --- | --- |
| Sentinel-1 | `incidence_angle`, `elevation_angle`, `slant_range_time` (seconds), `height` (metres) |
| Sentinel-2 | `sun_zenith`, `sun_azimuth`, `view_zenith`, `view_azimuth` |
| Landsat | `sun_zenith`, `sun_azimuth`, `view_zenith`, `view_azimuth` |
| VIIRS DNB | `satellite_zenith`, `satellite_azimuth`, `solar_zenith`, `solar_azimuth`, `lunar_zenith`, `lunar_azimuth` |
| MODIS (with its M?D03) | `solar_zenith`, `solar_azimuth`, `satellite_zenith`, `satellite_azimuth` |
| Sentinel-3 OLCI EFR | `solar_zenith`, `solar_azimuth`, `satellite_zenith`, `satellite_azimuth` |
| NISAR GCOV | `incidence_angle`, `elevation_angle`, `slant_range` (metres), `los_east` / `los_north` / `along_track_east` / `along_track_north` (unit vectors), `ground_track_velocity` (m/s) |

This is per-pixel geometry (varies across the scene). Per-*band* identity lives
on `product.raw` instead — the labelled `band` coordinate, plus `wavelength_nm`
for Sentinel-2. Scene-wide scalars are `product.metadata.attrs`.

Each field also materialises as a lazy full-grid `(y, x)` `xarray.DataArray`
(`m.sun_zenith.grid`), and patches from `product.patches()` carry a matching lazy
view over their window:

```python
for patch in product.patches(512):
    patch.meta.sun_zenith          # lazy (512, 512) DataArray for this window
    patch.meta.at((y, x))          # -> {field: value} at a patch-local pixel
    patch.meta.sample()            # -> {field: value} at the patch centre
    patch.meta.corners()           # -> {field: {'top_left': ..., ..., 'center': ...}}
```

`corners()` samples five points (the four corners and the centre) without
materialising the patch grid — a cheap way to see how a field varies across a
tile. `corners()[field]["center"]` equals `sample()[field]`.

### Geometry without the product

Every product's `geometry` -- its transformer, image shape, coarse metadata
grids and scene attrs -- is a small dict that survives strict JSON (e.g. a
PostgreSQL `jsonb` column; `NaN` is stored as `null`). Store it while the
product is open and keep converting coordinates and sampling metadata after the
file is gone. For a SAR product, load it as a `SAROrbitGeometry` to also keep
the moving-target correction (next section):

```python
with satimg.open("S1A_IW_GRDH_....SAFE.zip") as product:
    stored = product.geometry.to_dict()      # ~30-80 KB

geometry = satimg.SAROrbitGeometry.from_dict(stored)   # SceneGeometry for optical products
geometry.transformer.latlon_to_rowcol((lat, lon))
geometry.metadata.incidence_angle.at((row, col))
geometry.correct_position(lat, lon, speed_mps, heading_deg)   # SAR only
```

Whichever class loads it, the transformer comes back as the kind that was
stored: affine, ground control points (Sentinel-1) or swath (VIIRS, MODIS,
OLCI, ICEYE; stored to within a third of a pixel).

Landsat's angle fields and NISAR's radar-grid fields are stored resampled to 32 x 32.

## Moving targets in SAR

A target moving towards or away from the radar is displaced along track in
a focused SAR image by its own Doppler shift -- the ship sitting off its own
wake: tens of metres per m/s of its speed along the line of sight. Every SAR
product (`SARProduct`: Sentinel-1, NISAR, Umbra, Capella, ICEYE) corrects it
the same way, given the target's speed and heading (from AIS, say):

```python
product.correct_position(lat, lon, speed_mps, heading_deg)           # where it was seen -> where it is
product.doppler_azimuth_shift_m((row, col), speed_mps, heading_deg)  # metres, + towards the way the sensor flies
product.doppler_pixel_shift((row, col), speed_mps, heading_deg)      # (d_row, d_col), on or off the image
product.heading_to_los((row, col), heading_deg)                      # 0 moving away from the sensor
product.heading_in_image((row, col), heading_deg)                    # compass -> direction on the raster
product.heading_from_image((row, col), image_heading_deg)            # and back
```

All of it is worked out on the ground from the sensor's own Earth-fixed
orbit (`metadata.attrs["orbit"]`), not from the pixel frame, so a north-up
map (NISAR, Capella), a rotated grid (Umbra) and mirrored radar geometry
(Sentinel-1, ICEYE) work alike, as do either look side and squinted
collects (the beam aimed fore or aft of square to the flight, as Umbra's
and Capella's spotlights often are -- it makes the shift larger, by about
`1 / cos(squint)`). Image-frame headings come from the local pixel grid.

Sentinel-1, NISAR, Capella and ICEYE ship their state vectors, so every
target gets its own imaging time and geometry. Umbra's GEC metadata has
none: its orbit is rebuilt from the scene-centre line of sight and slant
range, assuming the circular sun-synchronous orbit Umbra flies -- within
0.5 % of the true shift against real collects' SICD aperture positions,
squinted up to 45 degrees. Against a brute-force focusing simulation on real
Capella (broadside and 30 degrees squinted), ICEYE and Umbra orbits, the
shift agrees to within 0.5 %.

## NISAR

A NISAR L2 GCOV granule is a single `.h5` file; `satimg.open` takes it as it
is (or a zip holding it):

```python
product = satimg.open("NISAR_L2_PR_GCOV_..._001.h5")

product.raw.band.values    # ['HHHH', 'HVHV'] -- frequency A diagonal terms, linear gamma-0 power, NaN off-swath
product.visual             # 1-band dB stretch, like Sentinel-1
```

GCOV is geocoded -- a north-up UTM (or polar stereographic) grid -- not a
radar-geometry GRD, so it is neither rotated into the flight direction nor
mirrored, and NISAR looks *left*; the moving-target correction (see
[Moving targets in SAR](#moving-targets-in-sar)) handles both.

The detection / characterisation models were trained on Sentinel-1; NISAR's
`visual` is stretched so open sea is dark and ships bright in the same way,
but L-band at 10-20 m is a different look -- expect to fine-tune before
trusting them on it. NISAR also images the open ocean only sparsely; coasts,
straits and sea ice are where its coverage is.

## Umbra, Capella and ICEYE

Umbra, Capella and ICEYE publish part of their commercial X-band SAR as open
data (CC BY 4.0) in public AWS buckets: spotlight collects at ~0.25-1 m,
plus stripmap (~3 m) from Capella and ICEYE and scan (~15 m, 100-200 km
wide) from ICEYE -- tasked rather than systematic: ports, straits, cities,
and still growing. At spotlight resolution a ship is hundreds of pixels,
with its shape. satimg reads the least-processed product each one ships
that is already geocoded: Umbra's and Capella's **GEC** (geocoded,
ellipsoid corrected: detected and projected onto the WGS 84 ellipsoid --
exact at sea level -- not terrain corrected), and ICEYE's **GRD** (ground
range detected, in the radar's own geometry, located by a grid of ground
control points -- ICEYE's open data has no map-projected product). Open the
product folder as the bucket lays it out, a zip of it (what the connectors
write), or the `.tif` (with its metadata JSON beside it, for Umbra and
Capella):

```python
product = satimg.open("2025-01-31-14-10-48_UMBRA-08")    # _GEC.tif + .stac.v2.json / _METADATA.json
product.raw                  # uint8 amplitude, Umbra's own scaling (uncalibrated), band VV / HH
product.visual               # 1-band dB stretch: water dark, ships bright

product = satimg.open("CAPELLA_C13_SP_GEC_HH_20260116014108_20260116014119")   # .tif + _extended.json
product.raw                  # uint16 amplitude numbers, band HH / VV
product.sigma0(product.raw)  # calibrated sigma-nought, linear, NaN off the image
product.visual               # 1-band dB stretch of sigma0

product = satimg.open("ICEYE_W21Z0X_20260827T153629Z_10399690_X61_SM")   # _GRD.tif, self-contained
product.raw                  # uint16, amplitude packed by the band's scale / offset, band VV
product.sigma0(product.raw)  # unpacked and calibrated sigma-nought, linear, NaN off the image

product.metadata.attrs       # incidence_angle, squint_angle, look_direction, pass, pixel_spacing, ...
```

An Umbra GEC is on an EPSG:4326 grid rotated to the collect (the
`transformer` is a full affine), a Capella GEC on a north-up UTM grid, an
ICEYE GRD in sensor geometry -- range down the rows, azimuth along the
columns -- with a `SwathTransformer` over its GCP grid (sub-pixel against
ICEYE's own footprint). All three have overviews, so `visual_overview` and
`thumbnail` read a few hundred KB.
The metadata is scene-centre values only -- no per-pixel fields. The image models were trained on
10 m Sentinel-1; at sub-metre resolution a ship looks nothing like that, so
expect to fine-tune (or tile coarser) before trusting them here.

Moving ships: see [Moving targets in SAR](#moving-targets-in-sar) -- at
these resolutions the Doppler shift is hundreds of pixels.

`get_connector("umbra-gec")` / `"capella-gec"` / `"iceye-grd"` search each
bucket's static STAC catalogue and download anonymously -- no account:

```python
connector = get_connector("capella-gec")
items = connector.search(geojson=aoi, start_datetime=t0, stop_datetime=t1)
connector.download(items[0], "/data/collect.zip")    # GEC + metadata (+ quick-look), a few hundred MB
```

There is no search API behind these catalogues, so `search` walks its tree,
skipping the year / month / day branches outside the time range: a date
range of a few weeks takes seconds, the whole catalogue up to a minute.
ICEYE's lists its ~700 images flat, with no date branches, so each search
reads them all (~10 s). Umbra's catalogue lags its bucket by a few months.
An ICEYE download is the GRD alone (~100 MB for a spotlight, up to ~1 GB
for a stripmap); it carries its own metadata.

## VIIRS Day/Night Band

The VIIRS Day/Night Band sees light at night down to a few nW / (cm^2 sr):
towns, gas flares -- and lit boats, above all the squid jiggers and other
light-luring fleets, at ~750 m, every night, worldwide. satimg reads NASA's
L1B granules -- a radiance file with its geolocation file, 6 minutes, ~3232 x
4064 pixels:

| Satellite | Radiance | Geolocation |
| --- | --- | --- |
| NOAA-20 | `VJ102DNB_NRT` | `VJ103DNB_NRT` |
| NOAA-21 | `VJ202DNB_NRT` | `VJ203DNB_NRT` |

(the standard-archive pairs without `_NRT`, and SNPP's `VNP02DNB`, are the
same format and open too). Open the radiance file with its geolocation file
next to it, or a folder / zip holding both:

```python
product = satimg.open("VJ102DNB_NRT.A2026309.1654.021.2026309185751.nc")

product.raw            # radiance, W / (cm^2 sr), float32 -- x 1e9 for nW
product.visual         # log stretch, moonlit cloud to boat lights
product.metadata.attrs["moon_illumination"]   # 0-1: how bright the background is
```

The image is in sensor (swath) geometry, not map projected: `transformer` is a
`SwathTransformer` over the geolocation file's per-pixel positions, scan by
scan, to within 50 m. Boats show up at night as their lights, a pixel or two
each, not as hulls.

`get_connector("viirs-dnb")` searches NOAA-20 and NOAA-21 near-real-time
granules together (`satellite="noaa-20"` / `"noaa-21"` for one; `nrt=False`
for the standard archive, for older dates) through NASA's CMR, anonymously,
and downloads from LANCE / LAADS with an Earthdata login (`EARTHDATA_TOKEN`
etc., as for NISAR):

```python
connector = get_connector("viirs-dnb")
items = connector.search(geojson=aoi, start_datetime=t0, stop_datetime=t1, day_night="night")
connector.download(items[0], "/data/granule.zip")       # both files, one zip
```

## MODIS

Terra and Aqua MODIS 250 m L1B -- `MOD02QKM` / `MYD02QKM`, Collection 7
(netCDF4; Collection 6.1's HDF4 is refused with a clear error) -- with its
`MOD03` / `MYD03` geolocation file beside it, or a folder / zip holding both:

```python
product = satimg.open("MOD02QKM.A2026305.1035.007.2026305170237.nc")

product.raw                       # uint16 scaled integers, bands B01 (red) / B02 (NIR)
product.reflectance(product.raw)  # TOA reflectance x cos(sun zenith), fills NaN
product.visual                    # the NIR band: water darkest, ships / wakes / cloud bright
product.metadata.solar_zenith     # sun / view angles, from the M?D03 file
```

Daytime only (night granules carry no 250 m data). Like VIIRS it is a swath
in sensor geometry with overlapping scans, so `transformer` is a scan-aware
`SwathTransformer` over the 1 km geolocation, placed with MODIS's 1.5-pixel
track offset. At 250 m only large ships and wakes show; the image models
were not trained on MODIS. `get_connector("modis-qkm")` searches Terra and
Aqua together (`satellite="terra"` / `"aqua"` for one), pairing each granule
with its geolocation file; download needs an Earthdata login.

## Sentinel-3 OLCI

Sentinel-3A / -3B OLCI full-resolution Level-1B (`OL_1_EFR___`): 21 bands at
~300 m over a ~1270 km push-broom swath. Open the `.SEN3` folder, or the zip
Copernicus distributes:

```python
product = satimg.open("S3A_OL_1_EFR____20240916T101050_..._NT_004.SEN3")

product.raw                            # uint16, Oa01 .. Oa21, wavelength_nm on the band axis
product.radiance(product.raw)          # mW / (m^2 sr nm), fills NaN
product.visual                         # true colour, Oa08 / Oa06 / Oa04
product.metadata.satellite_zenith      # sun / view angles, from the tie points
```

The transformer interpolates the tie-point geolocation: smooth, within about
a third of a pixel of the per-pixel positions at sea (the per-pixel ones are
terrain corrected, which no smooth grid follows over mountains). Daytime
only; at 300 m only large ships, and wakes in sun glint, are visible.
`get_connector("sentinel-3-olci-efr")` searches Copernicus Data Space
(near-real-time by default, `timeliness="ntc"` for the consolidated archive)
and downloads with the same CDSE account as Sentinel-1 / -2.

## Downloading

`search` is anonymous; `download` needs a (free) account for the archive --
except Umbra, Capella and ICEYE, which need none at all.
Pass credentials to the connector, or set environment variables
(`CDSE_USERNAME` / `CDSE_PASSWORD` for Copernicus, `USGS_USERNAME` /
`USGS_PASSWORD` / optional `USGS_TOKEN` for USGS, `EARTHDATA_TOKEN` -- or
`EARTHDATA_USERNAME` / `EARTHDATA_PASSWORD` -- for NISAR via NASA Earthdata).

```python
from satimg import get_connector

connector = get_connector("sentinel-2-l1c")                     # search only
items = connector.search(geojson=aoi, start_datetime=start, stop_datetime=stop)

connector = get_connector("sentinel-2-l1c",
                          username="me@example.com", password="...")
connector.download(items[0], "/data/scene.zip")
```

A scene that ESA or USGS reprocesses comes back under a new name: Sentinel-1
changes its product unique id (`..._04368F_4953_COG` → `..._04368F_A1B2_COG`),
Sentinel-2 its processing baseline and generation time, Landsat its correction
level, processing date and tier. `satimg.scene_key` drops those parts, so every
version of one acquisition gets the same key -- use it to skip a scene you
already have:

```python
satimg.scene_key("S1A_IW_GRDH_1SDV_20210102T224803_20210102T224828_035965_04368F_4953_COG")
# 'S1A_IW_GRDH_1SDV_20210102T224803_20210102T224828_035965_04368F'
```

It takes a search item id, a folder or zip name, or a path. Names of other
products are returned as they are.

`get_connector("nisar-gcov")` searches the ASF DAAC; its `download` writes the
granule's own `.h5` rather than a zip. Every other `download` gives you a zip
archive — see
[Opening a product](#opening-a-product) for reading its metadata straight
off the archive, or extracting it for pixel access.

## Land, wind farms, ports, platforms and fish farms

Every mask answers `mask.contains(lat, lon)` for matching `lat`/`lon` points
(scalars or arrays of any shape), giving booleans of that shape:

```python
from satimg.masks.fishfarm_mask import FishFarmMask
from satimg.masks.land_mask import LandMask
from satimg.masks.platform_mask import PlatformMask
from satimg.masks.port_mask import HarborMask, PortMask, features_in_bbox
from satimg.masks.windfarm_mask import WindfarmMask

LandMask().contains(lat, lon)              # on land
WindfarmMask(year=2025).contains(lat, lon)  # in a wind farm built by 2025 (any farm without a year)
PortMask().contains(lat, lon)              # in a commercial port
HarborMask().contains(lat, lon)            # in a marina or other small-boat harbor
PlatformMask().contains(lat, lon)          # at an offshore platform
FishFarmMask().contains(lat, lon)          # at an offshore fish farm

features_in_bbox(min_lon, min_lat, max_lon, max_lat)  # the port and harbor areas, e.g. for a map
```

Each data file loads once per process (the ports take ~0.5 s), whatever the
number of masks. Points a detection's centre would never quite hit are widened:
an offshore turbine is a 50 m disc, a platform a 200 m disc, a fish farm a 250 m
disc and a berth a 150 m disc, and a port is grown by 50 m to take in the ships
at berth. Berths and oil terminals by the water count as ports.

`Detector` tags every detection with where it lies, in `Detection.tags`:
`on_land`, `turbine`, `platform`, `fishery`, `in_port` and `in_harbor` (a ship at a quay can
be both `on_land` and `in_port`). No detection is dropped for where it lies;
filter on the tags. `satimg.prediction.context.context_tags(lat,
lon, year=None)` gives the same tags for any points.

The data is rebuilt by `scripts/build_ports.py`, `scripts/build_windfarms.py`,
`scripts/build_platforms.py` and `scripts/build_fishfarms.py`.

Data: ports, harbors, berths, oil terminals, platforms, and wind and fish farms
outside EMODnet's © OpenStreetMap contributors, available under the
[ODbL](https://opendatacommons.org/licenses/odbl/); European wind and fish farms from
[EMODnet Human Activities](https://emodnet.ec.europa.eu/en/human-activities).

## Deep Zoom

```python
from satimg.deepzoom import DeepZoom

DeepZoom(tile_size=512).build(product.visual, "/tmp/scene")  # -> /tmp/scene.dzi
```

## Adding a product

Subclass `Product`, implement the abstract hooks (`_open_raw(tile, overview)`,
`_render_visual(raw, tile)` — both return an `xarray.DataArray` dask-chunked to
`tile`; normalise dims with `satimg.as_band_yx(...)` and name the band axis
with `satimg.label_bands(da, [...])` — and `thumbnail`), set
`self._transformer`, `self._timestamp` and `self._footprint` in `__init__`
(the base class serves them as `transformer` / `timestamp` / `footprint`),
optionally override `_read_metadata` to expose per-pixel metadata and the
`scene_key` classmethod if reprocessing changes the product's name (see
[Downloading](#downloading)), and register a filename pattern. For `visual_overview`,
`_open_raw` also takes an `overview` factor (pass it on to `merge_bands`) and
`_visual_paths()` names the rasters the visual is read from:

```python
from satimg.registry import register

@register(r"^MY_SENSOR_\d{8}.*$")
class MySensorL1(Product):
    ...
```

Importing `satimg` registers the built-ins.

### Package layout

```
satimg/
  product.py, patch.py, registry.py      the Product base, patches, filename registry
  transform/   transformer · affine_transformer · gcp_transformer · swath_transformer
               · transformer_factory · transformer_utils   pixel <-> lat/lon, one module per kind
  source/      source · local_source · zip_source · source_factory
                                         where a product's files live (dir, file, zip)
  readers/     raster · hdf5 · vrt · thumbnail  file IO shared by the products
  metadata/    field · metadata · patch_meta · grids   per-pixel metadata fields
  masks/       mask · land_mask · port_mask · platform_mask · windfarm_mask · fishfarm_mask
  products/    <constellation>/<product>/: <constellation>_<product>.py, _connector.py,
               <constellation>_<product>_parsing.py, e.g.
               sentinel2/l1c/sentinel2_l1c.py holds Sentinel2L1C;
               swath_nodes.py: node grids shared by VIIRS, MODIS, OLCI
  sar_product.py  SARProduct: the interface every SAR product shares
  sar_orbit_geometry.py  SAROrbitGeometry: moving-target correction and headings
               from the sensor orbit
  sar.py       the SAR physics behind it: ellipsoid / orbit helpers, ground shift
  geojson.py   unwrapping a GeoJSON geometry / Feature, its bounding box
  connectors/  the generic and provider connectors the product ones subclass:
               connector · connector_factory · connector_utils · static_stac_connector
               · static_stac_utils · copernicus_dataspace_connector · nasa_earthdata_connector
               · usgs_ers_connector
  prediction/  detectors and characterisers
```

Every module is named for what it holds, so no two share a file name. A
module named for a class holds that class only; the functions it needs live
in a sibling `*_utils.py` (shared ones) or in the product's own
`_parsing.py` (product-specific ones -- never in a common module). Package
`__init__.py` files are empty; only the top-level `satimg` re-exports the
public classes (`from satimg import Sentinel2L1C, get_connector, Detector`).

A new product goes in `products/<constellation>/<product>/`, e.g.
`products/sentinel2/l1c/`: `sentinel2_l1c.py` for the `Product` subclass
(`Sentinel2L1C`, named constellation + product, no `Product` suffix),
`sentinel2_l1c_parsing.py` for parsing its file format. Add
`<constellation>_<product>_geometry.py` if it needs a `SceneGeometry` subclass.

## Logging

`satimg` logs under the `satimg.*` logger namespace and never installs a handler
of its own. Opt in from your application:

```python
import logging

logging.basicConfig(level=logging.INFO)              # your app configures handlers
logging.getLogger("satimg").setLevel(logging.DEBUG)  # DEBUG for per-tile / per-request detail
```

`INFO` covers milestones (downloads, Deep Zoom builds, detection runs); `DEBUG`
adds STAC queries, redirect hops, per-tile counts and product resolution.
Credentials are never logged.

## Development

```sh
uv sync
uv run pytest                      # fast unit tests + product integration tests
uv run pytest tests/test_geometry.py tests/test_tiling.py   # just the fast ones
```

Integration tests run against minified scenes under `tests/data/` — real
georeferencing and metadata, zeroed pixels.
