wolfhece.wolf_array._base

Author: HECE - University of Liege, Pierre Archambeau Date: 2024-2026

Copyright (c) 2024 University of Liege. All rights reserved.

This script and its content are protected by copyright law. Unauthorized copying or distribution of this file, via any medium, is strictly prohibited.

Module Contents

wolfhece.wolf_array._base.pgcd_decimal(a, b)[source]
class wolfhece.wolf_array._base.OGLRenderer(*args, **kwds)[source]

Bases: enum.Enum

Inheritance diagram of wolfhece.wolf_array._base.OGLRenderer

Create a collection of name/value pairs.

Example enumeration:

>>> class Color(Enum):
...     RED = 1
...     BLUE = 2
...     GREEN = 3

Access them by:

  • attribute access:

>>> Color.RED
<Color.RED: 1>
  • value lookup:

>>> Color(1)
<Color.RED: 1>
  • name lookup:

>>> Color['RED']
<Color.RED: 1>

Enumerations can be iterated over, and know how many members they have:

>>> len(Color)
3
>>> list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

Methods can be added to enumerations, and members can have their own attributes – see the documentation for details.

LIST = 0[source]
SHADER = 1[source]
classmethod get(value: int)[source]

Return the OGLRenderer value corresponding to an integer value

wolfhece.wolf_array._base.DEFAULT_OGLRENDERER[source]
wolfhece.wolf_array._base.VERSION_RGB = 3[source]
wolfhece.wolf_array._base.custom_gradient(array: numpy.ndarray)[source]

Calculate the gradient manually

wolfhece.wolf_array._base.hillshade(array: numpy.ndarray, azimuth: float, angle_altitude: float) numpy.ndarray[source]

Create a hillshade array

class wolfhece.wolf_array._base.Rebin_Ops(*args, **kwds)[source]

Bases: enum.Enum

Inheritance diagram of wolfhece.wolf_array._base.Rebin_Ops

Enum for rebin/downsampling operations (no wx dependency).

MIN = 0[source]
MEAN = 1[source]
MAX = 2[source]
SUM = 3[source]
MEDIAN = 4[source]
classmethod get_numpy_ops()[source]

Return a list of numpy functions corresponding to the enum values

classmethod get_ops(name: str)[source]

Return the numpy function corresponding to a string

class wolfhece.wolf_array._base.WolfArrayModel(fname: str = None, mold: WolfArrayModel = None, masknull: bool = True, crop: list[list[float], list[float]] = None, whichtype=WOLF_ARRAY_FULL_SINGLE, preload: bool = True, nullvalue: float = 0.0, srcheader: wolfhece.wolf_array._header_wolf.header_wolf = None, idx: str = '', mask_source: numpy.ndarray = None, np_source: numpy.ndarray = None)[source]

Bases: wolfhece.wolf_array._header_wolf.header_wolf

Inheritance diagram of wolfhece.wolf_array._base.WolfArrayModel

Data-only WolfArrayModel class (no GUI/OpenGL dependency at class level).

For GUI support (OpenGL rendering, wx dialogs), use WolfArray from _base_gui.py.

simple précision, double précision, entier…

array: numpy.ma.masked_array[source]
_cache_grid: dict[source]
linkedvec: wolfhece.PyVertexvectors.vector[source]
linkedarrays: list[WolfArrayModel][source]
origx: float[source]
origy: float[source]
origz: float[source]
translx: float[source]
transly: float[source]
translz: float[source]
myops: wolfhece.ui.wolf_array_ops.Ops_Array[source]
_rendering_machine[source]
mngselection = None[source]
myblocks = None[source]
_active_blocks = None[source]
flipupd = False[source]
filename = ''[source]
isblock = False[source]
blockindex = 0[source]
wolftype = 1[source]
preload = True[source]
loaded = False[source]
masknull = True[source]
alpha = 1.0[source]
shading = False[source]
azimuthhill = 315.0[source]
altitudehill = 0.0[source]
shaded = None[source]
_nullvalue = 0.0[source]
nbnotnull = 99999[source]
nbnotnullzoom = 99999[source]
nbtoplot = 0[source]
_gridsize = 256[source]
_lod_max_whole_array = -1[source]
mypal[source]
_cache_grid_last_call = None[source]
_cache_grid_frequency_useconds = 1000[source]
_shader_2d: WolfArrayShader2D | None = None[source]
_array3d = None[source]
_array2d = None[source]
viewers3d: list[wolfhece.opengl.py3d.WolfArrayPlotShader] = [][source]
cropini = None[source]
property memory_usage[source]

Return the memory usage of the header

property memory_usage_mask[source]

Return the memory usage of the mask

property nullvalue: float[source]

Return the null value

property nodata: float[source]

alias for nullvalue

property SelectionData: wolfhece.wolf_array._selection_data.SelectionData[source]

Return the data of the selection

property active_blocks: list[WolfArrayModel][source]

Return the active blocks

property dtype[source]

Return the numpy dtype corresponding to the WOLF type

Pay ettention to the difference between :
  • LOGICAL : Fortran and VB6

  • Bool : Python

In VB6, logical is stored as int16 In Fortran, there are Logical*1, Logical*2, Logical*4, Logical*8 In Python, bool is one byte In Numpy, np.bool_ is one byte

property dtype_gdal[source]

Return the GDAL dtype corresponding to the WOLF type

property dtype_str[source]

Return the numpy dtype corresponding to the WOLF type, as a string

Pay ettention to the difference between :
  • LOGICAL : Fortran and VB6

  • Bool : Python

In VB6, logical is stored as int16 In Fortran, there are Logical*1, Logical*2, Logical*4, Logical*8 In Python, bool is one byte In Numpy, np.bool_ is one byte

property zmin[source]

Return the minimum value of the masked array

property zmax[source]

Return the maximum value of the masked array

property zmin_global[source]

Return the minimum value of the array – all data (masked or not)

property zmax_global[source]

Return the maximum value of the array – all data (masked or not)

get_mapviewer()[source]

Return the mapviewer

set_mapviewer(newmapviewer=None)[source]

Attach a (new) mapviewer to the object

Parameters:

newmapviewer – new mapviewer instance to attach (None to detach)

_prompt_crop(dx: float, dy: float) list | None[source]

Prompt user for crop bounds. Returns [[xmin,xmax],[ymin,ymax]] or None.

In data-only mode, returns None (no interaction possible). Overridden in WolfArray to show CropDialog.

Parameters:
  • dx – cell size in x direction (used for pre-filling the dialog)

  • dy – cell size in y direction (used for pre-filling the dialog)

_prompt_band_selection(band_names: list[str]) int | None[source]

Prompt user for band selection. Returns 1-based band index or None.

In data-only mode, returns 1 (first band). Overridden in WolfArray to show SingleChoiceDialog.

Parameters:

band_names – list of band name strings to choose from

_prompt_save_file(message: str, wildcard: str) str | None[source]

Prompt user for a file path to save. Returns path or None.

In data-only mode, returns None. Overridden in WolfArray to show FileDialog.

Parameters:
  • message – dialog title / prompt message

  • wildcard – file filter pattern (e.g. "TIFF files (*.tif)|*.tif")

_show_error_dialog(message: str)[source]

Show an error dialog to the user.

In data-only mode, just logs. Overridden in WolfArray to show wx.MessageDialog.

Parameters:

message – error message to display or log

reset_plot(whichpal=0, mimic=True)[source]

Reset plot - no-op in data-only mode; overridden in WolfArray (GUI)

Parameters:
  • whichpal – palette index (default: 0)

  • mimic – if True, propagate to linked arrays

updatepalette(which: int = 0, onzoom=[])[source]

Update palette - minimal version without OGL; overridden in WolfArray (GUI)

Parameters:
  • which – palette index (default: 0)

  • onzoom – zoom window [xmin, xmax, ymin, ymax]; empty list for whole array

delete_lists()[source]

Delete OpenGL lists - no-op in data-only mode; overridden in WolfArray (GUI)

find_minmax(update=False)[source]

Find min/max spatial extent

Parameters:

update – if True, recalculate spatial bounds from array dimensions

_new_like() WolfArrayModel[source]

Create a new empty instance of the same concrete type, copying grid geometry but not array data.

Uses type(self)(...) so that subclasses (e.g. WolfArray) return an instance of the subclass without needing to override this method. Override in a subclass only if extra initialisation is required (e.g. attaching a mapviewer).

Returns:

new instance with the same spatial properties and wolftype

Return type:

same type as self

allocate_ressources()[source]

Allocate the numpy masked array according to the current dtype and dimensions.

reset()[source]

Reset the array to nullvalue

init_from_header(myhead: wolfhece.wolf_array._header_wolf.header_wolf, dtype: numpy.dtype = None, force_type_from_header: bool = False)[source]

Initialize the array properties from a header_wolf object

Parameters:
  • myhead – header_wolf object

  • dtype – numpy dtype

  • force_type_from_header – force the type from the header passed as argument

get_header(abs: bool = True) wolfhece.wolf_array._header_wolf.header_wolf[source]

Return a header_wolf object - different from the self object header

Parameters:

abs – if True (default), return an absolute header (shifted origin) and translation set to 0.

Returns:

new header_wolf with copied spatial properties

Return type:

header_wolf

set_header(header: wolfhece.wolf_array._header_wolf.header_wolf)[source]

Set the header from a header_wolf object

Parameters:

headerheader_wolf instance to copy properties from

set_array_from_numpy(array: numpy.ndarray, nullvalue: float = None)[source]

Set array from numpy array

Parameters:
  • array – numpy array with shape (nbx, nby)

  • nullvalue – null value to apply and mask; if None, use current nullvalue

read_all(which_band=None)[source]

Read the array from disk, auto-detecting the file format (WOLF binary, GeoTIFF, VRT, NumPy).

Parameters:

which_band – band index (1-based) for multi-band rasters (GeoTIFF, VRT)

read_data()[source]

Read binary array data from the current file, with optional cropping.

_read_binary_data(f, seek=0)[source]

Read binary data from file

Parameters:
  • f – open file handle in binary read mode

  • seek – byte offset to seek to before reading (0 = read from current position)

read_txt_header()[source]

Read header from txt file Supercharged by WolfArrayModel to avoid explicit call to read_txt_header with parameters

_reload()[source]

Reload the data from the file

write_all(newpath: str | pathlib.Path = None, EPSG: int = None)[source]

Ecriture de tous les fichiers d’un Wolf array

Parameters:
  • newpath – new path and filename with extension – if None, use the current filename

  • EPSG – EPSG code for geotiff

write_array()[source]

Write the raw binary array data to the current file.

write_txt_header()[source]

Write header to txt file Supercharged by WolfArrayModel to avoid explicit call to write_txt_header with parameters

write_xyz(fname: str)[source]

Write all unmasked cell data as an XYZ text file.

Parameters:

fname – output file path for the XYZ file

get_xyz(which='all') numpy.ndarray[source]

Return an array of xyz coordinates and values

Parameters:

which – which values to export: 'all' includes all unmasked cells

Returns:

Nx3 array of [x, y, z] coordinates for all unmasked cells

Return type:

numpy.ndarray

_import_npy(fn: str = '', crop: list[float] = None)[source]

Import a numpy file.

Must be called after the header is initialized, e.g. read_txt_header.

Parameters:
  • fn – filename

  • crop – crop the data - [xmin, xmax, ymin, ymax]

import_vrt(fn: str = '', which: int = None, crop: list[float] = None)[source]

Import a VRT file.

A Virtual Raster Tile (VRT) is an XML-based format used by GDAL to describe a raster dataset. It allows users to create virtual datasets that reference other raster files without duplicating the actual data. VRT files can be used to mosaic multiple raster files, apply transformations, or define custom raster structures.

Parameters:
  • fn – filename

  • which – band to import

  • crop – crop the data - [xmin, xmax, ymin, ymax]

import_geotif(fn: str = '', which: int = None, crop: list[float] = None)[source]

Import Geotiff Raster file.

A Geotiff (Geographic Tagged Image File Format) is a widely used raster file format that embeds geographic metadata within the TIFF file structure. It allows for the storage of georeferencing information, such as coordinate systems, map projections, and spatial extents, alongside the raster image data. This makes Geotiff files suitable for use in Geographic Information Systems (GIS) and remote sensing applications.

Formats supportés :
  • Int8

  • Int16

  • Int32

  • Float32

  • Float64

  • uInt8

  • uInt16

  • uInt32

Parameters:
  • fn – filename

  • which – band to import

  • crop – crop the data - [xmin, xmax, ymin, ymax] or [[xmin, xmax], [ymin, ymax]]

import_from_gltf(fn: str = '', fnpos: str = '', interp_method: Literal['matplotlib', 'scipy'] = 'matplotlib')[source]

Import from GLTF/GLB format

Parameters:
  • fn – filename

  • fnpos – filename for the position’s information

  • interp_method – method for the interpolation – ‘matplotlib’ or ‘scipy’

export_geotif(outdir: str = '', extent: str = '', EPSG: int = None)[source]

Export de la matrice au format Geotiff

Pour sauvegarder l’objet au format Geotiff, il est recommandé d’utiliser la fonction write_all plutôt que celle-ci directement.

Formats supportés :
  • Int32

  • Int16

  • Int8

  • Byte

  • Float32

  • Float64

Parameters:
  • outdir – directory - If provided, the file will be savd as “outdir/idx+extent.tif” If not provided, we use the filename attribute

  • extent – suffix to add to the filename before the extension ‘.tif’ (only if outdir is provided)

  • EPSG – EPSG code, by default 31370 (Lambert 72)

export_cityjson(outdir: str = '', extent: str = '', EPSG: int = None)[source]

Export the array as a CityJSON file with one polygon per grid cell.

Parameters:
  • outdir – output directory; empty string uses filename

  • extent – suffix appended to filename before .json extension

  • EPSG – EPSG code for the coordinate reference system (default: 31370)

export_to_gltf(bounds: list[float] = None, fn: str = '')[source]

Export to GLTF/GLB format

Parameters:
  • bounds – [[xmin,xmax],[ymin,ymax]]

  • fn – filename

check_bounds_ij(i: int, j: int)[source]

Check if i and j are inside the array bounds

Parameters:
  • i – column index (0-based)

  • j – row index (0-based)

Returns:

True if (i, j) is inside the array bounds

Return type:

bool

check_bounds_xy(x: float, y: float)[source]

Check if i and j are inside the array bounds

Parameters:
  • x – x-coordinate in world space

  • y – y-coordinate in world space

Returns:

True if (x, y) falls inside the array spatial extent

Return type:

bool

get_centers(usenap: bool = True)[source]

Get the centers of the cells

Parameters:

usenap – if True, return only unmasked cell centers; if False, return all

Returns:

flattened array of cell center coordinates [x1, y1, x2, y2, ...]

Return type:

numpy.ndarray

get_dxdy_min()[source]

Return the minimal size

Mainly useful in PyVertexVectors to get the minimal size of the cells and ensure compatibility with the 2D results (GPU and Multiblocks)

get_dxdy_max()[source]

Return the maximal size

Mainly useful in PyVertexVectors to get the minimal size of the cells and ensure compatibility with the 2D results (GPU and Multiblocks)

meshgrid(mode: Literal['gc', 'borders'] = 'gc')[source]

Création d’un maillage 2D

Parameters:

mode – ‘gc’ pour les centres de mailles, ‘borders’ pour les bords de mailles

get_value(x: float, y: float, z: float = 0.0, nullvalue: float = -99999, convert_to_float: bool = True)[source]

Return the value at given coordinates

Parameters:
  • x – x coordinate

  • y – y coordinate

  • z – z coordinate

  • nullvalue – value to return if the point is outside the array

  • convert_to_float – if True, cast the result to float

get_xlim(window_x: float, window_y: float)[source]

Return the limits in x for a given window size

Parameters:
  • window_x – window size in x

  • window_y – window size in y

get_ylim(window_x: float, window_y: float)[source]

Retrun the limits in y for a given window size

Parameters:
  • window_x – window size in x

  • window_y – window size in y

get_working_array(onzoom: list[float] = [])[source]

Return the part of the array in the zoom window

Parameters:

onzoom – zoom window – [xmin, xmax, ymin, ymax]

loadnap_and_apply()[source]

Load a mask file (aka nap) and apply it to the array;

The mask values are set to the nullvalue.

The mask file must have the same name as the array file, with the extension .napbin. It is useful for 2D WOLF simulations.

mask_data(value)[source]

Mask all cells whose value equals the given value.

Parameters:

value – cells equal to this value will be masked

mask_lower(value)[source]

Mask cell where values are strictly lower than value

Parameters:

value – cells strictly below this value will be masked

mask_lowerequal(value)[source]

Mask cell where values are lower or equal than value

Parameters:

value – cells below or equal to this value will be masked

mask_greater(value)[source]

Mask cell where values are strictly greater than value

Parameters:

value – cells strictly above this value will be masked

mask_greaterequal(value)[source]

Mask cell where values are greater or equal than value

Parameters:

value – cells above or equal to this value will be masked

mask_allexceptdata(value)[source]

Mask cell where values are different from value

Parameters:

value – only cells with this exact value remain unmasked

mask_invert()[source]

Invert the mask

mask_outsidepoly(myvect: wolfhece.PyVertexvectors.vector, eps: float = 0.0, set_nullvalue: bool = True, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict')[source]

Mask all cells located outside a polygon.

Parameters:
  • myvect – target vector in global coordinates

  • eps – tolerance for boundary detection

  • set_nullvalue – if True, set masked cells to nullvalue

  • method – spatial method: 'mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'

mask_insidepoly(myvect: wolfhece.PyVertexvectors.vector, eps: float = 0.0, set_nullvalue: bool = True, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'mpl')[source]

Mask all cells located inside a polygon.

Parameters:
  • myvect – target vector in global coordinates

  • eps – tolerance for boundary detection

  • set_nullvalue – if True, set masked cells to nullvalue

  • method – spatial method: 'mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'

mask_insidepolys(myvects: list[wolfhece.PyVertexvectors.vector], eps: float = 0.0, set_nullvalue: bool = True, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'mpl')[source]

Mask all cells located inside any of the given polygons.

Parameters:
  • myvect – target vector in global coordinates

  • myvects – list of polygon vectors to mask inside

  • eps – tolerance for boundary detection

  • set_nullvalue – if True, set masked cells to nullvalue

  • method – spatial method: 'mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'

copy_mask(source: WolfArrayModel, forcenullvalue: bool = False, link: bool = True)[source]

Copy/Link the mask from another WolfArrayModel

Parameters:
  • source – WolfArrayModel source

  • forcenullvalue – force nullvalue in the masked zone

  • link – link the mask if True (default), copy it otherwise

mask_union(source: WolfArrayModel, link: bool = True)[source]

Union of the mask with another WolfArrayModel

Parameters:
  • source – WolfArrayModel source

  • link – link the mask if True (default), copy it otherwise

mask_unions(sources: list[WolfArrayModel], link: bool = True)[source]

Compute the union of masks from this array and a list of source arrays.

Parameters:
  • source – list of WolfArrayModel sourceq

  • link – link the mask if True (default), copy it otherwise

  • sources – list of WolfArrayModel whose masks are unified

copy_mask_log(mask: numpy.ndarray, link: bool = True)[source]

Copy the mask from a numpy array

Parameters:
  • mask – numpy array

  • link – link the mask if True (default), copy it otherwise

set_nullvalue_in_mask()[source]

Set nullvalue in masked cells

mask_force_null()[source]

Force to unmask all and mask null value

unmask()[source]

alias to mask_reset

mask_clear()[source]

alias to mask_reset

mask_reset()[source]

Unmask everything

create_binary_mask(threshold: float = 0.0) WolfArrayModel[source]

Create a binary mask from the array

Parameters:

threshold – values above this threshold become 1 (unmasked), others become 0 (masked)

Returns:

new binary array (1 where value > threshold, 0 otherwise)

Return type:

WolfArrayModel

count()[source]

Count the number of not masked values

get_xy_inside_polygon(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon, usemask: bool = True, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict', epsilon: float = 0.0)[source]

Return the coordinates inside a polygon.

Main principle: - Get all the coordinates in the footprint of the polygon (taking into account the epsilon if provided) - Test each coordinate if it is inside the polygon or not (and along boundary if method allows it) - Apply the mask if requested

Returned values are stored in an array of shape (N,2) with N the number of points found inside the polygon.

Parameters:
  • myvect – target vector - vector or Shapely Polygon

  • usemask – limit potential nodes to unmaksed nodes

  • method – method to use (‘mpl’, ‘shapely_strict’, ‘shapely_wboundary’, ‘rasterio’) - default is ‘shapely_strict’

  • epsilon – tolerance for the point-in-polygon test - default is 0.

get_xy_strictly_on_borders(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon | shapely.geometry.LineString, usemask: bool = True, method: Literal['shapely'] = 'shapely')[source]

Return the coordinates strictly on the borders of a polygon.

ATTENTION : Tests are performed numerically, so the results may not be exact in the sense of pure geometry.

Do not confuse with “get_xy_under_polyline” which “rasterize” the polyline to find useful coordinates.

Parameters:
  • myvect – target vector

  • usemask – limit potential nodes to unmaksed nodes

  • method – method to use (‘shapely’ for now)

get_xy_strictly_on_vertices(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon | shapely.geometry.LineString, usemask: bool = True, method: Literal['shapely'] = 'shapely', eps: float = 0.0001)[source]

Return the coordinates strictly on the vertices of a polygon, Linestring or vector.

ATTENTION : Tests are performed numerically, so the results may not be exact in the sense of pure geometry.

Parameters:
  • myvect – target vector

  • usemask – limit potential nodes to unmaksed nodes

  • method – method to use (‘shapely’ for now)

  • eps – distance tolerance for matching a vertex to a cell center

get_xy_inside_polygon_mpl(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon, usemask: bool = True, epsilon: float = 0.0)[source]

Return the coordinates inside a polygon

Parameters:
  • myvect – target vector

  • usemask – limit potential nodes to unmaksed nodes

  • epsilon – tolerance for path containment (matplotlib)

get_xy_inside_polygon_shapely(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon, usemask: bool = True, strictly: bool = True, epsilon: float = 0.0)[source]

Return the coordinates inside a polygon

Parameters:
  • myvect – target vector

  • usemask – limit potential nodes to unmaksed nodes

  • strictly – if True, use strict containment; otherwise include boundary

  • epsilon – buffer tolerance for boundary inclusion

get_xy_inside_polygon_rasterio(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon, usemask: bool = True, epsilon: float = 0.0)[source]

Return the coordinates inside a polygon

Parameters:
  • myvect – polygon vector in global coordinates

  • usemask – if True, consider only unmasked cells

  • epsilon – tolerance (not used in rasterio method)

get_xy_under_polyline(myvect: wolfhece.PyVertexvectors.vector, usemask: bool = True)[source]

Return the coordinates along a polyline

Parameters:
  • myvect – target vector

  • usemask – limit potential nodes to unmaksed nodes

get_ij_inside_polygon(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon, usemask: bool = True, eps: float = 0.0, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict')[source]

Return the indices inside a polygon.

Main principle: - First, get all indices in the footprint of the polygon (bounding box + epsilon) - Then, test each point if it is inside the polygon with the selected method - Filter with the mask if needed

Returned indices are stored in an array of shape (N,2) with N the number of points found inside the polygon.

Parameters:
  • myvect – target vector

  • usemask – limit potential nodes to unmaksed nodes

  • eps – epsilon for the intersection

  • method – method to use (‘mpl’, ‘shapely_strict’, ‘shapely_wboundary’, ‘rasterio’) - default is ‘shapely_strict’

get_ij_inside_listofpolygons(myvects: list[wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon], usemask: bool = True, eps: float = 0.0, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict')[source]

Return the indices inside a list of polygons :param myvects: target vector :param usemask: limit potential nodes to unmaksed nodes :param eps: epsilon for the intersection :param method: method to use (‘mpl’, ‘shapely_strict’, ‘shapely_wboundary’, ‘rasterio’) - default is ‘shapely_strict’

get_ij_inside_polygon_mpl(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon, usemask: bool = True, eps: float = 0.0)[source]

Return the indices inside a polygon

Parameters:
  • myvect – target vector

  • usemask – limit potential nodes to unmaksed nodes

  • eps – epsilon for the intersection

get_ij_inside_polygon_shapely(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon, usemask: bool = True, eps: float = 0.0, strictly: bool = True)[source]

Return the indices inside a polygon with the contains method of shapely

Parameters:
  • myvect – target vector

  • usemask – limit potential nodes to unmaksed nodes

  • eps – epsilon for the intersection

  • strictly – if True, the points on the border are not considered inside

_get_ij_inside_polygon_rasterio(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon, usemask: bool = True, eps: float = 0.0)[source]

Return the indices inside a polygon with the geometry_mask method of rasterio.

Remark:

get_ij_inside_polygon_shapely is more efficient

FIXME : geometry_mask seems strange – it does not work as documented – RatsrIO 1.3.x

Parameters:
  • myvect – target vector

  • usemask – limit potential nodes to unmaksed nodes

  • eps – epsilon for the intersection

intersects_polygon(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon, usemask: bool = True, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict', buffer: float = 0.0) bool[source]

Return True if the array intersects the polygon

Parameters:
  • myvect – target vector

  • usemask – limit potential nodes to unmaksed nodes

  • method – spatial method: 'mpl', 'shapely_strict', 'shapely_wboundary', or 'rasterio'

  • buffer – buffer distance around the polygon for intersection test

intersects_polygon_shapely(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon, eps: float = 0.0, usemask: bool = True, buffer: float = 0.0) bool[source]

Return True if the array intersects the polygon

Parameters:
  • myvect – target vector

  • usemask – limit potential nodes to unmaksed nodes

  • eps – epsilon for the intersection

  • buffer – buffer for the intersection - using buffer from Shapely [m]

interects_listofpolygons(myvects: wolfhece.PyVertexvectors.zone | list[wolfhece.PyVertexvectors.vector], usemask: bool = True, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict', buffer: float = 0.0) list[bool][source]

Element-wise intersection with a list of polygons

Parameters:
  • myvects – list of polygon vectors to test

  • usemask – if True, consider only unmasked cells

  • method – spatial query method for intersection test

  • buffer – buffer distance around each polygon

intersects_zones(zones: wolfhece.PyVertexvectors.Zones | list[wolfhece.PyVertexvectors.zone], usemask: bool = True, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict', buffer: float = 0.0) list[list[bool]][source]

Element-wise intersection with a list of zones

Parameters:
  • zonesZones instance containing polygons to test

  • usemask – if True, consider only unmasked cells

  • method – spatial query method for intersection test

  • buffer – buffer distance around each polygon

get_total_area_if_intersects(myvects: wolfhece.PyVertexvectors.Zones | list[wolfhece.PyVertexvectors.vector], usemask: bool = True, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict', buffer: float = 0.0, coefficient: float = 1.0) float | list[float][source]

Return the area of the intersection with a list of polygons

Parameters:
  • myvects – list of polygon vectors

  • usemask – if True, consider only unmasked cells

  • method – spatial query method for intersection test

  • buffer – buffer distance around each polygon

  • coefficient – area multiplier (e.g. for unit conversion)

get_ij_under_polyline(myvect: wolfhece.PyVertexvectors.vector, usemask: bool = True, step_factor: float = 1.0)[source]

Return the indices along a polyline

Parameters:
  • myvect – target vector

  • usedmask – limit potential nodes to unmaksed nodes

  • step_factor – step factor for the discretization of myvect (<1 for thinner, >1 for coarser)

  • usemask – if True, exclude masked cells from result

Returns:

array of shape (N,2) with N the number of points found under the polyline

get_values_insidepoly(myvect: wolfhece.PyVertexvectors.vector, usemask: bool = True, getxy: bool = False, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict') tuple[numpy.ndarray, numpy.ndarray | None][source]

Return the cell values located inside a polygon.

Parameters:
  • usemask – (optional) restreint les éléments aux éléments non masqués de la matrice

  • getxy – (optional) retourne en plus les coordonnées des points

  • myvect – polygon vector in global coordinates

  • method – spatial method: 'mpl', 'shapely_strict', etc.

get_values_inside_listofpolygons(myvects: wolfhece.PyVertexvectors.zone | list[wolfhece.PyVertexvectors.vector], usemask: bool = True, getxy: bool = False) dict[source]

Return the cell values located inside a list of polygons.

Parameters:
  • myvects – list of polygon vectors

  • usemask – if True, consider only unmasked cells

  • getxy – if True, also return xy coordinates

get_values_inside_zones(zones: wolfhece.PyVertexvectors.Zones | list[WolfArrayModel.get_values_inside_zones.zone], usemask: bool = True, getxy: bool = False) dict[source]

Return the cell values located inside all polygons of a Zones object.

Parameters:
  • zonesZones instance

  • usemask – if True, consider only unmasked cells

  • getxy – if True, also return xy coordinates

get_values_underpoly(myvect: wolfhece.PyVertexvectors.vector, usemask: bool = True, getxy: bool = False)[source]

Return the cell values located under a polyline.

Parameters:
  • usemask – (optional) restreint les éléments aux éléments non masqués de la matrice

  • getxy – (optional) retourne en plus les coordonnées des points

  • myvect – polyline vector in global coordinates

get_all_values_insidepoly(myvect: wolfhece.PyVertexvectors.vector, usemask: bool = True, getxy: bool = False)[source]

Return all cell values (including masked) inside a polygon.

Parameters:
  • usemask – (optional) restreint les éléments aux éléments non masqués de la matrice

  • getxy – (optional) retourne en plus les coordonnées des points

  • myvect – polygon vector in global coordinates

ICI on retourne le résultat de get_values_insidepoly, car une seule matrice, mais une autre classe pourrait vouloir faure autre chose

C’est le cas notamment de Wolfresults_2D

get_all_values_underpoly(myvect: wolfhece.PyVertexvectors.vector, usemask: bool = True, getxy: bool = False)[source]

Return all cell values (including masked) under a polyline.

Parameters:
  • usemask – (optional) restreint les éléments aux éléments non masqués de la matrice

  • getxy – (optional) retourne en plus les coordonnées des points

  • myvect – polyline vector in global coordinates

ICI on retourne le résultat de get_values_underpoly, car une seule matrice, mais une autre classe pourrait vouloir faure autre chose

C’est le cas notamment de Wolfresults_2D

count_unique_pixels() dict[int, int][source]

Count the number of pixels for each unique value in the array :return: dictionary with the code as key and the number of pixels as value

get_unique_areas(format: Literal['m2', 'ha', 'km2'] = 'm2') dict[int, float][source]

Get the areas of each code in the array :param array: numpy array or WolfArrayModel :param format: output format: 'dict' returns a dict, 'list' returns a list :return: dictionary with the code as key and the area in m² as value

count_insidepoly(myvect: wolfhece.PyVertexvectors.vector, usemask: bool = True, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict', coefficient: float = 1.0)[source]

Compte le nombre de valeurs contenues dans un polygone

Parameters:
  • myvect – target vector

  • usemask – (optional) restreint les éléments aux éléments non masqués de la matrice

  • method – (optional) method to use

  • coefficient – (optional) coefficient to apply to the count (default 1.)

count_inside_listofpolygons(myvects: wolfhece.PyVertexvectors.zone | list[wolfhece.PyVertexvectors.vector], usemask: bool = True, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict', coefficient: float = 1.0)[source]

Compte le nombre de valeurs contenues dans une instance Zones ou une liste de vecteurs

Parameters:
  • myvects – target vectors or zone

  • usemask – (optional) restreint les éléments aux éléments non masqués de la matrice

  • method – (optional) method to use

  • coefficient – (optional) coefficient to apply to the count (default 1.)

count_inside_zones(zones: wolfhece.PyVertexvectors.Zones | list[wolfhece.PyVertexvectors.zone], usemask: bool = True, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict', coefficient: float = 1.0)[source]

Compte le nombre de valeurs contenues dans une instance Zones ou une liste de “zone”

Parameters:
  • zones – target zones or list of zones

  • usemask – (optional) restreint les éléments aux éléments non masqués de la matrice

  • method – (optional) method to use

  • coefficient – (optional) coefficient to apply to the count (default 1.)

interpolate_on_polygon(working_vector: wolfhece.PyVertexvectors.vector, method: Literal['nearest', 'linear', 'cubic'] = 'linear', keep: Literal['all', 'below', 'above'] = 'all', rescale: bool = False, method_selection: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict', usemask: bool = True, epsilon: float = 0.0)[source]

Interpolation sous un polygone.

L’interpolation a lieu :
  • uniquement dans les mailles sélectionnées si elles existent

  • dans les mailles contenues dans le polygone sinon

On utilise ensuite “griddata” de Scipy pour interpoler les altitudes des mailles depuis les vertices 3D du polygone.

ATTENTION:

l’interpolation est réalisée en réels flottants 64 bits. Le résultat sera ensuite transformé dans le type de la matrice.

Parameters:
  • working_vector – vector - polygon with z values

  • method – interpolation method - ‘nearest’, ‘linear’ or ‘cubic’

  • keep – ‘all’ to keep all interpolated values ‘below’ to keep only values below the current value in the array ‘above’ to keep only values above the current value in the array

  • rescale – rescale the input data to [0, 1] for better numerical stability (only for ‘linear’ and ‘cubic’ methods)

  • method_selection – cell selection method: 'mpl', 'shapely_strict', 'shapely_wboundary', or 'rasterio'

  • usemask – if True, interpolate only within unmasked cells

  • epsilon – tolerance for boundary detection

Returns:

None

interpolate_on_polygons(working_zone: wolfhece.PyVertexvectors.zone, method: Literal['nearest', 'linear', 'cubic'] = 'linear', keep: Literal['all', 'below', 'above'] = 'all')[source]

Interpolate values inside each polygon of a zone using vertex elevations.

Parameters:
  • working_zone – zone containing multiple polygons

  • method – interpolation method: 'nearest', 'linear', or 'cubic'

  • keep – value-keeping strategy: 'all', 'below', or 'above'

interpolate_strictly_on_polyline(working_vector: wolfhece.PyVertexvectors.vector, usemask=True, keep: Literal['all', 'below', 'above'] = 'all')[source]

Set cell values along a polyline using the z-coordinates of the polyline vertices.

On utilise ensuite “interpolate” de shapely pour interpoler les altitudes des mailles depuis les vertices 3D de la polyligne

Parameters:
  • working_vector – polyline vector with 3D vertices

  • usemask – if True, only update unmasked cells

  • keep – value-keeping strategy: 'all', 'below', or 'above'

interpolate_strictly_on_vertices(working_vector: wolfhece.PyVertexvectors.vector, usemask=True, keep: Literal['all', 'below', 'above'] = 'all')[source]

Set cell values at the exact positions of the vector vertices.

On utilise ensuite “interpolate” de shapely pour interpoler les altitudes des mailles depuis les vertices 3D de la polyligne

Parameters:
  • working_vector – vector with 3D vertices

  • usemask – if True, only update unmasked cells

  • keep – value-keeping strategy: 'all', 'below', or 'above'

interpolate_on_polyline(working_vector: wolfhece.PyVertexvectors.vector, usemask=True)[source]

Interpolate cell values along a polyline based on its 3D vertices.

L’interpolation a lieu :
  • uniquement dans les mailles sélectionnées si elles existent

  • dans les mailles sous la polyligne sinon

On utilise ensuite “interpolate” de shapely pour interpoler les altitudes des mailles depuis les vertices 3D de la polyligne

Parameters:
  • working_vector – polyline vector with 3D vertices

  • usemask – if True, only update unmasked cells

interpolate_on_polylines(working_zone: wolfhece.PyVertexvectors.zone, usemask=True)[source]

Interpolate cell values along all polylines in a zone.

Parameters:
  • working_zone – zone containing multiple polylines

  • usemask – if True, only update unmasked cells

interpolate_on_cloud(xy: numpy.ndarray, z: numpy.ndarray, method: Literal['linear', 'nearest', 'cubic'] = 'linear')[source]

Interpolation sur un nuage de points.

L’interpolation a lieu :
  • uniquement dans les mailles sélectionnées si elles existent

  • dans les mailles contenues dans le polygone convexe contenant les points sinon

Using griddata from Scipy.

Parameters:
  • xy – numpy.array of vertices - shape (n,2)

  • z – numpy.array of values - shape (n,)

  • method – method for the interpolation – ‘nearest’, ‘linear’ or ‘cubic’

See : https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html

interpolate_on_triangulation(coords, triangles, grid_x=None, grid_y=None, mask_tri=None, interp_method: Literal['matplotlib', 'scipy'] = 'scipy', keep: Literal['all', 'below', 'above'] = 'all', points_along_edges: bool = True)[source]

Interpolation sur une triangulation.

L’interpolation a lieu :
  • uniquement dans les mailles sélectionnées si elles existent

  • dans les mailles contenues dans la triangulation sinon

Scipy(griddata) is used by default (more robust), but Matplotlib can be used as well (more strict). If Matplotlib crashes, try with Scipy.

Matplotlib is more strict on the quality of the triangulation.

Parameters:
  • coords – numpy.array of vertices - shape (n,3)

  • triangles – numpy.array of triangles - shape (m,3)

  • grid_x – numpy.array of x values where the interpolation will be done – if None, the grid is created from the array

  • grid_y – numpy.array of y values where the interpolation will be done – if None, the grid is created from the array

  • mask_tri – numpy.array of mask for the triangles

  • interp_method – method for the interpolation – ‘matplotlib’ or ‘scipy’

  • keep – ‘all’ to keep all values, ‘below’ to keep only values below the current array, ‘above’ to keep only values above the current array

  • points_along_edges – number of extra points to add along triangle edges for refinement

For matplotlib algo, see : https://matplotlib.org/stable/gallery/images_contours_and_fields/triinterp_demo.html For scipy algo, see : https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html

interpolate_on_triangulations(multiple_triangulations: list[wolfhece.PyVertexvectors.Triangulation], interp_method: Literal['matplotlib', 'scipy'] = 'scipy', keep: Literal['all', 'below', 'above'] | list[str] = 'all')[source]

Interpolation sur plusieurs triangulations.

Parameters:
  • multiple_triangulations – list of Triangulation objects

  • interp_method – method for the interpolation – ‘matplotlib’ or ‘scipy’

  • keep – ‘all’ to keep all values, ‘below’ to keep only values below the current array, ‘above’ to keep only values above the current array or a list of such values for each triangulation

interpolation2D(key: str = '1')[source]

Perform a 2D interpolation over the selected cells using key reference points.

Parameters:

key – interpolation key identifying the source data or method

rasterize_vector_valuebyid(working_vector: wolfhece.PyVertexvectors.vector, id, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict', usemask: bool = True, epsilon: float = 0.0)[source]

Rasterize a vector using the value of the id

Parameters:
  • working_vector – vector to rasterize

  • id – attribute id whose value will fill the rasterized cells

  • method – spatial method: 'mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'

  • usemask – if True, only rasterize unmasked cells

  • epsilon – boundary tolerance

rasterize_zone_valuebyid(working_zone: wolfhece.PyVertexvectors.zone, id, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict', usemask: bool = True, epsilon: float = 0.0)[source]

Rasterize each vector of a zone using the value of the given attribute id.

Parameters:
  • working_zone – zone containing vectors to rasterize

  • id – attribute id whose value will fill rasterized cells

  • method – spatial method for cell selection

  • usemask – if True, only rasterize unmasked cells

  • epsilon – boundary tolerance

rasterize_zones_valuebyid(working_zones: wolfhece.PyVertexvectors.Zones, id, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict', usemask: bool = True, epsilon: float = 0.0)[source]

Rasterize each vector of a Zones collection using the value of the given attribute id.

Parameters:
  • working_zonesZones containing vectors to rasterize

  • id – attribute id whose value will fill rasterized cells

  • method – spatial method for cell selection

  • usemask – if True, only rasterize unmasked cells

  • epsilon – boundary tolerance

fillin_vector_with_value(working_vector: wolfhece.PyVertexvectors.vector, value: int | float | str, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict', usemask: bool = True, epsilon: float = 0.0)[source]

Fill in a vector using the provided value

Parameters:
  • working_vector – vector

  • value – value to fill in (float or int depending on the array type)

  • method – method to get points inside the polygon - ‘mpl’ : matplotlib.path.Path.contains_points (fast for simple polygons) - ‘shapely_strict’ : shapely contains (strictly inside the polygon) - ‘shapely_wboundary’ : shapely contains or on the boundary (inside or on the polygon) - ‘rasterio’ : rasterio.features.rasterize (fast for complex polygons with holes)

  • usemask – if True, only fill in the masked points

  • epsilon – tolerance for shapely methods (to consider points on the boundary)

fillin_zone_with_value(working_zone: wolfhece.PyVertexvectors.zone, value, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict', usemask: bool = True, epsilon: float = 0.0)[source]

Fill all cells inside each vector of a zone with the given value.

Parameters:
  • working_zone – zone whose vectors define the fill area

  • value – value to assign to cells inside the zone vectors

  • method – spatial method for cell selection

  • usemask – if True, only fill unmasked cells

  • epsilon – boundary tolerance

fillin_zones_with_value(working_zones: wolfhece.PyVertexvectors.Zones, value, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict', usemask: bool = True, epsilon: float = 0.0)[source]

Fill all cells inside each vector of a Zones collection with the given value.

Parameters:
  • working_zonesZones whose vectors define the fill areas

  • value – value to assign to cells inside the zone vectors

  • method – spatial method for cell selection

  • usemask – if True, only fill unmasked cells

  • epsilon – boundary tolerance

fillin_from_xyz(xyz: numpy.ndarray)[source]

Remplissage du tableau à partir d’un tableau xyz.

Parameters:

xyz – Numpy array - shape (n, 3)

fillin_from_ijz(ijz: numpy.ndarray)[source]

Remplissage du tableau à partir d’un tableau ijz

Parameters:

ijz – Numpy array - shape (n, 3)

filter_inundation(epsilon: float = None, mask: numpy.ndarray = None)[source]
Apply filter on array :
  • mask data below eps

  • mask data outisde linkedvec

Parameters:
  • epsilon – value under which data are masked

  • mask – mask to apply if eps is None

If all params are None, the function will mask NaN values

filter_independent_zones(n_largest: int = 1, reset_plot: bool = True)[source]

Label independent connected regions and keep only the n largest.

Parameters:
  • n_largest – number of largest zones to keep

  • reset_plot – if True, reset the plot after filtering

filter_zone(set_null: bool = False, reset_plot: bool = True)[source]

Keep only the labeled regions that contain at least one selected cell. mailles sont sélectionnées

Parameters:
  • set_null – if True, set filtered-out cells to nullvalue

  • reset_plot – if True, reset the plot after filtering

clean_small_patches(min_size: int = 1, set_null: bool = False, reset_plot: bool = True)[source]

Clean small patches in the array

Parameters:
  • min_size – minimum patch size in cells; smaller patches are removed

  • set_null – if True, set removed cells to nullvalue

  • reset_plot – if True, reset the plot after cleaning

labelling(reset_plot: bool = True)[source]

Labelling of the array using Scipy

Parameters:

reset_plot – if True, reset the plot after labelling

statistics(inside_polygon: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon | numpy.ndarray = None) dict[str, float | numpy.ndarray][source]

Statistics on Selected data or the whole array if no selection

Parameters:

inside_polygon – vector or Polygon to select data inside the polygon

Returns:

mean, std, median, sum, volume (sum*dx*dy), values

Return type:

dict[str, float | np.ndarray]

Translated Keys are:
  • _(‘Mean’): mean value of the selected data

  • _(‘Std’): standard deviation of the selected data

  • _(‘Median’): median value of the selected data

  • _(‘Sum’): sum of the selected data

  • _(‘Volume’): volume of the selected data (sum * dx * dy)

  • _(‘Values’): values of the selected data as a numpy array

  • _(‘Min’): minimum value of the selected data

  • _(‘Max’): maximum value of the selected data

get_unique_values()[source]

Return unique values in the array

map_values(keys_vals: dict, default: float = None)[source]

Mapping array values to new values defined by a dictionnary.

First, check if all values are in keys_vals. If not, set to default. If default is None, set to nullvalue.

Parameters:
  • keys_vals – dictionary of values to map

  • default – default value if key not found

add_crosslinked_array(newlink: WolfArrayModel)[source]

Add a bidirectional cross-link between this array and another.

Parameters:

newlinkWolfArrayModel to cross-link with this array

share_palette()[source]

Share the color palette object with all cross-linked arrays.

paste_all(fromarray: WolfArrayModel, mask_after: bool = True)[source]

Paste the data from another array into this one where geometries overlap.

Parameters:
  • fromarray – source WolfArrayModel from which to paste values

  • mask_after – if True, mask cells equal to nullvalue after pasting

set_values_sel(xy: list[float], z: list[float], update: bool = True)[source]

Set values at the selected positions

Parameters:
  • xy – [[x1,y1],[x2,y2],…]

  • z – [z1,z2,…]

  • update – update the plot

crop_array(bbox: list[list[float], list[float]], setnull_trx_try: bool = False) WolfArrayModel[source]

Crop the data based on the bounding box.

Beware of the grid: - If the cropped region is smaller than a cell, then the cropped array

will be empty.

  • If the cropped region doesn’t align with the source array grid, it will be forced to do so.

Parameters:
  • bbox – bounding box [[xmin, xmax], [ymin, ymax]].

  • setnull_trx_try – set the translation to 0 if True, origx and origy will be set to the lower left corner of the bbox. Default is False.

crop_masked_at_edges()[source]

Crop the array to remove masked cells at the edges of the array :return: cropped array, WolfArrayModel instance

crop(i_start: int, j_start: int, nbx: int, nby: int, k_start: int = 1, nbz: int = 1)[source]

Crop the array

Parameters:
  • i_start – start index in x

  • j_start – start index in y

  • nbx – number of cells in x

  • nby – number of cells in y

  • k_start – start index in z

  • nbz – number of cells in z

Returns:

cropped array, WolfArrayModel instance

extend(x_ext: int, y_ext: int)[source]

Extend the array

Crop is the opposite

Parameters:
  • x_ext – number of cells to add/remove in the x direction (positive = extend, negative = shrink)

  • y_ext – number of cells to add/remove in the y direction (positive = extend, negative = shrink)

extremum(which: Literal['min', 'max'] = 'min')[source]

Return the extremum value

Parameters:

which – which extremum to find: 'min' or 'max'

nullify_border(width: int = 1)[source]

Set border to nullvalue

Parameters:

width – number of border cells to set to nullvalue

convolve(filter, method: Literal['scipyfft', 'jaxfft', 'classic'] = 'scipyfft', inplace: bool = True) WolfArrayModel[source]

Convolve the array with a filter.

The array and the filter should have the same dtype. If not, a warning is issued and the array dtype is used.

Thus:

  • An int8 array convolved with float32 filter will be converted to int8.

  • A float32 array convolved with int8 filter will be converted to float32.

User should be careful with the dtype of both the array AND the filter.

Parameters:
  • filter – filter to convolve with

  • method – method to use for convolution (‘scipyfft’, ‘jaxfft’, ‘classic’)

  • inplace – if True, the array is modified in place, otherwise a new array is returned – same type as the original one

Returns:

convolved array, WolfArrayModel instance

concatenate(list_arr: list[WolfArrayModel], nullvalue: float = 0.0)[source]

Concatenate the values from another WolfArrays into a new one

Parameters:
  • list_arr – list of WolfArrayModel objects

  • nullvalue – null value for the output array

Returns:

a new WolfArrayModel

Return_type:

WolfArrayModel

as_WolfArray(abs: bool = True) WolfArrayModel[source]

Return a WolfArrayModel object from this WolfArrayModel

Parameters:

abs – if True, use absolute coordinates

volume_estimation(zmax: float = None, nb: int = 10, labeled: bool = False, use_memory: bool = False, memory_key: str = None, output_fn: str = None, axs: matplotlib.pyplot.Axes = None)[source]

Estimation of the volume of the selected zone.

Parameters:
  • zmax – maximum elevation (if None, uses array max)

  • nb – number of elevation steps

  • labeled – if True, use labeling to identify connected areas

  • use_memory – if True, use memory selection to identify areas

  • memory_key – key of the memory selection to use (if use_memory)

  • output_fn – filename for zoning result (if None, no file is written)

  • axs – matplotlib Axes to plot the results

Returns:

(fig, axs) or None if cancelled

surface_volume_estimation_from_elevation(axs: matplotlib.pyplot.Axes = None, desired_zmin: float = None, desired_zmax: float = None, nb: int = 100, method: Literal['all below', 'largest area', 'selected'] = 'largest area', selected_cells: list[tuple[float, float]] = None, dirout: str | pathlib.Path = None, invert_z: bool = False, array_to_integrate: WolfArrayModel = None)[source]

Estimation of the surface and volume from an elevation array.

Parameters:
  • axs – Axes to plot the results

  • desired_zmin – Minimum elevation to consider

  • desired_zmax – Maximum elevation to consider

  • nb – Number of elevation steps

  • method – Method to use for the estimation (‘all below’, ‘largest area’, ‘selected’)

  • selected_cells – List of kernel cells (if method is ‘selected’) – Consider only the areas containing these cells

  • dirout – Directory to save the results

  • invert_z – if True, invert the elevation axis (useful for bathymetry)

  • array_to_integrate – optional array whose values are integrated instead of pure surface area

Returns:

Figure and Axes with the results

Return type:

tuple[plt.Figure, plt.Axes]

surface_volume_estimation_from_waterdepth(axs: matplotlib.pyplot.Axes = None, desired_zmin: float = None, desired_zmax: float = None, nb: int = 100, method: Literal['all below', 'largest area', 'selected'] = 'largest', selected_cells: list[tuple[float, float]] = None, dirout: str | pathlib.Path = None)[source]

Estimation of the surface and volume from a water depth array. :param axs: Axes to plot the results :param desired_zmin: Minimum water depth to consider :param desired_zmax: Maximum water depth to consider :param nb: Number of water depth steps :param method: Method to use for the estimation (‘all below’, ‘largest area’, ‘selected’) :param selected_cells: List of kernel cells (if method is ‘selected’) – Consider only the areas containing these cells :param dirout: Directory to save the results :return: Figure and Axes with the results :rtype: tuple[plt.Figure, plt.Axes]

hillshade(azimuth: float, angle_altitude: float)[source]

Create a hillshade array – see “hillshade” function accelerated by JIT

Parameters:
  • azimuth – sun azimuth angle in degrees (default: 315°)

  • angle_altitude – sun altitude angle in degrees above the horizon

get_gradient_norm()[source]

Compute and return the norm of the gradient

get_laplace()[source]

Compute and return the laplacian

suxsuy_contour(filename: str = '', abs: bool = False, one_vec_if_ml: bool = True) tuple[list[int, int], list[int, int], wolfhece.PyVertexvectors.vector | wolfhece.PyVertexvectors.zone, bool][source]

The borders are computed on basis of the current mask

Parameters:
  • filename – if provided, write ‘sux’, ‘sux’ and ‘xy’ files

  • abs – add translation coordinates (Global World Coordinates)

  • one_vec_if_ml – if True, merge multi-level contour segments into a single vector

Returns:

indicesX, indicesY, contourgen, interior

indicesX : list of coupled indices along X - vertical border - 1-based like Fortran indicesY : list of coupled indices along Y - horizontal border - 1-based like Fortran contourgen : external contour interior : if False, contour is unique ; if True, interior contours exist -> interior parts are merged

contour(levels: int | list[float] = 10) wolfhece.PyVertexvectors.Zones[source]

Compute contour lines

Parameters:

levels – list of contour levels to extract

inpaint(mask_array: WolfArrayModel = None, test_array: WolfArrayModel = None, ignore_last: int = 1, multiprocess: bool = True)[source]

InPaintaing holes in the array

Parameters:
  • mask_array – where computation is done

  • test_array – used in test – interpolation is accepted if new value is over test_array

  • ignore_last – number of last patches to ignore

  • multiprocess – use multiprocess for inpainting

_inpaint_waterlevel_dem_dtm(dem: WolfArrayModel, dtm: WolfArrayModel, ignore_last: int = 1, use_fortran: bool = False, multiprocess: bool = True)[source]

InPaintaing waterlevel holes in the array.

We use DEM and DTM to mask and constraint the inpainting process.

Parameters:
  • dem – Digital Elevation Model (same as simulation model)

  • dtm – Digital Terrain Model

  • ignore_last – number of last patches to ignore

  • use_fortran – use Fortran inpainting code

  • multiprocess – use multiprocess for inpainting

count_holes(mask: WolfArrayModel = None)[source]

Count holes in the array

Parameters:

mask – boolean mask array; if None, use array.mask

select_holes(mask: WolfArrayModel = None, ignore_last: int = 1)[source]

Select holes in the array

Parameters:
  • mask – boolean mask array; if None, use array.mask

  • ignore_last – if True, ignore the largest (background) hole

create_mask_holes(ignore_last: int = 1) WolfArrayModel[source]

Select holes in the array and create a new aray

Parameters:

ignore_last – if True, ignore the largest (background) hole

fill_holes_with_value(value: float, mask: WolfArrayModel = None, ignore_last: int = 1)[source]

Fill holes in the array with a value

Parameters:
  • value – value to fill holes with

  • mask – boolean mask defining the holes; if None, auto-detect

  • ignore_last – if True, ignore the largest (background) hole

fill_holes_with_value_if_intersects(value: float, vects: list[wolfhece.PyVertexvectors.vector] | wolfhece.PyVertexvectors.Zones, method: Literal['matplotlib', 'shapely_strict', 'shapely'] = 'shapely_strict', buffer: float = 0.0)[source]

Fill holes in the array with a value if it intersects with the mask

Parameters:
  • value – value to fill holes with

  • vects – list of polygon vectors for intersection test

  • method – spatial method for intersection check

  • buffer – buffer distance for intersection test

_fill_holes_with_value_if_intersects(value: float, vect: wolfhece.PyVertexvectors.vector, method: Literal['matplotlib', 'shapely_strict', 'shapely'] = 'shapely_strict', buffer: float = 0.0) WolfArrayModel[source]

Internal helper: fill a single labelled hole if it intersects the given polygon.

Parameters:
  • value – value to fill holes with

  • vect – polygon vector for intersection test

  • method – spatial method for intersection check

  • buffer – buffer distance for intersection test

_create_building_holes_dem_dtm(dem: WolfArrayModel, dtm: WolfArrayModel, ignore_last: int = 1) WolfArrayModel[source]

Create a mask identifying building footprints from the difference between DEM and DTM.

Parameters:
  • dem – Digital Elevation Model array

  • dtm – Digital Terrain Model array

  • ignore_last – if True, ignore the largest (background) hole

get_triangulation(bounds: list[float] = None)[source]

Traingulation of the array

Parameters:

bounds – [[xmin,xmax],[ymin,ymax]]

compare_cloud(mycloud: wolfhece.PyVertex.cloud_vertices, delta: list[float] = [0.15, 0.5, 1.0])[source]

Graphique de comparaison des valeurs d’un nuage de points et des valeurs de la matrice sous les mêmes positions

Parameters:
  • mycloud – cloud_vertices

  • delta – list of tolerance for the comparison

compare_tri(mytri: wolfhece.PyVertexvectors.Triangulation)[source]

Plot a comparison between array values and triangulation vertex elevations.

Parameters:

mytriTriangulation object to compare against the array

plot_matplotlib(figax: tuple = None, getdata_im: bool = False, update_palette: bool = True, vmin: float = None, vmax: float = None, figsize: tuple = None, Walonmap: bool = False, cat: Literal['IMAGERIE/ORTHO_1971', 'IMAGERIE/ORTHO_1994_2000', 'IMAGERIE/ORTHO_2006_2007', 'IMAGERIE/ORTHO_2009_2010', 'IMAGERIE/ORTHO_2012_2013', 'IMAGERIE/ORTHO_2015', 'IMAGERIE/ORTHO_2016', 'IMAGERIE/ORTHO_2017', 'IMAGERIE/ORTHO_2018', 'IMAGERIE/ORTHO_2019', 'IMAGERIE/ORTHO_2020', 'IMAGERIE/ORTHO_2021', 'IMAGERIE/ORTHO_2022_PRINTEMPS', 'IMAGERIE/ORTHO_2022_ETE', 'IMAGERIE/ORTHO_2023_ETE', 'IMAGERIE/ORTHO_LAST', 'orthoimage_coverage', 'orthoimage_coverage_2016', 'orthoimage_coverage_2017', 'orthoimage_coverage_2018', 'orthoimage_coverage_2019', 'orthoimage_coverage_2020', 'orthoimage_coverage_2021', 'orthoimage_coverage_2022', 'crossborder', 'crossborder_grey', 'overlay', 'topo', 'topo_grey'] = 'IMAGERIE/ORTHO_LAST', first_mask_data: bool = True, with_legend: bool = False, IGN: bool = False, Cartoweb: bool = False)[source]

Plot the array - Matplotlib version

Using imshow and RGB array

Plot the array using Matplotlib. This method visualizes the array data using Matplotlib’s imshow function. It supports optional overlays, custom palettes, and value range adjustments.

Notes:

  • The method applies a mask to the data using the nullvalue attribute before plotting.

  • If Walonmap is True, the method fetches and overlays a map image using the WalOnMap service.

  • The aspect ratio of the plot is set to ‘equal’.

param figax:

A tuple containing a Matplotlib figure and axis (fig, ax). If None, a new figure and axis are created.

type figax:

tuple, optional (Default value = None)

param getdata_im:

If True, returns the image object along with the figure and axis. Default is False, then it only returns (fig, ax).

type getdata_im:

bool, optional (Default value = False)

param update_palette:

If True, updates the color palette before plotting. Default is True.

type update_palette:

bool, optional (Default value = True)

param vmin:

Minimum value for color scaling. If None, the minimum value is determined automatically. Default is None.

type vmin:

float, optional (Default value = None)

param vmax:

Maximum value for color scaling. If None, the maximum value is determined automatically. Default is None.

type vmax:

float, optional (Default value = None)

param figsize:

Size of the figure in inches (width, height). Only used if figax is None. Default is None.

type figsize:

tuple, optional (Default value = None)

param Walonmap:

If True, overlays a map image using the WalOnMap service. Default is False.

type Walonmap:

bool, optional (Default value = False)

param cat:

The category of the map to fetch from the WalOnMap service. Default is ‘IMAGERIE/ORTHO_2022_ETE’. Available orthos: - ‘IMAGERIE/ORTHO_1971’ - ‘IMAGERIE/ORTHO_1994_2000’ - ‘IMAGERIE/ORTHO_2006_2007’ - ‘IMAGERIE/ORTHO_2009_2010’ - ‘IMAGERIE/ORTHO_2012_2013’ - ‘IMAGERIE/ORTHO_2015’ - ‘IMAGERIE/ORTHO_2016’ - ‘IMAGERIE/ORTHO_2017’ - ‘IMAGERIE/ORTHO_2018’ - ‘IMAGERIE/ORTHO_2019’ - ‘IMAGERIE/ORTHO_2020’ - ‘IMAGERIE/ORTHO_2021’ - ‘IMAGERIE/ORTHO_2022_PRINTEMPS’ - ‘IMAGERIE/ORTHO_2022_ETE’ - ‘IMAGERIE/ORTHO_2023_ETE’ - ‘IMAGERIE/ORTHO_LAST’ - ‘orthoimage_coverage’ - ‘orthoimage_coverage_2016’, - ‘orthoimage_coverage_2017’, - ‘orthoimage_coverage_2018’, - ‘orthoimage_coverage_2019’, - ‘orthoimage_coverage_2020’, - ‘orthoimage_coverage_2021’, - ‘orthoimage_coverage_2022’ - ‘crossborder’, - ‘crossborder_grey’, - ‘overlay’, - ‘topo’, - ‘topo_grey’

type cat:

str, optional (Default value = ‘IMAGERIE/ORTHO_2022_ETE’)

param first_mask_data:

If True, applies the mask to the data before plotting. Default is True.

type first_mask_data:

bool, optional (Default value = True)

param with_legend:

If True, adds a color legend to the plot. Default is False.

type with_legend:

bool, optional (Default value = False)

param IGN:

if True, overlay the IGN basemap

param Cartoweb:

if True, overlay the Cartoweb basemap

return:

If getdata_im is False, returns (fig, ax), where fig is the Matplotlib figure and ax is the axis. If getdata_im is True, returns (fig, ax, im), where im is the image object created by imshow.

rtype:

tuple

imshow(figax: tuple[matplotlib.figure.Figure, matplotlib.axis.Axis] = None, cmap: matplotlib.colors.Colormap = None, step_ticks=100.0) tuple[matplotlib.figure.Figure, matplotlib.axis.Axis][source]

Create Matplotlib image from WolfArrayModel

Parameters:
  • figax – tuple (fig, ax) of matplotlib Figure and Axes; created if None

  • cmap – matplotlib colormap name (default: None uses internal palette)

  • step_ticks – step (in world units) between tick labels on the axes

get_rebin_shape_size(factor: float, reshape_array_if_necessary: bool = False) tuple[tuple[int, int], tuple[float, float]][source]

Return the new shape after rebinning.

newdx = dx * factor newdy = dy * factor

The shape is adjusted to be a multiple of the factor.

Parameters:
  • factor (float) – factor of resolution change – > 1.0 : decrease resolution, < 1.0 : increase resolution

  • reshape_array_if_necessary – if True, pad array so dimensions are divisible by the downsampling factor

Returns:

new shape

Return type:

Tuple[int, int], Tuple[float, float]

get_rebin_header(factor: float) wolfhece.wolf_array._header_wolf.header_wolf[source]

Return a new header after rebinning.

Parameters:

factor (float) – factor of resolution change – > 1.0 : decrease resolution, < 1.0 : increase resolution

Returns:

new header

Return type:

header_wolf

rebin(factor: float, operation: Literal['mean', 'sum', 'min', 'max', 'median'] = 'mean', operation_matrix: WolfArrayModel = None) None[source]

Change resolution - in place.

If you want to keep current data, copy the WolfArrayModel into a new variable -> newWA = Wolfarray(mold=curWA).

Parameters:
  • factor (float) – factor of resolution change – > 1.0 : decrease resolution, < 1.0 : increase resolution

  • operation (str, Rebin_Ops) – operation to apply on the blocks (‘mean’, ‘sum’, ‘min’, ‘max’, ‘median’)

  • operation_matrix (WolfArrayModel) – operation matrix to apply on the blocks – see the Enum “Rebin_Ops” for more infos. The matrix must have the same shape as the new array

classmethod from_other_epsg_coo(input_raster_path: str, input_srs='EPSG:3812', output_srs='EPSG:31370', resampling_method=gdal.GRA_Bilinear, xRes: float = 0.5, yRes: float = 0.5)[source]

Reprojects and resamples a raster file from an other EPSG coordinates and return it as a WolfArrayModel.

Parameters:
  • input_raster_path (str) – The path to the input raster file.

  • input_srs (str) – The input spatial reference system (SRS) in the format ‘EPSG:XXXX’. Defaults to Lambert 2008 ‘EPSG:3812’.

  • output_srs (str) – The output spatial reference system (SRS) in the format ‘EPSG:XXXX’. Defaults to Belgian Lambert 72 ‘EPSG:31370’.

  • resampling_method – The resampling method to use. Defaults to gdal.GRA_Bilinear. Resampling method can be chosen among the gdal GRA_*

constants (gdal.GRA_Average; gdal.GRA_Bilinear; gdal.GRA_Cubic; gdal.GRA_CubicSpline; gdal.GRA_Lanczos; gdal.GRA_Mode; gdal.GRA_NearestNeighbour) :type resampling_method: int :param xRes: The desired output resolution in the x direction. Defaults to 0.5. :type xRes (float): float :param yRes: The desired output resolution in the y direction. Defaults to 0.5. :type yRes (float): float

Raises:
  • AssertionError – If the input or output raster file is not a GeoTIFF file.

  • RuntimeError – If the input raster file cannot be opened.

  • PermissionError – If there is a permission error while trying to delete the output raster file.

  • Exception – If an unexpected error occurs while trying to delete the output raster file.

  • RuntimeError – If the reprojection fails for the input raster file.

Returns:

WolfArrayModel

reproject(output_epsg: int, resampling_method=gdal.GRA_Bilinear) WolfArrayModel[source]

Reprojects and resamples the WolfArrayModel to a new EPSG coordinate system.

Parameters:
  • output_epsg (int) – The output EPSG code for the desired coordinate system.

  • resampling_method – The resampling method to use. Defaults to gdal.GRA_Bilinear. Resampling method can be chosen among the gdal GRA_*

constants (gdal.GRA_Average; gdal.GRA_Bilinear; gdal.GRA_Cubic; gdal.GRA_CubicSpline; gdal.GRA_Lanczos; gdal.GRA_Mode; gdal.GRA_NearestNeighbour) :type resampling_method: int :return: WolfArrayModel

classmethod merge(others: list, abs: bool = True, copy: bool = True) WolfArrayModel[source]

Merge several WolfArrayModel into a single WolfArrayModel

Parameters:
  • others – list of WolfArrayModel to merge

  • abs – if True -> Global World Coordinates

  • copy – if True -> copy data (Not necessary if data header CAN BE modified. It can be save memory)

classmethod set_general_frame_from_xyz(fname: str, dx: float, dy: float, border_size: int = 5, delimiter: str = ',', fillin: bool = False)[source]

Lecture d’un fichier texte xyz et initialisation des données de base

Parameters:
  • fname – nom du fichier xyz

  • dx – pas en x

  • dy – pas en y

  • border_size – nombre de mailles de bordure en plus de l’extension spatiale du fichier

  • delimiter – column delimiter in the XYZ file (e.g. "\t", " ")

  • fillin – if True, fill the array with values from the XYZ file

classmethod set_general_frame_from_xyz_dir(path: str, bounds: list, delimiter: str = ',', dxdy: tuple[float, float] = None, border_size: int = 5, fillin: bool = True)[source]

Lecture d’un dossier contenant des fichiers texte xyz, initialisation des données de base et chargement de la matrice Renvoie un WolfArrayModel or False si le fichier n’est pas dans les limites

Parameters:
  • path – chemin du dossier avec les fichier xyz

  • bounds – limites de l’extension spatiale

  • delimiter – délimiteur des fichiers xyz

  • border_size – nombre de mailles de bordure en plus de l’extension spatiale du fichier

  • dxdy – tuple (dx, dy) cell size; if None, infer from data

  • fillin – if True, fill the array with values from the XYZ files

Dtype path:

str

Dtype bounds:

list

Dtype delimiter:

str

Dtype border_size:

int