Reference
For simple calculation, the recommended way to run NICHE is through the Niche class, as demonstrated in the Tutorials.
In the low level interface, it is possible to run the three classes
Vegetation
, Acidity
and NutrientLevel
directly using numpy arrays.
This allows a greater flexibility and control over the details of the calculation,
Niche
- class niche_vlaanderen.Niche(ct_acidity=None, ct_soil_mlw_class=None, ct_soil_codes=None, lnk_acidity=None, ct_seepage=None, ct_vegetation=None, ct_management=None, ct_nutrient_level=None, ct_mineralisation=None)[source]
Main Niche model class
- property name
Get model instance name
- plot(key, ax=None, fixed_scale=True)[source]
Plots the result or input of a Niche object
Creates a plot of an input layer of a Niche object or of the result of a Niche object.
Note that depending on your matplotlib environment you may still have to call the matplotlib show method to actually show the plot:
>>> myniche.plot(11) >>> import matplotlib.pyplot as plt >>> plt.show()
- Parameters:
key (veg_code (1..28) or input_code) – key of the vegetation type that should be plotted, eg myniche.plot(7) or key of the input layer you want to plot eg myniche(“mhw”). If deviation was calculated with the model, this can also be plotted, by using input_code_veg_code eg mhw_14
ax (matplotlib.axes.Axes) – optional axis parameter. Can be specified when you want to plot different plots in one layout
fixed_scale (boolean (default: True)) – Use a fixed scale
- Returns:
ax – Can be used to update the plot (eg change the title).
- Return type:
- plot_detail(key, limit_legend=True, cmap='tab20')[source]
Detailed plot for a vegetation type key: veg_code (1..28)
key of the vegetation type that should be plotted
- limit_legend: boolean
limits the legend to the types present in the figure
- cmap: colormap
colormap to use for the maps. Note that 9 combinations of presence/absence are possible, so keep this in mind if changing from the default value.
- read_config_file(config, overwrite_ct=False)[source]
Sets the input based on an input file, without running it
Configures a model based on a config file
- Parameters:
overwrite_ct (bool (False)) – Allows the user to override the default codetables (after the class has been initialized).
- read_rasterio_to_grid(file_name, variable_name=None)[source]
Read grid files using rasterio as Numpy arrays
- Parameters:
file_name (string | Pathlib.Path) – Path to the file to be read
variable_name (string) – Name of the variable this grid file represents
- run(full_model=True, deviation=False, strict_checks=True)[source]
Run the niche model
Runs niche Vlaanderen model. Requires that the necessary input values have been added using set_input.
- Parameters:
full_model (bool) – Uses the full niche model. The simple model only uses mhw, mlw and soil_code as input.
deviation (bool) – Create the maps with the difference between the needed MHW and MLW and the actual MHW/MLW for a vegetation type.
strict_checks (bool) – By default running a model will fail if impossible combinations of MxW exist somewhere in the input files. By disabling strict checks models can still be run. It will still emit a warning. Note that this is provided to be backwards compatibility and it is recommended to fix the data rather than disabling this.
- run_config_file(config, overwrite_ct=False)[source]
Runs Niche using a configuration file
This will configure the model, run and output as specified.
- Parameters:
config (string) – path to a config file
overwrite_ct (boolean (False)) – overwrite codetables using the values specified in the configuration file.
- set_input(key, value)[source]
Adds a raster or numeric value as input layer
- Parameters:
key (string) – The type of grid that you want to assign (eg msw, soil_code, …). Possible options are listed in https://inbo.github.io/niche_vlaanderen/cli.html#id1
value (string | number) – Path to a file containing the grid. Can be a folder for certain grid types (eg ArcGIS rasters). Can also be a number: in that case a constant value is applied everywhere.
- property table
Dataframe containing the potential area (ha) per vegetation type
- write(folder, overwrite_files=False, detailed_files=False)[source]
Saves the model results to a folder
Saves the model results to a folder. Files will be written as geotiff. Vegetation files have names V1 … V28 Abiotic files are exported as well (nutrient_level.tif and acidity.tif) if they were not input files.
- Parameters:
folder (string) – Output folder to which files will be written. Parent directory must already exist.
overwrite_files (bool) – Overwrite files when saving. Note writing will fail if any of the files to be written already exists.
detailed_files (bool) – Save detailed information on factor affecting vegetation possibility
- zonal_stats(vectors, outside=True, attribute=None, vegetation_types=None, upscale=1)[source]
Calculates zonal statistics using vectors
- Parameters:
vectors (path to a vector source or geo-like python objects) –
you can specify a path to a vector file eg “../test.shp”, or pass geo objects from other python functions.
Note that the vector should be in the same coordinate system as the raster.
outside (bool (default: True)) – report values outside shapes as well. The area which is not covered by any shapefile will get shape_id -1.
attribute (string(default None):) – attribute of the vector source that will be exported along in the table.
vegetation_types (List | None) – optional list of vegetation types (as integer number) for which the statistics must be calculated. Calculation will happen for all niche vegetation types by default.
upscale (int) – upscaling factor: decrease the cell size by this factor to increase the resolution
- Returns:
table
- Return type:
pandas.DataFrame
Niche Delta
- class niche_vlaanderen.NicheDelta(n1, n2)[source]
Class containing the difference between two niche runs
The difference can be visualized using the plot method. It is also possible to derive a table with the area’s according to each group.
See the tutorial at: Comparing Niche classes
- plot(key, ax=None)[source]
Plots the difference between two classes
- Parameters:
key (number) – The vegetation code (1-28)
- property table
Return a summarized dataframe for a NicheDelta object
- Returns:
df
- Return type:
- write(folder, overwrite_files=False)[source]
Writes the difference grids to grid files.
The differences are coded using these values:
0: “not present in both models”
1: “present in both models”
2: “only in model 1”
3: “only in model 2”
4: “nodata in one model”
- Parameters:
folder (path) – Path to which the output files will be written.
overwrite_files (bool) – Whether files should be overwritten on save.
Flooding
- class niche_vlaanderen.Flooding(depth=None, duration=None, frequency=None, lnk_potential=None, potential=None, name='')[source]
Predict the vegetation response to (frequent) flooding
A Flooding object can be used to predict the response of vegetation to (frequent) flooding.
The code tables used can be overwritten when initializing the object. Optionally also a name can be given which is used in plots and output files.
- calculate(depth_file_path, frequency, period, duration)[source]
Calculate a floodplain object
- Parameters:
depth_file_path (pahtlib.Path | str (file_path)) – The filename containing a classified grid with inundation dephts. The classes used must correspond to the codes in the depth.csv code table.
frequency (str (frequency code)) – The frequency with which flooding occurs, eg T2, T10, T25 or T50. Valid values are given in the frequency.csv code table.
period (str, winter | summer) – Period in which the flooding occurs. Must be either “summer” or “winter”.
duration (int (duration code)) –
- Period with which the flooding occurs (1, 2…). Check the first column
of the duration.csv file for the available codes.
- combine(niche_result)[source]
Combines a Flooding model with a Niche model
Both models must be run prior to combining them. The niche model will act as a “mask” making areas where Niche predicts a vegetation type to be not present are set to “not combinable”.
- read_depth_to_grid(file_name)[source]
Read depth file using rasterio to numpy array and set extent
- Parameters:
file_name (string | Pathlib.Path) – Path to the file to be read
- property table
Dataframe containing the potential area (ha) per vegetation type
- write(folder, overwrite_files=False)[source]
Writes the floodplain grids to grid files.
The differences are coded using the values specified in the potential.csv table.
- Parameters:
folder (pathlib.Path) – Path to which the output files will be written.
overwrite_files (bool, default False) – Overwrite files when saving. Note writing will fail if any of the files to be written already exists.
Validation
- class niche_vlaanderen.NicheValidation(niche, map, mapping_file=None, upscale=5, id=None)[source]
Creates a new NicheValidation object
Overlays a vegetation map with niche in order to obtain the accuracy of the model.
- Parameters:
niche – niche_vlaanderen.Niche Niche object containing predicted variables types according to niche. The model must have run prior to the overlay
map –
Path Path to a file containing the vegetation map in one of the formats supported by fiona, eg shape. must contain these attributes: * HABx: vegetation type * pHABx: proportion of the vegetation type
different vegetation types can be supplied, eg HAB1, HAB2, … for every HABx variable a proportion must be given.
mapping_file –
Path | None optional file containing the mapping between habitat (HAB) code on the vegetation map and Niche vegetation types. The default mapping is a mapping of the BWK map (biologische waarderingskaart), and is part of the package at niche_vlaanderen/system_tables/hab_nich_join.csv
If a mapping is provided by the user, it must contain a HAB and a NICHE column. Other columns are ignored.
upscale – int optional upscale value that is used to increase the resolution of the niche rasters while doing the overlay. instead of using only the cell center, the comparison between the vegetation map and the niche model is done at upscale*upscale places in the cell. Defaults to 5. More details in https://inbo.github.io/niche_vlaanderen/validation.html
id – str (optional) field to use as id for the provided map file. This id will be used in the overlay. If no id is supplied, the shape_index (row number) of the vector file will be used, starting from 0.
- write(path, overwrite_files=False)[source]
Write the result of the validation to a folder
- path: string | pathlib.Path
Output folder to which files will be written. Parent directory must already exist.
- overwrite_files: bool
Overwrite files when saving. Note writing will fail if any of the files to be written already exists.
Array based functions
At the lowest level of Niche sit a number of array-based classes which calculate the actual Niche model. These require numpy arrays as an input: all handling of gis files/… is done in the Niche class.
NutrientLevel
- class niche_vlaanderen.NutrientLevel(ct_lnk_soil_nutrient_level=None, ct_management=None, ct_mineralisation=None, ct_soil_code=None, ct_nutrient_level=None)[source]
Calculate the NutrientLevel
The used codetables can be overwritten by using the corresponding ct_* arguments.
- calculate(soil_code, msw, nitrogen_atmospheric, nitrogen_animal, nitrogen_fertilizer, management, inundation)[source]
Calculates the nutrient level based on the input arrays provided
- Parameters:
soil_code (numpy.ndarray, np.uint8) – Array containing the soil codes. Values must be present in the soil_code table.
msw (numpy.ndarray, np.float32) – Array containing the mean spring waterlevel.
nitrogen_atmospheric (numpy.ndarray, np.float32) – Array containing the atmospheric deposition of Nitrogen.
nitrogen_animal (numpy.ndarray, np.float32) – Array containing the animal contribution of Nitrogen.
nitrogen_fertilizer (numpy.ndarray, np.float32) – Array containing the fertilizer contribution of Nitrogen.
management (numpy.ndarray, np.uint8) – Array containing the management.
inundation (numpy.ndarray, np.uint8) – Array containing the inundation values.
- Returns:
nutrient level
- Return type:
numpy.ndarray, np.uint8
Acidity
- class niche_vlaanderen.Acidity(ct_acidity=None, ct_soil_mlw_class=None, ct_soil_code=None, lnk_acidity=None, ct_seepage=None)[source]
Calculate the Acidity
The used codetables can be overwritten by using the corresponding ct_* arguments.
- calculate(soil_code, mlw, inundation, seepage, minerality, rainwater)[source]
Calculate the Acidity
- Parameters:
soil_code (numpy.ndarray, numpy.uint8) – Array containing the soil codes. Values must be present in the soil_code table. -99 is used as no data value.
mlw (numpy.ndarray, numpy.float32) – Array containing the mean lowest waterlevel.
inundation (numpy.ndarray, numpy.uint8) – Array containing rate of inundation. https://inbo.github.io/niche_vlaanderen/invoer.html#overstroming-trofie-inundation-nutrient
seepage (numpy.ndarray, numpy.float32) – Array containing the flux of groundwater at the location https://inbo.github.io/niche_vlaanderen/invoer.html#overstroming-trofie-inundation-nutrient
minerality (numpy.ndarray, numpy.uint8) – Array noting whether the groundwater is rich(1) or poor in minerals https://inbo.github.io/niche_vlaanderen/invoer.html#mineraalrijkdom-minerality
rainwater (numpy.ndarray, numpy.uint8) – Array denoting whether rainwater lenses occur. https://inbo.github.io/niche_vlaanderen/invoer.html#regenlens-rainwater
- Returns:
acidity
- Return type:
numpy.ndarray, numpy.uint8
Vegetation
- class niche_vlaanderen.Vegetation(ct_vegetation=None, ct_soil_code=None, ct_acidity=None, ct_management=None, ct_nutrient_level=None, ct_inundation=None)[source]
Calculate vegetation based on input arrays
This class helps predicting vegetation based on a number of input arrays. On initialization the input codetables are parsed (and validated).
Note that to use grid inputs (eg raster files) it is recommended to use the Niche Class
- Parameters:
ct_vegetation (filename, .csv) – optional alternative classification table Must contain the columns mentioned in the documentation: https://inbo.github.io/niche_vlaanderen/codetables.html
- calculate(soil_code, mhw, mlw, nutrient_level=None, acidity=None, management=None, inundation=None, return_all=True, full_model=True)[source]
Calculate vegetation types based on input arrays
- Parameters:
soil_code (numpy.ndarray, numpy.uint8) – Array containing the soil codes. Values must be present in the soil_code system table.
mhw (numpy.ndarray, numpy.float32) – Array containing the mean high waterlevel.
mlw (numpy.ndarray, numpy.float32) – Array containing the mean low waterlevel.
nutrient_level (numpy.ndarray, numpy.uint8) – Array containing the nutrient levels. Values must be present in the nutrient_level system table.
acidity (numpy.ndarray, numpy.uint8) – Array containing the acidity levels. Values must be present in the acidity system table.
management (numpy.ndarray, numpy.uint8) – Array containing the management codes. Values must be present in the management system table.
inundation (numpy.ndarray, numpy.uint8) – Array containing the inundation values.
return_all (boolean) – A boolean (default=True) whether all grids should be returned or only grids containing data.
full_model (bool) – If True, the full niche model is applied
- Returns:
veg (dict) – A dictionary containing the different output arrays per veg_code value.
expected (int) – Expected code in veg arrays if all conditions are met
veg_occurrence (dict) – A dictionary containing the percentage of the area where the vegetation can occur.
- calculate_deviation(soil_code, mhw, mlw)[source]
Calculates the deviation between the mhw/mlw and the reference
This function calculates the difference between the mhw and mlw and the reference values for each vegetation type.
Positive values indicate too dry values, negative values indicate too wet values.
Values of zero indicate that the vegetation type can occur based on soil type and the value under consideration (mhw or mlw)
- Parameters:
soil_code (numpy.ndarray, numpy.uint8) – Array containing the soil codes. Values must be present in the soil_code system table.
mhw (numpy.ndarray, numpy.float32) – Array containing the mean high waterlevel.
mlw (numpy.ndarray, numpy.float32) – Array containing the mean low waterlevel.
- Returns:
difference – A dictionary containing the difference between the vegetation value an the actual value. Keys are eg mhw_01 for mhw and vegetation type 01
- Return type:
dict
Example
The low level api can be used to calculate single values without having to create a full grid.
>>> import numpy as np >>> import niche_vlaanderen >>> nutrient_level = np.array([4]) >>> acidity = np.array([3]) >>> mlw = np.array([50]) >>> mhw = np.array([10]) >>> soil_codes = np.array([14]) >>> nv = niche_vlaanderen.Vegetation() >>> veg_predict, veg_occurrence = nv.calculate(soil_codes,mhw,mlw,nutrient_level,acidity) >>> veg_occurrence {1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0, 6: 0.0, 7: 1.0, 8: 1.0, 9: 0.0, 10: 0.0, 11: 0.0, 12: 1.0, 13: 0.0, 14: 0.0, 15: 0.0, 16: 1.0, 17: 0.0, 18: 0.0, 19: 0.0, 20: 0.0, 21: 0.0, 22: 0.0, 23: 0.0, 24: 0.0, 25: 0.0, 26: 0.0, 27: 0.0, 28: 0.0}The potential vegetation types that can occur (in 100% of the area, since we have only one pixel) are 7, 8, 12 and 16.
If we also use the value foor floodings, this becomes:
>>> import numpy as np >>> import niche_vlaanderen >>> nutrient_level = np.array([4]) >>> acidity = np.array([3]) >>> mlw = np.array([50]) >>> mhw = np.array([10]) >>> soil_codes = np.array(["L1"]) >>> nv = niche_vlaanderen.Vegetation() >>> inundation = np.array([1]) >>> veg_predict, veg_occurrence = nv.calculate(soil_codes,mhw,mlw,nutrient_level,acidity,inundation=inundation) >>> veg_occurrence {7: 1.0, 12: 1.0, 16: 1.0}Vegetation type 8 is no longer a potential vegetation type.