watex.decorators.assert_doi(doi)[source]#

assert the depth of investigation Depth of investigation converter

Parameters:

doi (str|float) – depth of investigation in meters. If value is given as string following by yhe index suffix of kilometers ‘km’, value should be converted instead.

:returns doi:value in meter :rtype: float

watex.decorators.available_if(check)[source]#

An attribute that is available only if check returns a truthy value

Parameters:

check (callable) – When passed the object with the decorated method, this should return a truthy value if the attribute is available, and either return False or raise an AttributeError if not available.

Examples

>>> from sklearn.utils.metaestimators import available_if
>>> class HelloIfEven:
...    def __init__(self, x):
...        self.x = x
...
...    def _x_is_even(self):
...        return self.x % 2 == 0
...
...    @available_if(_x_is_even)
...    def say_hello(self):
...        print("Hello")
...
>>> obj = HelloIfEven(1)
>>> hasattr(obj, "say_hello")
False
>>> obj.x = 2
>>> hasattr(obj, "say_hello")
True
>>> obj.say_hello()
Hello
watex.decorators.catmapflow(cat_classes=['FR0', 'FR1', 'FR2', 'FR3', 'FR4'])[source]#

Decorator function collected from the func`the `target_values to be categorized and the cat_range_values to change into cat_classes like:

cat_range_values= [0.0, [0.0, 3.0], [3.0, 6.0], [6.0, 10.0], 10.0]
target_values =[1, 2., 3., 6., 7., 9., 15., 25, ...]

Decorated Fonction returns the new function decorated holding values categorized into categorial cat_classes. For instance in groundwater exploration:

- FR0 --> `flow` is equal to ``0.``m3/h
- FR1 --> `flow` is ``0 < FR ≤ 3`` m3/h
- FR2 --> `flow` is ``3 < FR ≤ 6`` m3/h
- FR3 --> `flow` is ``6 < FR ≤ 10`` m3/h
- FR4 --> `flow` is ``10.+`` in m3/h
Returns:

Iterable object with new categorized values converted

into cat_classes.

Author: LKouadio ~ @Daniel03 Date: 13/07/2021

class watex.decorators.catmapflow2(cat_classes=['FR0', 'FR1', 'FR2', 'FR3', 'FR4'])[source]#

Bases: object

Decorator function collected from the func`the `target_values to be categorized and the cat_range_values to change into cat_classes like:

cat_range_values= [0.0, [0.0, 3.0], [3.0, 6.0], [6.0, 10.0], 10.0]
target_values =[1, 2., 3., 6., 7., 9., 15., 25, ...]

Decorated Fonction returns the new function decorated holding values categorized into categorial cat_classes. For instance in groundwater exploration:

  • FR0 –> flow is equal to ``0.``m3/h

  • FR1 –> flow is 0 < FR 3 m3/h

  • FR2 –> flow is 3 < FR 6 m3/h

  • FR3 –> flow is 6 < FR 10 m3/h

  • FR4 –> flow is 10.+ in m3/h

Returns:

Iterable object with new categorized values converted into cat_classes.

Author: @Daniel03 Date: 13/07/2021

categorized_dec(func)[source]#

Decorator can be adapted to other categorized problem by changing the cat_classes arguments to another categorized classes for other purposes like

cat_classes=['dry', 'HV', 'IHV', 'IVH+', 'UH']

Where IVHU means I:improved V:village H:hydraulic and U:urban.

Note:

If func to be decorated contains ` cat_classes` arguments, the cat_classes argument should be erased by the given from func.

mapf(crval)[source]#

Categorizing loop to hold the convenient classes according to the cat_range_value provided. Come as supplement tools when maping object doesnt work properly.

Parameters:
  • crval – value to be categorized

  • nfval – array of cat_range_values

  • fc – Object to replace the`crval` belonging to cat_classes

class watex.decorators.deprecated(reason)[source]#

Bases: object

Used to mark functions, methods and classes deprecated, and prints warning message when it called decorators based on https://stackoverflow.com/a/40301488 .

Author: YingzhiGou Date: 20/06/2017

class watex.decorators.docAppender(func0, from_='Parameters', to='Returns', insertfrom='Parameters', remove=True)[source]#

Bases: object

Decorator to generate a new doctring from appending the other class docstrings.

Indeed from the startpoint <from_> and the endpoint<to>, one can select the part of the any function or class doctrings to append to the existing doctring for a new doctring creation. This trip is useful to avoid redundancing parameters definitions everywhere in the scripts.

Parameters:
  • func0 (callable,) – Function or class to collect the doctring from.

  • from (str) – Reference word or expression to start the collection of the necessary doctring from the func0. It is the startpoint. The default is Parameters.

  • to (str) – Reference word to end the collection of the necessary part of the docstring of func0. It is the endpoint. The default is Returns.

  • insert (str,) – Reference word or expression to insert the collected doctring from the func0 and append of the index of the insert word in func. If not found in the func doctring, it should retun None so nothing should be appended. The default is Parameters.

Examples

>>> from watex.decorators import docAppender
>>> def func0 (*args, **kwargs):
...        '''Im here so share my doctring.
...
...        Parameters
...        -----------
...        * args: list,
...            Collection of the positional arguments
...        ** kwargs: dict
...            Collection of keywords arguments
...        Returns
...        -------
...             None: nothing
...        '''
...        pass
>>> def func(s, k=0):
...        ''' Im here to append the docstring from func0
...        Parameters
...        ----------
...        s: str ,
...            Any string value
...        k: dict,
...            first keyword arguments
...
...        Returns
...        --------
...            None, I return nothing
...        '''
>>> deco = docAppender(func0 , from_='Parameters',
...                        to='Returns', insert ='---\n')(func)
>>> deco.__doc__
...

Warning

Be sure to append two doctrings with the same format. One may choose either the sphinx or the numpy doc formats. Not Mixing the both.

insert_ = ('parameters', 'returns', 'raises', 'examples', 'notes', 'references', 'see also', 'warnings')#
make_newdoc(func)[source]#

make a new docs from the given class of function

class watex.decorators.docSanitizer[source]#

Bases: object

Decorator to clean the doctring and set all values of sections to the same level.

It sanitizes the doctring for the use of sphinx documentation.

Examples

>>> from watex.decorators import docSanitizer
>>> def messdocfunc():
...        '''My doctring is mess. I need to be polished and well arranged.
...
...        Im here to sanitize the mess doctring.
...
...        Parameters
...        ----------
...                * args: list,
...                    Collection of the positional arguments
...                ** kwargs: dict
...                    Collection of keywords arguments
...
...        * kwargs: list,
...        Collection of the keyword arguments
...
...        Warnings
...        --------
...        Let check for warnings string ...
...
...       '''
...       pass
>>> cleandocfunc = docSanitizer()(messfocfunc)
>>> print(cleandocfunc.__doc__)
... '''
...    My doctring is mess. I need to be polished and well arranged.
...
...    Parameters
...    ----------
...    * args: list,
...       Collection of the positional arguments
...    ** kwargs: dict
...        Collection of keywords arguments
...    * kwargs: list,
...        Collection of the keyword arguments
...    '''
insert_ = ('parameters', 'returns', 'raises', 'examples', 'notes', 'references', 'see also', 'warnings', ':param', ':rtype')#
class watex.decorators.docstring(func0, start='Parameters', end=None)[source]#

Bases: object

Generate new doctring of a function or class by appending the doctring of another function from the words considered as the startpoint start to endpoint end.

Sometimes two functions inherit the same parameters. Repeat the writing of the same parameters is redundancy. So the most easier part is to collect the doctring of the inherited function and paste to the new function from the startpoint.

Parameters:
  • func0 (callable,) – function to use its doctring

  • start (str) – Value from which the new docstring should be start.

  • end (str) – endpoint Value of the doctring. Stop considering point.

Examples

>>> from watex.decorators import writedf , predPlot, docstring
>>> docs = doctring(writedf, start ='param reason', end='param to_')(predPlot)
>>> docs.__doc__
>>> predPlot.__doc__ # doc modified and holds the writedf docstring too.

Author: @Daniel03 Date: 18/09/2021

class watex.decorators.donothing(reason=None)[source]#

Bases: object

Decorator to do nothing. Just return the func as it was. The param reason is just used to specify the skipping reason.

class watex.decorators.gdal_data_check(func, raise_error=False, verbose=0)[source]#

Bases: object

class watex.decorators.gplot2d(reason=None, **kws)[source]#

Bases: object

Decorator class to plot geological models.

Parameters:
  • **reason** (type of plot, can be misfit or model. If `` None``,) – will plot model.

  • reason (str) – related to the kind of plot

  • kws (Matplotlib properties and model properties) –

  • descriptions (Additional keywords attributes and) –

  • =============================================== (======================) –

  • Description (keywords) –

  • ===============================================

  • bar (cb_shrink percentage to shrink the color) –

  • bar

  • resistivity (climits limits of the color scale for) – in log scale (min, max)

  • values (cmap name of color map for resistivity) –

  • of (fig_aspect aspect ratio between width and height) – resistivity image. 1 for equal axes

  • dots-per-inch (fig_dpi resolution of figure in) –

  • instance (fig_num number of figure) –

  • (width (fig_size size of figure in inches) –

  • height)

  • labels (font_size size of axes tick) –

  • +2 (axes labels is) –

  • string (grid [ 'both' | 'major' |'minor' | None ]) –

    to tell the program to make a grid on the specified axes.

  • marker (station_marker station marker. if inputing a LaTex) –

  • 'n'] (plot_yn [ 'y' |) – ‘y’ –> to plot on instantiation ‘n’ –> to not plot on instantiation

  • marker

  • label (station_font_weight font weight of station) –

  • marker

  • is (station_font_rotation angle of station label in degrees 0) – horizontal

  • label

  • label

  • name (station_id index to take station label from station) –

  • marker – be sure to input as r”LaTexMarker” otherwise might not plot properly

  • the (title title of plot. If None then the name of) – iteration file and containing folder will be the title with RMS and Roughness.

  • (km) (ypad padding in negative y-direction) –

  • direction (xminorticks increment of minor ticks in x) –

  • km (xpad padding in x-direction in) –

  • (km)

  • y-direction (yminorticks increment of minor ticks in) –

  • (km)

  • plot (yscale [ 'km' | 'm' ] scale of) – will be scaled accordingly.

  • everything (if 'm') – will be scaled accordingly.

  • ===============================================

g2dgridandcbManager(axm, _f=None)[source]#

Plot2d model by configure grid and colorbar. :param axm: 2d axis plot :param _f: resize flag; misfit =2 and model =1

plot2DModel(func)[source]#
watex.decorators.nullify_output(suppress_stdout=True, suppress_stderr=True)[source]#

suppress stdout and stderr messages using context manager. https://www.codeforests.com/2020/11/05/python-suppress-stdout-and-stderr/

class watex.decorators.pfi(reason='pfi', turn='off', **kwargs)[source]#

Bases: object

Decorator to plot Permutation future importance.

Can also plot dendrogram figure by setting reason to ‘dendro`. Quick plot the permutation importance diagram. Can be customize using the multiples keywargs arguments.

Parameters:
class watex.decorators.predplot(turn='off', **kws)[source]#

Bases: object

Decorator to plot the prediction.

Once called, will quick plot the prediction. Quick plot the prediction model. Can be customize using the multiples keywargs arguments.

Parameters:
  • turn – Continue the plotting or switch off the plot and return the function. default is off else on.

  • kws – Could be the keywords arguments for matplotlib.pyplot library

Author: LKouadio alias @Daniel Date: 23/07/2021

class watex.decorators.redirect_cls_or_func(*args, **kwargs)[source]#

Bases: object

Used to redirected functions or classes. Deprecated functions or class can call others use functions or classes.

Use new function or class to replace old function method or class with multiple parameters.

Author: LKouadio~@Daniel03 Date: 18/10/2020

class watex.decorators.refAppender(docref=None)[source]#

Bases: object

Append the module docstring with reStructured Text references.

Indeed, when a func is decorated, it will add the reStructured Text references as an appender to its reference docstring. So, sphinx can auto-retrieve some replacing values found inline from the watex.documentation.

Parameters:
  • docref (str) – Reference of the documentation for appending.

  • replace: (.. ERP) – Vertical Electrical Sounding:

  • replace: – Electrical Resistivity Profiling:

Examples

>>> from watex.documentation import __doc__
>>> from watex.tools import decorators
>>> def donothing ():
        ''' Im here to just replace the `|VES|` and `|RES|` values by their
        real meanings.'''
        pass
>>> decorated_donothing = decorators.refAppender(__doc__)(donothing)
>>> decorated_donothing.__doc__
... #new doctring appended and `|VES|` and `|ERP|` are replaced by
... #Vertical Electrical Sounding and Electrical resistivity profiling
... #during compilation in ReadTheDocs.
nfunc(f)[source]#
watex.decorators.rpop(listitem)[source]#

remove all blank line in the item list. :param listitem: list- list of the items and pop all the existing blanck lines.

class watex.decorators.suppress_output(suppress_stdout=False, suppress_stderr=False)[source]#

Bases: object

Python recipes- suppress stdout and stderr messages

If you have worked on some projects that requires API calls to the external parties or uses 3rd party libraries, you may sometimes run into the problem that you are able to get the correct return results but it also comes back with a lot of noises in the stdout and stderr. For instance, the developer may leave a lot of “for your info” messages in the standard output or some warning or error messages due to the version differences in some of the dependency libraries.

All these messages would flood your console and you have no control on the source code, hence you cannot change its behavior. To reduce these noises, one option is to suppress stdout and stderr messages during making the function call. In this article, we will discuss about some recipes to suppress the messages for such scenarios.

watex.decorators.suppress_stdout()[source]#
class watex.decorators.temp2d(reason=None, **kws)[source]#

Bases: object

Two dimensional plot template

Parameters:

reason (str, Any) – Does nothing. But if supplied, it should be the purpose of the plot.

Note

For customizing the plot, _temp2d uses at the last parameter of the function to be decorated, the plotting arguments from watex.property.BasePlot parameters. If not given, an atttribute errors will raise.

plot2d(arr2d, y=None, x=None, posix=None)[source]#

Template for 2D plot. Basically if use the stations and positions as xlabel and positions i explicitly both are not supplied.

Parameters:
  • arr2d (ndarray , shape (N, M)) – 2D array for plotting. For instance, it can be a 2D resistivity collected at all stations (N) and all frequency (M)

  • y (array-like) – Y-coordinates. It should have the length N, the same of the arr2d. the rows of the arr2d.

  • x (array-like) – X-coordinates. It should have the length M, the same of the arr2d; the columns of the 2D dimensional array. Note that if x is given, the `distance is not needed.

  • posix (list of str) – List of stations names. If given, it should have the same length of the columns M, of arr2d`

Returns:

axe

Return type:

Matplotllib axis

class watex.decorators.visualize_valearn_curve(reason='valcurve', turn='off', **kwargs)[source]#

Bases: object

Decorator to visualize the validation curve and learning curve Once called, will quick plot the validation curve.

Quick plot the validation curve

Parameters:
  • reason – what_going_there? validation cure or learning curve. - val for validation curve -learn for learning curve

  • turn – Continue the plotting or switch off the plot and return the function. default is off else on.

  • kwargs

    Could be the keywords arguments for matplotlib.pyplot library:

    train_kws={c:'r', s:10, marker:'s', alpha :0.5}
    val_kws= {c:'blue', s:10, marker:'h', alpha :1}
    

class watex.decorators.writef(reason=None, from_=None, to=None, savepath=None, **kws)[source]#

Bases: object

Used to redirected functions or classes. Deprecated functions or class can call others use functions or classes.

Decorate function or class to replace old function method or class with multiple parameters and export files into many other format. .xlsx , .csv or regular format. Decorator mainly focus to export data to other files. Exported file can regular file or excel sheets.

Parameters:
  • reason – Explain the “What to do?”. Can be write or convert.

  • from (str df or regular) – Can be df or regular. If df, func is called and collect its input argguments and write to appropriate extension. If from_`is ``regular`, Can be a simple data put on list of string ready to output file into other format.

  • to – Exported file extension. Can be excel sheeet (.xlsx, csv) or other kind of format.

  • savepath – Give the path to save the new file written.

Author: LKouadio ~ @Daniel03 Date: 09/07/2021

class watex.decorators.writef2(reason=None, from_=None, to=None, savepath=None, **kws)[source]#

Bases: object

Used to redirected functions or classes. Deprecated functions or class can call others use functions or classes.

Decorate function or class to replace old function method or class with multiple parameters and export files into many other format. .xlsx , .csv or regular format. Decorator mainly focus to export data to other files. Exported file can regular file or excel sheets.

Parameters:
  • reason – Explain the “What to do?”. Can be write or convert.

  • from (str df or regular) – Can be df or regular. If df, func is called and collect its input arguments and write to appropriate extension. If from_`is ``regular`, Can be a simple data put on list of string ready to output file into other format.

  • to – Exported file extension. Can be excel sheeet (.xlsx, csv) or other kind of format.

  • savepath – Give the path to save the new file written.

Author: LKouadio ~ @Daniel03 Date: 09/07/2021