API Reference
Summary
|
Read Marthe Grid File as xarray.Dataset |
|
Write Dataset as MartheGrid v9 file |
Full Guide
IO Operations
- gridmarthe.gridmarthe.read_dates_from_pastp(fpastp, encoding='ISO-8859-1')[source]
Read simulation timesteps from a .pastp file
- gridmarthe.gridmarthe.scan_var(xfile)[source]
List all variables stored in a Marthe grid file
- gridmarthe.gridmarthe.load_marthe_grid(filename, varname=None, dates=None, fpastp=None, nanval=None, drop_nan=False, xyfactor=1.0, keepligcol=False, add_id_grid=False, title=None, var_attrs={}, model_attrs={'domain': 'FR-France', 'projection': 'epsg:27572', 'resolution_units': 'm'}, verbose=False)[source]
Read Marthe Grid File as xarray.Dataset
The gridfile is read as a sequence: the variable for all layer for main grid, then all layer for nested grids, is stored in a 1D vector for every timestep. A single spatial identifier zone is used to map spatial coordinates.
Before plot operations, user can assign coordinates (set x,y as dimension coordinates and drop zone) to get 2-D arrays (or 3D arrays if multilayer) for every timesteps.
- Parameters:
filename (str) – A path to marthegrid file (*.permh, *.out, etc.)
varname (str, Optionnal) – variable to access in martgrid file, e.g CHARGE for groundwater head. See marthegrid file content. if None is passed (default), function will scan all varnames in filename and keep first only if ‘all’ is passed, function will scan all varnames in filename and keep all. All datavars are added to dataset, using recursive call to func if wrong variable name is passed, empty data will be returned.
dates (sequence, Optionnal) – Can be a pd.date_range, pd.Series, pd.DatetimeIndex, np.array or list of datetime/np.datetime objects. If no dates (or no fpastp) is provided, a fake sequence of dates from 1850 to 1900 will be used for xarray object
fpastp (str, Optionnal) – A pastp file to read for dates
nanval (float, Optionnal) – A code value for nan values. Default is 9999.
drop_nan (bool, Optionnal) – Drop nan values (corresponding to nanval) in xarray object to return. Default is False (keep nan values).
xyfactor (int or float, Optionnal) – factor to transform X and Y values. e.g.: 1000 to convert km XY to meters. Default is 1.
keepligcol (bool, Optionnal) – Add columns (col) and rows (lig) index (from 1 to n), Default is False.
add_id_grid (bool, Optionnal) – Add grid id (from 0 to n), useful for nested grids. 0 is main grid, Default is False
title (str , Optionnal) – Title for grid attributes. Default is None (not used)
var_attrs (dict, Optionnal) – Dictionnary of attributes to add to variable DataArray.
model_attrs (dict, Optionnal) – Dictionnary of attributes to add to Dataset. by default, gis attrs are added and can be modified >>> ‘resolution_units’: ‘m’, >>> ‘projection’ : ‘epsg:27572’, >>> ‘domain’ : ‘FR-France’,
verbose (bool, Optionnal) – Print some information about execution in stdout. Default is False.
- Returns:
ds (xr.Dataset) – A xarray.Dataset object containing values and attributes read from Marthe grid file.
- gridmarthe.gridmarthe.dropna(ds, varname, nanval)[source]
Drop values corrresponding to NaN (marthe convention, eg. code 9999.) for 1D (or 2D (time, zone)) array zone must me a coordinate dimension.
- Returns:
dataset where variable != nanval
- gridmarthe.gridmarthe.subset(ds, varname, value)[source]
Subset dataset based on variable name and value. –> inverse of
dropna()- Returns:
dataset where variable = value
- gridmarthe.gridmarthe.replace(ds, varname, value, replace)[source]
Replace a value in xr.Dataset for a variable
- gridmarthe.gridmarthe.fillna(ds, varname, value)[source]
Replace real nan (np.nan) value in dataset[varname], edge case of
replace()
- gridmarthe.gridmarthe.assign_coords(da_in, add_lay=True, coords=['x', 'y', 'z'], keep_zone=False, zone_label='zone')[source]
assign coords to transform a 1D or 2D (time, zone) array to 3D or 4D
- gridmarthe.gridmarthe.stack_coords(ds, coords=['z', 'y', 'x'], dropna=False)[source]
Transform a 3 or 4D aray into 1 or 2D array inverse of
assign_coords()
- gridmarthe.gridmarthe.reset_geometry(ds, path_to_permh, variable='permeab', fillna=False)[source]
Reset a Marthe grid geometry based on permh dataset All values (nan, nested grid margins) should be included in permh dataset. Join is performed with xy[z] (if xy are present in coords) or zone to get zone back in full domain (if dropped, or nan were dropped, etc.) Useful before writting marthe grid (full domain is needed)
- Parameters:
ds (xr.Dataset)
path_to_permh (str) – path to the .permh file containing domain
variable (str) – variable (ds key) containing data
fillna (bool (Optionnal)) – to fillna WITH permh nan value. permh nan value are used because it can contain different nan values (0 and -9999 for nested grids) for simplier nan fills, this can be performed outside of this function.
- Returns:
xr.Dataset containing original variables and geometry read from permh file
- gridmarthe.gridmarthe.write_marthe_grid(ds, fileout='grid.out', varname='charge', file_permh=None, title=None, dims=None, debug=False)[source]
Write Dataset as MartheGrid v9 file
ds should contain x, y, dx, dy, attrs[[‘title’, ‘original_dimensions’]] in case of error, please use
gm.reset_geometry()first. When providing a path to file_permh argument,gm.reset_geometry()is called automatically.A good pratice is to provide the permh file when writing dataset to marthegrid format.
>>> gm.write_marthe_grid(ds, 'toto.out', file_permh='./mymodel/model.permh')
WARNING: This function was developped to write parameters grids to marthe format. Not to recreate simulation results (hydraulic head at several timesteps for example) as gridmarthe format. This means that this function should not be used for dataset with several timesteps. Example, to create a new initial hydraulic head file based on simulation, select the timestep in dataset before writing.
>>> ds = ds_head.isel(time=16) # or do an aggregation (eg mean over a period) >>> gm.write_marthe_grid(ds, 'mymodel.charg')
- Parameters:
ds (xr.Dataset) – dataset containing data, coordinates (x,y[,z]), dx,dy and dimensions (in attrs).
fileout (str) – filename to write
varname (str (Optionnal)) – variable name (key) containing values.
file_permh (str (Optionnal)) – path to the permh file corresponding to current Marthe model. Needed to recreate full dimension if NaN dropped before.
title (str (Optionnal)) – title written in marthe grid file
dims (list of array) – list containing array of dimension for every grid (ie len(dims) > 1 if nested grid) format is [[x_main_grid, y_main_grid, z_main_grid], [x_nested_1, …], …] eg. [[354,252,2], [182,156,2]] if only main grid : [[x,y,z]] if None (default, dims will be parsed from ds.attrs[‘original_dimensions’] which is added when read with
gridmarthe.load_marthe_grid(). If not present (lost in some computation for example), please use py:func:gridmarthe.reset_geometry(ds) or provide list of dims manually.debug (bool, Optionnal (default is False).)
- Returns:
status (int.) – 0 if everything’s ok. 1 otherwise.
Visualisation
- gridmarthe.plot.plot_nested_grid(da, ax=None, var='charge', **kwargs)[source]
Usefull function to plot nested grids, keeping heterogeneous resolution
- Parameters:
da (xr.Dataset) – the dataset MUST be a 2D array, with dims = x,y. In other words, you may need to sel z and time before plot, and you need to apply assign_coord()
ax (matplotlib axe, Optionnal.) – if provided, data are plotted on this axis, otherwise fig, ax instances will be created.
var (str, Optionnal) – the variable to plot in dataset. Default is ‘charge’.
kwargs (optionnal.) – any keywords argument from xr.Dataset.plot.pcolormesh()
- Returns:
ax (matplotlib axis.)
- gridmarthe.plot.plot_mesh_time_serie(*arg, zone, varname='charge', show=False, figsize=(12, 4), **kwargs)[source]
Usefull function to plot time serie from any dataset, by extracting a specific cell timeserie
- Parameters:
arg (xr.Dataset,) – any datasets (you can pass multiple datasets, eg. plot_mesh_time_serie(ds1, ds2, ds3, … zone=32)
zone (int) – zone value (dimension) to select data
varname (str, Optionnal (default is 'charge')) – Variable to plot. Must be a key of all dataset passed as *arg.
show (bool, Optionnal.) – show plot using plt.show()
figsize (tuple[int], Optionnal.) – figsize argument for matplotlib.
kwargs (any keywords argument for xr.Dataset.plot() method)
- Returns:
ax (matplotlib axis.)
- gridmarthe.plot.plot_outcrop(ds_outcrop, fout=None, engine='xr', show=False)[source]
Usefull function to plot outcrop layers of a marthe (multilayer) grid
The Marthe grid must have a z dimension.
There is two mode implementend yet, using xr.plot or gpd.plot (useful for nested grid) TODO xr version for nested with plot_nested_grid(), see func below in src
if engine == ‘xr’ => ds_outcrop need to get coords before (use gm.assign_coords(ds_outcrop, add_lay=False)) if engine == ‘gpd => ds_outcrop need to be a gpd.GeoDataframe (use gm.to_geodataframe(ds_outcrop))
- Parameters:
docstring (TODO)