# Utils¶

## Version¶

### printinfo – Tools to print date, time, and version information¶

Print or return date, time, and package version information in any environment (Jupyter notebook, IPython console, Python console, QT console), either as html-table (notebook) or as plain text (anywhere).

This script is an adapted version of empymod.printversions (https://empymod.github.io), which itself was heavily inspired by

Always shown are the OS, number of CPU(s), numpy, scipy, SimPEG, cython, properties, vectormath, discretize, pymatsolver, sys.version, and time/date.

Additionally shown are, if they can be imported, IPython, matplotlib, and ipywidgets. It also shows MKL information, if available.

All modules provided in add_pckg are also shown. They have to be imported before versions is called.

SimPEG.Utils.printinfo.versions(mode='print', add_pckg=None, ncol=4)

Return date, time, and version information.

Print or return date, time, and package version information in any environment (Jupyter notebook, IPython console, Python console, QT console), either as html-table (notebook) or as plain text (anywhere).

This script is an adapted version of empymod.printversions, (https://empymod.github.io) which itself was heavily inspired by

This is a wrapper for versions_html and versions_text.

Parameters

mode : string, optional; {<’print’>, ‘HTML’, ‘Pretty’, ‘plain’, ‘html’}
Defaults to ‘print’:
• ‘print’: Prints text-version to stdout, nothing returned.
• ‘HTML’: Returns html-version as IPython.display.HTML(html).
• ‘html’: Returns html-version as plain text.
• ‘Pretty’: Returns text-version as IPython.display.Pretty(text).
• ‘plain’: Returns text-version as plain text.

‘HTML’ and ‘Pretty’ require IPython.

Package or list of packages to add to output information (must be imported beforehand).
ncol : int, optional
Number of package-columns in html table; only has effect if mode='HTML' or mode='html'. Defaults to 3.

Returns

Depending on mode (HTML-instance; plain text; html as plain text; or nothing, only printing to stdout).

Examples

>>> import pytest
>>> import dateutil
>>> from SimPEG import versions
>>> versions()                 # Default values
>>> versions('plain', pytest)  # Provide additional package
>>> versions('HTML', [pytest, dateutil], ncol=5)  # HTML

SimPEG.Utils.printinfo.versions_html(add_pckg=None, ncol=4)

HTML version.

See versions for details.

SimPEG.Utils.printinfo.versions_text(add_pckg=None)

Plain-text version.

See versions for details.

## Matrix Utilities¶

SimPEG.Utils.matutils.avExtrap(**kwargs)
SimPEG.Utils.matutils.cartesian2spherical(m)

Convert from cartesian to spherical

SimPEG.Utils.matutils.coterminal(theta)

Compute coterminal angle so that [-pi < theta < pi]

SimPEG.Utils.matutils.diagEst(matFun, n, k=None, approach='Probing')

Estimate the diagonal of a matrix, A. Note that the matrix may be a function which returns A times a vector.

Three different approaches have been implemented:

1. Probing: cyclic permutations of vectors with 1’s and 0’s (default)
2. Ones: random +/- 1 entries
3. Random: random vectors
Parameters: matFun (callable) – takes a (numpy.ndarray) and multiplies it by a matrix to estimate the diagonal n (int) – size of the vector that should be used to compute matFun(v) k (int) – number of vectors to be used to estimate the diagonal approach (str) – approach to be used for getting vectors numpy.ndarray est_diag(A)
SimPEG.Utils.matutils.dip_azimuth2cartesian(dip, azm_N)

Function converting degree angles for dip and azimuth from north to a 3-components in cartesian coordinates.

INPUT dip : Value or vector of dip from horizontal in DEGREE azm_N : Value or vector of azimuth from north in DEGREE

OUTPUT M : [n-by-3] Array of xyz components of a unit vector in cartesian

Created on Dec, 20th 2015

@author: dominiquef

SimPEG.Utils.matutils.spherical2cartesian(m)

Convert from spherical to cartesian

SimPEG.Utils.matutils.uniqueRows(M)

## Solver Utilities¶

class SimPEG.Utils.SolverUtils.Solver(A, **kwargs)
clean()
class SimPEG.Utils.SolverUtils.SolverBiCG(A, **kwargs)
clean()
class SimPEG.Utils.SolverUtils.SolverCG(A, **kwargs)
clean()
class SimPEG.Utils.SolverUtils.SolverDiag(A)

docstring for SolverDiag

clean()
class SimPEG.Utils.SolverUtils.SolverLU(A, **kwargs)
clean()
SimPEG.Utils.SolverUtils.SolverWrapD(fun, factorize=True, checkAccuracy=True, accuracyTol=1e-06, name=None)

Wraps a direct Solver.

import scipy.sparse as sp
Solver   = SolverUtils.SolverWrapD(sp.linalg.spsolve, factorize=False)
SolverLU = SolverUtils.SolverWrapD(sp.linalg.splu, factorize=True)

SimPEG.Utils.SolverUtils.SolverWrapI(fun, checkAccuracy=True, accuracyTol=1e-05, name=None)

Wraps an iterative Solver.

import scipy.sparse as sp
SolverCG = SolverUtils.SolverWrapI(sp.linalg.cg)


## Model Builder Utilities¶

SimPEG.Utils.ModelBuilder.PolygonInd(mesh, pts)

Finde a volxel indices included in mpolygon (2D) or polyhedra (3D) uniformly distributed model.

Parameters: shape (tuple) – shape of the model. seed (int) – pick which model to produce, prints the seed if you don’t choose. anisotropy (numpy.ndarray) – this is the (3 x n) blurring kernel that is used. its (int) – number of smoothing iterations bounds (list) – bounds on the model, len(list) == 2 numpy.ndarray M, the model
SimPEG.Utils.ModelBuilder.addBlock(gridCC, modelCC, p0, p1, blockProp)

Add a block to an exsisting cell centered model, modelCC

Parameters: BlockProp float blockProp: gridCC (numpy.ndarray) – mesh.gridCC is the cell centered grid modelCC (numpy.ndarray) – cell centered model p0 (numpy.ndarray) – bottom, southwest corner of block p1 (numpy.ndarray) – top, northeast corner of block property to assign to the model model with block
SimPEG.Utils.ModelBuilder.defineBlock(ccMesh, p0, p1, vals=None)

Build a block with the conductivity specified by condVal. Returns an array. vals[0] conductivity of the block vals[1] conductivity of the ground

SimPEG.Utils.ModelBuilder.defineElipse(ccMesh, center=None, anisotropy=None, slope=10.0, theta=0.0)
SimPEG.Utils.ModelBuilder.defineTwoLayers(ccMesh, depth, vals=None)

Define a two layered model. Depth of the first layer must be specified. CondVals vector with the conductivity values of the layers. Eg:

Convention to number the layers:

<----------------------------|------------------------------------>
0                          depth                                 zf
1st layer                       2nd layer

SimPEG.Utils.ModelBuilder.getIndicesBlock(p0, p1, ccMesh)

Creates a vector containing the block indices in the cell centers mesh. Returns a tuple

The block is defined by the points

p0, describe the position of the left upper front corner, and

p1, describe the position of the right bottom back corner.

ccMesh represents the cell-centered mesh

The points p0 and p1 must live in the the same dimensional space as the mesh.

SimPEG.Utils.ModelBuilder.getIndicesSphere(center, radius, ccMesh)

Creates a vector containing the sphere indices in the cell centers mesh. Returns a tuple

The sphere is defined by the points

p0, describe the position of the center of the cell

r, describe the radius of the sphere.

ccMesh represents the cell-centered mesh

The points p0 must live in the the same dimensional space as the mesh.

SimPEG.Utils.ModelBuilder.layeredModel(ccMesh, layerTops, layerValues)

Define a layered model from layerTops (z-positive up)

Parameters: ccMesh (numpy.ndarray) – cell-centered mesh layerTops (numpy.ndarray) – z-locations of the tops of each layer layerValue (numpy.ndarray) – values of the property to assign for each layer (starting at the top) numpy.ndarray M, layered model on the mesh
SimPEG.Utils.ModelBuilder.randomModel(shape, seed=None, anisotropy=None, its=100, bounds=None)

Create a random model by convolving a kernel with a uniformly distributed model.

Parameters: shape (tuple) – shape of the model. seed (int) – pick which model to produce, prints the seed if you don’t choose. anisotropy (numpy.ndarray) – this is the (3 x n) blurring kernel that is used. its (int) – number of smoothing iterations bounds (list) – bounds on the model, len(list) == 2 numpy.ndarray M, the model
SimPEG.Utils.ModelBuilder.scalarConductivity(ccMesh, pFunction)

Define the distribution conductivity in the mesh according to the analytical expression given in pFunction

## Interpolation Utilities¶

discretize.utils.interputils.interpmat(locs, x, y=None, z=None)[source]

Local interpolation computed for each receiver point in turn

Parameters: loc (numpy.ndarray) – Location of points to interpolate to x (numpy.ndarray) – Tensor of 1st dimension of grid. y (numpy.ndarray) – Tensor of 2nd dimension of grid. None by default. z (numpy.ndarray) – Tensor of 3rd dimension of grid. None by default. scipy.sparse.csr_matrix Interpolation matrix

## Counter Utilities¶

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class MyClass(object): def __init__(self, url): self.counter = Counter() @count def MyMethod(self): pass @timeIt def MySecondMethod(self): pass c = MyClass('blah') for i in range(100): c.MyMethod() for i in range(300): c.MySecondMethod() c.counter.summary() 
 1 2 3 4 5 Counters: MyClass.MyMethod : 100 Times: mean sum MyClass.MySecondMethod : 1.70e-06, 5.10e-04, 300x 

### The API¶

class SimPEG.Utils.CounterUtils.Counter

Counter allows anything that calls it to record iterations and timings in a simple way.

Also has plotting functions that allow quick recalls of data.

If you want to use this, import count or timeIt and use them as decorators on class methods.

class MyClass(object):
def __init__(self, url):
self.counter = Counter()

@count
def MyMethod(self):
pass

@timeIt
def MySecondMethod(self):
pass

c = MyClass('blah')
for i in range(100): c.MyMethod()
for i in range(300): c.MySecondMethod()
c.counter.summary()

count(prop)

Increases the count of the property.

countTic(prop)

Times a property call, this is the init call.

countToc(prop)

Times a property call, this is the end call.

summary()

Provides a text summary of the current counters and timers.

SimPEG.Utils.CounterUtils.count(f)
SimPEG.Utils.CounterUtils.timeIt(f)