pymarthe.utils.xs_utils
Attributes
Classes
Wrapper Marthe --> python |
|
MartheModel Cross Section Management class |
Functions
|
Read a shapefile into a Pandas dataframe with |
Module Contents
- pymarthe.utils.xs_utils.read_shapefile(shpname)
Read a shapefile into a Pandas dataframe with a ‘coords’ column holding the geometry information.
- Parameters:
(str) (shpname) –
Returns –
-------- –
(DataFrame) (df) –
Examples –
-------- –
read_shapefile('mypoints.shp') (points =) –
- class pymarthe.utils.xs_utils.MartheField(field, data, mm, use_imask=True)
Wrapper Marthe –> python
- get_xyvertices(stack=False)
Function to fetch x and y vertices of the modelgrid.
Parameters:
- stack (bool)stack output array
- Formatnp.array([vx1, vy1],
- [vx2, vy2],
… )
Default is False.
Returns:
- if stack is False:
vx, vy (array) : xy-vertices.
- if stack is True:
vxy (array) : stacked xy-vertices
Examples:
vx, vy = mf.get_xyvertices()
- sample(x, y, layer, masked_values=None, as_mask=False, as_idx=False)
Sample field data by x, y, layer coordinates. It will perform simple a spatial intersection with field data.
Parameters:
x, y (float/iterable) : xy-coordinate(s) of the required point(s) layer (int/iterable) : layer id(s) to intersect data. masked_values (None/list, optional) : values to ignore during the sampling process
Default is None.
- as_mask (bool, optional)return field boolean mask.
Does not allow duplicated value (array <= x,y). Default is False.
- as_idx (bool, optional)return field indexes (=cell ids, =node numbers).
Allows duplicated values (array >= x,y)
Returns:
rec (np.recarray) : data intersected on point(s) mask (np.array [1D]) : field boolean mask (if as_mask = True) idx (np.array [1D]) : cell ids/node number/field indexes (if as_idx = True)
Examples:
rec = mf.sample(x=456.32, y=567.1, layer=0)
- get_data(layer=None, inest=None, as_array=False, as_mask=False, masked_values=list())
Function to select/subset NON-masked values.
Parameters:
- layer (int, optional)number(s) of layer required.
If None, all layers are considered. Default is None.
- inest (int, optional)number(s) of nested grid required.
If None, all nested are considered. Default is None.
- as_array (bool, optional)returning data as 3D-array.
Format : (layer*inest, row, col) Default is False.
- as_mask (bool, optional)returning data as boolean index.
Default is False.
Returns:
- if as_array is False:
rec (np.recarray) : selected data as recarray.
- if as_array is True:
arr (3D-array) : selected data as array.
- Note: if all arguments are set to None,
all data is returned.
Examples:
rec1 = mf.get_data(layer=[1,5,8], inest = 1) arr1 = mf.get_data(inest=3, as_array=True)
- set_data(data, layer=None, inest=None)
Set field data for active cells (where imask is 1) and NON-masked values (see dmv)
Parameters:
- data (object)field data to read/set.
- Can be:
Marthe property file (‘mymodel.permh’)
Recarray with layer, inest,… informations
3D-array
- layer (int, optional)number(s) of layer required.
If None, all layers are considered. Default is None.
- inest (int, optional)number(s) of nested grid required.
If None, all nested are considered. Default is None.
Returns:
Set field data inplace.
Examples:
mf.set_data(permh_recarray) mf.set_data(permh3darray) # structured grids only mf.set_data(2.3e-3) # all layers/inest mf.set_data(2.3e-3, layer=2, inest=3) # one nest
- get_masked(rec)
Return field data (rec.array) after masking with model active cells (.imask). Note : if the field is not related to the model (`use_imask`=False) then return
the input data.
Parameters:
rec (rec.array) : field data.
Returns:
mrec (rec.array) : masked field data
Examples:
mf.get_masked()
- set_data_from_parfile(parfile, izone, btrans='none')
Set field data from parameter file inplace.
Parameters:
- parfile (str)path to parameter file to read.
Can be either zpc or pp parameter.
izone (MartheField) : parameter zone(s) field.
- btrans (str, optional)string function to back-transform
field values. Default is ‘none’.
Examples:
parfile = ‘par/hk_zpc.dat’ mf.set_data_from_parfile(parfile,
izone, btrans=’lambda x: 10**x’)
- as_3darray()
Wrapper to .get_data(inest=0, as_array=True) with error handling for nested model.
Parameters:
self (MartheField) : MartheField instance.
Returns:
- arr (3D-array)array 3D of main grid only.
Format : (layer, row, col)
Examples:
arr3d = mf.as_3darray()
- static grids2rec(grids)
Read Marthe field property file. Wrapper of marthe_utils.read_grid_file().
Parameters:
filename (str) : path to Marthe field property file.
Returns:
- rec (np.recarray)recarray with all usefull informations
for each model grid cell such as layer, inest, value, …
Examples:
rec = mf._grid2rec(‘mymodel.emmca’)
- _3d2rec(arr3d)
Convert 3D-array Wrapper of marthe_utils.read_grid_file().
Parameters:
filename (str) : path to Marthe field property file.
Returns:
- rec (np.recarray)recarray with all usefull informations
for each model grid cell such as layer, inest, value, …
Examples:
rec = mf._grid2rec(‘mymodel.emmca’)
- _rec2grid(layer, inest)
Single MartheGrid instance construction from given layer and inest.
Parameters:
layer (int) : number of layer required. inest (int) : number of nested grid required.
Returns:
mg (MartheGrid) : Single Marthe grid instance.
Examples:
rec = mf._grid2rec(‘mymodel.emmca’)
- to_grids(layer=None, inest=None)
Converting internal data (recarray) to a list of MartheGrid instance for given layers and inests.
Parameters:
- layer (int, optional)number(s) of layer required.
If None, all layers are considered. Default is None.
- inest (int, optional)number(s) of nested grid required.
If None, all nested are considered. Default is None.
Returns:
mgrids (list) : Required MartheGrid instances.
Examples:
mg = mf.to_grids(layer)
- write_data(filename=None, keep_uniform_fmt=False)
Write field data in Marthe field property file.
Parameters:
filename (str) : path to write field data.
- keep_uniform_fmt (bool, optional)whatever to conserve marthe light format
for uniform grid. If True, light format will be conserved. If False, all grids will be written explictly. Default is False. /!/ CAREFULL /!/ keeping uniform light format on permh field can modify the model geometry.
Returns:
Write in Marthe field property file on disk.
Examples:
mf.write_data(‘modified.permh’)
- to_shapefile(filename=None, layer=0, inest=None, masked_values=dmv, log=False, epsg=None, prj=None)
Write field data as shapefile by layer.
Parameters:
- filename (str, optional)shapefile path to write.
If None, filename = ‘field_layer.shp’. Default is None
- layer (int, optional)layer numerical id to export.
Note : a unique layer id is allowed Default is 0.
- inest (int, optional)nested grid numerical id to export.
If None, all nested grid are considered. Default is None.
- masked_values (list, optional)field values to ignore.
Default is [-9999., 0., 9999].
- log (bool, optional)logarithmic transformation of all values.
Default is False.
- epsg (int, optional)Geodetic Parameter Dataset.
Default is None.
- prj (str, optional)cartographic projection and coordinates
Default is None.
Returns:
Write shape in filename.
Examples:
filename = os.path.join(‘gis’, ‘permh_layer5.shp’) mf.to_shapefile(filename, layer=5)
- plot(ax=None, layer=0, inest=None, vmin=None, vmax=None, log=False, extent=None, masked_values=dmv, basemap=False, **kwargs)
Plot data by layer
Parameters:
- ax (matplotlib.axes, optional)matplotlib.axes custom ax.
If None basic ax will be create. Default is None.
- layer (int, optional)layer numerical id to export.
Note : a unique layer id is allowed Default is 0.
- inest (int, optional)nested grid numerical id to export.
If None, all nested grid are considered. Default is None.
vmin, vmax (float, optional) : min/max value(s) to plot.
- log (bool, optional)logarithmic transformation of all values.
Default is False.
- extent (tuple/list, optional): xy-limits of the plot window.
Format: (xmin, ymin, xmax, ymax). If None, window correspond to the entire model domain. Default is None.
- masked_values (list, optional)field values to ignore.
Default is [-9999., 0., 9999].
- basemap (dict/bool, optional)add base map to AxesSubplot.
/!/ Required python contextily module /!/ Can be:
False : not adding any basemap
- Trueadd standard basemap.
-> provider: Stamen Terrain web tiles. -> crs: Spherical Mercator projection (EPSG:3857)
- dict()contextily.add_basemap() arguments.
- Format:
- {‘source’:TileProvider object,
zoom:’auto’, … , ‘crs’: ‘EPSG:2154’}
Default is False.
- **kwargs (optional)matplotlib.PathCollection arguments.
(ex: cmap, lw, ls, edgecolor, …)
Returns:
- ax (matplotlib.axes)standard ax with 2 collections:
1 for rectangles
1 for colorbar
Examples:
ax = mf.plot(layer=6, cmap=’jet’) ax.set_title(‘Field (layer = 6)’, fontsize=14)
- zonal_stats(stats, polygons, layer=None, names=None, trans='none')
Perform statistics on zonal areas.
Parameters:
- stats (str/list)statistics functions to perform.
Must be recognize by pandas.DataFrame.agg() method. Example: stats = [‘mean’, ‘min’,’max’,’median’,’count’].
- polygons (it)iterable containing single part polygons.
- Format: [ [(x0, y0),(x1,y1),(x2,y2)],.., [(x’N,y’N),..], ..]
<=> [ polygon_0 ,.., polygon_N ].
- layer (int/it, optional)layer id(s) on wich perform zonal statistics.
If None, all layers are considered. Default is None.
- names (str/it, optional)names of zones in the output.
If None, generic names are created with field and zone number (‘field_z0’, ‘field_z1’,…). Default is None.
- trans (str/func, optional): function/function name to transform field values
before applying statistics. If None, field values are not transformed. Default is ‘none’.
Returns:
zstats_df (DataFrame) : DataFrame with rows MultiIndex (‘zone’, ‘layer’).
Examples:
stats = [‘mean’,’max’,’min’,’median’,’count’] polygons = shp_utils.read_shapefile(‘mypolygons.shp’)[‘coords’] zdf = mf.zonal_stats(stats, polygons, layer=[4,5,6])
- to_vtk(filename=None, trans='none', masked_values=dmv, **kwargs)
Build vtk unstructured grid from model geometry and add current field to cell dataset.
**kwargs correspond to the arguments of the MartheModel.get_vtk() method.
Required python vtk package.
Parameters:
- filename (str, optional)vtk file name to write without extension.
Extension will be inferred. If None, filename = field. Default is None.
- trans (str, optional)transformation to apply to the values.
See pymarthe.utils.pest_utils.transform. Default is ‘none’.
- masked_values (float/it, optional)values to mask of the current field data.
Default are [9999, 0, -9999].
- vertical_exageration (float, kwargs)floating point value to scale vertical
exageration of the vtk points. Default is 0.05.
- hws (str, kwargs)hanging wall state, flag to define whatever the superior
hanging walls of the model are defined as normal layers (explivitly) or not (implicitly). Can be:
‘implicit’
‘explicit’
Default is ‘implicit’.
- smooth (bool, kwargs)boolean flag to enable interpolating vertex elevations
based on shared cell. Default is False.
- binary (bool, kwargs)Enable binary writing, otherwise classic ASCII format
will be consider. Default is True. Note : binary is prefered as paraview can produced bug
representing NaN values from ASCII (non xml) files.
- xml (bool, kwargs)Enable xml based VTK files writing.
Default is False.
- shared_points (bool, kwargs)Enable sharing points in grid polyhedron construction.
Default is False. Note : False is prefered as paraview has a bug (8/4/2021)
where some polyhedron will not properly close when using shared points.
Returns:
vtk (pymarthe.utils.vtk_utils.Vtk) : Vtk class containg unstructured vtk grid
Example:
mf = mm.prop[‘permh’] myvtk = mf.to_vtk(filename = mf.field, trans=’log10’, vertical_exageration=0.02)
- __str__()
Internal string method.
- pymarthe.utils.xs_utils.DEFAULT_PATH_KWARGS
- pymarthe.utils.xs_utils.DEFAULT_LAYERS_COLORBAR_KWARGS
- pymarthe.utils.xs_utils.DEFAULT_ARRAY_COLORBAR_KWARGS
- pymarthe.utils.xs_utils.DEFAULT_CROSS_SECTION_LINE_KWARGS
- pymarthe.utils.xs_utils.DEFAULT_CROSS_SECTION_TRANSLATED_LINE_KWARGS
- pymarthe.utils.xs_utils.DEFAULT_SURFACE_KWARGS
- class pymarthe.utils.xs_utils.CrossSection(mm, cross_section_line)
MartheModel Cross Section Management class
- property valid_xsnodes: numpy.ndarray
Valid cross section node numbers (icells)
- property plottable_xsnodes
- Valid cross section node numbers for plotting purpose (icells)
- property offset
- Computed offset applied to cross section line to avoid intersecting cell's border
- validate_ax(ax)
Check if given axe was generated by either .plot_xs() or plot_xs_field() internal method
Parameters:
ax (Axesubplot) : matplotlib subplot.
Examples:
ax = xs.plot_xs() xs.validate_ax(ax)
- get_modelgrid()
Return main model modelgrid with z-dimension.
Returns:
modelgrid (DataFrame) : MartheModel modelgrid.
Examples:
mg = xs.get_modelgrid() # or xs.modelgrid
- set_cross_section_line(xsline)
Set cross section line as LineString in attribut
Parameters:
- xsline (list/dict/str): cross line definition object.
- It can be:
str : shapefile object
list: list of points forming a line
- dict: 1-key dictionary.
- Accepted key words are:
- i or row: row number to draw the cross line.
(not available for nested model)
- j or column: column number to draw the cross line.
(not available for nested model)
x: x-coordinate to draw the cross line.
y: y_coordinate to draw the cross line.
Examples:
mm = MartheModel(‘model.rma’) xs = CrossSection(mm, cross_section_line=’crossline.shp’) xs.set_cross_section_line([(235.4, 356.2), (476.1, 789.3)]) xs.set_cross_section_line({‘row’: 25})
- get_xs_df()
Extract all usefull informations about crossed cells as dataframe.
Returns:
- xs_df (DataFrame): cross section dataframe.
- Additional columns from modelgrid are:
- ‘x_curv0’: curvilinear abscissa of first intersection
point between cell border and cross line
- ‘x_curv1’: curvilinear abscissa of second intersection
point between cell border and cross line
‘zvertices’: cell vertices on the z-dimension
Examples:
xs_df = xs.get_xs_df()
- plot(ax=None, add_translated=False, **kwargs)
Visualize cross section line in xy-dimension.
Parameters:
ax (Axesubplot, optional) : custom matplotlib subplot. add_translated (bool, optional): whatever plot translated cross section line
Default is False.
Returns:
ax (Axesubplot) : output matplotlib subplot.
Examples:
ax = xs.plot(lw=1.5, ls=’:’, color=’green’) plt.show()
- plot_xs(vertical_ratio=None, extent=None, by_layer=False, **kwargs)
Visualize crossed cells in xz-dimension.
Parameters:
- vertical_ratio (int/float, optional): ratio between x- and z- dimension.
Default is None (equivalent to ‘auto’ aspect).
- extent (tuple/list, optional): xy-limits of the plot window.
Format: (xmin, ymin, xmax, ymax). If None, window correspond to the entire model domain. Default is None.
- by_layer (bool, optional): whatever inserting a different facecolor for each layer.
- Note: this will add a explained colorbar referencing
the layer id on top of the figure.
Default is False.
- **kwargs: matplotlib.PathCollection arguments.
(ex: cmap, lw, ls, edgecolor, …)
Returns:
ax (Axesubplot) : output matplotlib subplot.
Examples:
ax = xs.plot_xs(by_layer=True, ec=’white’, lw=.3) plt.show()
- plot_xs_field(field='permh', log=False, vmin=None, vmax=None, cmap='viridis', vertical_ratio=None, extent=None, cb_kwargs={}, **kwargs)
Visualize crossed cells in xz-dimension filled by given field values.
Parameters:
- field (str/MartheField, optional): field to consider.
Default is ‘permh’.
- log (bool, optional)whatever perform logaritmic transformation on field values.
Default is False.
vmin, vmax (float, optional) : min/max field value(s) to plot. cmap (str, optional): matplotlib colormap name.
Default is ‘viridis’.
- vertical_ratio (int/float, optional): ratio between x- and z- dimension.
Default is None (equivalent to ‘auto’ aspect).
- extent (tuple/list, optional): xy-limits of the plot window.
Format: (xmin, ymin, xmax, ymax). If None, window correspond to the entire model domain. Default is None.
- cb_kwargs (dict, optional): colorbar arguments to customized generated colorbar.
(ex: {‘shrink’: .75, ‘location’: ‘bottom’}) Default is {}.
- **kwargs: matplotlib.PathCollection arguments.
(ex: lw, ls, edgecolor, …)
Returns:
ax (Axesubplot) : output matplotlib subplot.
Examples:
ax = xs.plot_xs(by_layer=True, ec=’white’, lw=.3) plt.show()
- add_location(ax, loc, tolerance=None, text_kws=None, **kwargs)
Adding a vertical line to a cross section plot from xy-coordinates.
Parameters:
- ax (AxeSubplot): existing axe generated by .plot_xs()
or .plot_xs_field() methods.
loc (shapely.geometry.Point/iterable): points xy-coordinates. tolerance (float/int/None, optional): distance around the cross line to accept or
denied plotting the vertical line on plot
- text_kws (dict, None, optional): optional plt.text() arguments to write in plot.
If None, text will not be added. Default is None.
- **kwargs: matplotlib.AxeSubplot.axvline arguments
(ex: lw, ls, color, …)
Examples:
ax = xs.plot_xs(by_layer=True) trans = blended_transform_factory(ax.transData, ax.transAxes) xs.add_location(ax, loc=(355, 291),
tolerance=None, text_kws=dict(y=1.03, s=’Bordeaux’,
color=’red’, transform=trans, va=’center’, ha=’center’),
lw=.8, color=’red’)
plt.show()
- add_vertices_locations(ax, text_kws={}, prefix='', **kwargs)
Adding a vertical line to a cross section plot at cross line vertices (if exists).
Parameters:
- ax (AxeSubplot): existing axe generated by .plot_xs()
or .plot_xs_field() methods.
- text_kws (dict, optional): optional plt.text() arguments to write in plot.
If None, text will not be added. Default is {}.
- prefix (str, optional): input prefix before vertices number.
Default is ‘’.
- **kwargs: matplotlib.AxeSubplot.axvline arguments
(ex: lw, ls, color, …)
Examples:
ax = xs.plot_xs(by_layer=True) xs.add_vertices_locations(
ax, text_kws={‘color’: ‘red’}, color=’red’ )
- add_surface(ax, surface, layer=None, **kwargs)
Adding a horizontal lines (surface) to a existing cross section plot
Parameters:
- ax (AxeSubplot): existing axe generated by .plot_xs()
or .plot_xs_field() methods.
- surface (MatheField|iterable): surface z-values.
Must have the same length as the number of plottable nodes. Can be :
- MartheField: it will automatically extract the
required value in the field.
- ‘top’|’bottom’: it will consider the already
existent top, bottom coordinates of each cells as surface.
- iterable: flexible imputed that must have the same
length as the number of plottable nodes
- layer (int|iterable|None, optional): layer id to consider while plotting
surfaces. If None, all layers will be considered. Default is None.
- **kwargs: matplotlib.AxeSubplot.hlines arguments
(ex: lw, ls, color, alpha, …)
Examples:
ax = xs.plot_xs(by_layer=True) xs.add_surface(ax=ax, surface=’bottom’,
layer=[8, 9], lw=1.15, color=’k’)
plt.show()