wolfhece.wolf_array._base ========================= .. py:module:: wolfhece.wolf_array._base .. autoapi-nested-parse:: 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 --------------- .. py:function:: pgcd_decimal(a, b) .. py:class:: OGLRenderer(*args, **kwds) Bases: :py:obj:`enum.Enum` .. autoapi-inheritance-diagram:: wolfhece.wolf_array._base.OGLRenderer :parts: 1 :private-bases: 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 - value lookup: >>> Color(1) - name lookup: >>> Color['RED'] Enumerations can be iterated over, and know how many members they have: >>> len(Color) 3 >>> list(Color) [, , ] Methods can be added to enumerations, and members can have their own attributes -- see the documentation for details. .. py:attribute:: LIST :value: 0 .. py:attribute:: SHADER :value: 1 .. py:method:: get(value: int) :classmethod: Return the OGLRenderer value corresponding to an integer value .. py:data:: DEFAULT_OGLRENDERER .. py:data:: VERSION_RGB :value: 3 .. py:function:: custom_gradient(array: numpy.ndarray) Calculate the gradient manually .. py:function:: hillshade(array: numpy.ndarray, azimuth: float, angle_altitude: float) -> numpy.ndarray Create a hillshade array .. py:class:: Rebin_Ops(*args, **kwds) Bases: :py:obj:`enum.Enum` .. autoapi-inheritance-diagram:: wolfhece.wolf_array._base.Rebin_Ops :parts: 1 :private-bases: Enum for rebin/downsampling operations (no wx dependency). .. py:attribute:: MIN :value: 0 .. py:attribute:: MEAN :value: 1 .. py:attribute:: MAX :value: 2 .. py:attribute:: SUM :value: 3 .. py:attribute:: MEDIAN :value: 4 .. py:method:: get_numpy_ops() :classmethod: Return a list of numpy functions corresponding to the enum values .. py:method:: get_ops(name: str) :classmethod: Return the numpy function corresponding to a string .. py:class:: 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) Bases: :py:obj:`wolfhece.wolf_array._header_wolf.header_wolf` .. autoapi-inheritance-diagram:: wolfhece.wolf_array._base.WolfArrayModel :parts: 1 :private-bases: 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... .. py:attribute:: array :type: numpy.ma.masked_array .. py:attribute:: _cache_grid :type: dict .. py:attribute:: linkedvec :type: wolfhece.PyVertexvectors.vector .. py:attribute:: linkedarrays :type: list[WolfArrayModel] .. py:attribute:: origx :type: float .. py:attribute:: origy :type: float .. py:attribute:: origz :type: float .. py:attribute:: translx :type: float .. py:attribute:: transly :type: float .. py:attribute:: translz :type: float .. py:attribute:: myops :type: wolfhece.ui.wolf_array_ops.Ops_Array .. py:attribute:: _rendering_machine .. py:attribute:: mngselection :value: None .. py:attribute:: myblocks :value: None .. py:attribute:: _active_blocks :value: None .. py:attribute:: flipupd :value: False .. py:attribute:: filename :value: '' .. py:attribute:: isblock :value: False .. py:attribute:: blockindex :value: 0 .. py:attribute:: wolftype :value: 1 .. py:attribute:: preload :value: True .. py:attribute:: loaded :value: False .. py:attribute:: masknull :value: True .. py:attribute:: alpha :value: 1.0 .. py:attribute:: shading :value: False .. py:attribute:: azimuthhill :value: 315.0 .. py:attribute:: altitudehill :value: 0.0 .. py:attribute:: shaded :value: None .. py:attribute:: _nullvalue :value: 0.0 .. py:attribute:: nbnotnull :value: 99999 .. py:attribute:: nbnotnullzoom :value: 99999 .. py:attribute:: nbtoplot :value: 0 .. py:attribute:: _gridsize :value: 256 .. py:attribute:: _lod_max_whole_array :value: -1 .. py:attribute:: mypal .. py:attribute:: _cache_grid_last_call :value: None .. py:attribute:: _cache_grid_frequency_useconds :value: 1000 .. py:attribute:: _shader_2d :type: WolfArrayShader2D | None :value: None .. py:attribute:: _array3d :value: None .. py:attribute:: _array2d :value: None .. py:attribute:: viewers3d :type: list[wolfhece.opengl.py3d.WolfArrayPlotShader] :value: [] .. py:attribute:: cropini :value: None .. py:property:: memory_usage Return the memory usage of the header .. py:property:: memory_usage_mask Return the memory usage of the mask .. py:property:: nullvalue :type: float Return the null value .. py:property:: nodata :type: float alias for nullvalue .. py:property:: SelectionData :type: wolfhece.wolf_array._selection_data.SelectionData Return the data of the selection .. py:property:: active_blocks :type: list[WolfArrayModel] Return the active blocks .. py:property:: dtype 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 .. py:property:: dtype_gdal Return the GDAL dtype corresponding to the WOLF type .. py:property:: dtype_str 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 .. py:property:: zmin Return the minimum value of the masked array .. py:property:: zmax Return the maximum value of the masked array .. py:property:: zmin_global Return the minimum value of the array -- all data (masked or not) .. py:property:: zmax_global Return the maximum value of the array -- all data (masked or not) .. py:method:: get_mapviewer() Return the mapviewer .. py:method:: set_mapviewer(newmapviewer=None) Attach a (new) mapviewer to the object :param newmapviewer: new mapviewer instance to attach (``None`` to detach) .. py:method:: _prompt_crop(dx: float, dy: float) -> list | None 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. :param dx: cell size in x direction (used for pre-filling the dialog) :param dy: cell size in y direction (used for pre-filling the dialog) .. py:method:: _prompt_band_selection(band_names: list[str]) -> int | None 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. :param band_names: list of band name strings to choose from .. py:method:: _prompt_save_file(message: str, wildcard: str) -> str | None Prompt user for a file path to save. Returns path or None. In data-only mode, returns None. Overridden in WolfArray to show FileDialog. :param message: dialog title / prompt message :param wildcard: file filter pattern (e.g. ``"TIFF files (*.tif)|*.tif"``) .. py:method:: _show_error_dialog(message: str) Show an error dialog to the user. In data-only mode, just logs. Overridden in WolfArray to show wx.MessageDialog. :param message: error message to display or log .. py:method:: reset_plot(whichpal=0, mimic=True) Reset plot - no-op in data-only mode; overridden in WolfArray (GUI) :param whichpal: palette index (default: 0) :param mimic: if ``True``, propagate to linked arrays .. py:method:: updatepalette(which: int = 0, onzoom=[]) Update palette - minimal version without OGL; overridden in WolfArray (GUI) :param which: palette index (default: 0) :param onzoom: zoom window ``[xmin, xmax, ymin, ymax]``; empty list for whole array .. py:method:: delete_lists() Delete OpenGL lists - no-op in data-only mode; overridden in WolfArray (GUI) .. py:method:: find_minmax(update=False) Find min/max spatial extent :param update: if ``True``, recalculate spatial bounds from array dimensions .. py:method:: _new_like() -> WolfArrayModel 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*). :return: new instance with the same spatial properties and wolftype :rtype: same type as ``self`` .. py:method:: allocate_ressources() Allocate the numpy masked array according to the current dtype and dimensions. .. py:method:: reset() Reset the array to nullvalue .. py:method:: init_from_header(myhead: wolfhece.wolf_array._header_wolf.header_wolf, dtype: numpy.dtype = None, force_type_from_header: bool = False) Initialize the array properties from a header_wolf object :param myhead: header_wolf object :param dtype: numpy dtype :param force_type_from_header: force the type from the header passed as argument .. py:method:: get_header(abs: bool = True) -> wolfhece.wolf_array._header_wolf.header_wolf Return a header_wolf object - different from the self object header :param abs: if True (default), return an absolute header (shifted origin) and translation set to 0. :return: new header_wolf with copied spatial properties :rtype: header_wolf .. py:method:: set_header(header: wolfhece.wolf_array._header_wolf.header_wolf) Set the header from a header_wolf object :param header: :class:`header_wolf` instance to copy properties from .. py:method:: set_array_from_numpy(array: numpy.ndarray, nullvalue: float = None) Set array from numpy array :param array: numpy array with shape ``(nbx, nby)`` :param nullvalue: null value to apply and mask; if ``None``, use current :attr:`nullvalue` .. py:method:: read_all(which_band=None) Read the array from disk, auto-detecting the file format (WOLF binary, GeoTIFF, VRT, NumPy). :param which_band: band index (1-based) for multi-band rasters (GeoTIFF, VRT) .. py:method:: read_data() Read binary array data from the current file, with optional cropping. .. py:method:: _read_binary_data(f, seek=0) Read binary data from file :param f: open file handle in binary read mode :param seek: byte offset to seek to before reading (0 = read from current position) .. py:method:: read_txt_header() Read header from txt file Supercharged by WolfArrayModel to avoid explicit call to read_txt_header with parameters .. py:method:: _reload() Reload the data from the file .. py:method:: write_all(newpath: str | pathlib.Path = None, EPSG: int = None) Ecriture de tous les fichiers d'un Wolf array :param newpath: new path and filename with extension -- if None, use the current filename :param EPSG: EPSG code for geotiff .. py:method:: write_array() Write the raw binary array data to the current file. .. py:method:: write_txt_header() Write header to txt file Supercharged by WolfArrayModel to avoid explicit call to write_txt_header with parameters .. py:method:: write_xyz(fname: str) Write all unmasked cell data as an XYZ text file. :param fname: output file path for the XYZ file .. py:method:: get_xyz(which='all') -> numpy.ndarray Return an array of xyz coordinates and values :param which: which values to export: ``'all'`` includes all unmasked cells :return: Nx3 array of ``[x, y, z]`` coordinates for all unmasked cells :rtype: numpy.ndarray .. py:method:: _import_npy(fn: str = '', crop: list[float] = None) Import a numpy file. Must be called after the header is initialized, e.g. read_txt_header. :param fn: filename :param crop: crop the data - [xmin, xmax, ymin, ymax] .. py:method:: import_vrt(fn: str = '', which: int = None, crop: list[float] = None) 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. :param fn: filename :param which: band to import :param crop: crop the data - [xmin, xmax, ymin, ymax] .. py:method:: import_geotif(fn: str = '', which: int = None, crop: list[float] = None) 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 :param fn: filename :param which: band to import :param crop: crop the data - [xmin, xmax, ymin, ymax] or [[xmin, xmax], [ymin, ymax]] .. py:method:: import_from_gltf(fn: str = '', fnpos: str = '', interp_method: Literal['matplotlib', 'scipy'] = 'matplotlib') Import from GLTF/GLB format :param fn: filename :param fnpos: filename for the position's information :param interp_method: method for the interpolation -- 'matplotlib' or 'scipy' .. py:method:: export_geotif(outdir: str = '', extent: str = '', EPSG: int = None) 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 :param outdir: directory - If provided, the file will be savd as "outdir/idx+extent.tif" If not provided, we use the filename attribute :param extent: suffix to add to the filename before the extension '.tif' (only if outdir is provided) :param EPSG: EPSG code, by default 31370 (Lambert 72) .. py:method:: export_cityjson(outdir: str = '', extent: str = '', EPSG: int = None) Export the array as a CityJSON file with one polygon per grid cell. :param outdir: output directory; empty string uses :attr:`filename` :param extent: suffix appended to filename before ``.json`` extension :param EPSG: EPSG code for the coordinate reference system (default: 31370) .. py:method:: export_to_gltf(bounds: list[float] = None, fn: str = '') Export to GLTF/GLB format :param bounds: [[xmin,xmax],[ymin,ymax]] :param fn: filename .. py:method:: check_bounds_ij(i: int, j: int) Check if i and j are inside the array bounds :param i: column index (0-based) :param j: row index (0-based) :return: ``True`` if (i, j) is inside the array bounds :rtype: bool .. py:method:: check_bounds_xy(x: float, y: float) Check if i and j are inside the array bounds :param x: x-coordinate in world space :param y: y-coordinate in world space :return: ``True`` if (x, y) falls inside the array spatial extent :rtype: bool .. py:method:: get_centers(usenap: bool = True) Get the centers of the cells :param usenap: if ``True``, return only unmasked cell centers; if ``False``, return all :return: flattened array of cell center coordinates ``[x1, y1, x2, y2, ...]`` :rtype: numpy.ndarray .. py:method:: get_dxdy_min() 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) .. py:method:: get_dxdy_max() 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) .. py:method:: meshgrid(mode: Literal['gc', 'borders'] = 'gc') Création d'un maillage 2D :param mode: 'gc' pour les centres de mailles, 'borders' pour les bords de mailles .. py:method:: get_value(x: float, y: float, z: float = 0.0, nullvalue: float = -99999, convert_to_float: bool = True) Return the value at given coordinates :param x: x coordinate :param y: y coordinate :param z: z coordinate :param nullvalue: value to return if the point is outside the array :param convert_to_float: if ``True``, cast the result to ``float`` .. py:method:: get_xlim(window_x: float, window_y: float) Return the limits in x for a given window size :param window_x: window size in x :param window_y: window size in y .. py:method:: get_ylim(window_x: float, window_y: float) Retrun the limits in y for a given window size :param window_x: window size in x :param window_y: window size in y .. py:method:: get_working_array(onzoom: list[float] = []) Return the part of the array in the zoom window :param onzoom: zoom window -- [xmin, xmax, ymin, ymax] .. py:method:: loadnap_and_apply() 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. .. py:method:: mask_data(value) Mask all cells whose value equals the given value. :param value: cells equal to this value will be masked .. py:method:: mask_lower(value) Mask cell where values are strictly lower than `value` :param value: cells strictly below this value will be masked .. py:method:: mask_lowerequal(value) Mask cell where values are lower or equal than `value` :param value: cells below or equal to this value will be masked .. py:method:: mask_greater(value) Mask cell where values are strictly greater than `value` :param value: cells strictly above this value will be masked .. py:method:: mask_greaterequal(value) Mask cell where values are greater or equal than `value` :param value: cells above or equal to this value will be masked .. py:method:: mask_allexceptdata(value) Mask cell where values are different from `value` :param value: only cells with this exact value remain unmasked .. py:method:: mask_invert() Invert the mask .. py:method:: mask_outsidepoly(myvect: wolfhece.PyVertexvectors.vector, eps: float = 0.0, set_nullvalue: bool = True, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict') Mask all cells located **outside** a polygon. :param myvect: target vector in global coordinates :param eps: tolerance for boundary detection :param set_nullvalue: if ``True``, set masked cells to :attr:`nullvalue` :param method: spatial method: ``'mpl'``, ``'shapely_strict'``, ``'shapely_wboundary'``, ``'rasterio'`` .. py:method:: mask_insidepoly(myvect: wolfhece.PyVertexvectors.vector, eps: float = 0.0, set_nullvalue: bool = True, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'mpl') Mask all cells located **inside** a polygon. :param myvect: target vector in global coordinates :param eps: tolerance for boundary detection :param set_nullvalue: if ``True``, set masked cells to :attr:`nullvalue` :param method: spatial method: ``'mpl'``, ``'shapely_strict'``, ``'shapely_wboundary'``, ``'rasterio'`` .. py:method:: mask_insidepolys(myvects: list[wolfhece.PyVertexvectors.vector], eps: float = 0.0, set_nullvalue: bool = True, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'mpl') Mask all cells located **inside** any of the given polygons. :param myvect: target vector in global coordinates :param myvects: list of polygon vectors to mask inside :param eps: tolerance for boundary detection :param set_nullvalue: if ``True``, set masked cells to :attr:`nullvalue` :param method: spatial method: ``'mpl'``, ``'shapely_strict'``, ``'shapely_wboundary'``, ``'rasterio'`` .. py:method:: copy_mask(source: WolfArrayModel, forcenullvalue: bool = False, link: bool = True) Copy/Link the mask from another WolfArrayModel :param source: WolfArrayModel source :param forcenullvalue: force nullvalue in the masked zone :param link: link the mask if True (default), copy it otherwise .. py:method:: mask_union(source: WolfArrayModel, link: bool = True) Union of the mask with another WolfArrayModel :param source: WolfArrayModel source :param link: link the mask if True (default), copy it otherwise .. py:method:: mask_unions(sources: list[WolfArrayModel], link: bool = True) Compute the union of masks from this array and a list of source arrays. :param source: list of WolfArrayModel sourceq :param link: link the mask if True (default), copy it otherwise :param sources: list of :class:`WolfArrayModel` whose masks are unified .. py:method:: copy_mask_log(mask: numpy.ndarray, link: bool = True) Copy the mask from a numpy array :param mask: numpy array :param link: link the mask if True (default), copy it otherwise .. py:method:: set_nullvalue_in_mask() Set nullvalue in masked cells .. py:method:: mask_force_null() Force to unmask all and mask null value .. py:method:: unmask() alias to mask_reset .. py:method:: mask_clear() alias to mask_reset .. py:method:: mask_reset() Unmask everything .. py:method:: create_binary_mask(threshold: float = 0.0) -> WolfArrayModel Create a binary mask from the array :param threshold: values above this threshold become 1 (unmasked), others become 0 (masked) :return: new binary array (1 where value > threshold, 0 otherwise) :rtype: WolfArrayModel .. py:method:: count() Count the number of not masked values .. py:method:: 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) 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. :param myvect: target vector - vector or Shapely Polygon :param usemask: limit potential nodes to unmaksed nodes :param method: method to use ('mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio') - default is 'shapely_strict' :param epsilon: tolerance for the point-in-polygon test - default is 0. .. py:method:: get_xy_strictly_on_borders(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon | shapely.geometry.LineString, usemask: bool = True, method: Literal['shapely'] = 'shapely') 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. :param myvect: target vector :param usemask: limit potential nodes to unmaksed nodes :param method: method to use ('shapely' for now) .. py:method:: 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) 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. :param myvect: target vector :param usemask: limit potential nodes to unmaksed nodes :param method: method to use ('shapely' for now) :param eps: distance tolerance for matching a vertex to a cell center .. py:method:: get_xy_inside_polygon_mpl(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon, usemask: bool = True, epsilon: float = 0.0) Return the coordinates inside a polygon :param myvect: target vector :param usemask: limit potential nodes to unmaksed nodes :param epsilon: tolerance for path containment (matplotlib) .. py:method:: get_xy_inside_polygon_shapely(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon, usemask: bool = True, strictly: bool = True, epsilon: float = 0.0) Return the coordinates inside a polygon :param myvect: target vector :param usemask: limit potential nodes to unmaksed nodes :param strictly: if ``True``, use strict containment; otherwise include boundary :param epsilon: buffer tolerance for boundary inclusion .. py:method:: get_xy_inside_polygon_rasterio(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon, usemask: bool = True, epsilon: float = 0.0) Return the coordinates inside a polygon :param myvect: polygon vector in global coordinates :param usemask: if ``True``, consider only unmasked cells :param epsilon: tolerance (not used in rasterio method) .. py:method:: get_xy_under_polyline(myvect: wolfhece.PyVertexvectors.vector, usemask: bool = True) Return the coordinates along a polyline :param myvect: target vector :param usemask: limit potential nodes to unmaksed nodes .. py:method:: 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') 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. :param myvect: 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' .. py:method:: 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') 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' .. py:method:: get_ij_inside_polygon_mpl(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon, usemask: bool = True, eps: float = 0.0) Return the indices inside a polygon :param myvect: target vector :param usemask: limit potential nodes to unmaksed nodes :param eps: epsilon for the intersection .. py:method:: get_ij_inside_polygon_shapely(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon, usemask: bool = True, eps: float = 0.0, strictly: bool = True) Return the indices inside a polygon with the contains method of shapely :param myvect: target vector :param usemask: limit potential nodes to unmaksed nodes :param eps: epsilon for the intersection :param strictly: if True, the points on the border are not considered inside .. py:method:: _get_ij_inside_polygon_rasterio(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon, usemask: bool = True, eps: float = 0.0) 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 :param myvect: target vector :param usemask: limit potential nodes to unmaksed nodes :param eps: epsilon for the intersection .. py:method:: 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 Return True if the array intersects the polygon :param myvect: target vector :param usemask: limit potential nodes to unmaksed nodes :param method: spatial method: ``'mpl'``, ``'shapely_strict'``, ``'shapely_wboundary'``, or ``'rasterio'`` :param buffer: buffer distance around the polygon for intersection test .. py:method:: intersects_polygon_shapely(myvect: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon, eps: float = 0.0, usemask: bool = True, buffer: float = 0.0) -> bool Return True if the array intersects the polygon :param myvect: target vector :param usemask: limit potential nodes to unmaksed nodes :param eps: epsilon for the intersection :param buffer: buffer for the intersection - using buffer from Shapely [m] .. py:method:: 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] Element-wise intersection with a list of polygons :param myvects: list of polygon vectors to test :param usemask: if ``True``, consider only unmasked cells :param method: spatial query method for intersection test :param buffer: buffer distance around each polygon .. py:method:: 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]] Element-wise intersection with a list of zones :param zones: :class:`Zones` instance containing polygons to test :param usemask: if ``True``, consider only unmasked cells :param method: spatial query method for intersection test :param buffer: buffer distance around each polygon .. py:method:: 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] Return the area of the intersection with a list of polygons :param myvects: list of polygon vectors :param usemask: if ``True``, consider only unmasked cells :param method: spatial query method for intersection test :param buffer: buffer distance around each polygon :param coefficient: area multiplier (e.g. for unit conversion) .. py:method:: get_ij_under_polyline(myvect: wolfhece.PyVertexvectors.vector, usemask: bool = True, step_factor: float = 1.0) Return the indices along a polyline :param myvect: target vector :param usedmask: limit potential nodes to unmaksed nodes :param step_factor: step factor for the discretization of myvect (<1 for thinner, >1 for coarser) :param usemask: if ``True``, exclude masked cells from result :return: array of shape (N,2) with N the number of points found under the polyline .. py:method:: 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] Return the cell values located inside a polygon. :param usemask: (optional) restreint les éléments aux éléments non masqués de la matrice :param getxy: (optional) retourne en plus les coordonnées des points :param myvect: polygon vector in global coordinates :param method: spatial method: ``'mpl'``, ``'shapely_strict'``, etc. .. py:method:: get_values_inside_listofpolygons(myvects: wolfhece.PyVertexvectors.zone | list[wolfhece.PyVertexvectors.vector], usemask: bool = True, getxy: bool = False) -> dict Return the cell values located inside a list of polygons. :param myvects: list of polygon vectors :param usemask: if ``True``, consider only unmasked cells :param getxy: if ``True``, also return xy coordinates .. py:method:: get_values_inside_zones(zones: wolfhece.PyVertexvectors.Zones | list[WolfArrayModel.get_values_inside_zones.zone], usemask: bool = True, getxy: bool = False) -> dict Return the cell values located inside all polygons of a :class:`Zones` object. :param zones: :class:`Zones` instance :param usemask: if ``True``, consider only unmasked cells :param getxy: if ``True``, also return xy coordinates .. py:method:: get_values_underpoly(myvect: wolfhece.PyVertexvectors.vector, usemask: bool = True, getxy: bool = False) Return the cell values located under a polyline. :param usemask: (optional) restreint les éléments aux éléments non masqués de la matrice :param getxy: (optional) retourne en plus les coordonnées des points :param myvect: polyline vector in global coordinates .. py:method:: get_all_values_insidepoly(myvect: wolfhece.PyVertexvectors.vector, usemask: bool = True, getxy: bool = False) Return all cell values (including masked) inside a polygon. :param usemask: (optional) restreint les éléments aux éléments non masqués de la matrice :param getxy: (optional) retourne en plus les coordonnées des points :param 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 .. py:method:: get_all_values_underpoly(myvect: wolfhece.PyVertexvectors.vector, usemask: bool = True, getxy: bool = False) Return all cell values (including masked) under a polyline. :param usemask: (optional) restreint les éléments aux éléments non masqués de la matrice :param getxy: (optional) retourne en plus les coordonnées des points :param 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 .. py:method:: count_unique_pixels() -> dict[int, int] 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 .. py:method:: get_unique_areas(format: Literal['m2', 'ha', 'km2'] = 'm2') -> dict[int, float] 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 .. py:method:: count_insidepoly(myvect: wolfhece.PyVertexvectors.vector, usemask: bool = True, method: Literal['mpl', 'shapely_strict', 'shapely_wboundary', 'rasterio'] = 'shapely_strict', coefficient: float = 1.0) Compte le nombre de valeurs contenues dans un polygone :param myvect: target vector :param usemask: (optional) restreint les éléments aux éléments non masqués de la matrice :param method: (optional) method to use :param coefficient: (optional) coefficient to apply to the count (default 1.) .. py:method:: 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) Compte le nombre de valeurs contenues dans une instance Zones ou une liste de vecteurs :param myvects: target vectors or zone :param usemask: (optional) restreint les éléments aux éléments non masqués de la matrice :param method: (optional) method to use :param coefficient: (optional) coefficient to apply to the count (default 1.) .. py:method:: 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) Compte le nombre de valeurs contenues dans une instance Zones ou une liste de "zone" :param zones: target zones or list of zones :param usemask: (optional) restreint les éléments aux éléments non masqués de la matrice :param method: (optional) method to use :param coefficient: (optional) coefficient to apply to the count (default 1.) .. py:method:: 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) 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. :param working_vector: vector - polygon with z values :param method: interpolation method - 'nearest', 'linear' or 'cubic' :param 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 :param rescale: rescale the input data to [0, 1] for better numerical stability (only for 'linear' and 'cubic' methods) :param method_selection: cell selection method: ``'mpl'``, ``'shapely_strict'``, ``'shapely_wboundary'``, or ``'rasterio'`` :param usemask: if ``True``, interpolate only within unmasked cells :param epsilon: tolerance for boundary detection :return: None .. py:method:: interpolate_on_polygons(working_zone: wolfhece.PyVertexvectors.zone, method: Literal['nearest', 'linear', 'cubic'] = 'linear', keep: Literal['all', 'below', 'above'] = 'all') Interpolate values inside each polygon of a zone using vertex elevations. :param working_zone: zone containing multiple polygons :param method: interpolation method: ``'nearest'``, ``'linear'``, or ``'cubic'`` :param keep: value-keeping strategy: ``'all'``, ``'below'``, or ``'above'`` .. py:method:: interpolate_strictly_on_polyline(working_vector: wolfhece.PyVertexvectors.vector, usemask=True, keep: Literal['all', 'below', 'above'] = 'all') 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 :param working_vector: polyline vector with 3D vertices :param usemask: if ``True``, only update unmasked cells :param keep: value-keeping strategy: ``'all'``, ``'below'``, or ``'above'`` .. py:method:: interpolate_strictly_on_vertices(working_vector: wolfhece.PyVertexvectors.vector, usemask=True, keep: Literal['all', 'below', 'above'] = 'all') 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 :param working_vector: vector with 3D vertices :param usemask: if ``True``, only update unmasked cells :param keep: value-keeping strategy: ``'all'``, ``'below'``, or ``'above'`` .. py:method:: interpolate_on_polyline(working_vector: wolfhece.PyVertexvectors.vector, usemask=True) 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 :param working_vector: polyline vector with 3D vertices :param usemask: if ``True``, only update unmasked cells .. py:method:: interpolate_on_polylines(working_zone: wolfhece.PyVertexvectors.zone, usemask=True) Interpolate cell values along all polylines in a zone. :param working_zone: zone containing multiple polylines :param usemask: if ``True``, only update unmasked cells .. py:method:: interpolate_on_cloud(xy: numpy.ndarray, z: numpy.ndarray, method: Literal['linear', 'nearest', 'cubic'] = 'linear') 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. :param xy: numpy.array of vertices - shape (n,2) :param z: numpy.array of values - shape (n,) :param method: method for the interpolation -- 'nearest', 'linear' or 'cubic' See : https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html .. py:method:: 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) 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.** :param coords: numpy.array of vertices - shape (n,3) :param triangles: numpy.array of triangles - shape (m,3) :param grid_x: numpy.array of x values where the interpolation will be done -- if None, the grid is created from the array :param grid_y: numpy.array of y values where the interpolation will be done -- if None, the grid is created from the array :param mask_tri: numpy.array of mask for the triangles :param interp_method: method for the interpolation -- 'matplotlib' or 'scipy' :param keep: 'all' to keep all values, 'below' to keep only values below the current array, 'above' to keep only values above the current array :param 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 .. py:method:: interpolate_on_triangulations(multiple_triangulations: list[wolfhece.PyVertexvectors.Triangulation], interp_method: Literal['matplotlib', 'scipy'] = 'scipy', keep: Literal['all', 'below', 'above'] | list[str] = 'all') Interpolation sur plusieurs triangulations. :param multiple_triangulations: list of Triangulation objects :param interp_method: method for the interpolation -- 'matplotlib' or 'scipy' :param 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 .. py:method:: interpolation2D(key: str = '1') Perform a 2D interpolation over the selected cells using key reference points. :param key: interpolation key identifying the source data or method .. py: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) Rasterize a vector using the value of the id :param working_vector: vector to rasterize :param id: attribute id whose value will fill the rasterized cells :param method: spatial method: ``'mpl'``, ``'shapely_strict'``, ``'shapely_wboundary'``, ``'rasterio'`` :param usemask: if ``True``, only rasterize unmasked cells :param epsilon: boundary tolerance .. py:method:: 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) Rasterize each vector of a zone using the value of the given attribute id. :param working_zone: zone containing vectors to rasterize :param id: attribute id whose value will fill rasterized cells :param method: spatial method for cell selection :param usemask: if ``True``, only rasterize unmasked cells :param epsilon: boundary tolerance .. py:method:: 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) Rasterize each vector of a :class:`Zones` collection using the value of the given attribute id. :param working_zones: :class:`Zones` containing vectors to rasterize :param id: attribute id whose value will fill rasterized cells :param method: spatial method for cell selection :param usemask: if ``True``, only rasterize unmasked cells :param epsilon: boundary tolerance .. py:method:: 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) Fill in a vector using the provided value :param working_vector: vector :param value: value to fill in (float or int depending on the array type) :param 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) :param usemask: if True, only fill in the masked points :param epsilon: tolerance for shapely methods (to consider points on the boundary) .. py:method:: 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) Fill all cells inside each vector of a zone with the given value. :param working_zone: zone whose vectors define the fill area :param value: value to assign to cells inside the zone vectors :param method: spatial method for cell selection :param usemask: if ``True``, only fill unmasked cells :param epsilon: boundary tolerance .. py:method:: 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) Fill all cells inside each vector of a :class:`Zones` collection with the given value. :param working_zones: :class:`Zones` whose vectors define the fill areas :param value: value to assign to cells inside the zone vectors :param method: spatial method for cell selection :param usemask: if ``True``, only fill unmasked cells :param epsilon: boundary tolerance .. py:method:: fillin_from_xyz(xyz: numpy.ndarray) Remplissage du tableau à partir d'un tableau xyz. :param xyz: Numpy array - shape (n, 3) .. py:method:: fillin_from_ijz(ijz: numpy.ndarray) Remplissage du tableau à partir d'un tableau ijz :param ijz: Numpy array - shape (n, 3) .. py:method:: filter_inundation(epsilon: float = None, mask: numpy.ndarray = None) Apply filter on array : - mask data below eps - mask data outisde linkedvec :param epsilon: value under which data are masked :param mask: mask to apply if eps is None If all params are None, the function will mask NaN values .. py:method:: filter_independent_zones(n_largest: int = 1, reset_plot: bool = True) Label independent connected regions and keep only the *n* largest. :param n_largest: number of largest zones to keep :param reset_plot: if ``True``, reset the plot after filtering .. py:method:: filter_zone(set_null: bool = False, reset_plot: bool = True) Keep only the labeled regions that contain at least one selected cell. mailles sont sélectionnées :param set_null: if ``True``, set filtered-out cells to :attr:`nullvalue` :param reset_plot: if ``True``, reset the plot after filtering .. py:method:: clean_small_patches(min_size: int = 1, set_null: bool = False, reset_plot: bool = True) Clean small patches in the array :param min_size: minimum patch size in cells; smaller patches are removed :param set_null: if ``True``, set removed cells to :attr:`nullvalue` :param reset_plot: if ``True``, reset the plot after cleaning .. py:method:: labelling(reset_plot: bool = True) Labelling of the array using Scipy :param reset_plot: if ``True``, reset the plot after labelling .. py:method:: statistics(inside_polygon: wolfhece.PyVertexvectors.vector | shapely.geometry.Polygon | numpy.ndarray = None) -> dict[str, float | numpy.ndarray] Statistics on Selected data or the whole array if no selection :param inside_polygon: vector or Polygon to select data inside the polygon :return: mean, std, median, sum, volume (sum*dx*dy), values :rtype: 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 .. py:method:: get_unique_values() Return unique values in the array .. py:method:: map_values(keys_vals: dict, default: float = None) 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. :param keys_vals: dictionary of values to map :param default: default value if key not found .. py:method:: add_crosslinked_array(newlink: WolfArrayModel) Add a bidirectional cross-link between this array and another. :param newlink: :class:`WolfArrayModel` to cross-link with this array .. py:method:: share_palette() Share the color palette object with all cross-linked arrays. .. py:method:: paste_all(fromarray: WolfArrayModel, mask_after: bool = True) Paste the data from another array into this one where geometries overlap. :param fromarray: source :class:`WolfArrayModel` from which to paste values :param mask_after: if ``True``, mask cells equal to :attr:`nullvalue` after pasting .. py:method:: set_values_sel(xy: list[float], z: list[float], update: bool = True) Set values at the selected positions :param xy: [[x1,y1],[x2,y2],...] :param z: [z1,z2,...] :param update: update the plot .. py:method:: crop_array(bbox: list[list[float], list[float]], setnull_trx_try: bool = False) -> WolfArrayModel 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. :param bbox: bounding box [[xmin, xmax], [ymin, ymax]]. :param 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`. .. py:method:: crop_masked_at_edges() Crop the array to remove masked cells at the edges of the array :return: cropped array, WolfArrayModel instance .. py:method:: crop(i_start: int, j_start: int, nbx: int, nby: int, k_start: int = 1, nbz: int = 1) Crop the array :param i_start: start index in x :param j_start: start index in y :param nbx: number of cells in x :param nby: number of cells in y :param k_start: start index in z :param nbz: number of cells in z :return: cropped array, WolfArrayModel instance .. py:method:: extend(x_ext: int, y_ext: int) Extend the array Crop is the opposite :param x_ext: number of cells to add/remove in the x direction (positive = extend, negative = shrink) :param y_ext: number of cells to add/remove in the y direction (positive = extend, negative = shrink) .. py:method:: extremum(which: Literal['min', 'max'] = 'min') Return the extremum value :param which: which extremum to find: ``'min'`` or ``'max'`` .. py:method:: nullify_border(width: int = 1) Set border to nullvalue :param width: number of border cells to set to :attr:`nullvalue` .. py:method:: convolve(filter, method: Literal['scipyfft', 'jaxfft', 'classic'] = 'scipyfft', inplace: bool = True) -> WolfArrayModel 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.** :param filter: filter to convolve with :param method: method to use for convolution ('scipyfft', 'jaxfft', 'classic') :param inplace: if True, the array is modified in place, otherwise a new array is returned -- same type as the original one :return: convolved array, WolfArrayModel instance .. py:method:: concatenate(list_arr: list[WolfArrayModel], nullvalue: float = 0.0) Concatenate the values from another WolfArrays into a new one :param list_arr: list of WolfArrayModel objects :param nullvalue: null value for the output array :return: a new WolfArrayModel :return_type: WolfArrayModel .. py:method:: as_WolfArray(abs: bool = True) -> WolfArrayModel Return a WolfArrayModel object from this WolfArrayModel :param abs: if ``True``, use absolute coordinates .. py:method:: 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) Estimation of the volume of the selected zone. :param zmax: maximum elevation (if None, uses array max) :param nb: number of elevation steps :param labeled: if True, use labeling to identify connected areas :param use_memory: if True, use memory selection to identify areas :param memory_key: key of the memory selection to use (if use_memory) :param output_fn: filename for zoning result (if None, no file is written) :param axs: matplotlib Axes to plot the results :return: (fig, axs) or None if cancelled .. py:method:: 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) Estimation of the surface and volume from an elevation array. :param axs: Axes to plot the results :param desired_zmin: Minimum elevation to consider :param desired_zmax: Maximum elevation to consider :param nb: Number of elevation 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 :param invert_z: if ``True``, invert the elevation axis (useful for bathymetry) :param array_to_integrate: optional array whose values are integrated instead of pure surface area :return: Figure and Axes with the results :rtype: tuple[plt.Figure, plt.Axes] .. py:method:: 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) 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] .. py:method:: hillshade(azimuth: float, angle_altitude: float) Create a hillshade array -- see "hillshade" function accelerated by JIT :param azimuth: sun azimuth angle in degrees (default: 315°) :param angle_altitude: sun altitude angle in degrees above the horizon .. py:method:: get_gradient_norm() Compute and return the norm of the gradient .. py:method:: get_laplace() Compute and return the laplacian .. py:method:: 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] The borders are computed on basis of the current *mask* :param filename: if provided, write 'sux', 'sux' and 'xy' files :param abs: add translation coordinates (Global World Coordinates) :param one_vec_if_ml: if ``True``, merge multi-level contour segments into a single vector :return: 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 .. py:method:: contour(levels: Union[int, list[float]] = 10) -> wolfhece.PyVertexvectors.Zones Compute contour lines :param levels: list of contour levels to extract .. py:method:: inpaint(mask_array: WolfArrayModel = None, test_array: WolfArrayModel = None, ignore_last: int = 1, multiprocess: bool = True) InPaintaing holes in the array :param mask_array: where computation is done :param test_array: used in test -- interpolation is accepted if new value is over test_array :param ignore_last: number of last patches to ignore :param multiprocess: use multiprocess for inpainting .. py:method:: _inpaint_waterlevel_dem_dtm(dem: WolfArrayModel, dtm: WolfArrayModel, ignore_last: int = 1, use_fortran: bool = False, multiprocess: bool = True) InPaintaing waterlevel holes in the array. We use DEM and DTM to mask and constraint the inpainting process. :param dem: Digital Elevation Model (same as simulation model) :param dtm: Digital Terrain Model :param ignore_last: number of last patches to ignore :param use_fortran: use Fortran inpainting code :param multiprocess: use multiprocess for inpainting .. py:method:: count_holes(mask: WolfArrayModel = None) Count holes in the array :param mask: boolean mask array; if ``None``, use :attr:`array.mask` .. py:method:: select_holes(mask: WolfArrayModel = None, ignore_last: int = 1) Select holes in the array :param mask: boolean mask array; if ``None``, use :attr:`array.mask` :param ignore_last: if ``True``, ignore the largest (background) hole .. py:method:: create_mask_holes(ignore_last: int = 1) -> WolfArrayModel Select holes in the array and create a new aray :param ignore_last: if ``True``, ignore the largest (background) hole .. py:method:: fill_holes_with_value(value: float, mask: WolfArrayModel = None, ignore_last: int = 1) Fill holes in the array with a value :param value: value to fill holes with :param mask: boolean mask defining the holes; if ``None``, auto-detect :param ignore_last: if ``True``, ignore the largest (background) hole .. py:method:: 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) Fill holes in the array with a value if it intersects with the mask :param value: value to fill holes with :param vects: list of polygon vectors for intersection test :param method: spatial method for intersection check :param buffer: buffer distance for intersection test .. py:method:: _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 Internal helper: fill a single labelled hole if it intersects the given polygon. :param value: value to fill holes with :param vect: polygon vector for intersection test :param method: spatial method for intersection check :param buffer: buffer distance for intersection test .. py:method:: _create_building_holes_dem_dtm(dem: WolfArrayModel, dtm: WolfArrayModel, ignore_last: int = 1) -> WolfArrayModel Create a mask identifying building footprints from the difference between DEM and DTM. :param dem: Digital Elevation Model array :param dtm: Digital Terrain Model array :param ignore_last: if ``True``, ignore the largest (background) hole .. py:method:: get_triangulation(bounds: list[float] = None) Traingulation of the array :param bounds: [[xmin,xmax],[ymin,ymax]] .. py:method:: compare_cloud(mycloud: wolfhece.PyVertex.cloud_vertices, delta: list[float] = [0.15, 0.5, 1.0]) Graphique de comparaison des valeurs d'un nuage de points et des valeurs de la matrice sous les mêmes positions :param mycloud: cloud_vertices :param delta: list of tolerance for the comparison .. py:method:: compare_tri(mytri: wolfhece.PyVertexvectors.Triangulation) Plot a comparison between array values and triangulation vertex elevations. :param mytri: :class:`Triangulation` object to compare against the array .. py:method:: 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) 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 .. py:method:: 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] Create Matplotlib image from WolfArrayModel :param figax: tuple ``(fig, ax)`` of matplotlib Figure and Axes; created if ``None`` :param cmap: matplotlib colormap name (default: ``None`` uses internal palette) :param step_ticks: step (in world units) between tick labels on the axes .. py:method:: get_rebin_shape_size(factor: float, reshape_array_if_necessary: bool = False) -> tuple[tuple[int, int], tuple[float, float]] Return the new shape after rebinning. newdx = dx * factor newdy = dy * factor The shape is adjusted to be a multiple of the factor. :param factor: factor of resolution change -- > 1.0 : decrease resolution, < 1.0 : increase resolution :type factor: float :param reshape_array_if_necessary: if ``True``, pad array so dimensions are divisible by the downsampling factor :return: new shape :rtype: Tuple[int, int], Tuple[float, float] .. py:method:: get_rebin_header(factor: float) -> wolfhece.wolf_array._header_wolf.header_wolf Return a new header after rebinning. :param factor: factor of resolution change -- > 1.0 : decrease resolution, < 1.0 : increase resolution :type factor: float :return: new header :rtype: header_wolf .. py:method:: rebin(factor: float, operation: Literal['mean', 'sum', 'min', 'max', 'median'] = 'mean', operation_matrix: WolfArrayModel = None) -> None Change resolution - **in place**. If you want to keep current data, copy the WolfArrayModel into a new variable -> newWA = Wolfarray(mold=curWA). :param factor: factor of resolution change -- > 1.0 : decrease resolution, < 1.0 : increase resolution :type factor: float :param operation: operation to apply on the blocks ('mean', 'sum', 'min', 'max', 'median') :type operation: str, Rebin_Ops :param operation_matrix: 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 :type operation_matrix: WolfArrayModel .. py:method:: 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) :classmethod: Reprojects and resamples a raster file from an other EPSG coordinates and return it as a WolfArrayModel. :param input_raster_path: The path to the input raster file. :type input_raster_path: str :param input_srs: The input spatial reference system (SRS) in the format 'EPSG:XXXX'. Defaults to Lambert 2008 'EPSG:3812'. :type input_srs: str :param output_srs: The output spatial reference system (SRS) in the format 'EPSG:XXXX'. Defaults to Belgian Lambert 72 'EPSG:31370'. :type output_srs: str :param 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. :raises RuntimeError: If the input raster file cannot be opened. :raises PermissionError: If there is a permission error while trying to delete the output raster file. :raises Exception: If an unexpected error occurs while trying to delete the output raster file. :raises RuntimeError: If the reprojection fails for the input raster file. :return: WolfArrayModel .. py:method:: reproject(output_epsg: int, resampling_method=gdal.GRA_Bilinear) -> WolfArrayModel Reprojects and resamples the WolfArrayModel to a new EPSG coordinate system. :param output_epsg: The output EPSG code for the desired coordinate system. :type output_epsg: int :param 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 .. py:method:: merge(others: list, abs: bool = True, copy: bool = True) -> WolfArrayModel :classmethod: Merge several WolfArrayModel into a single WolfArrayModel :param others: list of WolfArrayModel to merge :param abs: if True -> Global World Coordinates :param copy: if True -> copy data (**Not necessary** if data header CAN BE modified. It can be save memory) .. py:method:: set_general_frame_from_xyz(fname: str, dx: float, dy: float, border_size: int = 5, delimiter: str = ',', fillin: bool = False) :classmethod: Lecture d'un fichier texte xyz et initialisation des données de base :param fname: nom du fichier xyz :param dx: pas en x :param dy: pas en y :param border_size: nombre de mailles de bordure en plus de l'extension spatiale du fichier :param delimiter: column delimiter in the XYZ file (e.g. ``"\t"``, ``" "``) :param fillin: if ``True``, fill the array with values from the XYZ file .. py:method:: set_general_frame_from_xyz_dir(path: str, bounds: list, delimiter: str = ',', dxdy: tuple[float, float] = None, border_size: int = 5, fillin: bool = True) :classmethod: 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 :param path: chemin du dossier avec les fichier xyz :dtype path: str :param bounds: limites de l'extension spatiale :dtype bounds: list :param delimiter: délimiteur des fichiers xyz :dtype delimiter: str :param border_size: nombre de mailles de bordure en plus de l'extension spatiale du fichier :param dxdy: tuple ``(dx, dy)`` cell size; if ``None``, infer from data :param fillin: if ``True``, fill the array with values from the XYZ files :dtype border_size: int