pygimli.utils¶
Useful utility functions.
Overview¶
Functions
|
Transform any Gauss-Krueger to UTM autodetect GK zone from offset. |
|
Return real/imaginary parts retrieved by Kramers-Kronig relations. |
|
Print string centered in a box. |
|
Return default colormap for physical quantity name. |
|
Cache decorator. |
|
Return chi square value. |
|
Return default colormap for physical quantity name. |
|
Compute inverse square root (C^{-0.5} of matrix. |
|
Converts CRS indices to uncompressed indices (row, col). |
|
Geostatistical covariance matrix (cell or node) for given mesh. |
|
Return datetime as string (e.g. |
|
|
|
Create the path structure specified by list. |
|
|
|
Create a result Folder. |
|
|
|
The progressive, i.e., cumulative length for a path p. |
|
Cuts the array v into n parts |
|
Calculate approximate derivative. |
|
Calculate the distance for each position in p relative to pos c(x,y,z). |
|
TODO DOCUMENTME. |
|
Filter all lines from a file.readlines output which begins with one of the symbols in the comment_str. |
|
TODO DOCUMENTME. |
|
Find utm zone for lon and lat values. |
|
Generate geostatistical model (cell or node) for given mesh. |
|
TODO DOCUMENTME. |
|
Syntactic sugar to get some default Projections. |
|
TODO. |
|
Create and return the current coordinate projection. |
|
Convert pygimli matrix into numpy.array. |
|
Create array with possible increasing spacing. |
|
Filter coefficients for Hankel transformation. |
|
numpy.interp interpolation function extended by linear extrapolation. |
|
Return symmetric interpercentiles for alpha-trim outliers. |
|
Return point of integral (cumulative) histogram. |
|
Check numpy or pg.Vector if have complex data type |
|
Find parameter bounds by iterating model parameter. |
|
Create logarithmic scaled copy of p. |
|
Formal model covariance matrix (MCM) from inversion. |
|
Compute the root mean square excluding nan values. |
|
Create nice logarithmic space from the next decade lower to vMin to decade larger then vMax. |
|
List of strings (deprecated, for backward-compatibility). |
|
Convert numpy.array into pygimli RMatrix. |
|
Return prettified string for value .. |
|
Return prettified string for a float value. |
|
Create RVector of length n with normally distributed random numbers. |
|
Create n normally distributed random numbers with optional seed. |
|
Extract GPS Waypoint from GPS Exchange Format (GPX). |
|
Compute the root mean square. |
|
Compute (abs-)root-mean-square of values with error above threshold. |
|
Compute (abs-)root-mean-square of values with error above threshold. |
|
Round float using a number of counting digits. |
|
Compute the relative (regarding a) root mean square. |
|
Save rms/chi2 results into filename. |
|
Extract indices and value from sparse matrix (SparseMap or CRS) |
|
Convert sparse matrix to dense ndarray |
|
Convert SparseMatrix to scipy.coo_matrix. |
Convert SparseMatrix to scipy.csr_matrix. |
|
|
Squeeze complex valued array into [real, imag] or [amp, phase(rad)] |
|
|
|
Create a streamline from start coordinate and following a vector field in up and down direction. |
|
down = -1, up = 1, both = 0 |
|
|
|
|
|
Convert real values into complex (z = a + ib) valued array. |
|
Convert complex (z = a + ib) values array into amplitude and phase in radiant |
|
Convert complex valued matrix into a real valued Blockmatrix |
Convert any matrix type to pg.SparseMatrix and return copy of it. |
|
Convert any matrix type to pg.SparseMatrix and return copy of it. |
|
|
Return properly formatted docstring. |
|
TODO DOCUMENTME. |
|
Return list of unique elements ever seen with preserving order. |
|
Sum double values found by indices in a various number of arrays. |
|
Return iterator of unique elements ever seen with preserving order. |
|
Return unique rows in a 2D array. |
|
Return the name of a physical quantity with its unit. |
Classes
|
Animated text-based progressbar. |
Functions¶
GKtoUTM¶
KramersKronig¶
boxprint¶
-
pygimli.utils.
boxprint
(s, width=80, sym='#')[source]¶ Print string centered in a box.
Examples
>>> from pygimli.utils import boxprint >>> boxprint("This is centered in a box.", width=40, sym='+') ++++++++++++++++++++++++++++++++++++++++ + This is centered in a box. + ++++++++++++++++++++++++++++++++++++++++
computeInverseRootMatrix¶
convertCRSIndex2Map¶
covarianceMatrix¶
-
pygimli.utils.
covarianceMatrix
(mesh, nodes=False, **kwargs)[source]¶ Geostatistical covariance matrix (cell or node) for given mesh.
- Parameters
mesh (gimliapi:GIMLI::Mesh) – Mesh
nodes (bool [False]) – use node positions, otherwise (default) cell centers are used
**kwargs –
- Ifloat or list of floats
correlation lengths (range) in individual directions
- dipfloat
dip angle (in degree) of major axis (I[0])
- strikefloat
strike angle (for 3D)
- Returns
Cm – covariance matrix
- Return type
np.array (square matrix of size cellCount/nodeCount)
Examples using pygimli.utils.covarianceMatrix
createDateTimeString¶
createPath¶
createResultPath¶
cumDist¶
-
pygimli.utils.
cumDist
(p)[source]¶ The progressive, i.e., cumulative length for a path p.
d = [0.0, d[0]+ | p[1]-p[0] |, d[1] + | p[2]-p[1] | + …]
- Parameters
p (ndarray(N,2) | ndarray(N,3) | pg.core.R3Vector) – Position array
- Returns
d – Distance array
- Return type
ndarray(N)
Examples
>>> import pygimli as pg >>> from pygimli.utils import cumDist >>> import numpy as np >>> p = pg.core.R3Vector(4) >>> p[0] = [0.0, 0.0] >>> p[1] = [0.0, 1.0] >>> p[2] = [0.0, 1.0] >>> p[3] = [0.0, 0.0] >>> print(cumDist(p)) [0. 1. 1. 2.]
diff¶
-
pygimli.utils.
diff
(v)[source]¶ Calculate approximate derivative.
Calculate approximate derivative from v as d = [v_1-v_0, v2-v_1, …]
- Parameters
v (array(N) | pg.core.R3Vector(N)) – Array of double values or positions
- Returns
d – derivative array
- Return type
[type(v)](N-1) |
Examples
>>> import pygimli as pg >>> from pygimli.utils import diff >>> p = pg.core.R3Vector(4) >>> p[0] = [0.0, 0.0] >>> p[1] = [0.0, 1.0] >>> print(diff(p)[0]) RVector3: (0.0, 1.0, 0.0) >>> print(diff(p)[1]) RVector3: (0.0, -1.0, 0.0) >>> print(diff(p)[2]) RVector3: (0.0, 0.0, 0.0) >>> p = pg.Vector(3) >>> p[0] = 0.0 >>> p[1] = 1.0 >>> p[2] = 2.0 >>> print(diff(p)) 2 [1.0, 1.0]
dist¶
-
pygimli.utils.
dist
(p, c=None)[source]¶ Calculate the distance for each position in p relative to pos c(x,y,z).
- Parameters
p (ndarray(N,2) | ndarray(N,3) | pg.core.R3Vector) – Position array
c ([x,y,z] [None]) – relative origin. default = [0, 0, 0]
- Returns
d – Distance array
- Return type
ndarray(N)
Examples
>>> import pygimli as pg >>> from pygimli.utils import dist >>> import numpy as np >>> p = pg.core.R3Vector(4) >>> p[0] = [0.0, 0.0] >>> p[1] = [0.0, 1.0] >>> print(dist(p)) [0. 1. 0. 0.] >>> x = pg.Vector(4, 0) >>> y = pg.Vector(4, 1) >>> print(dist(np.array([x, y]).T)) [1. 1. 1. 1.]
filterLinesByCommentStr¶
findUTMZone¶
generateGeostatisticalModel¶
-
pygimli.utils.
generateGeostatisticalModel
(mesh, **kwargs)[source]¶ Generate geostatistical model (cell or node) for given mesh.
- Parameters
mesh (gimliapi:GIMLI::Mesh) – Mesh
nodes (bool [False]) – use node positions, otherwise (default) cell centers are used
**kwargs –
- Ifloat or list of floats
correlation lengths (range) in individual directions
- dipfloat
dip angle of major axis (I[0])
- strikefloat
strike angle (for 3D)
- Returns
res
- Return type
np.array of size cellCount or nodeCount (nodes=True)
Examples using pygimli.utils.generateGeostatisticalModel
getProjection¶
getUTMProjection¶
gmat2numpy¶
grange¶
-
pygimli.utils.
grange
(start, end, dx=0, n=0, log=False)[source]¶ Create array with possible increasing spacing.
Create either array from start step-wise filled with dx until end reached [start, end] (like np.array with defined end). Fill the array from start to end with n steps. [start, end] (like np.linespace) Fill the array from start to end with n steps but logarithmic increasing, dx will be ignored.
- Parameters
Examples
>>> from pygimli.utils import grange >>> v1 = grange(start=0, end=10, dx=3) >>> v2 = grange(start=0, end=10, n=3) >>> print(v1) 4 [0.0, 3.0, 6.0, 9.0] >>> print(v2) 3 [0.0, 5.0, 10.0]
- Returns
ret – Return resulting array
- Return type
GIMLI::RVector
Examples using pygimli.utils.grange
hankelFC¶
-
pygimli.utils.
hankelFC
(order)[source]¶ Filter coefficients for Hankel transformation.
10 data points per decade.
DOCUMENTME .. Author RUB?
- Parameters
order (int) – order=1: NY=+0.5 (SIN) order=2: NY=-0.5 (COS) order=3: NY=0.0 (J0) order=4: NY=1.0 (J1)
- Returns
fc (np.array()) – Filter coefficients
nc0 (int) – fc[nc0] refers to zero argument
interpExtrap¶
interperc¶
inthist¶
isComplex¶
iterateBounds¶
-
pygimli.utils.
iterateBounds
(inv, dchi2=0.5, maxiter=100, change=1.02)[source]¶ Find parameter bounds by iterating model parameter.
Find parameter bounds by iterating model parameter until error bound is reached
- Parameters
inv – gimli inversion object
dchi2 – allowed variation of chi^2 values [0.5]
maxiter – maximum iteration number for parameter iteration [100]
change – changing factor of parameters [1.02, i.e. 2%]
logDropTol¶
-
pygimli.utils.
logDropTol
(p, dropTol=0.001)[source]¶ Create logarithmic scaled copy of p.
Examples
>>> from pygimli.utils import logDropTol >>> x = logDropTol((-10, -1, 0, 1, 100)) >>> print(x.array()) [-4. -3. 0. 3. 5.]
Examples using pygimli.utils.logDropTol
modCovar¶
-
pygimli.utils.
modCovar
(inv)[source]¶ Formal model covariance matrix (MCM) from inversion.
var, MCMs = modCovar(inv)
- Parameters
inv (pygimli inversion object) –
- Returns
var (variances (inverse square roots of MCM matrix))
MCMs (scaled MCM (such that diagonals are 1.0))
>>> # import pygimli as pg >>> # import matplotlib.pyplot as plt >>> # from matplotlib.cm import bwr >>> # INV = pg.Inversion(data, f) >>> # par = INV.run() >>> # var, MCM = modCovar(INV) >>> # i = plt.imshow(MCM, interpolation='nearest', >>> # cmap=bwr, vmin=-1, vmax=1) >>> # plt.colorbar(i)
nanrms¶
niceLogspace¶
-
pygimli.utils.
niceLogspace
(vMin, vMax, nDec=10)[source]¶ Create nice logarithmic space from the next decade lower to vMin to decade larger then vMax.
- Parameters
Examples
>>> from pygimli.utils import niceLogspace >>> v1 = niceLogspace(vMin=0.1, vMax=0.1, nDec=1) >>> print(v1) [0.1 1. ] >>> v1 = niceLogspace(vMin=0.09, vMax=0.11, nDec=1) >>> print(v1) [0.01 0.1 1. ] >>> v1 = niceLogspace(vMin=0.09, vMax=0.11, nDec=10) >>> print(len(v1)) 21 >>> print(v1) [0.01 0.01258925 0.01584893 0.01995262 0.02511886 0.03162278 0.03981072 0.05011872 0.06309573 0.07943282 0.1 0.12589254 0.15848932 0.19952623 0.25118864 0.31622777 0.39810717 0.50118723 0.63095734 0.79432823 1. ]
num2str¶
numpy2gmat¶
prettify¶
prettyFloat¶
rand¶
randn¶
-
pygimli.utils.
randn
(n, seed=None)[source]¶ Create n normally distributed random numbers with optional seed.
- Parameters
- Returns
r – Random numbers.
- Return type
np.array
Examples
>>> import numpy as np >>> from pygimli.utils import randn >>> a = randn(5, seed=1337) >>> b = randn(5) >>> c = randn(5, seed=1337) >>> print(np.array_equal(a, b)) False >>> print(np.array_equal(a, c)) True
readGPX¶
-
pygimli.utils.
readGPX
(fileName)[source]¶ Extract GPS Waypoint from GPS Exchange Format (GPX).
Currently only simple waypoint extraction is supported.
<gpx version=”1.0” creator=”creator”>
<metadata> <name>Name</name> </metadata> <wpt lat=”51.” lon=”11.”> <name>optional</name> <time>optional</time> <description>optional</description> </wpt>
</gpx>
rmsWithErr¶
rmswitherr¶
-
pygimli.utils.
rmswitherr
(a, b, err, errtol=1)¶ Compute (abs-)root-mean-square of values with error above threshold.
rrms¶
saveResult¶
sparseMatrix2Array¶
-
pygimli.utils.
sparseMatrix2Array
(matrix, indices=True, getInCRS=True)[source]¶ Extract indices and value from sparse matrix (SparseMap or CRS)
Get python Arrays from SparseMatrix or SparseMapMatrix in either CRS convention (row index, column Start_End, values) or row index, column index, values.
- Parameters
matrix (pg.matrix.SparseMapMatrix or pg.matrix.SparseMatrix) – Input matrix to be transformed to numpy arrays.
indices (boolean (True)) – Decides weather the indices of the matrix will be returned or not.
getInCSR (boolean (True)) – If returned, the indices can have the format of a compressed row storage (CSR), the default or uncompressed lists with column and row indices.
- Returns
vals (numpy.ndarray) – Entries of the matrix.
indices (list, list) – Optional. Returns additional array with the indices for reconstructing the matrix in the defined format.
sparseMatrix2Dense¶
sparseMatrix2coo¶
-
pygimli.utils.
sparseMatrix2coo
(A, rowOffset=0, colOffset=0)[source]¶ Convert SparseMatrix to scipy.coo_matrix.
- Parameters
A (pg.matrix.SparseMapMatrix | pg.matrix.SparseMatrix) – Matrix to convert from.
- Returns
mat – Matrix to convert into.
- Return type
scipy.coo_matrix
Examples using pygimli.utils.sparseMatrix2coo
sparseMatrix2csr¶
-
pygimli.utils.
sparseMatrix2csr
(A)[source]¶ Convert SparseMatrix to scipy.csr_matrix.
Compressed Sparse Row matrix, i.e., Compressed Row Storage (CRS)
- Parameters
A (pg.matrix.SparseMapMatrix | pg.matrix.SparseMatrix) – Matrix to convert from.
- Returns
mat – Matrix to convert into.
- Return type
scipy.csr_matrix
squeezeComplex¶
-
pygimli.utils.
squeezeComplex
(z, polar=False, conj=False)[source]¶ Squeeze complex valued array into [real, imag] or [amp, phase(rad)]
Examples using pygimli.utils.squeezeComplex
streamline¶
streamlineDir¶
toComplex¶
-
pygimli.utils.
toComplex
(amp, phi=None)[source]¶ Convert real values into complex (z = a + ib) valued array.
If no phases phi are given, assuming z = amp[0:N] + i amp[N:2N].
If phi is given in (rad) complex values are generated: z = amp*(cos(phi) + i sin(phi))
Examples using pygimli.utils.toComplex
toPolar¶
-
pygimli.utils.
toPolar
(z)[source]¶ Convert complex (z = a + ib) values array into amplitude and phase in radiant
If z is real valued we assume its squeezed.
- Parameters
z (iterable (floats, complex)) – If z contains of floats and squeezedComplex is assumed [real, imag]
- Returns
amp, phi – Amplitude amp and phase angle phi in radiant.
- Return type
ndarray
toRealMatrix¶
toSparseMapMatrix¶
toSparseMatrix¶
trimDocString¶
-
pygimli.utils.
trimDocString
(docstring)[source]¶ Return properly formatted docstring.
From: https://www.python.org/dev/peps/pep-0257/
Examples
>>> from pygimli.utils import trimDocString >>> docstring = ' This is a string with indention and whitespace. ' >>> trimDocString(docstring).replace('with', 'without') 'This is a string without indention and whitespace.'
unique¶
uniqueAndSum¶
-
pygimli.utils.
uniqueAndSum
(indices, to_sum, return_index=False, verbose=False)[source]¶ Sum double values found by indices in a various number of arrays.
Returns the sorted unique elements of a column_stacked array of indices. Another column_stacked array is returned with values at the unique indices, while values at double indices are properly summed.
- Parameters
ar (array_like) – Input array. This will be flattened if it is not already 1-D.
to_sum (array_like) – Input array to be summed over axis 0. Other existing axes will be broadcasted remain untouched.
return_index (bool, optional) – If True, also return the indices of ar (along the specified axis, if provided, or in the flattened array) that result in the unique array.
- Returns
unique (ndarray) – The sorted unique values.
summed_array (ndarray) – The summed array, whereas all values for a specific index is the sum over all corresponding nonunique values.
unique_indices (ndarray, optional) – The indices of the first occurrences of the unique values in the original array. Only provided if return_index is True.
Examples
>>> import numpy as np >>> from pygimli.utils import uniqueAndSum >>> idx1 = np.array([0, 0, 1, 1, 2, 2]) >>> idx2 = np.array([0, 0, 1, 2, 3, 3]) >>> # indices at positions 0 and 1 and at positions 5 and 6 are not unique >>> to_sort = np.column_stack((idx1, idx2)) >>> # its possible to stack more than two array >>> # you need for example 3 array to find unique node positions in a mesh >>> values = np.arange(0.1, 0.7, 0.1) >>> print(values) [0.1 0.2 0.3 0.4 0.5 0.6] >>> # some values to be summed together (for example attributes of nodes) >>> unique_idx, summed_vals = uniqueAndSum(to_sort, values) >>> print(unique_idx) [[0 0] [1 1] [1 2] [2 3]] >>> print(summed_vals) [0.3 0.3 0.4 1.1]
unique_everseen¶
-
pygimli.utils.
unique_everseen
(iterable, key=None)[source]¶ Return iterator of unique elements ever seen with preserving order.
Return iterator of unique elements ever seen with preserving order.
From: https://docs.python.org/3/library/itertools.html#itertools-recipes
Examples
>>> from pygimli.utils import unique_everseen >>> s1 = 'AAAABBBCCDAABBB' >>> s2 = 'ABBCcAD' >>> list(unique_everseen(s1)) ['A', 'B', 'C', 'D'] >>> list(unique_everseen(s2, key=str.lower)) ['A', 'B', 'C', 'D']
See also
unique_rows¶
Classes¶
ProgressBar
-
class
pygimli.utils.
ProgressBar
(its, width=80, sign=':')[source]¶ Bases:
object
Animated text-based progressbar.
Animated text-based progressbar for intensive loops. Should work in the console and in the IPython Notebook.
optional: ‘estimated time’ instead of ‘x of y complete’
- itsint
Number of iterations of the process.
- widthint
Width of the ProgressBar, default is 80.
- signstr
Sign used to fill the bar.
>>> from pygimli.utils import ProgressBar >>> pBar = ProgressBar(its=20, width=40, sign='+') >>> pBar.update(5)
[+++++++++++ 30% ] 6 of 20 complete