pymarthe.utils.pp_utils

Pilot Points tools

Attributes

PP_NAMES

PPFMT

ZONE_KWARGS

BUFFER_KWARGS

PP_KWARGS

Classes

MartheModel

Wrapper MARTHE --> Python

MartheField

Wrapper Marthe --> python

PilotPoints

Manage pilot points generation from parametrize izone field.

Module Contents

class pymarthe.utils.pp_utils.MartheModel(rma_path, spatial_index=False, modelgrid=False)

Wrapper MARTHE –> Python

__iter__(only_active=False)

Generate cell spatial informations for spatial indexing using class generator format. Each cell will contain following informations:

  • ‘node’ : cell unique id

  • ‘layer’: layer id

  • ‘inest’: nested grid id

  • ‘i’ : row number

  • ‘j’ : column number

  • ‘xcc’ : x-coordinate of the cell centroid

  • ‘ycc’ : y-coordinate of the cell centroid

  • ‘dx’ : cell width

  • ‘dy’ : cell height

  • ‘area’ : cell area

  • ‘vertices’: cell vertices

  • ‘ative’: cell activity (0=inactive, 1=active)

Parameters:

only_active (bool) : enable/disable inactive cell consideration

Returns:

it (iterator) : generator of cell spatial data.

Examples:

it = mm.__iter__()

build_spatial_index(name=None, only_active=False)

Function to build a spatial index on field data.

Parameters:

name (str, optional)filename of output spatial index files.

If None, name is .mlname + ‘_si’. Default is None.

only_active (bool, optional) : enable/disable inactive cell consideration.

Examples:

mm..build_spatial_index()

build_modelgrid(add_z=False)

Build an large pandas.DataFrame and store it in .modelgrid attribute. Each row represent a cell with the following informations (columns):

  • ‘node’ : cell unique id

  • ‘layer’: layer id

  • ‘inest’: nested grid id

  • ‘i’ : row number

  • ‘j’ : column number

  • ‘xcc’ : x-coordinate of the cell centroid

  • ‘ycc’ : y-coordinate of the cell centroid

  • ‘dx’ : cell width

  • ‘dy’ : cell height

  • ‘area’ : cell area

  • ‘vertices’: cell vertices

  • ‘ative’: cell activity (0=inactive, 1=active)

Parameters:

add_z (bool, optional): whatever add informations about z-dimension such as:
  • ‘zcc’ : z-coordinate of the cell centroid

  • ‘dz’ : cell thickness

  • ‘bottom’ : cell bottom altitud

  • ‘top’ : cell top altitud

  • ‘volume’ : cell volume ([L^3])

Default is False. Note: this process can take a while since z-dimension

informations has to be extracted from ‘topog’, ‘hsubs’ and even ‘sepon’ fields.

Examples:

mm.build_modelgrid(add_z=True) xyzcellcenter = mm.modelgrid[[f’{dir}cc’ for dir in list(‘xyz’)]].values

_get_top_bottom_arrays()

Function to extract altitude of top and bottom of whole model cells in array with shape (nlay, ncpl)

load_geometry(g=None, **kwargs)

Load and store geometry grid information of a MartheModel instance.

Parameters:

g (str, optional)Marthe geometry grid file.

Can be ‘sepon’, ‘topog’, ‘hsubs’, .. If None all geometry grid file will be loaded. Default is None.

**kwargsadditional arguments of property classes.
Can be :
  • use_imask (bool) : Default will be False.

Returns:

mf (MartheField) : store geometry field in .geometry attribut.

Examples:

mm.load_geometry(‘sepon’)

build_imask()

Function to build a imask field based on permh with binary data : 0 -> inactive cell

1 -> active cell

Parameters:

self (MartheModel) : MartheModel instance

Returns:

imask (MartheField) : imask field

Examples:

imask = mf.build_imask()

load_prop(prop, **kwargs)

Load MartheModel properties by name.

Parameters:

prop (str)supported property name.

Can be : - Field (MartheField)

  • ‘permh’

  • ‘emmca’

  • ‘emmli’

  • ‘kepon’

  • Pumping (MarthePump)
    • ‘aqpump’

    • ‘rivpump’

  • Zonal Soil properties (MartheSoil)
    • ‘cap_sol_progr’

    • ‘aqui_ruis_perc’

    • ‘t_demi_percol’

    • ‘rumax’

**kwargs : additional arguments of property classes (e.g. use_imask for MartheField)

Returns:

Stock property class in prop dictionary

Examples:

mm = MartheModel(‘mona.rma’) mm.load_prop(‘emmca’)

write_prop(prop=None)

Write MartheModel required properties by name.

Parameters:

prop (str)supported property name.

Can be : - Field (MartheField)

  • ‘permh’

  • ‘emmca’

  • ‘emmli’

  • ‘kepon’

  • Pumping (MarthePump)
    • ‘aqpump’

    • ‘rivpump’

  • Zonal Soil properties (MartheSoil)
    • ‘cap_sol_progr’

    • ‘aqui_ruis_perc’

    • ‘t_demi_percol’

    • ‘rumax’

Returns:

write property data (already loaded)

Examples:

mm = MartheModel(‘mona.rma’) mm.write_prop(‘emmca’)

classmethod from_config(configfile)

Load an existing Marthe model from a configuration file written from pymarthe.MartheOptim.write_config(). The return MartheModel instance contains all parametrizes properties with values from related parameters files (‘grid’ and ‘list’ prameters). Note : for a forward run use, remember to write all the model properties

on disk using the .write_prop() method.

Parameters:

configfile (str) : parametrization configuration file.

Returns:

mm (MartheModel) : MartheModel instance with parametrizes properties.

Examples:

mmfrom = MartheModel.from_config(‘myconfiguration.config’)

get_extent()

Return the model domain extension.

Returns:

extent (list)model extension

Format: [xmin, ymin, xmax, ymax]

Examples:

mm.modelgrid.get_extent()

get_edges(closed=False)

Return the xy-coordinates of model domain edges.

Parameters:

closed (bool)whatever adding first point in return list

(in order to close polygon).

Returns:

edges (list)list of xy-coordinates (points).
If closed is False:
Format: [edge_lower_left, edge_upper_left,

edge_upper_right, edge_lower_right]

If closed is False:
Format: [edge_lower_left, edge_upper_left,

edge_upper_right, edge_lower_right]

Examples:

mm.modelgridget_edges(closed=False)

remove_autocal()

Function to make marthe auto calibration silent. wrapper to marthe_utils.remove_autocal().

Parameters:

self : MartheModel instance

Returns:

Write in .mart file inplace

Examples:

mm = MartheModel(rma_file) mm.remove_autocal()

make_silent()

Function to make marthe run silent

Parameters:

self : MartheModel instance

Returns:

Write in .mart inplace

Examples:

mm = MartheModel(rma_file) mm.make_silent()

get_outcrop(as_2darray=False, base=0)

Function to get outcropping layer number (integer) as MartheField instance or 2D-array.

Parameters:

as_2darray (bool, optional)return 2D-array of outcroping layer.

Only available for non nested model. Default is False

base (int, optional)output layer id n-base.

Marthe is 1-based (base=1), PyMarthe is 0-based (base=0). Default is 0.

Returns:

outcrop (MartheField/array) : outcropping layer numbers.

Examples:

mm = MartheModel(‘mymodel.rma’) outcrop_arr = mm.get_outcrop()

query_grid(target=None, **kwargs)

High level method to perform queries on model grid.

Parameters:

target (str/it)requeried grid information to extract.
Can be:
  • ‘node’ : cell unique id

  • ‘layer’: layer id

  • ‘inest’: nested grid id

  • ‘i’ : row number

  • ‘j’ : column number

  • ‘xcc’ : x-coordinate of the cell centroid

  • ‘ycc’ : y-coordinate of the cell centroi

  • ‘dx’ : cell width

  • ‘dy’ : cell height

  • ‘ative’: cell activity (0=inactive, 1=active)

If None, all grid informations will be considered. Default is None.

**kwargs : required spatial information to subset grid.

Returns:

df (DataFrame)subset DataFrame.

Index : query variable(s). Columns : target(s) variables.

Examples:

# – Query grid to extract x-y cell resolutions df = mm.query_grid(target=[‘dx’,’dy’],

i = [23,45,56], j = [45,67,89], layer = [0,5,4], inest = [0,0,0])

isin_extent(x, y)

Boolean response to check if (a) point(s) is in model extension.

Parameters:

x, y (float/iterable) : xy-coordinate(s) of the required point(s)

Returns:

res (list)boolean mask.

True : point in model domain False: point out of model domain

Examples:

mm._isin_extent(x=[256.8,278.1], y=[345.2,349.3])

get_node(x, y, layer=None, only_active=False)

Function to fetch node id(s) from xy-coordinates.

Parameters:

x, y (float/it) : xy-coordinate(s) of the required point(s) layer (int/it, optional) : layer(s) to intersect.

Can be an integer (same layer for all points) or a sequence of integers for each xy-coordinates. If None, all layer will be considered. Default None.

only_active (bool): whatever set unactive cell intersected to np.nan.

Default is None.

Returns:

nodes (list) : intersected nodes.

Examples:

x, y = [456788.78, 459388.78], [6789567.2, 6789569.89] nodes = get_nodes(x, y, layer=2, only_active=True)

all_active(node)

Check whatever a node or a serie of node are all active.

Parameters:

node (int/it) : node(s) to test

Returns:

res (bool) : boolean response.

Examples:

mm.is_active(6794)

any_active(node)

Check whatever a node or a serie of node contains at least 1 active.

Parameters:

node (int/it) : node(s) to test

Returns:

res (bool) : boolean response.

Examples:

mm.is_active(6794)

get_ij(x, y, stack=False)

Function to extract row(s) and column(s) from provided xy-coordinates in model extension. Simple wrapper to imask.intersects().

Parameters:

x, y (float/iterable) : xy-coordinate(s) of the required point(s) layer (int/iterable) : layer id(s) to intersect data.

Returns:

i, j (float/iterable) : correspondin row(s) and column(s) stack (bool) : stack output array

Formatnp.array([x1, x1],
[x2, y2],

… )

Default is False.

Examples:

mm = MartheModel(‘mymodel.rma’) x, y = [456788.78, 459388.78], [6789567.2, 6789569.89] rowcol = mm.get_ij(x,y, stack=True)

get_xy(i, j, stack=False)

Function to extract x-y cellcenters from provided row(s) and column(s) in model extension.

Parameters:

i, j(float/iterable) : row(s), column(s) stack (bool) : stack output array

Formatnp.array([i1, j1],
[i2, j2],

… )

Default is False.

Returns:

x, y (float/iterable) : correspondinf xy-cellcenters

Examples:

mm = MartheModel(‘mymodel.rma’) i, j= [23, 56, 89], [78, 123, 134] coords = mm.get_ij(i,j, stack=True)

extract_refine_levels()

Function to extract refine levels of each nested grid. The main grid (inest=0) must have a refine level equal to 1 (= division for each x-y direction).

Parameters:

Returns:

rlevelsrefine levels from grid file (permh).
Format{inest_0None,
inest_1refine_level_1,

inest_N : refine_level_N}

Examples:

rl = mm.extract_refine_levels()

get_xycellcenters(stack=False)

Function to get xy-cell centers of the model grid.

Parameters:

stack (bool)stack output array
Formatnp.array([x1, y1],
[x2, y2],

… )

Default is False.

Returns:

if stack is False:
xcc, ycc (array)xy-cell centers.

shape: (ncpl,) (ncpl,)

if stack is True:
xycc (array)stacked xy-cell centers

shape: (ncpl,2)

Examples:

xcc, ycc = mm.get_xycellcenters()

get_layer_from_depth(x, y, depth, as_list=True)

Function to infer the layer id at a given xyz coordonates. Note: still experimental.

Parameters:

x, y (float/iterable) : xy-coordinate(s) of the required point(s) depth (float/iterable) : depth to infer (=z) as_list (bool): whatever returning only list of layer ids or

whole Dataframe with x,y,depth,layer,name. Default is True.

Examples:

mm = MartheModel(‘mymodel.rma’) x, y = [456788.78, 459388.78], [6789567.2, 6789569.89] layers = mm.get_layer_from_depth(x,y,depth=[223.1, 368])

run_model(exe_name='marthe', rma_file=None, silent=True, verbose=False, pause=False, report=False, cargs=None)

Run Marthe model using subprocess.Popen. It communicates with the model’s stdout asynchronously and reports progress to the screen with timestamps

Parameters:
  • (str (rma_file) – Note: can be the entire path if the exename is not in environment path Default is ‘marthe’.

  • optional) (additional command line arguments to pass to the executable.) – Note: can be the entire path if the exename is not in environment path Default is ‘marthe’.

  • (str

  • optional)

  • (bool (report) –

  • optional)

  • (bool – Default is False.

  • optional) – Default is False.

  • (bool – Default is False.

  • optional) – Default is False.

  • (bool – which is returned by the method Default is True.

  • optional) – which is returned by the method Default is True.

  • (str/list (cargs) – Default is None.

  • optional) – Default is None.

Returns:

  • (success, buff)

  • success (bool) (Binary success of the run)

  • buff (list) (stdout)

get_vtk(vertical_exageration=0.05, hws=None, smooth=False, binary=True, xml=False, shared_points=False)

Build vtk unstructured grid from model geometry. Wrapper of pymarthe.utils.vtk_utils.Vtk class. Required python vtk package.

Parameters:

vertical_exageration (float)floating point value to scale vertical

exageration of the vtk points. Default is 0.05.

hws (str)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’

If None, self.hws will be use. Default is None.

smooth (bool)boolean flag to enable interpolating vertex elevations

based on shared cell. Default is False.

binary (bool)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)Enable xml based VTK files writing.

Default is False.

shared_points (bool)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:

mm = MartheModel(‘mymodel.rma’, spatial_index=’mymodel_si’) myvtk = mm.get_vtk(vertical_exageration=0.02,

hws= ‘implicit’, smooth=True)

show_run_times(logfile=None, tablefmt='fancy')

Print model run times.

Parameters:

logfile (str)log filename.

If None, logfile = .mldir + ‘bilandeb.txt’ Default is None.

Returns:

Print message on console.

Examples:

mm.run_model(exe_name = ‘Marth_R8’) mm.show_run_times()

get_time_window(tw_type='date')

Function to extract model time window in .mart file. Wrapper to marthe_utils.get_tw().

Parameters:

tw_type (str, optional)time window output type.
Can be :
  • ‘date’ : return pd.timestamp objects

  • ‘istep’: return integers

Default is ‘date’.

Returns:

tw_min, tw_max (tuple): time window bounds (start/end)

Examples:

# – From isteps istart, iend = get_time_window(tw_type=’istep’) # – Get time window dates start, end = get_time_window(tw_type=’date’)

set_time_window(start=None, end=None)

Function to set/change model time window in .mart file. Note: the .pastp file will not be modify. Wrapper to marthe_utils.set_tw()

Parameters:

start (str/int, optional)string date or istep number of required

first timestep to consider. If None, the first istep (in .pastp file) will be considered. Default is None.

end (str/int, optional)string date or istep number of required

last timestep to consider. If None, the last istep (in .pastp file) will be considered. Default is None.

Returns:

Change .mart file inplace with required time window.

Examples:

# – From isteps mm.set_time_window(start=10, end=35)

# – From dates mm.set_time_window(start=’1999/01/28’, end=65) mm.set_time_window(start=’1992/01/01’, end=’1993/05/02’)

set_hydrodyn_periodicity(istep, external=False, new_pastpfile=None)

Function to manage hydrodynamic computation periodicity in .pastp file. Wrapper to marthe_utils.mm.set_hydrodyn_periodicity().

Parameters:

istep (str/int/iterable)required istep to activate hydrodynamic computation.
Can be :
  • ‘all’ : activate for all timesteps

  • ‘none’: desactivate for all timesteps

  • ‘start:end:step’ : string sequence

  • [0,1,2,..] : any integer iterables

external (bool, optional)whatever create a external file with required

hydrodynamic computation periodicity. Note: external optional will not be considered

for global istep such as ‘all’, ‘none’

Default is False.

new_pastpfile (str, optional)path to the new pastp file to write.

If None, will overwrite the input pastp file. Default is None.

Returns:

(Over-)write pastp file. If external == True, will also write ‘cacul_hydro.txt’.

.

Examples:

# – All timesteps mm.set_hydrodyn_periodicity(istep= ‘all’, external=False) # – Weekly mm.set_hydrodyn_periodicity(istep= ‘::7’, external=True) # – Annual mm.set_hydrodyn_periodicity(istep= ‘::365’, external=False) # – Specific mm.set_hydrodyn_periodicity(istep= [0,5,6,7,9,11], external=True)

__str__()

Internal string method.

class pymarthe.utils.pp_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.pp_utils.PP_NAMES = ['parname', 'x', 'y', 'zone', 'value']
pymarthe.utils.pp_utils.PPFMT
pymarthe.utils.pp_utils.ZONE_KWARGS
pymarthe.utils.pp_utils.BUFFER_KWARGS
pymarthe.utils.pp_utils.PP_KWARGS
class pymarthe.utils.pp_utils.PilotPoints(izone)

Manage pilot points generation from parametrize izone field. /!/ Required python shapely module /!/

extract_active_polygons()

Convert all model grid cells with same pilot point parametrize ids into a shapely.polygon referenced by layer and `zone`ids.

Returns:

polygons (pandas.Series)active pilot point zone as shapely Polygon

indexing with a MultiIndex object ([layer, zone])

Examples

active_polygons = pp.extract_active_polygons()

check_layer_zone(layer, zone)

Raise assertion errors if the provided layer and zone ids not correspond to a pilot point parametrize zone

get_polygon(layer, zone)

Subset pilot point active polygons by layer and zone

Parameters:
  • (int) (zone) –

  • (int)

  • Returns

  • --------

  • (shapely.geometry.Polygon) (polygon) – zone as shapely Polygon

Examples

polygon = pp.get_polygon(layer=1, zone=1)

add_spacing_pp(layer, zone, xspacing, yspacing, xoffset=0, yoffset=0, buffer=0)

Generate pilot points from directional (xy) spacing.

Parameters:
  • (int) (zone) –

  • (int)

  • (int/float) (xspacing) –

  • (int/float)

  • (int/float (yoffset) – in x direction (lower left corner of polgyon extension). Default is 0.

  • optional) (exterior buffering distance of the required polygon.) – in x direction (lower left corner of polgyon extension). Default is 0.

  • (int/float – in y direction (lower left corner of polgyon extension). Default is 0.

  • optional) – in y direction (lower left corner of polgyon extension). Default is 0.

  • (int/foat (buffer) –

    Default is 0. Note: this argument can be used to exaggerate the polygon

    area while seending pilot points. That can be usefull with local irregular shaped aquifer domain.

  • optional)

    Default is 0. Note: this argument can be used to exaggerate the polygon

    area while seending pilot points. That can be usefull with local irregular shaped aquifer domain.

  • Returns

  • --------

  • attribut. (Store dictionary of generated pilot points data in main .data) –

  • Format

    ‘layer’: 2, |

    ’zone’: 1, | ‘xspacing’: 550, | ‘yspacing’: 930, | ‘xoffset’: 0, | METDADATA ‘yoffset’: 0, | ‘buffer’: 100, | ‘n’: 58 | … ‘pp’: shapely.geometry.MultiPoint | DATA }

Examples

pp = PilotPoints(izone) pp.add_spacing_pp(layer=2, zone=1, xspacing=550, yspacing=930, buffer=100)

add_n_pp(layer, zone, n, tol=1, xoffset=0, yoffset=0, buffer=0)

Generate pilot points from directional (xy) spacing.

Parameters:
  • (int) (n) –

  • (int)

  • (int)

  • (int/float (yoffset) –

    Default is 1. Note: a low value can slow down the points

    generation but offers a better precision.

  • optional) (exterior buffering distance of the required polygon.) –

    Default is 1. Note: a low value can slow down the points

    generation but offers a better precision.

  • (int/float – in x direction (lower left corner of polgyon extension). Default is 0.

  • optional) – in x direction (lower left corner of polgyon extension). Default is 0.

  • (int/float – in y direction (lower left corner of polgyon extension). Default is 0.

  • optional) – in y direction (lower left corner of polgyon extension). Default is 0.

  • (int/foat (buffer) –

    Default is 0. Note: this argument can be used to exaggerate the polygon

    area while seending pilot points. That can be usefull with local irregular shaped aquifer domain.

  • optional)

    Default is 0. Note: this argument can be used to exaggerate the polygon

    area while seending pilot points. That can be usefull with local irregular shaped aquifer domain.

  • Returns

  • --------

  • attribut. (Store dictionary of generated pilot points data in main .data) –

  • Format

    ‘layer’: 1, |

    ’zone’: 1, | ‘xspacing’: 600, | ‘yspacing’: 600, | ‘xoffset’: 0, | METDADATA ‘yoffset’: 0, | ‘buffer’: 100, | ‘n’: 40 | … ‘pp’: shapely.geometry.MultiPoint | DATA }

Examples

pp = PilotPoints(izone) pp.add_spacing_pp(layer=2, zone=1, n=40, tol=250, buffer=100)

plot(layer, zone, buffer=0, ax=None, zone_kwargs={}, buffer_kwargs={}, pp_kwargs={})

Pilot point internal ploting facility.

Parameters:
  • (int) (zone) –

  • (int)

  • (int/foat (buffer) –

    Default is 0. Note: this argument can be used to exaggerate the polygon

    area while seending pilot points. That can be usefull with local irregular shaped aquifer domain.

  • optional) (matplotlib.pyplot.scatter() arguments for pilot) –

    Default is 0. Note: this argument can be used to exaggerate the polygon

    area while seending pilot points. That can be usefull with local irregular shaped aquifer domain.

  • (matplotlib.axes (ax) – If None, basic AxesSubplot will be create. Default is None.

  • optional) – If None, basic AxesSubplot will be create. Default is None.

  • (dict (pp_kwargs) – point active polygon ploting (as dictioanry).

  • optional) – point active polygon ploting (as dictioanry).

  • (dict – point active buffered polygon ploting (as dictioanry).

  • optional) – point active buffered polygon ploting (as dictioanry).

  • (dict – point ploting (as dictioanry).

  • optional) – point ploting (as dictioanry).

  • Returns

  • --------

  • (matplotlib.axes) (ax) –

Examples

pp = PilotPoints(izone) pp.add_spacing_pp(layer=2, zone=1, xspacing=550, yspacing=930, buffer=100) pp.plot(layer=2, zone=1, buffer=100,

zone_kwargs={‘color’:’red’, ‘ls’:’, ‘lw’:1.5’, ‘label’:’PP ZONE’})

plt.show()

to_pp_data()

Convert generated pilot point data into a standard .pp_data dictionary of MartheGridParam class instance.

Returns:

pp_data (dict) :

Examples

pp = PilotPoints(izone) pp.add_spacing_pp(layer=0, zone=1, xspacing=500, yspacing=500) pp_data = pp.to_pp_data()

static pp_df_from_coords(parname, coords, layer, zone, value=0.001)

Create pilot point Dataframe from xy-coordinates with generic names.

Parameters:
  • (str) (parname) –

  • (list/array) (coords) – Format : [[ppx_0, ppy_0], …, [ppx_N, ppy_N]]

  • (int) (zone) –

  • (int)

  • (int/float (value) – Default is 1e-3.

  • optional) (initial pilot points value.) – Default is 1e-3.

Returns:

pp_df (Dataframe)

Format:

parname x y zone value

parname hk_l04_z01_00 hk_l04_z01_00 357.136364 209.0 1 1.780510e-05 hk_l04_z01_01 hk_l04_z01_01 373.681818 209.0 1 4.042830e-05 … … … … . … hk_l04_z01_N hk_l04_z01_N 357.136364 225.4 1 1.337280e-05

Return type:

pilot point standard DataFrame.

Examples

coords = shp_utils.shp2points(‘gis/pp_l04.shp’, stack=True) pp_df = PilotPoints.pp_df_from_coords(parname=’myfield’, coords, layer=4, zone=1)

extract_vgm_range(factor=3)

Infer standard variogram ranges for generated pilot points as N times the maximum distance between neighbors pilot points. Should be used in MartheOptim.write_kriging_factors().

Parameters:

(int/float) (factor) – neighbors pilot points. Default is 3.

Returns:

vgm_range (dict) – from added pilot points. Format: {layer_0 : {zone_0: range_0_0, …, zone_i: range_0_i},

…, layer_i : {zone_0: range_i_0, …, zone_i: range_i_i} }

Return type:

infered exponential variagrams ranges

Examples

pp.extract_vgm_range()

to_shapefile(path='.', onefile=False, epsg=None, prj=None)

Export generated pilot points to shapefile object(s).

Parameters:
  • (str (prj) –

    –> path the output folder to export

    pilot points shapefiles

    if onefile is set to True:
    –> output file name of exported

    pilot points.

    Default is ‘.’.

  • optional) (Existing projection file to be used with new shapefile.) –

    –> path the output folder to export

    pilot points shapefiles

    if onefile is set to True:
    –> output file name of exported

    pilot points.

    Default is ‘.’.

  • (bool (onefile) – unique shapefile. If False, all pilot point sets will be export in separated shape files with understable generic names. Format: ‘path/pp_l01_z01.shp’. Default is False.

  • optional) – unique shapefile. If False, all pilot point sets will be export in separated shape files with understable generic names. Format: ‘path/pp_l01_z01.shp’. Default is False.

  • (int (epsg) – See https://www.epsg-registry.org/ or spatialreference.org

  • optional) – See https://www.epsg-registry.org/ or spatialreference.org

  • (str

  • optional)

Examples

pp.to_shapefile(‘allpp.shp’, onefile=True)

__str__()

Internal string method.