Mesh size definition
- class ocsmesh.hfun.Hfun(hfun: Raster | EuclideanMesh2D | Iterable[Raster | EuclideanMesh2D | str], **kwargs: Any)
Bases:
object
Size function object factory
Factory class that creates and returns concrete mesh size function object based on the type of the inputs.
Methods
is_valid_type(hfun_object)
Static method to check if an object is a valid size function type
Notes
The object created when using this class is not an instance of this class or a subclass of it. It is a subclass of BaseHfun instead.
- Parameters:
- hfunCanCreateHfun
Object to create the mesh size function from. The type of this object determines the created size function object type
- **kwargsdict, optional
Keyword arguments passed to the constructor of the correct size function type
Methods
is_valid_type
(hfun_object)Checks if an object is a valid size function type
- static is_valid_type(hfun_object: Any) bool
Checks if an object is a valid size function type
- class ocsmesh.hfun.HfunRaster(raster: Raster, hmin: float | None = None, hmax: float | None = None, verbosity: int = 0)
Bases:
BaseHfun
,Raster
Raster based size function.
Creates a raster based size function. The mesh size is specified at each point of the grid of the input raster, based on the specified criteria.
- Attributes:
Methods
msh_t()
Return mesh sizes interpolated on an size-optimized unstructured mesh
apply_added_constraints()
Re-apply the existing constraint. Mostly used internally.
apply_constraints(constraint_list)
Apply constraint objects in the constraint_list.
add_topo_bound_constraint(…)
Add size fixed-per-point value constraint to the area bounded by specified bounds with expansion/contraction rate rate specified.
add_topo_func_constraint(…)
Add size value constraint based on function of depth/elevation to the area bounded by specified bounds with the expansion or contraction rate rate specified.
add_courant_num_constraint(…)
Add constraint based on approximated Courant number
add_region_constraint(…)
Add a constraint on size based on a specified region
add_patch(…)
Add a region of fixed size refinement with optional expansion rate for points outside the region to achieve smooth size transition.
add_contour(level expansion_rate target_size=None, nprocs=None)
Add refinement based on contour lines auto-extrcted from the underlying raster data. The size is calculated based on the specified rate, target_size and the distance from the extracted feature line.
add_channel(…)
Add refinement for auto-detected narrow domain regions. Optionally use an expansion rate for points outside detected narrow regions for smooth size transition.
add_feature(…)
Decorated method to add size refinement based on the specified expansion_rate, target_size, and distance from the input feature lines feature.
get_xy_memcache(window, dst_crs)
Get XY grid cached onto disk. Useful for when XY needs to be projected to UTM so as to avoid reprojecting on every call.
add_subtidal_flow_limiter(…)
Add mesh size refinement based on the value as well as gradient of the topography within the region between specified by lower and upper bound on topography.
add_constant_value(value, lower_bound=None, upper_bound=None)
Add fixed size mesh refinement in the region specified by upper and lower bounds on topography.
Notes
Currently the implementation of this size function is such that when an object is created, the “size” values of this object is set to be maximum np.float32, and maximum and minimum constraints are not applied. After application of any refinement or constrant these constraints are actually applied. As a result if a raster based size function is created and no add_* or apply_* method is called, the values of hmin and hmax attributes as well as any value on the size function grid is meaningless.
An important distinction that must be made is between refinements and constraints. These two concepts are applied differently when it comes to calculating the sizes. Refinements specification guarantees that the sizes in the specified region is at most equal to the specified value, however it does not have any guarantee on the minimum of sizes. In other words if multiple refinements are specified, then the size at everypoint is equal to the minimum calculated from all of those refinements. Contraints are applied a bit differently. Constraints ensure that a given condition is met at a given point. A list of specified constraints is created and after application of any refinements or other constraints, all the constraint are re-applied. As a result constraint can be used to ensure the size at a given point is not smaller that a specified value. Constraint can also be used similar to refinements to ensure the size is smaller than a specified value.
Another important different between contraints and refinements is that for refinements the final value is the minimum of all, but constraints are applied one at a time and depending on their type and condition, it might result on a value between all specified maximums and minimums.
Note that constraints can be conflicting, currently there’s no automatic conflict resolutions and the constrains are applied in the order specified, so if applicable the last one overrides all else.
Initialize a raster based size function object
- Parameters:
- rasterRaster
The input raster file. The sizes are calculated on the grid points of the raster’s grid. The input raster is not modified so that its elevation data can be used for topo-based refinement calculations.
- hminfloat or None, default=None
Global minimum size of mesh for the size function, if not specified, the calculated values during refinement and constraint applications are not capped off.
- hmaxfloat or None, default=None
Global maximum size of mesh for the size function, if not specified, the calculated values during refinement and constraint applications are not capped off.
- verbosityint, default=0
The verbosity of the outputs.
- Attributes:
bbox
Read-only attribute for the bounding box of the raster grid
chunk_size
Modfiable attribute for stored square raster window size
count
Read-only attribute for the number of bands of raster dataset
crs
Read-only attribute for raster CRS
dtypes
Read-only attribute for raster’s data type
dx
Read-only attribute for grid distance in x direction
dy
Read-only attribute for grid distance in y direction
height
Read-only attribute for the number of rows of raster grid
hmax
Read-only attribute for the maximum mesh size constraint
hmin
Read-only attribute for the minimum mesh size constraint
is_masked
Read-only attribute indicating whether raster has missing data.
md5
Read-only attribute for the hash of working raster file content
- nodata
- nodatavals
overlap
Modfiable attribute for stored raster windows overlap amount
path
Read-only attribute for the path to original raster file
raster
Read-only attribute to reference to the input raster
resampling_method
Modifiable attribute for stored raster resampling method
shape
Read-only attribute indicating the shape of raster grid
src
Read-only attribute for access to opened dataset handle
tmpfile
Read-only attribute for the path to working raster file
transform
Read-only attribute for raster’s transform
values
Read-only attribute for the raster grid data
verbosity
Modifiable attribute for the verbosity of the output
width
Read-only attribute for the number of columns of raster grid
x
Read-only attribute for the x-ticks of raster grid
xres
Read-only attribute for grid resolution in x direction
y
Read-only attribute for the y-ticks of raster grid
yres
Read-only attribute for grid resolution in y direction
Methods
add_band
(values, **tags)Add a new band for values with tags tags to the raster
adjust
([geom, inside_min, outside_max, cond])Adjust raster data in-place based on specified shape.
Apply all the added constraints
apply_constraints
(constraint_list)Applies constraints specified by the list of contraint objects.
average_filter
(size[, drop_above, ...])Apply average(mean) filter on the raster
clip
(geom)Clip raster data in-place, outside the specified shape.
close
()Delete source object
contourf
([band, window, axes, vmin, vmax, ...])Plot filled contour for raster data.
dtype
(i)Raster data type
Fill missing values in the raster in-place
gaussian_filter
(**kwargs)Apply Gaussian filter to the raster data in-place
generic_filter
(function, **kwargs)Apply Gaussian filter to the raster data in-place
get_bbox
([crs, output_type])Calculate the bounding box of the raster.
get_channels
([level, width, tolerance])Calculate narrow width polygons based on specified input
get_contour
(level[, window])Calculate contour lines for specified data level.
get_multipolygon
([zmin, zmax, window, ...])Calculate and return a multipolygon based on the raster data
get_values
([window, band])Return the data stored at each point in the raster grid
get_window_bounds
(window)Returns west, south, east, north bounds of the window
get_window_data
(window[, masked, band])Return the positions and values of raster data for the window
get_window_transform
(window)Returns raster's affine transform calculated for the window
get_x
([window])Get X positions of the raster grid.
get_xy
([window])Get raster positions tuple array
get_xy_memcache
(window, dst_crs)Get the transformed locations of raster points.
get_xyz
([window, band])Return the data stored at each point in the raster grid
get_y
([window])Get Y positions of the raster grid.
iter_windows
([chunk_size, overlap])Calculates sequence of windows for the raster
mask
(shapes[, i])Mask data based on input shapes in-place
modifying_raster
([use_src_meta])Context manager for modifying and storing raster data
msh_t
([window, marche, verbosity])Interpolates mesh size function on an unstructred mesh
nodataval
(i)Value used for filling no-data points
read
(i[, masked])Read the data from raster opened file
read_masks
([i])Read existing masks on the raster data
resample
(scaling_factor[, resampling_method])Resample raster data in-place based on a scaling factor
sample
(xy, i)Get value of the data in specified positions
save
(path)Save-as raster dataset to a new location
tags
([i])Return a dictionary of dataset or band's tags
warp
(dst_crs[, nprocs])Reproject the raster data to specified dst_crs in-place
add_channel
add_constant_value
add_contour
add_courant_num_constraint
add_feature
add_patch
add_region_constraint
add_subtidal_flow_limiter
add_topo_bound_constraint
add_topo_func_constraint
hold_applying_added_constratins
Notes
All the points in the raster grid are set to have maximum np.float32 value. The hmin and hmax arguments, even if provided, are not applied in during initialization.
- msh_t(window: Window | None = None, marche: bool = False, verbosity: bool | None = None) jigsaw_msh_t
Interpolates mesh size function on an unstructred mesh
Interpolate the calculated mesh sizes from the raster grid onto an unstructured mesh. This mesh is generated by meshing the input raster using the size function values. The return value is in a projected CRS. If the input raster CRS is geographic, then a local UTM CRS is calculated and used for the output of this method.
- Parameters:
- windowrasterio.windows.Window or None, default=None
If provided, a single window on raster for which the mesh size is to be returned.
- marchebool, default=False
Whether to run marche algorithm on the complete size function before calculating the unstructured mesh and interpolate values on it.
- verbositybool or None, default=None
The verbosity of the output.
- Returns:
- jigsaw_msh_t
Size function calculated and interpolated on an unstructured mesh.
Notes
In case the underlying raster is created in windowed calculation mode, this method calculated the mesh for each window separately and then combines (no remeshing) the elements of all the windows.
The output of this method needs to have length unit for distances (i.e. not degrees) since mesh size is specified in length units and the domain and size function are the passed to the mesh engine for cartesian meshing.
The reason the full high-resolution size function is interpolated on a generated mesh it to save memory and have the ability to process and combine many DEMs. By doing more sizes are specified at points where the size needs to be smaller in the final mesh.
To generate the mesh for size function interpolation, the raster size function (called
hmat
) is passed to the mesh engine along with the bounding box of the size function as the meshing domain.
- apply_added_constraints() None
Apply all the added constraints
This method is implemented for internal use. It’s public because it needs to be called from outside the class through a decorator.
- Parameters:
- Returns:
- None
- apply_constraints(constraint_list: Iterable[Constraint]) None
Applies constraints specified by the list of contraint objects.
Applies constraints from the provided list constraint_list, but doesn’t not store them in the internal size function constraint list. This is mostly for internal use.
- Parameters:
- constraint_listiterable of Constraint
List of constraint objects to be applied to (not stored in) the size function.
- Returns:
- None
- get_xy_memcache(window: Window, dst_crs: CRS | str) ndarray[Any, dtype[float]]
Get the transformed locations of raster points.
Get the locations of raster points in the dst_crs CRS. This method caches these transformed values for fast retrieval upon multiple calls.
- Parameters:
- windowrasterio.windows.Window
The raster window for querying location data.
- dst_crsCRS or str
The destination CRS for the raster points locations.
- Returns:
- np.ndarray
Locations of raster points after projecting to dst_crs
See also
get_xy
Get the locations of raster points from the raster file.
- property raster
Read-only attribute to reference to the input raster
- property hmin
Read-only attribute for the minimum mesh size constraint
- property hmax
Read-only attribute for the maximum mesh size constraint
- property verbosity
Modifiable attribute for the verbosity of the output
- add_band(values: ndarray[Any, dtype[float]], **tags: Any) int
Add a new band for values with tags tags to the raster
- Parameters:
- valuesarray-like
The values to be added to the raster, it must have the correct shape as the raster.
- **tagsdict, optional
The tags to be added for the new band of data.
- Returns:
- int
ID of the new band added to the raster.
- adjust(geom: None | Polygon | MultiPolygon = None, inside_min: float = -inf, outside_max: float = inf, cond: Callable[[ndarray[Any, dtype[float]]], ndarray[Any, dtype[bool]]] | None = None) None
Adjust raster data in-place based on specified shape.
This method can be used to adjust e.g. raster elevation values based on a more accurate land-mass polygon.
- Parameters:
- geomNone or Polygon or MultiPolygon
Filled shape to determine which points are considered inside or outside (usually land-mass polygon)
- inside_minfloat
The minimum value to truncate raster data that falls inside the specified geom shape
- outside_maxfloat
The maximum value to truncate raster data that falls outside the specified geom shape
- Returns:
- None
- average_filter(size: int | ndarray[Any, dtype[int]], drop_above: float | None = None, drop_below: float | None = None, apply_on_bands: List[int] | None = None) None
Apply average(mean) filter on the raster
- Parameters:
- size: int, npt.NDArray[int]
size of the footprint
- drop_above: float or None
elevation above which the cells are ignored for averaging
- drop_below: float or None
elevation below which the cells are ignored for averaging
- Returns:
- None
- property bbox: Polygon | Bbox
Read-only attribute for the bounding box of the raster grid
This is a read-only property that returns the same results as get_bbox method
- property chunk_size: int
Modfiable attribute for stored square raster window size
- clip(geom: Polygon | MultiPolygon) None
Clip raster data in-place, outside the specified shape.
- Parameters:
- geomPolygon or MultiPolygon
Shape used to clip the raster data
- Returns:
- None
- close() None
Delete source object
- contourf(band: int = 1, window: Window | None = None, axes: Axes | None = None, vmin: float | None = None, vmax: float | None = None, cmap: str = 'topobathy', levels: List[float] | None = None, show: bool = False, title: str | None = None, figsize: Tuple[float, float] | None = None, colors: int = 256, cbar_label: str | None = None, norm=None, **kwargs: Any) Axes
Plot filled contour for raster data.
- Parameters:
- bandint, default=1
Raster band from which data is used.
- windowwindows.Window or None, default=None
Raster window from which data is used.
- axesAxes or None, default=None
Matplotlib axes to draw contour on>
- vminfloat or None, default=None
Minimum value of the filled contour.
- vmaxfloat or None, default=None
Maximum value of the filled contour.
- cmapstr, default=’topobathy’
Colormap to use for filled contour.
- levelslist of float or None, default=None
Prespecified list of contour levels.
- showbool, default=False
Whether to show the contour on creation or not.
- titlestr or None, default=None
Title used on the axes of the contour
- figsizetuple of float or None, default=None
Figure size used for the contour figure
- colorsint, default=256
Contour colors associated with levels
- cbar_labelstr or None, default=None
Label of the colorbar
- normNormalize or None, default=None
Normalizer object
- **kwargsdict, optional
Keyword arguments passed to the matplotlib contourf() function
- Returns:
- Axes
Axes object from matplotlib library that holds onto the contour plot object
- property count: int
Read-only attribute for the number of bands of raster dataset
- property crs: CRS
Read-only attribute for raster CRS
This read-only property returns CRS as a pyproj.CRS type not rasterio.CRS.
- dtype(i: int) ndarray[Any, dtype[float]]
Raster data type
- Parameters:
- iint
The index of the band to read the data from
- Returns:
- Any
Data type of raster values
- property dtypes: Any
Read-only attribute for raster’s data type
- property dx: float
Read-only attribute for grid distance in x direction
- property dy: float
Read-only attribute for grid distance in y direction
- fill_nodata() None
Fill missing values in the raster in-place
- gaussian_filter(**kwargs: Any) None
Apply Gaussian filter to the raster data in-place
- Parameters:
- **kwargsdict, optional
Keyword arguments passed to SciPy gaussian_filter function
- Returns:
- None
- generic_filter(function, **kwargs: Any) None
Apply Gaussian filter to the raster data in-place
- Parameters:
- function: callable, LowLevelCallable
Function to be used on the footprint array
- **kwargsdict, optional
Keyword arguments passed to SciPy generic_filter function
- Returns:
- None
- get_bbox(crs: str | CRS | None = None, output_type: Literal['polygon', 'bbox'] = 'polygon') Polygon | Bbox
Calculate the bounding box of the raster.
- Parameters:
- crsstr or CRS or None, default=None
The CRS in which the bounding box is requested.
- output_type{‘polygon’, ‘bbox’}
The label of the return type for bounding box, either a shapely ‘polygon’ or matplotlib ‘bbox’.
- Returns:
- box or Bbox
The bounding box of the raster.
- Raises:
- TypeError
If the label of return type is not valid.
- get_channels(level: float = 0, width: float = 1000, tolerance: float | None = None) Polygon | MultiPolygon
Calculate narrow width polygons based on specified input
By using buffer functionality this method finds narrow regions of the domain. The level specifies at which data level domain polygon should be calculated and width describes the narrow region cut-off. tolerance is used for simplifying the polygon before buffering it to reduce computational cost.
- Parameters:
- levelfloat, default=0
Reference level to calculate domain polygon for narrow region calculation.
- widthfloat, default=1000
Cut-off used for designating narrow regions.
- tolerancefloat or None, default=None
Tolerance used for simplifying domain polygon.
- Returns:
- Polygon or MultiPolygon
The calculated narrow regions based on raster data
- get_contour(level: float, window: Window | None = None) LineString | MultiLineString
Calculate contour lines for specified data level.
This method can be used e.g. to calculated coastline based on raster data.
- Parameters:
- levelfloat
The level for which contour lines must be calculated
- windowwindows.Window or None
The raster window for which contour lines must be calculated
- Returns:
- LineString or MultiLineString
The contour lines calculated for the specified level
- get_multipolygon(zmin: float | None = None, zmax: float | None = None, window: Window | None = None, overlap: int | None = None, band: int = 1) MultiPolygon
Calculate and return a multipolygon based on the raster data
Calculates filled contour from raster data between specified limits on the specified band and creates a multipolygon from the filled contour to return.
- Parameters:
- zminfloat or None, default=None
Lower bound of raster data for filled contour calculation
- zmaxfloat or None, default=None
Upper bound of raster data for filled contour calculation
- windowwindows.Window or None, default=None
Window over whose data the multipolygon is calculated
- overlapint or None, default=None
Overlap used for generating windows if window is not provided
- bandint, default=1
Raster band over whose data multipolygon is calculated
- Returns:
- MultiPolygon
The calculated multipolygon from raster data
- get_values(window: Window | None = None, band: int | None = None, **kwargs: Any) ndarray[Any, dtype[float]]
Return the data stored at each point in the raster grid
- Parameters:
- windowwindows.Window, default=None
The window over which values are to be returned.
- bandint, default=None
The band from which the values should be read. If None return data from band 1.
- **kwargsdict, optional
Additional arguments to pass to rasterio.DatasetReader.read.
- Returns:
- np.ndarray
A 2D matrix of values on the raster grid.
- get_window_bounds(window: Window) Tuple[int, int, int, int]
Returns west, south, east, north bounds of the window
- Returns:
- tuple of int
West, south, east, north bounds of the window
- get_window_data(window: Window, masked: bool = True, band: int | None = None) Tuple[ndarray[Any, dtype[float]], ndarray[Any, dtype[float]], ndarray[Any, dtype[float]]]
Return the positions and values of raster data for the window
- Returns:
- tuple of np.ndarray
The triple of x-ticks, y-ticks and data on the raster grid
- get_window_transform(window: Window) None | Affine
Returns raster’s affine transform calculated for the window
- Returns:
- Affine
Affine transform matrix for specified window
- get_x(window: Window | None = None) ndarray[Any, dtype[float]]
Get X positions of the raster grid.
- Parameters:
- windowwindows.Window, default=None
The window over which X positions are to be returned
- Returns:
- np.ndarray
A vector X positions from minimum to the maximum
- get_xy(window: Window | None = None) ndarray
Get raster positions tuple array
- Parameters:
- windowwindows.Window, default=None
The window over which positions are to be returned
- Returns:
- np.ndarray
A n :math:` imes 2` matrix of positions
- get_xyz(window: Window | None = None, band: int | None = None) ndarray
Return the data stored at each point in the raster grid
- Parameters:
- windowwindows.Window, default=None
The window over which positions and values are to be returned.
- bandint, default=None
The band from which the values should be read. If None return data from band 1.
- Returns:
- np.ndarray
A n :math:` imes 3` matrix of x, y and values
- get_y(window: Window | None = None) ndarray[Any, dtype[float]]
Get Y positions of the raster grid.
- Parameters:
- windowwindows.Window, default=None
The window over which Y positions are to be returned
- Returns:
- np.ndarray
A vector Y positions from minimum to the maximum
- property height: int
Read-only attribute for the number of rows of raster grid
- property is_masked: bool
Read-only attribute indicating whether raster has missing data.
This is a read-only property that indicates whether or not the raster has missing data points. The value of this property is recalculated every time the property is retrieved.
- iter_windows(chunk_size: int | None = None, overlap: int | None = None) Generator[Window, None, None]
Calculates sequence of windows for the raster
This method calculates the sequence of square windows for the raster based on the provided chunk_size and overlap.
- Parameters:
- chunk_sizeint or None , default=None
Square window size to be used for data chunking
- overlapint or None , default=None
Overlap size for calculating chunking windows on the raster
- Yields:
- windows.Window
Calculated square window on raster based on the window size and windows overlap values.
- mask(shapes: Iterable, i: int | None = None, **kwargs: Any) None
Mask data based on input shapes in-place
- Parameters:
- shapesiterable
List of GeoJSON like dict or objects that implement Python geo interface protocol (passed to rasterio.mask.mask).
- iint or None, default=None
The index of the band to read the data from.
- **kwargsdict, optional
Keyword arguments used to create new raster Dataset.
- Returns:
- None
- property md5: str
Read-only attribute for the hash of working raster file content
This is a read-only property that is recalculated every time from the content of the temporary working raster file.
- modifying_raster(use_src_meta: bool = True, **kwargs: Any) Generator[DatasetReader, None, None]
Context manager for modifying and storing raster data
This is a helper context manager method that handles creating new temporary file and replacing the old one with it when raster data is successfully modified.
- Parameters:
- use_src_metabool, default=True
Whether or not to copy the metadata of the source raster when creating the new empty raster file
- **kwargsdict, optional
Options to be passed as metadata to raster database. These options override values taken from source raster in case use_src_meta is True
- Yields:
- rasterio.DatasetReader
Handle to the opened dataset on temporary file which will override the old values if no exception occurs during the context
- nodataval(i: int) float
Value used for filling no-data points
- Parameters:
- iint
The index of the band to read the data from
- Returns:
- float
The value to be used for points that have missing data
- property overlap: int
Modfiable attribute for stored raster windows overlap amount
- property path: Path
Read-only attribute for the path to original raster file
- read(i: int, masked: bool = True, **kwargs: Any) ndarray[Any, dtype[float]]
Read the data from raster opened file
- Parameters:
- iint
The index of the band to read the data from
- maskedbool, default=True
Whether or not to return a masked array
- **kwargsdict, optional
Additional keyword arguments passed to rasterio read()
- Returns:
- ndarray
Array of raster data
- read_masks(i: int | None = None) ndarray[Any, dtype[bool]]
Read existing masks on the raster data
- Parameters:
- iint or None, default=None
- Returns:
- np.ndarray or view
Raster band mask from the dataset
- resample(scaling_factor: float, resampling_method: str | None = None) None
Resample raster data in-place based on a scaling factor
- Parameters:
- scaling_factorfloat
The scaling factor to use for resampling data
- resampling_methodstr or None, default=None
Name of the resampling method passed to rasterio.DatasetReader.read
- Returns:
- None
- property resampling_method: Resampling
Modifiable attribute for stored raster resampling method
- sample(xy: Iterable, i: int) ndarray[Any, dtype[float]]
Get value of the data in specified positions
- Parameters:
- xyiterable
Pairs of xy coordinates for which data is retrieved
- iint
The index of the band to read the data from
- Returns:
- ndarray
Array of values for specified input positions
- save(path: str | PathLike) None
Save-as raster dataset to a new location
- Parameters:
- pathstr or path-like
The path to which raster must be saved.
- Returns:
- None
- property shape: Tuple[int, int]
Read-only attribute indicating the shape of raster grid
- property src: DatasetReader
Read-only attribute for access to opened dataset handle
- tags(i: int | None = None) Dict[str, str]
Return a dictionary of dataset or band’s tags
- Parameters:
- iint or None, default=None
The band from which the tags are read.
- Returns:
- dict
Dictionary of tags
- property tmpfile: Path
Read-only attribute for the path to working raster file
- property transform: Affine
Read-only attribute for raster’s transform
- property values: ndarray[Any, dtype[float]]
Read-only attribute for the raster grid data
This is a read-only property that returns the same results as get_values method
- warp(dst_crs: CRS | str, nprocs: int = -1) None
Reproject the raster data to specified dst_crs in-place
- Parameters:
- dst_crsCRS or str
Destination CRS to which raster must be transformed
- nprocsint, default=-1
Number of processors to use for the operation
- Returns:
- None
- property width: int
Read-only attribute for the number of columns of raster grid
- property x: ndarray[Any, dtype[float]]
Read-only attribute for the x-ticks of raster grid
This is a read-only property that returns the same results as get_x method
- property xres: float
Read-only attribute for grid resolution in x direction
This read-only property returns the same value as dx
- property y: ndarray[Any, dtype[float]]
Read-only attribute for the y-ticks of raster grid
This is a read-only property that returns the same results as get_y method
- property yres: float
Read-only attribute for grid resolution in y direction
This read-only property returns the same value as -dy
- class ocsmesh.hfun.HfunMesh(mesh: Mesh)
Bases:
BaseHfun
Mesh based size function.
Creates a mesh based size function. The mesh size is specified at each point of the mesh based on the specified criteria.
- Attributes:
Methods
msh_t()
Return mesh sizes specified on the points of the underlying mesh.
size_from_mesh()
Calculate values of the size function at each point on the underlying mesh, based on the length of edges connected to that point.
add_patch(multipolygon, expansion_rate=None,
target_size=None, nprocs=None) Add a region of fixed size refinement with optional expansion rate for points outside the region to achieve smooth size transition.
add_feature(feature, expansion_rate, target_size=None,
max_verts=200, *, nprocs=None, pool=None) Decorated method to add size refinement based on the specified expansion_rate, target_size, and distance from the input feature lines feature.
apply_added_constraints()
Re-apply the existing constraint. Mostly used internally.
apply_constraints(constraint_list)
Apply constraint objects in the constraint_list.
add_region_constraint(…)
Add a constraint on size based on a specified region.
get_bbox(**kwargs)
Return the bounding box of the underlying mesh.
Notes
Unlike raster size function, mesh based size function doesn’t support topo-based constraint at this point.
Initialize a mesh based size function object
- Parameters:
- meshMesh
Input mesh object whose points are used for specifying sizes of the mesh to be generated. Note the underlying mesh is not copied, it is overriden by methods in the object of this type.
- Attributes:
Methods
Apply all the added constraints
apply_constraints
(constraint_list)Applies constraints specified by the list of contraint objects.
get_bbox
(**kwargs)Returns the bounding box of the underlying mesh
msh_t
()Return the size function specified on the underlying mesh
Calculates sizes based on the underlying mesh edge lengths.
add_feature
add_patch
add_region_constraint
hold_applying_added_constratins
Notes
When a size function is created from a mesh, it takes the values associated with the underlying mesh. Unless size_from_mesh is called or refinements are applied, the values can be meaningless.
Unlike raster size function where the user defines the minimum and maximum, for mesh based hfun, the minimum and maximum is based on the values stored on the mesh.
Note that currently object of this type holds onto a crs variable separate from mesh.crs. Because of this, if the user is not careful, one might run into unexpected behavior!
- msh_t() jigsaw_msh_t
Return the size function specified on the underlying mesh
Return the size function values stored on the underlying mesh. The return value is in a projected CRS. If the input mesh CRS is geographic, then a local UTM CRS is calculated and used for the output of this method.
- Parameters:
- Returns:
- jigsaw_msh_t
The size function specified on the points of input mesh.
Notes
This method effectively overrides the CRS of the objects and modifies it if the CRS is initially geographic. Note that this also affects the underlying mesh object which is not copied in the contructor.
- size_from_mesh() None
Calculates sizes based on the underlying mesh edge lengths.
Get size function values based on the underlying input mesh This method overwrites the values in underlying msh_t.
- Parameters:
- Returns:
- None
Notes
The size calculations are done in a projected CRS or a local UTM CRS. However, this method does not modify the CRS of the size function, it only updates the values and discard the projected CRS it used for calculations.
- apply_added_constraints() None
Apply all the added constraints
This method is implemented for internal use. It’s public because it needs to be called from outside the class through a decorator.
- Parameters:
- Returns:
- None
- apply_constraints(constraint_list: Iterable[Constraint]) None
Applies constraints specified by the list of contraint objects.
Applies constraints from the provided list constraint_list, but doesn’t not store them in the internal size function constraint list. This is mostly for internal use.
- Parameters:
- constraint_listiterable of Constraint
List of constraint objects to be applied to (not stored in) the size function.
- Returns:
- None
- property hmin
Read-only attribute for the minimum mesh size constraint
- property hmax
Read-only attribute for the maximum mesh size constraint
- property mesh
Read-only attribute to reference to the input mesh
- property crs
Read-only attribute holding onto hfun CRS
- get_bbox(**kwargs) Polygon | Bbox
Returns the bounding box of the underlying mesh
- Parameters:
- kwargsdict, optional
Arguments passed to the underlying mesh get_bbox
- Returns:
- Polygon or Bbox
The bounding box of the underlying mesh
- class ocsmesh.hfun.HfunCollector(in_list: Iterable[Raster | EuclideanMesh2D | str], base_mesh: Mesh | None = None, hmin: float | None = None, hmax: float | None = None, nprocs: int | None = None, verbosity: int = 0, method: Literal['exact', 'fast'] = 'exact', base_as_hfun: bool = True, base_shape: Polygon | MultiPolygon | None = None, base_shape_crs: str | CRS = 'EPSG:4326')
Bases:
BaseHfun
Define size function based on multiple inputs of different types
- Attributes:
Methods
msh_t()
Return mesh sizes interpolated on an size-optimized unstructured mesh
add_topo_bound_constraint(…)
Add size fixed-per-point value constraint to the area bounded by specified bounds with expansion/contraction rate rate specified. This refinement is only applied on rasters with specified indices. The index is w.r.t the full input list for collector object creation.
add_topo_func_constraint(upper_bound=np.inf, lower_bound=-np.inf,
value_type=’min’, rate=0.01) Add size value constraint based on function of depth/elevation to the area bounded by specified bounds with the expansion or contraction rate rate specified. This constraint is only applied on rasters with specified indices. The index is w.r.t the full input list for collector object creation.
add_region_constraint(…)
Add a constraint on size based on a specified region
add_patch(…)
Add a region of fixed size refinement with optional expansion rate for points outside the region to achieve smooth size transition.
add_contour(…)
Add refinement based on contour lines auto-extrcted from the underlying raster data. The size is calculated based on the specified rate, target_size and the distance from the extracted feature line. For refinement contours are extracted only from raster inputs, but are applied on all input size function bases.
add_channel(…)
Add refinement for auto-detected narrow domain regions. Optionally use an expansion rate for points outside detected narrow regions for smooth size transition.
add_subtidal_flow_limiter(…)
Add mesh size refinement based on the value as well as gradient of the topography within the region between specified by lower and upper bound on topography. This refinement is only applied on rasters with specified indices. The index is w.r.t the full input list for collector object creation.
add_constant_value(…)
Add fixed size mesh refinement in the region specified by upper and lower bounds on topography. This refinement is only applied on rasters with specified indices. The index is w.r.t the full input list for collector object creation.
Notes
All the refinements and constraints of this collector size function are applied lazily. That means the size values are not evaluated at the time they are called. Instead the effect of all these refinements and constraints on the size is calculated when msh_t() method is called.
Two distinct algorithms are implemented for storing the size function values during evaluation and before creating the “background mesh” on which sizes are specified. Currently the difference between algorithms are only due to how raster inputs to the collector are processed. The exact algorithm is more computationally expensive; it processes all refinements on the original rasters and applies the indivitually on all of those individual rasters; this results in exponential time calculation of contours or raster features as the extracted features on all rasters must be applied on all rasters. Application of features usually involve distance calculation using a tree and can be very expensive when many rasters-features are involved. The fast approach is less exact and can use more memory, but it is much faster. The approach it takes is to still extract the raster features individually but then apply it to a lower resolution large raster that covers all the input rasters.
Initialize a collector size function object
- Parameters:
- in_listCanCreateMultipleHfun
- base_meshMesh or None, default=None
- hminfloat or None, default=None
- hmaxfloat or None, default=None
- nprocsint or None, default=None
- verbosityint, default=0
- method{‘exact’, ‘fast’}, default=’exact
- base_as_hfunbool, default=True
- base_shape: Polygon or MultiPolygon or None, default=None
- base_shape_crs: str or CRS, default=’EPSG:4326’
Methods
add_channel
([level, width, target_size, ...])Add refinement for auto detected channels
add_constant_value
(value[, lower_bound, ...])Add refinement of fixed value in the region specified by bounds.
add_contour
([level, expansion_rate, ...])Add refinement for auto extracted contours
add_courant_num_constraint
([upper_bound, ...])Add constraint based on approximated Courant number bounds
add_feature
([shape, line_defn, shapefile, ...])Add refinement as a region of fixed size with an optional rate
add_patch
([shape, patch_defn, shapefile, ...])Add refinement as a region of fixed size with an optional rate
add_region_constraint
(value, shape[, crs, ...])Add a value contraint for the points in specified region
add_subtidal_flow_limiter
([hmin, hmax, ...])Add mesh refinement based on topography.
add_topo_bound_constraint
(value[, ...])Add a fixed-value or fixed-matrix constraint.
add_topo_func_constraint
([func, ...])Add constraint based on a function of the topography
msh_t
()Interpolates mesh size functions on an unstructred mesh
- msh_t() jigsaw_msh_t
Interpolates mesh size functions on an unstructred mesh
Calculates and the interpolate the mesh sizes from all inputs onto an unstructured mesh. This mesh is generated by meshing the inputs using the size function values. The return value is in a projected CRS. If the inputs CRS the same and geographic, then a local UTM CRS is calculated and used for the output of this method.
- Parameters:
- Returns:
- jigsaw_msh_t
Size function calculated and interpolated on an unstructured mesh.
Notes
The actual application of refinements and constrains for this collector size function happens after calling this method. This calculation is cached in case of ‘exact’ algorithm and not cached for ‘fast’ algorithm.
- add_topo_bound_constraint(value: float | ndarray[Any, dtype[float32]], upper_bound: float = inf, lower_bound: float = -inf, value_type: Literal['min', 'max'] = 'min', rate: float = 0.01, source_index: List[int] | int | None = None) None
Add a fixed-value or fixed-matrix constraint.
Add a fixed-value or fixed-matrix constraint to the region of the size function specified by lower and upper elevation of the underlying DEM. Optionally a rate can be specified to relax the constraint gradually outside the bounds.
- Parameters:
- valuefloat or array-like
A single fixed value or array of values to be used for mesh size if condition is not met based on value_type. In case of an array the dimensions must match or be broadcastable to the raster grid.
- upper_boundfloat, default=np.inf
Maximum elevation to cut off the region where the constraint needs to be applied
- lower_boundfloat, default=-np.inf
Minimum elevation to cut off the region where the constraint needs to be applied
- value_type{‘min’, ‘max’}, default=’min’
Type of contraint. If ‘min’, it means the mesh size should not be smaller than the specified value at each point.
- ratefloat, default=0.01
Rate of relaxation of constraint outside the region defined by lower_bound and upper_bound.
- source_indexint or list of ints or None, default=None
The index of entries from the input list argument of the constructor of collector size function. If None all input rasters are used.
- Returns:
- None
- add_topo_func_constraint(func: ~typing.Callable[[~numpy.ndarray[~typing.Any, ~numpy.dtype[~numpy.float32]]], ~numpy.ndarray[~typing.Any, ~numpy.dtype[~numpy.float32]]] = <function HfunCollector.<lambda>>, upper_bound: float = inf, lower_bound: float = -inf, value_type: ~typing.Literal['min', 'max'] = 'min', rate: float = 0.01, source_index: ~typing.List[int] | int | None = None) None
Add constraint based on a function of the topography
Add a constraint based on the provided function func of the topography and apply to the region of the size function specified by lower and upper elevation of the underlying DEM. Optionally a rate can be specified to relax the constraint gradually outside the bounds.
- Parameters:
- funccallable
A function to be applied on the topography to acquire the values to be used for mesh size if condition is not met based on value_type.
- upper_boundfloat, default=np.inf
Maximum elevation to cut off the region where the constraint needs to be applied
- lower_boundfloat, default=-np.inf
Minimum elevation to cut off the region where the constraint needs to be applied
- value_type{‘min’, ‘max’}, default=’min’
Type of contraint. If ‘min’, it means the mesh size should not be smaller than the value calculated from the specified func at each point.
- ratefloat, default=0.01
Rate of relaxation of constraint outside the region defined by lower_bound and upper_bound.
- source_indexint or list of ints or None, default=None
The index of entries from the input list argument of the constructor of collector size function. If None all input rasters are used.
- Returns:
- None
- add_courant_num_constraint(upper_bound: float = 0.9, lower_bound: float | None = None, timestep: float = 150, wave_amplitude: float = 2, source_index: List[int] | int | None = None) None
Add constraint based on approximated Courant number bounds
- Parameters:
- upper_boundfloat, default=0.9
Maximum Courant number to allow on this mesh size function
- lower_boundfloat or None, default=None
Minimum Courant number to allow on this mesh size function
- timestepfloat
Timestep size (\(seconds\)) to
- wave_amplitudefloat, default=2
Free surface elevation (\(meters\)) from the reference (i.e. wave height)
- source_indexint or list of ints or None, default=None
The index of entries from the input list argument of the constructor of collector size function. If None all input rasters are used.
- Returns:
- None
- add_region_constraint(value: float | ndarray[Any, dtype[float32]], shape: Polygon | MultiPolygon, crs: CRS | str = None, value_type: Literal['min', 'max'] = 'min', rate: float = 0.01, source_index: List[int] | int | None = None) None
Add a value contraint for the points in specified region
Add a fixed-value constraint to the region of the size function specified by the input shape. Optionally a rate can be specified to relax the constraint gradually outside the bounds.
- Parameters:
- valuefloat or array-like
A single fixed value to be used for mesh size if condition is not met based on value_type.
- shape: MultiPolygon or Polygon
Region of specified constraint
- crs: CRS or None, default=None
The CRS of the input shape
- value_type{‘min’, ‘max’}, default=’min’
Type of contraint. If ‘min’, it means the mesh size should not be smaller than the specified value at each point.
- ratefloat, default=0.01
Rate of relaxation of constraint outside the specified region
- source_index: int or list of ints or None, default=None
The index of input hfun source. If None all inputs are used.
- Returns:
- None
- add_contour(level: List[float] | float | None = None, expansion_rate: float = 0.01, target_size: float | None = None, contour_defn: Contour | None = None) None
Add refinement for auto extracted contours
Add refinement for the contour lines extracted based on level or levels specified by level. The refinement is relaxed with expansion_rate and distance from the extracted contour lines. Contours are extracted only from the raster inputs, but are applied on all inputs passed to the collector constructor.
- Parameters:
- levelfloat or list of floats or None, default=None
Level(s) at which contour lines should be extracted.
- expansion_ratefloat, default=0.01
Rate to use for expanding refinement with distance away from the extracted contours.
- target_sizefloat or None, default=None
Target size to use on the extracted contours and expand from with distance.
- contour_defnContour or None, default=None
Contour definition objects which defines contour extraction specification from rasters.
- Returns:
- None
- add_channel(level: float = 0, width: float = 1000, target_size: float = 200, expansion_rate: float | None = None, tolerance: float | None = None, channel_defn: Channel | None = None) None
Add refinement for auto detected channels
Automatically detects narrow regions in the domain and apply refinement size with an expanion rate (if provided) outside the detected area.
- Parameters:
- levelfloat, default=0
High water mark at which domain is extracted for narrow region or channel calculations.
- widthfloat, default=1000
The cut-off width for channel detection.
- target_sizefloat, default=200
Target size to use on the detected channels and expand from with distance.
- expansion_ratefloat or None, default=None
Rate to use for expanding refinement with distance away from the detected channels.
- tolerancefloat or None, default=None
Tolerance to use for simplifying the polygon extracted from DEM data. If None don’t simplify.
- channel_defnContour or None
Channel definition objects which defines channel extraction specification from rasters.
- Returns:
- None
- add_subtidal_flow_limiter(hmin: float | None = None, hmax: float | None = None, lower_bound: float | None = None, upper_bound: float | None = None, source_index: List[int] | int | None = None) None
Add mesh refinement based on topography.
Calculates a pre-defined function of topography to use as values for refinement. The function values are cut off using hmin and hmax and is applied to the region bounded by lower_bound and upper_bound.
- Parameters:
- hminfloat or None, default=None
Minimum mesh size in the refinement
- hmaxfloat or None, default=None
Maximum mesh size in the refinement
- lower_boundfloat or None, default=None
Lower limit of the cut-off elevation for region to apply the fixed value.
- upper_boundfloat or None, default=None
Higher limit of the cut-off elevation for region to apply the fixed value.
- source_indexint or list of ints or None, default=None
The index of raster entries from the input list argument of the constructor of collector size function. If None all input rasters are used.
- Returns:
- None
See also
hfun.raster.HfunRaster.add_subtidal_flow_limiter
- add_constant_value(value: float, lower_bound: float | None = None, upper_bound: float | None = None, source_index: List[int] | int | None = None)
Add refinement of fixed value in the region specified by bounds.
Apply fixed value mesh size refinement to the region specified by bounds (if provided) or the whole domain.
- Parameters:
- valuefloat
Fixed value to use for refinement size
- lower_boundfloat or None, default=None
Lower limit of the cut-off elevation for region to apply the fixed value.
- upper_boundfloat or None, default=None
Higher limit of the cut-off elevation for region to apply the fixed value.
- source_indexint or list of ints or None, default=None
The index of raster entries from the input list argument of the constructor of collector size function. If None all input rasters are used.
- Returns:
- None
- add_patch(shape: MultiPolygon | Polygon | None = None, patch_defn: Patch | None = None, shapefile: None | str | Path = None, expansion_rate: float | None = None, target_size: float | None = None) None
Add refinement as a region of fixed size with an optional rate
Add a refinement based on a region specified by shape, patch_defn or shapefile. The fixed target_size refinement can be expanded outside the region specified by the shape if expansion_rate is provided.
- Parameters:
- shapeMultiPolygon or Polygon or None, default=None
Shape of the region to use specified target_size for refinement. Only one of shape, patch_defn or shapefile must be specified.
- patch_defnPatch or None, default=None
Shape of the region to use specified target_size for refinement. Only one of shape, patch_defn or shapefile must be specified.
- shapefileNone or str or Path, default=None
Shape of the region to use specified target_size for refinement. Only one of shape, patch_defn or shapefile must be specified.
- expansion_ratefloat or None, default=None
Optional rate to use for expanding refinement outside the specified shape in multipolygon.
- target_sizefloat or None, default=None
Fixed target size of mesh to use for refinement in multipolygon
- Returns:
- None
- add_feature(shape: MultiLineString | LineString | None = None, line_defn: LineFeature | None = None, shapefile: None | str | Path = None, expansion_rate: float = 0.01, target_size: float | None = None, crs: CRS = 4326) None
Add refinement as a region of fixed size with an optional rate
Add a refinement based on lines specified by shape, line_defn or shapefile. The fixed target_size refinement is expanded by the expansion_rate.
- Parameters:
- shapeMultiLineString or LineString or None, default=None
Shape of the region to use specified target_size for refinement. Only one of shape, line_defn or shapefile must be specified.
- line_defnLineFeature or None, default=None
Shape of the region to use specified target_size for refinement. Only one of shape, line_defn or shapefile must be specified.
- shapefileNone or str or Path, default=None
Shape of the region to use specified target_size for refinement. Only one of shape, line_defn or shapefile must be specified.
- expansion_ratefloat, default=0.01
Rate to use for expanding refinement away from the specified shape
- target_sizefloat or None, default=None
Fixed target size of mesh to use for refinement in multipolygon
- crsCRS, default 4326
The CRS of the input shape
- Returns:
- None