Core API
L1 event
- class pyrawph.l1.l1_event.L1_event(arr: ndarray, meta: Dict[str, Any], product_folder: str, scene_id: int, product_kind: str, device: str = 'cpu')[source]
Bases:
objectRepresent a local ΦSat-2 L1 scene together with its array data, metadata, and derived in-memory tiles.
This class is the main high-level entry point for loading a ΦSat-2 product, accessing spectral bands, computing simple spectral products, cropping the scene in pixel coordinates, splitting it into tiles, plotting its geographic location, and exporting arrays to GeoTIFF.
An event stores the full scene as a NumPy array with shape (C, H, W), where C is the number of bands, and keeps a metadata dictionary containing geospatial information such as CRS, affine transform, bounds, wavelengths, and product-related paths.
The recommended constructor is
from_path(), which reads a local product folder and initializes the event from disk.- as_numpy() ndarray[source]
Return the event data as a NumPy array.
The returned array is the internal scene array stored by the event and is expected to have shape (C, H, W).
- Returns:
The event data as a NumPy array of shape (C, H, W).
- as_tensor(as_float32: bool = True)[source]
Return the event data as a PyTorch tensor on the configured device.
- Parameters:
as_float32 – If True, cast the tensor to torch.float32 before moving it to the target device.
- Returns:
A PyTorch tensor containing the event data, typically with shape (C, H, W).
- Raises:
ImportError – If PyTorch is not available in the current environment.
- crop_px(y0: int, y1: int, x0: int, x1: int) Tuple[ndarray, Dict[str, Any]][source]
Crop the event in pixel coordinates and return the cropped array and metadata.
The crop is defined using half-open intervals [y0:y1, x0:x1] in image coordinates. Bounds are clamped to the valid image extent. When geospatial metadata is available, the affine transform and geographic bounds are updated to match the cropped window.
- Parameters:
y0 – Start row index.
y1 – End row index (exclusive).
x0 – Start column index.
x1 – End column index (exclusive).
- Returns:
arr_crop is the cropped array with shape (C, h, w),
- meta_crop is a copy of the metadata updated with the cropped size and,
when possible, updated transform and bounds.
- Return type:
A tuple (arr_crop, meta_crop) where
- Raises:
ValueError – If the resulting crop is empty or invalid after clamping.
- export_to_tif(out_path: str, arr: ndarray | None = None, meta: Dict[str, Any] | None = None, **kwargs) str[source]
Export the event data, or a provided array, to a GeoTIFF file.
If arr is not provided, the event internal array is exported. If meta is not provided, the event metadata is used. Additional keyword arguments are forwarded to the low-level GeoTIFF export utility.
- Parameters:
out_path – Output path of the GeoTIFF file to create.
arr – Optional array to export. If None, the event internal array is used.
meta – Optional metadata dictionary to use for export. If None, the event metadata is used.
**kwargs – Additional keyword arguments forwarded to the underlying export utility.
- Returns:
The output path of the written GeoTIFF file.
- Raises:
ValueError – If the provided metadata is incomplete or incompatible with GeoTIFF export.
OSError – If the file cannot be written.
- classmethod from_path(product_folder: str, scene_id: int = 0, product_kind: str = 'BC', multiband: bool = True, bands: List[int] | None = None, as_float32: bool = True, verbose: bool = True, device: str = 'cpu') L1_event[source]
Create an
L1_eventfrom a local ΦSat-2 product folder.This class method loads one scene from disk using the ΦSat-2 L1 reader, builds the underlying (C, H, W) array, and attaches the corresponding metadata dictionary.
- Parameters:
product_folder – Path to the local ΦSat-2 product folder.
scene_id – Scene index to load from the product.
product_kind – Product variant to load, for example “BC”.
multiband – Whether to read the product as a multiband array.
bands – Optional subset of band indices to read. If None, all available bands are loaded.
as_float32 – Whether to cast the loaded array to float32.
verbose – If True, print a short loading message.
device – Target device used when converting the event to a torch tensor.
- Returns:
A new
L1_eventinstance initialized from the requested product.- Raises:
FileNotFoundError – If the product folder or required files are missing.
ValueError – If the requested scene or product configuration is invalid.
- get_band(band: int | str | float) ndarray[source]
Return one band from the event as a 2D array.
The band can be selected by: - integer band index, - float wavelength in nanometers, - string specification such as “NIR”, “RED”, “B3”, “BAND_7”,
or “842nm”.
String aliases are resolved through the event wavelength metadata using the closest matching wavelength when needed.
- Parameters:
band – Band selector.
- Returns:
A 2D NumPy array of shape (H, W) corresponding to the selected band.
- Raises:
ValueError – If the band specification cannot be resolved.
- get_meta() Dict[str, Any][source]
Return the metadata dictionary associated with the event.
The metadata may contain fields such as CRS, affine transform, bounds, wavelengths, product paths, sensing time, and creation time.
- Returns:
The event metadata dictionary.
- get_tile(idx_or_name: int | str) L1_tile[source]
Return one tile from the current tile collection.
A tile can be retrieved either by integer index or by its tile_name.
- Parameters:
idx_or_name – Tile index or tile name.
- Returns:
The requested
L1_tileinstance.- Raises:
IndexError – If an integer index is out of range.
KeyError – If a tile name is requested but no matching tile exists.
- get_tiles_info(tiles_idx=None) Dict[str, Any][source]
Return structured information for the currently available tiles.
Each entry is obtained from
L1_tile.get_tile_info()and stored in a dictionary keyed by tile name. The corresponding value is a tuple containing the tile name, sensing time, creation time, tile corner coordinates, and tile footprint coordinates.- Parameters:
tiles_idx – Optional iterable of tile indices to query. If None, all tiles are included.
- Returns:
A dictionary mapping each tile name to its information tuple.
- Raises:
ValueError – If the tile collection is empty.
IndexError – If one of the requested tile indices is out of range.
- get_tiles_names(tiles_idx=None) List[str][source]
Return the names of the currently available tiles.
If tiles_idx is not provided, names for all tiles in the current tile collection are returned. If a subset of indices is given, only the corresponding tile names are returned, in the requested order.
- Parameters:
tiles_idx – Optional iterable of tile indices to query.
- Returns:
A list of tile names.
- Raises:
ValueError – If the tile collection is empty.
IndexError – If one of the requested tile indices is out of range.
- get_wavelengths() List[int | None][source]
Return the list of band center wavelengths in nanometers.
The values are read from the “band_wavelength_nm” entry of the metadata. If no wavelength information is available, an empty list is returned.
- Returns:
A list of wavelengths in nanometers, or an empty list if unavailable.
- index(name: str, **kwargs) ndarray[source]
Compute a built-in normalized spectral index.
Currently supported indices are: - “NDVI”: (NIR - RED) / (NIR + RED) - “NDWI”: (GREEN - NIR) / (GREEN + NIR)
Band selectors can be overridden through keyword arguments. For example, nir, red, and green may each be given as an integer band index, a wavelength in nanometers, or a string alias such as “NIR” or “B3”.
- Parameters:
name – Name of the spectral index to compute.
**kwargs – Optional band selector overrides used by the selected index.
- Returns:
A 2D NumPy array containing the computed index.
- Raises:
ValueError – If the requested index name is not supported.
- make_tiles(tile_size: int = 512, overlap: int = 0, drop_last: bool = False) List[L1_tile][source]
Alias for
to_tiles().This method exists for API convenience and forwards all arguments to
to_tiles().- Parameters:
tile_size – Tile size in pixels for both height and width.
overlap – Overlap in pixels between consecutive tiles.
drop_last – Whether to discard incomplete border tiles.
- Returns:
A list of generated
L1_tileobjects.
- plot_location(mode: str = 'bounds', world: bool = True, tiles_idx=None, title: str | None = None)[source]
Plot the geographic location of the event and optionally overlay tile bounds.
Two plotting modes are supported: - “bounds”: plot the axis-aligned geographic bounding box stored in the event metadata, - “footprint”: plot the scene footprint derived from the GL JSON file referenced by the metadata.
If tiles_idx is provided, the geographic bounds of the selected tiles are overlaid as rectangles on top of the scene plot.
- Parameters:
mode – Plotting mode, either “bounds” or “footprint”.
world – If True, attempt to display the scene on top of a world basemap.
tiles_idx – Optional iterable of tile indices to overlay.
title – Optional plot title. If None, a default title based on the scene identifier and product kind is used.
- Returns:
The Matplotlib axes used for the plot.
- Raises:
ValueError – If the requested mode is unknown, or if the required geospatial metadata is missing for the selected mode.
- rgb(bands=('RED', 'GREEN', 'BLUE'), stretch=(2, 98), arr: ndarray | None = None) ndarray[source]
Build an RGB composite from three selected bands.
By default, the composite uses the “RED”, “GREEN”, and “BLUE” aliases. An optional source array can be provided instead of the event internal array, but it must follow the same band ordering and use shape (C, H, W).
- Parameters:
bands – A length-3 sequence describing the red, green, and blue channels. Each entry can use any valid band selector supported by
get_band().stretch – Percentile stretch applied before composing the RGB image.
arr – Optional source array with shape (C, H, W). If None, the event internal array is used.
- Returns:
An RGB image as a NumPy array, typically with shape (H, W, 3).
- show_bands(bands=None, tile=0, **kwargs) None[source]
Display one or more bands for a selected tile.
This is a convenience wrapper around
L1_tile.show_bands(). By default, it visualizes the first tile in the current collection.- Parameters:
bands – Optional sequence of band selectors to display. If None, all bands of the selected tile are shown.
tile – Tile index or tile name identifying which tile to visualize.
**kwargs – Additional keyword arguments forwarded to
L1_tile.show_bands(), such as downsampling, max_size, stretch, or cmap.
- Returns:
None.
- Raises:
IndexError – If the requested tile index is out of range.
KeyError – If the requested tile name does not exist.
ValueError – If one of the requested band selectors cannot be resolved.
- show_event_info() None[source]
Print a concise summary of the current event.
The printed summary includes the scene identifier, product kind, product folder, source path, array shape and dtype, CRS, geographic bounds, band wavelengths, GL file path, processing configuration path, and the current number of in-memory tiles.
- Returns:
None.
- show_tiles_info() None[source]
Print human-readable information for all currently available tiles.
For each tile, this method prints a PyRawS-style summary including the tile name, sensing time, creation time, corner coordinates, and footprint coordinates.
- Returns:
None.
- Raises:
ValueError – If the tile collection is empty.
- to_tiles(tile_size: int = 512, overlap: int = 0, drop_last: bool = False) List[L1_tile][source]
Split the event into a regular grid of in-memory tiles.
Tiles are extracted from the event array using a sliding window with optional overlap. Each produced tile is stored as an
L1_tileinstance and the internal tile collection of the event is replaced by the generated tiles.If drop_last=False, border tiles are kept even if they are smaller than tile_size. If drop_last=True, only full tiles are retained.
- Parameters:
tile_size – Tile size in pixels for both height and width.
overlap – Overlap in pixels between consecutive tiles.
drop_last – Whether to discard incomplete border tiles.
- Returns:
A list of generated
L1_tileobjects.- Raises:
ValueError – If overlap does not satisfy 0 <= overlap < tile_size.
L1 tile
- class pyrawph.l1.l1_tile.L1_tile(tile_name: str, arr: ndarray, meta: Dict[str, Any], device: str = 'cpu')[source]
Bases:
objectRepresent one local tile extracted from an L1 event.
A tile stores a local multiband array together with its metadata and provides convenience methods for array/tensor conversion, geographic corner retrieval, tile inspection, band visualization, and optional location plotting.
The tile array is expected to follow the (C, H, W) convention, where C is the number of spectral bands. Metadata may include geographic bounds, CRS, band wavelengths, sensing time, and creation time.
- arr: ndarray
- as_numpy() ndarray[source]
Return the tile data as a NumPy array.
The returned array is the internal tile array stored by the object and is expected to have shape (C, H, W).
- Returns:
The tile data as a NumPy array of shape (C, H, W).
- as_tensor(as_float32: bool = True)[source]
Return the tile data as a PyTorch tensor on the configured device.
- Parameters:
as_float32 – If True, cast the tensor to torch.float32 before moving it to the target device.
- Returns:
A PyTorch tensor containing the tile data, typically with shape (C, H, W).
- Raises:
ImportError – If PyTorch is not available in the current environment.
- device: str = 'cpu'
- get_tile_coordinates(latlon_format: bool = True) List[List[float]][source]
Return the four tile corner coordinates derived from the metadata bounds.
Corners are returned in the following order: top-left, bottom-left, bottom-right, top-right.
Coordinates are extracted from meta[“bounds”]. The returned values are formatted as [y, x] pairs. This method does not reproject coordinates; it only reformats the stored bounds values.
- Parameters:
latlon_format – If True, return coordinates in [lat, lon]-style ordering. In the current implementation, coordinates are returned as [y, x] pairs in all cases.
- Returns:
A list of four corner coordinates. If no bounds are available, returns an empty list.
- get_tile_footprint_coordinates(latlon_format: bool = True, closed: bool = False) List[List[float]][source]
Return the tile footprint coordinates as an ordered polygon-like sequence.
This method reuses
get_tile_coordinates()and optionally closes the footprint by repeating the first coordinate at the end.- Parameters:
latlon_format – Forwarded to
get_tile_coordinates().closed – If True, append the first coordinate at the end of the returned list.
- Returns:
A list of footprint coordinates. If no bounds are available, returns an empty list.
- get_tile_info()[source]
Return a compact summary of the tile.
The returned tuple contains the tile name, sensing time, creation time, corner coordinates, and footprint coordinates.
- Returns:
tile name,
sensing time,
creation time,
corner coordinates from
get_tile_coordinates(),footprint coordinates from
get_tile_footprint_coordinates().
- Return type:
A tuple of the form
- meta: Dict[str, Any]
- plot_location(world: bool = True, title: str | None = None)[source]
Plot the geographic location of the tile from its metadata bounds.
This method delegates the actual plotting to pyrawph.utils.optional_plots.plot_bounds. If available, a world basemap can be shown in the background; otherwise the tile rectangle alone is plotted.
- Parameters:
world – If True, attempt to display the tile on top of a world basemap.
title – Optional plot title. If None, the tile name is used.
- Returns:
The Matplotlib axes used for the plot.
- Raises:
ValueError – If the tile metadata does not contain geographic bounds.
- show_bands(bands: Sequence[int | float | str] | None = None, downsampling: bool = True, max_size: int = 512, stretch: Tuple[float, float] = (2.0, 98.0), cmap: str = 'viridis') None[source]
Display one or more tile bands for visual inspection.
If bands is None, all tile bands are displayed. Otherwise, each requested band is resolved from the tile metadata using integer indices, wavelengths in nanometers, or string specifications such as “B3”, “842nm”, “NIR”, or “RED”.
Displayed bands can be downsampled for faster rendering, and each band is independently normalized using a percentile stretch before display.
- Parameters:
bands – Optional sequence of band selectors to display. If None, all tile bands are shown.
downsampling – If True, apply stride-based downsampling so that the displayed image size remains manageable.
max_size – Target maximum size used to determine the downsampling stride.
stretch – Lower and upper percentiles used for contrast stretching.
cmap – Matplotlib colormap used for display.
- Returns:
None.
- Raises:
ValueError – If one of the requested band selectors cannot be resolved.
- tile_name: str