discretize.base.BaseTensorMesh

class discretize.base.BaseTensorMesh(*args, **kwargs)[source]

Bases: discretize.base.base_mesh.BaseMesh

Base class for tensor-product style meshes

This class contains properites and methods that are common to cartesian and cylindrical meshes defined by tensor-produts of vectors describing cell spacings.

Do not use this class directly, instead, inherit it if you plan to develop a tensor-style mesh (e.g. a spherical mesh) or use the discretize.TensorMesh() class to create a cartesian tensor mesh.

Required Properties:

  • axis_u (Vector3): Vector orientation of u-direction. For more details see the docs for the rotation_matrix property., a 3D Vector of <class ‘float’> with shape (3), Default: X

  • axis_v (Vector3): Vector orientation of v-direction. For more details see the docs for the rotation_matrix property., a 3D Vector of <class ‘float’> with shape (3), Default: Y

  • axis_w (Vector3): Vector orientation of w-direction. For more details see the docs for the rotation_matrix property., a 3D Vector of <class ‘float’> with shape (3), Default: Z

  • h (a tuple of Array): h is a list containing the cell widths of the tensor mesh in each dimension., a tuple (each item is a list or numpy array of <class ‘float’> with shape (*)) with length between 1 and 3

  • origin (Array): origin of the mesh (dim, ), a list or numpy array of <class ‘float’>, <class ‘int’> with shape (*)

  • reference_system (String): The type of coordinate reference frame. Can take on the values cartesian, cylindrical, or spherical. Abbreviations of these are allowed., a unicode string, Default: cartesian

Attributes
axis_u

axis_u (Vector3): Vector orientation of u-direction. For more details see the docs for the rotation_matrix property., a 3D Vector of <class ‘float’> with shape (3), Default: X

axis_v

axis_v (Vector3): Vector orientation of v-direction. For more details see the docs for the rotation_matrix property., a 3D Vector of <class ‘float’> with shape (3), Default: Y

axis_w

axis_w (Vector3): Vector orientation of w-direction. For more details see the docs for the rotation_matrix property., a 3D Vector of <class ‘float’> with shape (3), Default: Z

cell_centers

Cell-centered grid.

cell_centers_x

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

cell_centers_y

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

cell_centers_z

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

dim

The dimension of the mesh (1, 2, or 3).

edge_tangents

Edge Tangents

edges_x

Edge staggered grid in the x direction.

edges_y

Edge staggered grid in the y direction.

edges_z

Edge staggered grid in the z direction.

face_normals

Face Normals

faces_x

Face staggered grid in the x direction.

faces_y

Face staggered grid in the y direction.

faces_z

Face staggered grid in the z direction.

h

h (a tuple of Array): h is a list containing the cell widths of the tensor mesh in each dimension., a tuple (each item is a list or numpy array of <class ‘float’> with shape (*)) with length between 1 and 3

h_gridded

Returns an (nC, dim) numpy array with the widths of all cells in order

hx

Width of cells in the x direction

hy

Width of cells in the y direction

hz

Width of cells in the z direction

n_cells

Total number of cells in the mesh.

n_edges

Total number of edges.

n_edges_per_direction

The number of edges in each direction

n_edges_x

Number of x-edges

n_edges_y

Number of y-edges

n_edges_z

Number of z-edges

n_faces

Total number of faces.

n_faces_per_direction

The number of faces in each direction

n_faces_x

Number of x-faces

n_faces_y

Number of y-faces

n_faces_z

Number of z-faces

n_nodes

Total number of nodes

nodes

Nodal grid.

nodes_x

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

nodes_y

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

nodes_z

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

normals

normals has been deprecated. See face_normals for documentation

origin

origin (Array): origin of the mesh (dim, ), a list or numpy array of <class ‘float’>, <class ‘int’> with shape (*)

reference_is_rotated

True if the axes are rotated from the traditional <X,Y,Z> system

reference_system

reference_system (String): The type of coordinate reference frame. Can take on the values cartesian, cylindrical, or spherical. Abbreviations of these are allowed., a unicode string, Default: cartesian

rotation_matrix

Builds a rotation matrix to transform coordinates from their coordinate system into a conventional cartesian system.

tangents

tangents has been deprecated. See edge_tangents for documentation

vectorCCx

vectorCCx has been deprecated. See cell_centers_x for documentation

vectorCCy

vectorCCy has been deprecated. See cell_centers_y for documentation

vectorCCz

vectorCCz has been deprecated. See cell_centers_z for documentation

vectorNx

vectorNx has been deprecated. See nodes_x for documentation

vectorNy

vectorNy has been deprecated. See nodes_y for documentation

vectorNz

vectorNz has been deprecated. See nodes_z for documentation

x0

Methods

copy()

Make a copy of the current mesh

deserialize(value, **kwargs)

Creates HasProperties instance from serialized dictionary

equal(other)

Determine if two HasProperties instances are equivalent

from_omf(element)

Convert an OMF element to it’s proper discretize type.

getInterpolationMat(*args, **kwargs)

getInterpolationMat has been deprecated.

getTensor(*args, **kwargs)

getTensor has been deprecated.

get_interpolation_matrix(loc[, …])

Produces linear interpolation matrix

get_tensor(key)

Returns a tensor list.

isInside(*args, **kwargs)

isInside has been deprecated.

is_inside(pts[, location_type])

Determines if a set of points are inside a mesh.

plotGrid(*args, **kwargs)

plotGrid has been deprecated.

plotImage(*args, **kwargs)

plotImage has been deprecated.

plotSlice(*args, **kwargs)

plotSlice has been deprecated.

plot_3d_slicer(v[, xslice, yslice, zslice, …])

Plot slices of a 3D volume, interactively (scroll wheel).

plot_grid([ax, nodes, faces, centers, …])

Plot the nodal, cell-centered and staggered grids.

plot_image(v[, v_type, grid, view, ax, …])

Plots fields on the given mesh.

plot_slice(v[, v_type, normal, ind, …])

Plots slice of fields on the given 3D mesh.

projectEdgeVector(*args, **kwargs)

projectEdgeVector has been deprecated.

projectFaceVector(*args, **kwargs)

projectFaceVector has been deprecated.

project_edge_vector(edge_vector)

Project vectors onto the edges of the mesh

project_face_vector(face_vector)

Project vectors onto the faces of the mesh.

save([file_name, verbose])

Save the mesh to json :param str file: file_name for saving the casing properties :param str directory: working directory for saving the file

serialize([include_class, save_dynamic])

Serializes a HasProperties instance to dictionary

toVTK([models])

Convert this mesh object to it’s proper VTK or pyvista data object with the given model dictionary as the cell data of that dataset.

to_omf([models])

Convert this mesh object to it’s proper omf data object with the given model dictionary as the cell data of that dataset.

to_vtk([models])

Convert this mesh object to it’s proper VTK or pyvista data object with the given model dictionary as the cell data of that dataset.

validate()

Call all registered class validator methods

writeVTK(file_name[, models, directory])

Makes and saves a VTK object from this mesh and given models

write_vtk(file_name[, models, directory])

Makes and saves a VTK object from this mesh and given models

Attributes

BaseTensorMesh.axis_u

axis_u (Vector3): Vector orientation of u-direction. For more details see the docs for the rotation_matrix property., a 3D Vector of <class ‘float’> with shape (3), Default: X

BaseTensorMesh.axis_v

axis_v (Vector3): Vector orientation of v-direction. For more details see the docs for the rotation_matrix property., a 3D Vector of <class ‘float’> with shape (3), Default: Y

BaseTensorMesh.axis_w

axis_w (Vector3): Vector orientation of w-direction. For more details see the docs for the rotation_matrix property., a 3D Vector of <class ‘float’> with shape (3), Default: Z

BaseTensorMesh.cell_centers

Cell-centered grid.

BaseTensorMesh.cell_centers_x

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

BaseTensorMesh.cell_centers_y

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

BaseTensorMesh.cell_centers_z

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

BaseTensorMesh.dim

The dimension of the mesh (1, 2, or 3).

Returns
int

dimension of the mesh

BaseTensorMesh.edge_tangents

Edge Tangents

Returns
numpy.ndarray

normals, (n_edges, dim)

BaseTensorMesh.edges_x

Edge staggered grid in the x direction.

BaseTensorMesh.edges_y

Edge staggered grid in the y direction.

BaseTensorMesh.edges_z

Edge staggered grid in the z direction.

BaseTensorMesh.face_normals

Face Normals

Returns
numpy.ndarray

normals, (n_faces, dim)

BaseTensorMesh.faces_x

Face staggered grid in the x direction.

BaseTensorMesh.faces_y

Face staggered grid in the y direction.

BaseTensorMesh.faces_z

Face staggered grid in the z direction.

BaseTensorMesh.h

h (a tuple of Array): h is a list containing the cell widths of the tensor mesh in each dimension., a tuple (each item is a list or numpy array of <class ‘float’> with shape (*)) with length between 1 and 3

BaseTensorMesh.h_gridded

Returns an (nC, dim) numpy array with the widths of all cells in order

BaseTensorMesh.hx

Width of cells in the x direction

Returns
numpy.ndarray

Deprecated since version 0.5.0: hx will be removed in discretize 1.0.0 to reduce namespace clutter, please use mesh.h[0].

BaseTensorMesh.hy

Width of cells in the y direction

Returns
numpy.ndarray or None

Deprecated since version 0.5.0: hy will be removed in discretize 1.0.0 to reduce namespace clutter, please use mesh.h[1].

BaseTensorMesh.hz

Width of cells in the z direction

Returns
numpy.ndarray or None

Deprecated since version 0.5.0: hz will be removed in discretize 1.0.0 to reduce namespace clutter, please use mesh.h[2].

BaseTensorMesh.n_cells

Total number of cells in the mesh.

Returns
int

number of cells in the mesh

Notes

Also accessible as nC.

Examples

>>> import discretize
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> mesh = discretize.TensorMesh([np.ones(n) for n in [2,3]])
>>> mesh.plot_grid(centers=True, show_it=True)
>>> print(mesh.n_cells)

(Source code, png, pdf)

../../_images/discretize-base-BaseTensorMesh-1.png
BaseTensorMesh.n_edges

Total number of edges.

Returns
int

sum([n_edges_x, n_edges_y, n_edges_z])

Notes

Also accessible as nE.

BaseTensorMesh.n_edges_per_direction

The number of edges in each direction

Returns
n_edges_per_directiontuple

[n_edges_x, n_edges_y, n_edges_z], (dim, )

Notes

Also accessible as vnE.

Examples

>>> import discretize
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> M = discretize.TensorMesh([np.ones(n) for n in [2,3]])
>>> M.plot_grid(edges=True, show_it=True)

(Source code, png, pdf)

../../_images/discretize-base-BaseTensorMesh-2.png
BaseTensorMesh.n_edges_x

Number of x-edges

Returns
int

Notes

Also accessible as nEx.

BaseTensorMesh.n_edges_y

Number of y-edges

Returns
int

Notes

Also accessible as nEy.

BaseTensorMesh.n_edges_z

Number of z-edges

Returns
int

Notes

Also accessible as nEz.

BaseTensorMesh.n_faces

Total number of faces.

Returns
int

sum([n_faces_x, n_faces_y, n_faces_z])

Notes

Also accessible as nF.

BaseTensorMesh.n_faces_per_direction

The number of faces in each direction

Returns
n_faces_per_directiontuple

[n_faces_x, n_faces_y, n_faces_z], (dim, )

Notes

Also accessible as vnF.

Examples

>>> import discretize
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> M = discretize.TensorMesh([np.ones(n) for n in [2,3]])
>>> M.plot_grid(faces=True, show_it=True)

(Source code, png, pdf)

../../_images/discretize-base-BaseTensorMesh-3.png
BaseTensorMesh.n_faces_x

Number of x-faces

Returns
int

Notes

Also accessible as nFx.

BaseTensorMesh.n_faces_y

Number of y-faces

Returns
int

Notes

Also accessible as nFy.

BaseTensorMesh.n_faces_z

Number of z-faces

Returns
int

Notes

Also accessible as nFz.

BaseTensorMesh.n_nodes

Total number of nodes

Returns
int

number of nodes in the mesh

Notes

Also accessible as nN.

Examples

>>> import discretize
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> mesh = discretize.TensorMesh([np.ones(n) for n in [2,3]])
>>> mesh.plot_grid(nodes=True, show_it=True)
>>> print(mesh.n_nodes)

(Source code, png, pdf)

../../_images/discretize-base-BaseTensorMesh-4.png
BaseTensorMesh.nodes

Nodal grid.

BaseTensorMesh.nodes_x

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

BaseTensorMesh.nodes_y

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

BaseTensorMesh.nodes_z

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

BaseTensorMesh.normals

normals has been deprecated. See face_normals for documentation

BaseTensorMesh.origin

origin (Array): origin of the mesh (dim, ), a list or numpy array of <class ‘float’>, <class ‘int’> with shape (*)

BaseTensorMesh.reference_is_rotated

True if the axes are rotated from the traditional <X,Y,Z> system with vectors of \((1,0,0)\), \((0,1,0)\), and \((0,0,1)\)

BaseTensorMesh.reference_system

reference_system (String): The type of coordinate reference frame. Can take on the values cartesian, cylindrical, or spherical. Abbreviations of these are allowed., a unicode string, Default: cartesian

BaseTensorMesh.rotation_matrix

Builds a rotation matrix to transform coordinates from their coordinate system into a conventional cartesian system. This is built off of the three axis_u, axis_v, and axis_w properties; these mapping coordinates use the letters U, V, and W (the three letters preceding X, Y, and Z in the alphabet) to define the projection of the X, Y, and Z durections. These UVW vectors describe the placement and transformation of the mesh’s coordinate sytem assuming at most 3 directions.

Why would you want to use these UVW mapping vectors the this rotation_matrix property? They allow us to define the realationship between local and global coordinate systems and provide a tool for switching between the two while still maintaing the connectivity of the mesh’s cells. For a visual example of this, please see the figure in the docs for the InterfaceVTK.

BaseTensorMesh.tangents

tangents has been deprecated. See edge_tangents for documentation

BaseTensorMesh.vectorCCx

vectorCCx has been deprecated. See cell_centers_x for documentation

BaseTensorMesh.vectorCCy

vectorCCy has been deprecated. See cell_centers_y for documentation

BaseTensorMesh.vectorCCz

vectorCCz has been deprecated. See cell_centers_z for documentation

BaseTensorMesh.vectorNx

vectorNx has been deprecated. See nodes_x for documentation

BaseTensorMesh.vectorNy

vectorNy has been deprecated. See nodes_y for documentation

BaseTensorMesh.vectorNz

vectorNz has been deprecated. See nodes_z for documentation

BaseTensorMesh.x0

Methods

BaseTensorMesh.copy()

Make a copy of the current mesh

classmethod BaseTensorMesh.deserialize(value, **kwargs)

Creates HasProperties instance from serialized dictionary

This uses the Property deserializers to deserialize all JSON-compatible dictionary values into their corresponding Property values on a new instance of a HasProperties class. Extra keys in the dictionary that do not correspond to Properties will be ignored.

Parameters:

  • value - Dictionary to deserialize new instance from.

  • trusted - If True (and if the input dictionary has '__class__' keyword and this class is in the registry), the new HasProperties class will come from the dictionary. If False (the default), only the HasProperties class this method is called on will be constructed.

  • strict - Requires '__class__', if present on the input dictionary, to match the deserialized instance’s class. Also disallows unused properties in the input dictionary. Default is False.

  • assert_valid - Require deserialized instance to be valid. Default is False.

  • Any other keyword arguments will be passed through to the Property deserializers.

BaseTensorMesh.equal(other)

Determine if two HasProperties instances are equivalent

Equivalence is determined by checking if all Property values on two instances are equal, using Property.equal.

static BaseTensorMesh.from_omf(element)

Convert an OMF element to it’s proper discretize type. Automatically determines the output type. Returns both the mesh and a dictionary of model arrays.

BaseTensorMesh.getInterpolationMat(*args, **kwargs)

getInterpolationMat has been deprecated. See get_interpolation_matrix for documentation

BaseTensorMesh.getTensor(*args, **kwargs)

getTensor has been deprecated. See get_tensor for documentation

BaseTensorMesh.get_interpolation_matrix(loc, location_type='cell_centers', zeros_outside=False, **kwargs)[source]

Produces linear interpolation matrix

Parameters
locnumpy.ndarray

Location of points to interpolate to

location_typestr

What to interpolate (see below)

location_type can be:

'Ex', 'edges_x'           -> x-component of field defined on x edges
'Ey', 'edges_y'           -> y-component of field defined on y edges
'Ez', 'edges_z'           -> z-component of field defined on z edges
'Fx', 'faces_x'           -> x-component of field defined on x faces
'Fy', 'faces_y'           -> y-component of field defined on y faces
'Fz', 'faces_z'           -> z-component of field defined on z faces
'N', 'nodes'              -> scalar field defined on nodes
'CC', 'cell_centers'      -> scalar field defined on cell centers
'CCVx', 'cell_centers_x'  -> x-component of vector field defined on cell centers
'CCVy', 'cell_centers_y'  -> y-component of vector field defined on cell centers
'CCVz', 'cell_centers_z'  -> z-component of vector field defined on cell centers
Returns
scipy.sparse.csr_matrix

M, the interpolation matrix

BaseTensorMesh.get_tensor(key)[source]

Returns a tensor list.

Parameters
keystr

Which tensor (see below)

key can be:

'CC', 'cell_centers' -> location of cell centers
'N', 'nodes'         -> location of nodes
'Fx', 'faces_x'      -> location of faces with an x normal
'Fy', 'faces_y'      -> location of faces with an y normal
'Fz', 'faces_z'      -> location of faces with an z normal
'Ex', 'edges_x'      -> location of edges with an x tangent
'Ey', 'edges_y'      -> location of edges with an y tangent
'Ez', 'edges_z'      -> location of edges with an z tangent
Returns
list

list of the tensors that make up the mesh.

BaseTensorMesh.isInside(*args, **kwargs)

isInside has been deprecated. See is_inside for documentation

BaseTensorMesh.is_inside(pts, location_type='nodes', **kwargs)[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

BaseTensorMesh.plotGrid(*args, **kwargs)

plotGrid has been deprecated. See plot_grid for documentation

BaseTensorMesh.plotImage(*args, **kwargs)

plotImage has been deprecated. See plot_image for documentation

BaseTensorMesh.plotSlice(*args, **kwargs)

plotSlice has been deprecated. See plot_slice for documentation

BaseTensorMesh.plot_3d_slicer(v, xslice=None, yslice=None, zslice=None, v_type='CC', view='real', axis='xy', transparent=None, clim=None, xlim=None, ylim=None, zlim=None, aspect='auto', grid=[2, 2, 1], pcolor_opts=None, fig=None, **kwargs)

Plot slices of a 3D volume, interactively (scroll wheel).

If called from a notebook, make sure to set

%matplotlib notebook

See the class discretize.View.Slicer for more information.

It returns nothing. However, if you need the different figure handles you can get it via

fig = plt.gcf()

and subsequently its children via

fig.get_children()

and recursively deeper, e.g.,

fig.get_children()[0].get_children().

One can also provide an existing figure instance, which can be useful for interactive widgets in Notebooks. The provided figure is cleared first.

BaseTensorMesh.plot_grid(ax=None, nodes=False, faces=False, centers=False, edges=False, lines=True, show_it=False, **kwargs)

Plot the nodal, cell-centered and staggered grids.

Parameters
axmatplotlib.axes.Axes or None, optional

The axes to draw on. None produces a new Axes.

nodes, faces, centers, edges, linesbool, optional

Whether to plot the corresponding item

show_itbool, optional

whether to call plt.show()

colorColor or str, optional

If lines=True, the color of the lines, defaults to first color.

linewidthfloat, optional

If lines=True, the linewidth for the lines.

Returns
matplotlib.axes.Axes

Axes handle for the plot

Other Parameters
edges_x, edges_y, edges_z, faces_x, faces_y, faces_zbool, optional

When plotting a TreeMesh, these are also options to plot the individual component items.

cell_linebool, optional

When plotting a TreeMesh, you can also plot a line through the cell centers in order.

slice{‘both’, ‘theta’, ‘z’}

When plotting a CylindricalMesh, which dimension to slice over.

Notes

Excess arguments are passed on to plot

Examples

Plotting a 2D TensorMesh grid

>>> from matplotlib import pyplot as plt
>>> import discretize
>>> import numpy as np
>>> h1 = np.linspace(.1, .5, 3)
>>> h2 = np.linspace(.1, .5, 5)
>>> mesh = discretize.TensorMesh([h1, h2])
>>> mesh.plot_grid(nodes=True, faces=True, centers=True, lines=True)
>>> plt.show()

(Source code, png, pdf)

../../_images/discretize-base-BaseTensorMesh-5_00_00.png

Plotting a 3D TensorMesh grid

>>> from matplotlib import pyplot as plt
>>> 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.plot_grid(nodes=True, faces=True, centers=True, lines=True)
>>> plt.show()

(png, pdf)

../../_images/discretize-base-BaseTensorMesh-5_01_00.png

Plotting a 2D CurvilinearMesh

>>> from matplotlib import pyplot as plt
>>> import discretize
>>> X, Y = discretize.utils.exampleLrmGrid([10, 10], 'rotate')
>>> M = discretize.CurvilinearMesh([X, Y])
>>> M.plot_grid()
>>> plt.show()

(png, pdf)

../../_images/discretize-base-BaseTensorMesh-5_02_00.png

Plotting a 3D CurvilinearMesh

>>> from matplotlib import pyplot as plt
>>> import discretize
>>> X, Y, Z = discretize.utils.exampleLrmGrid([5, 5, 5], 'rotate')
>>> M = discretize.CurvilinearMesh([X, Y, Z])
>>> M.plot_grid()
>>> plt.show()

(png, pdf)

../../_images/discretize-base-BaseTensorMesh-5_03_00.png

Plotting a 2D TreeMesh

>>> from matplotlib import pyplot as plt
>>> import discretize
>>> M = discretize.TreeMesh([32, 32])
>>> M.insert_cells([[0.25, 0.25]], [4])
>>> M.plot_grid()
>>> plt.show()

(png, pdf)

../../_images/discretize-base-BaseTensorMesh-5_04_00.png

Plotting a 3D TreeMesh

>>> from matplotlib import pyplot as plt
>>> import discretize
>>> M = discretize.TreeMesh([32, 32, 32])
>>> M.insert_cells([[0.3, 0.75, 0.22]], [4])
>>> M.plot_grid()
>>> plt.show()

(png, pdf)

../../_images/discretize-base-BaseTensorMesh-5_05_00.png
BaseTensorMesh.plot_image(v, v_type='CC', grid=False, view='real', ax=None, clim=None, show_it=False, pcolor_opts=None, stream_opts=None, grid_opts=None, range_x=None, range_y=None, sample_grid=None, stream_thickness=None, stream_threshold=None, **kwargs)

Plots fields on the given mesh.

Parameters
vnumpy.ndarray

values to plot

v_type{‘CC’,’CCV’, ‘N’, ‘F’, ‘Fx’, ‘Fy’, ‘Fz’, ‘E’, ‘Ex’, ‘Ey’, ‘Ez’}

Where the values of v are defined.

view{‘real’, ‘imag’, ‘abs’, ‘vec’}

How to view the array.

axmatplotlib.axes.Axes, optional

The axes to draw on. None produces a new Axes.

climtuple of float, optional

length 2 tuple of (vmin, vmax) for the color limits

range_x, range_ytuple of float, optional

length 2 tuple of (min, max) for the bounds of the plot axes.

pcolor_optsdict, optional

Arguments passed on to pcolormesh

gridbool, optional

Whether to plot the edges of the mesh cells.

grid_optsdict, optional

If grid is true, arguments passed on to plot for grid

sample_gridtuple of numpy.ndarray, optional

If view == ‘vec’, mesh cell widths (hx, hy) to interpolate onto for vector plotting

stream_optsdict, optional

If view == ‘vec’, arguments passed on to streamplot

stream_thicknessfloat, optional

If view == ‘vec’, linewidth for streamplot

stream_thresholdfloat, optional

If view == ‘vec’, only plots vectors with magnitude above this threshold

show_itbool, optional

Whether to call plt.show()

numberingbool, optional

For 3D TensorMesh only, show the numbering of the slices

annotation_colorColor or str, optional

For 3D TensorMesh only, color of the annotation

Examples

2D TensorMesh plotting

>>> from matplotlib import pyplot as plt
>>> 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.plot_image(v)
>>> plt.show()

(Source code, png, pdf)

../../_images/discretize-base-BaseTensorMesh-6_00_00.png

3D TensorMesh plotting

>>> 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.plot_image(v, annotation_color='k')
>>> plt.show()

(png, pdf)

../../_images/discretize-base-BaseTensorMesh-6_01_00.png
BaseTensorMesh.plot_slice(v, v_type='CC', normal='Z', ind=None, slice_loc=None, grid=False, view='real', ax=None, clim=None, show_it=False, pcolor_opts=None, stream_opts=None, grid_opts=None, range_x=None, range_y=None, sample_grid=None, stream_threshold=None, stream_thickness=None, **kwargs)

Plots slice of fields on the given 3D mesh.

Parameters
vnumpy.ndarray

values to plot

v_type{‘CC’,’CCV’, ‘N’, ‘F’, ‘Fx’, ‘Fy’, ‘Fz’, ‘E’, ‘Ex’, ‘Ey’, ‘Ez’}, or tuple of these options

Where the values of v are defined.

normal{‘Z’, ‘X’, ‘Y’}

Normal direction of slicing plane.

indNone, optional

index along dimension of slice. Defaults to the center index.

slice_locNone, optional

Value along dimension of slice. Defaults to the center of the mesh.

view{‘real’, ‘imag’, ‘abs’, ‘vec’}

How to view the array.

axmatplotlib.axes.Axes, optional

The axes to draw on. None produces a new Axes. Must be None if v_type is a tuple.

climtuple of float, optional

length 2 tuple of (vmin, vmax) for the color limits

range_x, range_ytuple of float, optional

length 2 tuple of (min, max) for the bounds of the plot axes.

pcolor_optsdict, optional

Arguments passed on to pcolormesh

gridbool, optional

Whether to plot the edges of the mesh cells.

grid_optsdict, optional

If grid is true, arguments passed on to plot for the edges

sample_gridtuple of numpy.ndarray, optional

If view == ‘vec’, mesh cell widths (hx, hy) to interpolate onto for vector plotting

stream_optsdict, optional

If view == ‘vec’, arguments passed on to streamplot

stream_thicknessfloat, optional

If view == ‘vec’, linewidth for streamplot

stream_thresholdfloat, optional

If view == ‘vec’, only plots vectors with magnitude above this threshold

show_itbool, optional

Whether to call plt.show()

Examples

Plot a slice of a 3D TensorMesh solution to a Laplace’s equaiton.

First build the mesh:

>>> from matplotlib import pyplot as plt
>>> import discretize
>>> from pymatsolver import Solver
>>> hx = [(5, 2, -1.3), (2, 4), (5, 2, 1.3)]
>>> hy = [(2, 2, -1.3), (2, 6), (2, 2, 1.3)]
>>> hz = [(2, 2, -1.3), (2, 6), (2, 2, 1.3)]
>>> M = discretize.TensorMesh([hx, hy, hz])

then build the necessary parts of the PDE:

>>> q = np.zeros(M.vnC)
>>> q[[4, 4], [4, 4], [2, 6]]=[-1, 1]
>>> q = discretize.utils.mkvc(q)
>>> A = M.face_divergence * M.cell_gradient
>>> b = Solver(A) * (q)

and finaly, plot the vector values of the result, which are defined on faces

>>> M.plot_slice(M.cell_gradient*b, 'F', view='vec', grid=True, pcolor_opts={'alpha':0.8})
>>> plt.show()

(Source code, png, pdf)

../../_images/discretize-base-BaseTensorMesh-7_00_00.png

We can use the slice_loc kwarg to tell `plot_slice where to slice the mesh. Let’s create a mesh with a random model and plot slice of it. The slice_loc kwarg automatically determines the indices for slicing the mesh along a plane with the given normal.

>>> M = discretize.TensorMesh([32, 32, 32])
>>> v = discretize.utils.random_model(M.vnC, seed=789).reshape(-1, order='F')
>>> x_slice, y_slice, z_slice = 0.75, 0.25, 0.9
>>> plt.figure(figsize=(7.5, 3))
>>> ax = plt.subplot(131)
>>> M.plot_slice(v, normal='X', slice_loc=x_slice, ax=ax)
>>> ax = plt.subplot(132)
>>> M.plot_slice(v, normal='Y', slice_loc=y_slice, ax=ax)
>>> ax = plt.subplot(133)
>>> M.plot_slice(v, normal='Z', slice_loc=z_slice, ax=ax)
>>> plt.tight_layout()
>>> plt.show()

(png, pdf)

../../_images/discretize-base-BaseTensorMesh-7_01_00.png

This also works for TreeMesh. We create a mesh here that is refined within three boxes, along with a base level of refinement.

>>> TM = discretize.TreeMesh([32, 32, 32])
>>> TM.refine(3, finalize=False)
>>> BSW = [[0.25, 0.25, 0.25], [0.15, 0.15, 0.15], [0.1, 0.1, 0.1]]
>>> TNE = [[0.75, 0.75, 0.75], [0.85, 0.85, 0.85], [0.9, 0.9, 0.9]]
>>> levels = [6, 5, 4]
>>> TM.refine_box(BSW, TNE, levels)
>>> v_TM = discretize.utils.volume_average(M, TM, v)
>>> plt.figure(figsize=(7.5, 3))
>>> ax = plt.subplot(131)
>>> TM.plot_slice(v_TM, normal='X', slice_loc=x_slice, ax=ax)
>>> ax = plt.subplot(132)
>>> TM.plot_slice(v_TM, normal='Y', slice_loc=y_slice, ax=ax)
>>> ax = plt.subplot(133)
>>> TM.plot_slice(v_TM, normal='Z', slice_loc=z_slice, ax=ax)
>>> plt.tight_layout()
>>> plt.show()

(png, pdf)

../../_images/discretize-base-BaseTensorMesh-7_02_00.png
BaseTensorMesh.projectEdgeVector(*args, **kwargs)

projectEdgeVector has been deprecated. See project_edge_vector for documentation

BaseTensorMesh.projectFaceVector(*args, **kwargs)

projectFaceVector has been deprecated. See project_face_vector for documentation

BaseTensorMesh.project_edge_vector(edge_vector)

Project vectors onto the edges of the mesh

Given a vector, edge_vector, in cartesian coordinates, this will project it onto the mesh using the tangents

Parameters
edge_vectornumpy.ndarray

edge vector with shape (n_edges, dim)

Returns
numpy.ndarray

projected edge vector, (n_edges, )

BaseTensorMesh.project_face_vector(face_vector)

Project vectors onto the faces of the mesh.

Given a vector, face_vector, in cartesian coordinates, this will project it onto the mesh using the normals

Parameters
face_vectornumpy.ndarray

face vector with shape (n_faces, dim)

Returns
numpy.ndarray

projected face vector, (n_faces, )

BaseTensorMesh.save(file_name='mesh.json', verbose=False, **kwargs)

Save the mesh to json :param str file: file_name for saving the casing properties :param str directory: working directory for saving the file

BaseTensorMesh.serialize(include_class=True, save_dynamic=False, **kwargs)

Serializes a HasProperties instance to dictionary

This uses the Property serializers to serialize all Property values to a JSON-compatible dictionary. Properties that are undefined are not included. If the HasProperties instance contains a reference to itself, a properties.SelfReferenceError will be raised.

Parameters:

  • include_class - If True (the default), the name of the class will also be saved to the serialized dictionary under key '__class__'

  • save_dynamic - If True, dynamic properties are written to the serialized dict (default: False).

  • Any other keyword arguments will be passed through to the Property serializers.

BaseTensorMesh.toVTK(models=None)

Convert this mesh object to it’s proper VTK or pyvista data object with the given model dictionary as the cell data of that dataset.

Parameters
modelsdict(numpy.ndarray)

Name(‘s) and array(‘s). Match number of cells

BaseTensorMesh.to_omf(models=None)

Convert this mesh object to it’s proper omf data object with the given model dictionary as the cell data of that dataset.

Parameters
modelsdict(numpy.ndarray)

Name(‘s) and array(‘s). Match number of cells

BaseTensorMesh.to_vtk(models=None)

Convert this mesh object to it’s proper VTK or pyvista data object with the given model dictionary as the cell data of that dataset.

Parameters
modelsdict(numpy.ndarray)

Name(‘s) and array(‘s). Match number of cells

BaseTensorMesh.validate()

Call all registered class validator methods

These are all methods decorated with @properties.validator. Validator methods are expected to raise a ValidationError if they fail.

BaseTensorMesh.writeVTK(file_name, models=None, directory='')

Makes and saves a VTK object from this mesh and given models

Parameters
file_namestr

path to the output vtk file or just its name if directory is specified

modelsdict

dictionary of numpy.array - Name(‘s) and array(‘s). Match number of cells

directorystr

directory where the UBC GIF file lives

BaseTensorMesh.write_vtk(file_name, models=None, directory='')

Makes and saves a VTK object from this mesh and given models

Parameters
file_namestr

path to the output vtk file or just its name if directory is specified

modelsdict

dictionary of numpy.array - Name(‘s) and array(‘s). Match number of cells

directorystr

directory where the UBC GIF file lives