Tensor Mesh

class discretize.TensorMesh(h_in, x0=None)[source]

Bases: discretize.TensorMesh.BaseTensorMesh, discretize.BaseMesh.BaseRectangularMesh, discretize.View.TensorView, discretize.DiffOperators.DiffOperators, discretize.InnerProducts.InnerProducts, discretize.MeshIO.TensorMeshIO

TensorMesh is a mesh class that deals with tensor product meshes.

Any Mesh that has a constant width along the entire axis such that it can defined by a single width vector, called ‘h’.

hx = np.array([1, 1, 1])
hy = np.array([1, 2])
hz = np.array([1, 1, 1, 1])

mesh = Mesh.TensorMesh([hx, hy, hz])

Example of a padded tensor mesh using discretize.utils.meshutils.meshTensor():

import discretize
M = discretize.TensorMesh([
    [(10, 10, -1.3), (10, 40), (10, 10, 1.3)],
    [(10, 10, -1.3), (10, 20)]
])
M.plotGrid()

(Source code, png, hires.png, pdf)

../../_images/api_MeshCode-1.png

For a quick tensor mesh on a (10x12x15) unit cube:

mesh = discretize.TensorMesh([10, 12, 15])
vol

Construct cell volumes of the 3D model as 1d array.

area

Construct face areas of the 3D model as 1d array.

edge

Construct edge legnths of the 3D model as 1d array.

faceBoundaryInd

Find indices of boundary faces in each direction

cellBoundaryInd

Find indices of boundary faces in each direction

Cylindrical Mesh

class discretize.CylMesh(h, x0=None, cartesianOrigin=None)[source]

Bases: discretize.TensorMesh.BaseTensorMesh, discretize.BaseMesh.BaseRectangularMesh, discretize.InnerProducts.InnerProducts, discretize.View.CylView

CylMesh is a mesh class for cylindrical problems

Note

for a cylindrically symmetric mesh use [hx, 1, hz]

cs, nc, npad = 20., 30, 8
hx = utils.meshTensor([(cs,npad+10,-0.7), (cs,nc), (cs,npad,1.3)])
hz = utils.meshTensor([(cs,npad   ,-1.3), (cs,nc), (cs,npad,1.3)])
mesh = Mesh.CylMesh([hx,1,hz], [0.,0,-hz.sum()/2.])
isSymmetric
nNx

Number of nodes in the x-direction

Return type:int
Returns:nNx
nNy

Number of nodes in the y-direction

Return type:int
Returns:nNy
vnFx

Number of x-faces in each direction

Return type:numpy.array
Returns:vnFx, (dim, )
vnEy

Number of y-edges in each direction

Return type:numpy.array
Returns:vnEy or None if dim < 2, (dim, )
vnEz

Number of z-edges in each direction

Return type:numpy.array
Returns:vnEz or None if nCy > 1, (dim, )
nEz

Number of z-edges

Return type:int
Returns:nEz
vectorCCx

Cell-centered grid vector (1D) in the x direction.

vectorCCy

Cell-centered grid vector (1D) in the y direction.

vectorNx

Nodal grid vector (1D) in the x direction.

vectorNy

Nodal grid vector (1D) in the y direction.

edge

Edge lengths

area

Face areas

vol

Volume of each cell

faceDiv

Construct divergence operator (face-stg to cell-centres).

faceDivx

Construct divergence operator in the x component (face-stg to cell-centres).

faceDivy

Construct divergence operator in the y component (face-stg to cell-centres).

faceDivz

Construct divergence operator in the z component (face-stg to cell-centres).

cellGrad

The cell centered Gradient, takes you to cell faces.

nodalGrad

Construct gradient operator (nodes to edges).

nodalLaplacian

Construct laplacian operator (nodes to edges).

edgeCurl

The edgeCurl property.

aveE2CC

Construct the averaging operator on cell edges to cell centers.

aveE2CCV

Construct the averaging operator on cell edges to cell centers.

aveF2CC

Construct the averaging operator on cell faces to cell centers.

aveF2CCV

Construct the averaging operator on cell faces to cell centers.

getInterpolationMat(loc, locType='CC', zerosOutside=False)[source]

Produces interpolation matrix

Parameters:
  • loc (numpy.ndarray) – Location of points to interpolate to
  • locType (str) – What to interpolate (see below)
Return type:

scipy.sparse.csr_matrix

Returns:

M, the interpolation matrix

locType can be:

'Ex'    -> x-component of field defined on edges
'Ey'    -> y-component of field defined on edges
'Ez'    -> z-component of field defined on edges
'Fx'    -> x-component of field defined on faces
'Fy'    -> y-component of field defined on faces
'Fz'    -> z-component of field defined on faces
'N'     -> scalar field defined on nodes
'CC'    -> scalar field defined on cell centers
'CCVx'  -> x-component of vector field defined on cell centers
'CCVy'  -> y-component of vector field defined on cell centers
'CCVz'  -> z-component of vector field defined on cell centers
getInterpolationMatCartMesh(Mrect, locType='CC', locTypeTo=None)[source]

Takes a cartesian mesh and returns a projection to translate onto the cartesian grid.

Tree Mesh

class discretize.TreeMesh(h, x0=None, levels=None)[source]

Bases: discretize.TensorMesh.BaseTensorMesh, discretize.InnerProducts.InnerProducts, discretize.MeshIO.TreeMeshIO

levels
fill

How filled is the mesh compared to a TensorMesh? As a fraction: [0,1].

maxLevel

The maximum level used, which may be less than levels.

nC
nN
nF
nFx
nFy
nFz
nE
nEx
nEy
nEz
nhN
nhF
nhFx
nhFy
nhFz
nhE
nhEx
nhEy
nhEz
ntN
ntF
vntF
ntFx
ntFy
ntFz
ntE
vntE
ntEx
ntEy
ntEz
permuteCC
permuteF
permuteE
refine(function=None, recursive=True, cells=None, balance=True, verbose=False, _inRecursion=False)[source]
corsen(function=None, recursive=True, cells=None, balance=True, verbose=False, _inRecursion=False)[source]
balance(recursive=True, cells=None, verbose=False, _inRecursion=False)[source]
gridCC
gridN
gridFx
gridFy
gridFz
gridEx
gridEy
gridEz
vol
area
edge
number(balance=True, force=False)[source]
faceDiv
edgeCurl

Construct the 3D curl operator.

nodalGrad
aveEx2CC
aveEy2CC

Construct the averaging operator on cell edges to cell centers.

aveEz2CC

Construct the averaging operator on cell edges to cell centers.

aveE2CC

Construct the averaging operator on cell edges to cell centers.

aveE2CCV

Construct the averaging operator on cell edges to cell centers.

aveFx2CC
aveFy2CC
aveFz2CC
aveF2CC

Construct the averaging operator on cell faces to cell centers.

aveF2CCV

Construct the averaging operator on cell faces to cell centers.

aveN2CC
point2index(locs)[source]
getInterpolationMat(locs, locType, zerosOutside=False)[source]

Produces interpolation matrix

Parameters:
  • locs (numpy.ndarray) – Location of points to interpolate to
  • locType (str) – What to interpolate (see below)
Return type:

scipy.sparse.csr_matrix

Returns:

M, the interpolation matrix

locType can be:

'Ex'    -> x-component of field defined on edges
'Ey'    -> y-component of field defined on edges
'Ez'    -> z-component of field defined on edges
'Fx'    -> x-component of field defined on faces
'Fy'    -> y-component of field defined on faces
'Fz'    -> z-component of field defined on faces
'N'     -> scalar field defined on nodes
'CC'    -> scalar field defined on cell centers
plotGrid(ax=None, showIt=False, grid=True, cells=False, cellLine=False, nodes=False, facesX=False, facesY=False, facesZ=False, edgesX=False, edgesY=False, edgesZ=False)[source]
plotImage(I, ax=None, showIt=False, grid=False, clim=None)[source]
plotSlice(v, vType='CC', normal='Z', ind=None, grid=True, view='real', ax=None, clim=None, showIt=False, pcolorOpts=None, streamOpts=None, gridOpts=None)[source]

Curvilinear Mesh

class discretize.CurvilinearMesh(nodes)[source]

Bases: discretize.BaseMesh.BaseRectangularMesh, discretize.DiffOperators.DiffOperators, discretize.InnerProducts.InnerProducts, discretize.View.CurviView

CurvilinearMesh is a mesh class that deals with curvilinear meshes.

Example of a curvilinear mesh:

import discretize
X, Y = discretize.utils.exampleLrmGrid([3,3],'rotate')
M = discretize.CurvilinearMesh([X, Y])
M.plotGrid(showIt=True)

(Source code, png, hires.png, pdf)

../../_images/api_MeshCode-2.png
gridCC

Cell-centered grid

gridN

Nodal grid.

gridFx

Face staggered grid in the x direction.

gridFy

Face staggered grid in the y direction.

gridFz

Face staggered grid in the y direction.

gridEx

Edge staggered grid in the x direction.

gridEy

Edge staggered grid in the y direction.

gridEz

Edge staggered grid in the z direction.

vol

Construct cell volumes of the 3D model as 1d array

area
normals

Face normals: calling this will average the computed normals so that there is one per face. This is especially relevant in 3D, as there are up to 4 different normals for each face that will be different.

To reshape the normals into a matrix and get the y component:

NyX, NyY, NyZ = M.r(M.normals, 'F', 'Fy', 'M')
edge

Edge lengths

tangents

Edge tangents

Base Rectangular Mesh

class discretize.BaseMesh.BaseRectangularMesh(n, x0=None)[source]

Bases: discretize.BaseMesh.BaseMesh

nCx

Number of cells in the x direction

Return type:int
Returns:nCx
nCy

Number of cells in the y direction

Return type:int
Returns:nCy or None if dim < 2
nCz

Number of cells in the z direction

Return type:int
Returns:nCz or None if dim < 3
vnC

Total number of cells in each direction

Return type:numpy.array
Returns:[nCx, nCy, nCz]
nNx

Number of nodes in the x-direction

Return type:int
Returns:nNx
nNy

Number of nodes in the y-direction

Return type:int
Returns:nNy or None if dim < 2
nNz

Number of nodes in the z-direction

Return type:int
Returns:nNz or None if dim < 3
vnN

Total number of nodes in each direction

Return type:numpy.array
Returns:[nNx, nNy, nNz]
vnEx

Number of x-edges in each direction

Return type:numpy.array
Returns:vnEx
vnEy

Number of y-edges in each direction

Return type:numpy.array
Returns:vnEy or None if dim < 2
vnEz

Number of z-edges in each direction

Return type:numpy.array
Returns:vnEz or None if dim < 3
vnFx

Number of x-faces in each direction

Return type:numpy.array
Returns:vnFx
vnFy

Number of y-faces in each direction

Return type:numpy.array
Returns:vnFy or None if dim < 2
vnFz

Number of z-faces in each direction

Return type:numpy.array
Returns:vnFz or None if dim < 3
nC

Total number of cells

Return type:int
Returns:nC
nN

Total number of nodes

Return type:int
Returns:nN
nEx

Number of x-edges

Return type:int
Returns:nEx
nEy

Number of y-edges

Return type:int
Returns:nEy
nEz

Number of z-edges

Return type:int
Returns:nEz
nFx

Number of x-faces

Return type:int
Returns:nFx
nFy

Number of y-faces

Return type:int
Returns:nFy
nFz

Number of z-faces

Return type:int
Returns:nFz
r(x, xType='CC', outType='CC', format='V')[source]

r is a quick reshape command that will do the best it can at giving you what you want.

For example, you have a face variable, and you want the x component of it reshaped to a 3D matrix.

r can fulfil your dreams:

mesh.r(V, 'F', 'Fx', 'M')
       |   |     |    |
       |   |     |    {
       |   |     |      How: 'M' or ['V'] for a matrix
       |   |     |      (ndgrid style) or a vector (n x dim)
       |   |     |    }
       |   |     {
       |   |       What you want: ['CC'], 'N',
       |   |                       'F', 'Fx', 'Fy', 'Fz',
       |   |                       'E', 'Ex', 'Ey', or 'Ez'
       |   |     }
       |   {
       |     What is it: ['CC'], 'N',
       |                  'F', 'Fx', 'Fy', 'Fz',
       |                  'E', 'Ex', 'Ey', or 'Ez'
       |   }
       {
         The input: as a list or ndarray
       }

For example:

..code:

# Separates each component of the Ex grid into 3 matrices
Xex, Yex, Zex = r(mesh.gridEx, 'Ex', 'Ex', 'M')

# Given an edge vector, return just the x edges as a vector
XedgeVector = r(edgeVector, 'E', 'Ex', 'V')

# Separates each component of the edgeVector into 3 vectors
eX, eY, eZ = r(edgeVector, 'E', 'E', 'V')

Base Tensor Mesh

class discretize.TensorMesh.BaseTensorMesh(h_in, x0_in=None)[source]

Bases: discretize.BaseMesh.BaseMesh

h

h is a list containing the cell widths of the tensor mesh in each dimension.

hx

Width of cells in the x direction

hy

Width of cells in the y direction

hz

Width of cells in the z direction

vectorNx

Nodal grid vector (1D) in the x direction.

vectorNy

Nodal grid vector (1D) in the y direction.

vectorNz

Nodal grid vector (1D) in the z direction.

vectorCCx

Cell-centered grid vector (1D) in the x direction.

vectorCCy

Cell-centered grid vector (1D) in the y direction.

vectorCCz

Cell-centered grid vector (1D) in the z direction.

gridCC

Cell-centered grid.

gridN

Nodal grid.

gridFx

Face staggered grid in the x direction.

gridFy

Face staggered grid in the y direction.

gridFz

Face staggered grid in the z direction.

gridEx

Edge staggered grid in the x direction.

gridEy

Edge staggered grid in the y direction.

gridEz

Edge staggered grid in the z direction.

getTensor(key)[source]

Returns a tensor list.

Parameters:key (str) – What tensor (see below)
Return type:list
Returns:list of the tensors that make up the mesh.

key can be:

'CC'    -> scalar field defined on cell centers
'N'     -> scalar field defined on nodes
'Fx'    -> x-component of field defined on faces
'Fy'    -> y-component of field defined on faces
'Fz'    -> z-component of field defined on faces
'Ex'    -> x-component of field defined on edges
'Ey'    -> y-component of field defined on edges
'Ez'    -> z-component of field defined on edges
isInside(pts, locType='N')[source]

Determines if a set of points are inside a mesh.

Parameters:pts (numpy.ndarray) – Location of points to test
Return type:numpy.ndarray
Returns:inside, numpy array of booleans
getInterpolationMat(loc, locType='CC', zerosOutside=False)[source]

Produces interpolation matrix

Parameters:
  • loc (numpy.ndarray) – Location of points to interpolate to
  • locType (str) – What to interpolate (see below)
Return type:

scipy.sparse.csr_matrix

Returns:

M, the interpolation matrix

locType can be:

'Ex'    -> x-component of field defined on edges
'Ey'    -> y-component of field defined on edges
'Ez'    -> z-component of field defined on edges
'Fx'    -> x-component of field defined on faces
'Fy'    -> y-component of field defined on faces
'Fz'    -> z-component of field defined on faces
'N'     -> scalar field defined on nodes
'CC'    -> scalar field defined on cell centers
'CCVx'  -> x-component of vector field defined on cell centers
'CCVy'  -> y-component of vector field defined on cell centers
'CCVz'  -> z-component of vector field defined on cell centers

Mesh IO

class discretize.MeshIO.TensorMeshIO[source]

Bases: object

classmethod readUBC(TensorMesh, fileName)[source]

Read UBC GIF 3D tensor mesh and generate 3D TensorMesh.

Parameters:fileName (string) – path to the UBC GIF mesh file
Return type:TensorMesh
Returns:The tensor mesh for the fileName.
classmethod readVTK(TensorMesh, fileName)[source]

Read VTK Rectilinear (vtr xml file) and return Tensor mesh and model

Input: :param string fileName: path to the vtr model file to read :rtype: tuple :return: (TensorMesh, modelDictionary)

writeVTK(mesh, fileName, models=None)[source]

Makes and saves a VTK rectilinear file (vtr) for a Tensor mesh and model.

Input: :param string fileName: path to the output vtk file :param dict models: dictionary of numpy.array - Name(‘s) and array(‘s). Match number of cells

readModelUBC(mesh, fileName)[source]

Read UBC 3DTensor mesh model and generate 3D Tensor mesh model

Parameters:fileName (string) – path to the UBC GIF mesh file to read
Return type:numpy.ndarray
Returns:model with TensorMesh ordered
writeModelUBC(mesh, fileName, model)[source]

Writes a model associated with a TensorMesh to a UBC-GIF format model file.

Parameters:
writeUBC(mesh, fileName, models=None)[source]

Writes a TensorMesh to a UBC-GIF format mesh file.

Parameters:
  • fileName (string) – File to write to
  • models (dict) – A dictionary of the models
class discretize.MeshIO.TreeMeshIO[source]

Bases: object

writeUBC(mesh, fileName, models=None)[source]

Write UBC ocTree mesh and model files from a octree mesh and model.

Parameters:
  • fileName (string) – File to write to
  • models (dict) – Models in a dict, where each key is the filename
classmethod readUBC(TreeMesh, meshFile)[source]

Read UBC 3D OcTree mesh and/or modelFiles

Input: :param str meshFile: path to the UBC GIF OcTree mesh file to read :rtype: discretize.TreeMesh :return: The octree mesh

readModelUBC(mesh, fileName)[source]

Read UBC OcTree model and get vector

Parameters:fileName (string) – path to the UBC GIF model file to read
Return type:numpy.ndarray
Returns:OcTree model
writeVTK(mesh, fileName, models=None)[source]

Function to write a VTU file from a TreeMesh and model.

Mesh Viewing

class discretize.View.TensorView[source]

Bases: object

Provides viewing functions for TensorMesh

This class is inherited by TensorMesh

plotImage(v)[source]

Plots scalar fields on the given mesh.

Input:

Parameters:v (numpy.array) – vector

Optional Inputs:

Parameters:
  • vType (str) – type of vector (‘CC’, ‘N’, ‘F’, ‘Fx’, ‘Fy’, ‘Fz’, ‘E’, ‘Ex’, ‘Ey’, ‘Ez’)
  • ax (matplotlib.axes.Axes) – axis to plot to
  • showIt (bool) – call plt.show()

3D Inputs:

Parameters:
  • numbering (bool) – show numbering of slices, 3D only
  • annotationColor (str) – color of annotation, e.g. ‘w’, ‘k’, ‘b’
import discretize
import numpy as np
M = discretize.TensorMesh([20, 20])
v = np.sin(M.gridCC[:, 0]*2*np.pi)*np.sin(M.gridCC[:, 1]*2*np.pi)
M.plotImage(v, showIt=True)

(Source code, png, hires.png, pdf)

../../_images/api_MeshCode-3.png
import discretize
import numpy as np
M = discretize.TensorMesh([20, 20, 20])
v = np.sin(M.gridCC[:, 0]*2*np.pi)*np.sin(M.gridCC[:, 1]*2*np.pi)*np.sin(M.gridCC[:, 2]*2*np.pi)
M.plotImage(v, annotationColor='k', showIt=True)

(Source code, png, hires.png, pdf)

../../_images/api_MeshCode-4.png
plotSlice(v, vType='CC', normal='Z', ind=None, grid=False, view='real', ax=None, clim=None, showIt=False, pcolorOpts=None, streamOpts=None, gridOpts=None, range_x=None, range_y=None)[source]

Plots a slice of a 3D mesh.

(Source code, png, hires.png, pdf)

../../_images/api_MeshCode-5.png
plotGrid(ax=None, nodes=False, faces=False, centers=False, edges=False, lines=True, showIt=False)[source]

Plot the nodal, cell-centered and staggered grids for 1,2 and 3 dimensions.

Parameters:
  • nodes (bool) – plot nodes
  • faces (bool) – plot faces
  • centers (bool) – plot centers
  • edges (bool) – plot edges
  • lines (bool) – plot lines connecting nodes
  • showIt (bool) – call plt.show()
import discretize
import numpy as np
h1 = np.linspace(.1, .5, 3)
h2 = np.linspace(.1, .5, 5)
mesh = discretize.TensorMesh([h1, h2])
mesh.plotGrid(nodes=True, faces=True, centers=True, lines=True, showIt=True)

(Source code, png, hires.png, pdf)

../../_images/api_MeshCode-6.png
import discretize
import numpy as np
h1 = np.linspace(.1, .5, 3)
h2 = np.linspace(.1, .5, 5)
h3 = np.linspace(.1, .5, 3)
mesh = discretize.TensorMesh([h1, h2, h3])
mesh.plotGrid(nodes=True, faces=True, centers=True, lines=True, showIt=True)

(Source code, png, hires.png, pdf)

../../_images/api_MeshCode-7.png
class discretize.View.CylView[source]

Bases: object

plotGrid(*args, **kwargs)[source]
plotImage(*args, **kwargs)[source]
class discretize.View.CurviView[source]

Bases: object

Provides viewing functions for CurvilinearMesh

This class is inherited by CurvilinearMesh

plotGrid(ax=None, nodes=False, faces=False, centers=False, edges=False, lines=True, showIt=False)[source]

Plot the nodal, cell-centered and staggered grids for 1, 2 and 3 dimensions.

import discretize
X, Y = discretize.utils.exampleLrmGrid([3, 3], 'rotate')
M = discretize.CurvilinearMesh([X, Y])
M.plotGrid(showIt=True)

(Source code, png, hires.png, pdf)

../../_images/api_MeshCode-8.png
plotImage(I, ax=None, showIt=False, grid=False, clim=None)[source]