Movatterモバイル変換


[0]ホーム

URL:


You are reading an old version of the documentation (v2.0.0). For the latest version seehttps://matplotlib.org/stable/api/tri_api.html
matplotlib

Navigation


Travis-CI:

Table Of Contents

Related Topics

This Page

Quick search

triangular grids

matplotlib.tri

Unstructured triangular grid functions.

classmatplotlib.tri.Triangulation(x,y,triangles=None,mask=None)

An unstructured triangular grid consisting of npoints points andntri triangles. The triangles can either be specified by the useror automatically generated using a Delaunay triangulation.

Parameters:

x, y : array_like of shape (npoints)

Coordinates of grid points.

triangles : integer array_like of shape (ntri, 3), optional

For each triangle, the indices of the three points that makeup the triangle, ordered in an anticlockwise manner. If notspecified, the Delaunay triangulation is calculated.

mask : boolean array_like of shape (ntri), optional

Which triangles are masked out.

Notes

For a Triangulation to be valid it must not have duplicate points,triangles formed from colinear points, or overlapping triangles.

Attributes

edges 
neighbors 
is_delaunay(bool) Whether the Triangulation is a calculated Delaunay triangulation (wheretriangles was not specified) or not.
calculate_plane_coefficients(z)

Calculate plane equation coefficients for all unmasked triangles fromthe point (x,y) coordinates and specified z-array of shape (npoints).Returned array has shape (npoints,3) and allows z-value at (x,y)position in triangle tri to be calculated usingz = array[tri,0]*x + array[tri,1]*y + array[tri,2].

edges

Return integer array of shape (nedges,2) containing all edges ofnon-masked triangles.

Each edge is the start point index and end point index. Eachedge (start,end and end,start) appears only once.

staticget_from_args_and_kwargs(*args,**kwargs)

Return a Triangulation object from the args and kwargs, andthe remaining args and kwargs with the consumed values removed.

There are two alternatives: either the first argument is aTriangulation object, in which case it is returned, or the argsand kwargs are sufficient to create a new Triangulation toreturn. In the latter case, see Triangulation.__init__ forthe possible args and kwargs.

get_masked_triangles()

Return an array of triangles that are not masked.

get_trifinder()

Return the defaultmatplotlib.tri.TriFinder of thistriangulation, creating it if necessary. This allows the sameTriFinder object to be easily shared.

neighbors

Return integer array of shape (ntri,3) containing neighbortriangles.

For each triangle, the indices of the three triangles thatshare the same edges, or -1 if there is no such neighboringtriangle. neighbors[i,j] is the triangle that is the neighborto the edge from point index triangles[i,j] to point indextriangles[i,(j+1)%3].

set_mask(mask)

Set or clear the mask array. This is either None, or a booleanarray of shape (ntri).

classmatplotlib.tri.TriFinder(triangulation)

Abstract base class for classes used to find the triangles of aTriangulation in which (x,y) points lie.

Rather than instantiate an object of a class derived from TriFinder, it isusually better to use the functionmatplotlib.tri.Triangulation.get_trifinder().

Derived classes implement __call__(x,y) where x,y are array_like pointcoordinates of the same shape.

classmatplotlib.tri.TrapezoidMapTriFinder(triangulation)

Bases:matplotlib.tri.trifinder.TriFinder

TriFinder class implemented using the trapezoidmap algorithm from the book “Computational Geometry, Algorithms andApplications”, second edition, by M. de Berg, M. van Kreveld, M. Overmarsand O. Schwarzkopf.

The triangulation must be valid, i.e. it must not have duplicate points,triangles formed from colinear points, or overlapping triangles. Thealgorithm has some tolerance to triangles formed from colinear points, butthis should not be relied upon.

__call__(x,y)

Return an array containing the indices of the triangles in which thespecified x,y points lie, or -1 for points that do not lie within atriangle.

x,y are array_like x and y coordinates of the same shape and anynumber of dimensions.

Returns integer array with the same shape andx andy.

classmatplotlib.tri.TriInterpolator(triangulation,z,trifinder=None)

Abstract base class for classes used to perform interpolation ontriangular grids.

Derived classes implement the following methods:

  • __call__(x,y) ,where x, y are array_like point coordinates of the same shape, andthat returns a masked array of the same shape containing theinterpolated z-values.
  • gradient(x,y) ,where x, y are array_like point coordinates of the sameshape, and that returns a list of 2 masked arrays of the same shapecontaining the 2 derivatives of the interpolator (derivatives ofinterpolated z values with respect to x and y).
classmatplotlib.tri.LinearTriInterpolator(triangulation,z,trifinder=None)

Bases:matplotlib.tri.triinterpolate.TriInterpolator

A LinearTriInterpolator performs linear interpolation on a triangular grid.

Each triangle is represented by a plane so that an interpolated value atpoint (x,y) lies on the plane of the triangle containing (x,y).Interpolated values are therefore continuous across the triangulation, buttheir first derivatives are discontinuous at edges between triangles.

Parameters:

triangulation :Triangulation object

The triangulation to interpolate over.

z : array_like of shape (npoints,)

Array of values, defined at grid points, to interpolate between.

trifinder :TriFinder object, optional

If this is not specified, the Triangulation’s default TriFinder willbe used by callingmatplotlib.tri.Triangulation.get_trifinder().

Methods

__call__ (x, y)( Returns interpolated values at x,y points)
gradient (x, y)(Returns interpolated derivatives at x,y points)
__call__(x,y)

Returns a masked array containing interpolated values at the specifiedx,y points.

Parameters:

x, y : array-like

x and y coordinates of the same shape and any number ofdimensions.

Returns:

z : np.ma.array

Masked array of the same shape asx andy ; valuescorresponding to (x,y) points outside of the triangulationare masked out.

gradient(x,y)

Returns a list of 2 masked arrays containing interpolated derivativesat the specified x,y points.

Parameters:

x, y : array-like

x and y coordinates of the same shape and any number ofdimensions.

Returns:

dzdx, dzdy : np.ma.array

2 masked arrays of the same shape asx andy ; valuescorresponding to (x,y) points outside of the triangulationare masked out.The first returned array contains the values of and the second those of.

classmatplotlib.tri.CubicTriInterpolator(triangulation,z,kind='min_E',trifinder=None,dz=None)

Bases:matplotlib.tri.triinterpolate.TriInterpolator

A CubicTriInterpolator performs cubic interpolation on triangular grids.

In one-dimension - on a segment - a cubic interpolating function isdefined by the values of the function and its derivative at both ends.This is almost the same in 2-d inside a triangle, except that the valuesof the function and its 2 derivatives have to be defined at each trianglenode.

The CubicTriInterpolator takes the value of the function at each node -provided by the user - and internally computes the value of thederivatives, resulting in a smooth interpolation.(As a special feature, the user can also impose the value of thederivatives at each node, but this is not supposed to be the commonusage.)

Parameters:

triangulation :Triangulation object

The triangulation to interpolate over.

z : array_like of shape (npoints,)

Array of values, defined at grid points, to interpolate between.

kind : {‘min_E’, ‘geom’, ‘user’}, optional

Choice of the smoothing algorithm, in order to computethe interpolant derivatives (defaults to ‘min_E’):

  • if ‘min_E’: (default) The derivatives at each node is computedto minimize a bending energy.
  • if ‘geom’: The derivatives at each node is computed as aweighted average of relevant triangle normals. To be used forspeed optimization (large grids).
  • if ‘user’: The user provides the argumentdz, no computationis hence needed.

trifinder :TriFinder object, optional

If not specified, the Triangulation’s default TriFinder willbe used by callingmatplotlib.tri.Triangulation.get_trifinder().

dz : tuple of array_likes (dzdx, dzdy), optional

Used only ifkind =’user’. In this casedz must be provided as(dzdx, dzdy) where dzdx, dzdy are arrays of the same shape asz andare the interpolant first derivatives at thetriangulation points.

Notes

This note is a bit technical and details the way aCubicTriInterpolator computes a cubicinterpolation.

The interpolation is based on a Clough-Tocher subdivision scheme ofthetriangulation mesh (to make it clearer, each triangle of thegrid will be divided in 3 child-triangles, and on each child trianglethe interpolated function is a cubic polynomial of the 2 coordinates).This technique originates from FEM (Finite Element Method) analysis;the element used is a reduced Hsieh-Clough-Tocher (HCT)element. Its shape functions are described in[R1].The assembled function is guaranteed to be C1-smooth, i.e. it iscontinuous and its first derivatives are also continuous (thisis easy to show inside the triangles but is also true when crossing theedges).

In the default case (kind =’min_E’), the interpolant minimizes acurvature energy on the functional space generated by the HCT elementshape functions - with imposed values but arbitrary derivatives at eachnode. The minimized functional is the integral of the so-called totalcurvature (implementation based on an algorithm from[R2] - PCG sparsesolver):

If the casekind =’geom’ is chosen by the user, a simple geometricapproximation is used (weighted average of the triangle normalvectors), which could improve speed on very large grids.

References

[R1](1,2) Michel Bernadou, Kamal Hassan, “Basis functions for generalHsieh-Clough-Tocher triangles, complete or reduced.”,International Journal for Numerical Methods in Engineering,17(5):784 - 789. 2.01.
[R2](1,2) C.T. Kelley, “Iterative Methods for Optimization”.

Methods

__call__ (x, y)( Returns interpolated values at x,y points)
gradient (x, y)(Returns interpolated derivatives at x,y points)
__call__(x,y)

Returns a masked array containing interpolated values at the specifiedx,y points.

Parameters:

x, y : array-like

x and y coordinates of the same shape and any number ofdimensions.

Returns:

z : np.ma.array

Masked array of the same shape asx andy ; valuescorresponding to (x,y) points outside of the triangulationare masked out.

gradient(x,y)

Returns a list of 2 masked arrays containing interpolated derivativesat the specified x,y points.

Parameters:

x, y : array-like

x and y coordinates of the same shape and any number ofdimensions.

Returns:

dzdx, dzdy : np.ma.array

2 masked arrays of the same shape asx andy ; valuescorresponding to (x,y) points outside of the triangulationare masked out.The first returned array contains the values of and the second those of.

Examples

An example of effective application is shown below (plot of thedirection of the vector field derivated from a known potential field):

(Source code,png,pdf)

../_images/trigradient_demo1.png
classmatplotlib.tri.TriRefiner(triangulation)

Abstract base class for classes implementing mesh refinement.

A TriRefiner encapsulates a Triangulation object and provides tools formesh refinement and interpolation.

Derived classes must implements:

  • refine_triangulation(return_tri_index=False,**kwargs) , wherethe optional keyword argumentskwargs are defined in eachTriRefiner concrete implementation, and which returns :

    • a refined triangulation
    • optionally (depending onreturn_tri_index), for eachpoint of the refined triangulation: the index ofthe initial triangulation triangle to which it belongs.
  • refine_field(z,triinterpolator=None,**kwargs) , where:

    • z array of field values (to refine) defined at the basetriangulation nodes
    • triinterpolator is aTriInterpolator (optional)
    • the other optional keyword argumentskwargs are defined ineach TriRefiner concrete implementation

    and which returns (as a tuple) a refined triangular mesh and theinterpolated values of the field at the refined triangulation nodes.

classmatplotlib.tri.UniformTriRefiner(triangulation)

Bases:matplotlib.tri.trirefine.TriRefiner

Uniform mesh refinement by recursive subdivisions.

Parameters:

triangulation :Triangulation

The encapsulated triangulation (to be refined)

refine_field(z,triinterpolator=None,subdiv=3)

Refines a field defined on the encapsulated triangulation.

Returnsrefi_tri (refined triangulation),refi_z (interpolatedvalues of the field at the node of the refined triangulation).

Parameters:

z : 1d-array-like of lengthn_points

Values of the field to refine, defined at the nodes of theencapsulated triangulation. (n_points is the number of pointsin the initial triangulation)

triinterpolator :TriInterpolator, optional

Interpolator used for field interpolation. If not specified,aCubicTriInterpolator willbe used.

subdiv : integer, optional

Recursion level for the subdivision. Defaults to 3.Each triangle will be divided into4**subdiv child triangles.

Returns:

refi_tri :Triangulation object

The returned refined triangulation

refi_z : 1d array of length:refi_tri node count.

The returned interpolated field (atrefi_tri nodes)

Examples

The main application of this method is to plot high-qualityiso-contours on a coarse triangular grid (e.g., triangulation builtfrom relatively sparse test data):

(Source code,png,pdf)

../_images/tricontour_smooth_user2.png
refine_triangulation(return_tri_index=False,subdiv=3)

Computes an uniformly refined triangulationrefi_triangulation ofthe encapsulatedtriangulation.

This function refines the encapsulated triangulation by splitting eachfather triangle into 4 child sub-triangles built on the edges midsidenodes, recursively (level of recursionsubdiv).In the end, each triangle is hence divided into4**subdivchild triangles.The default value forsubdiv is 3 resulting in 64 refinedsubtriangles for each triangle of the initial triangulation.

Parameters:

return_tri_index : boolean, optional

Boolean indicating whether an index table indicating the fathertriangle index of each point will be returned. Default valueFalse.

subdiv : integer, optional

Recursion level for the subdivision. Defaults value 3.Each triangle will be divided into4**subdiv child triangles.

Returns:

refi_triangulation :Triangulation

The returned refined triangulation

found_index : array-like of integers

Index of the initial triangulation containing triangle, for eachpoint ofrefi_triangulation.Returned only ifreturn_tri_index is set to True.

classmatplotlib.tri.TriAnalyzer(triangulation)

Define basic tools for triangular mesh analysis and improvement.

A TriAnalizer encapsulates aTriangulationobject and provides basic tools for mesh analysis and mesh improvement.

Parameters:

triangulation :Triangulation object

The encapsulated triangulation to analyze.

Attributes

scale_factors 
circle_ratios(rescale=True)

Returns a measure of the triangulation triangles flatness.

The ratio of the incircle radius over the circumcircle radius is awidely used indicator of a triangle flatness.It is always<=0.5 and==0.5 only for equilateraltriangles. Circle ratios below 0.01 denote very flat triangles.

To avoid unduly low values due to a difference of scale between the 2axis, the triangular mesh can first be rescaled to fit inside a unitsquare withscale_factors (Only ifrescale is True, which isits default value).

Parameters:

rescale : boolean, optional

If True, a rescaling will be internally performed (based onscale_factors, so that the (unmasked) triangles fitexactly inside a unit square mesh. Default is True.

Returns:

circle_ratios : masked array

Ratio of the incircle radius over thecircumcircle radius, for each ‘rescaled’ triangle of theencapsulated triangulation.Values corresponding to masked triangles are masked out.

get_flat_tri_mask(min_circle_ratio=0.01,rescale=True)

Eliminates excessively flat border triangles from the triangulation.

Returns a masknew_mask which allows to clean the encapsulatedtriangulation from its border-located flat triangles(according to theircircle_ratios()).This mask is meant to be subsequently applied to the triangulationusingmatplotlib.tri.Triangulation.set_mask() .new_mask is an extension of the initial triangulation maskin the sense that an initially masked triangle will remain masked.

Thenew_mask array is computed recursively ; at each step flattriangles are removed only if they share a side with the currentmesh border. Thus no new holes in the triangulated domain will becreated.

Parameters:

min_circle_ratio : float, optional

Border triangles with incircle/circumcircle radii ratio r/R willbe removed if r/R <min_circle_ratio. Default value: 0.01

rescale : boolean, optional

If True, a rescaling will first be internally performed (based onscale_factors ), so that the (unmasked) triangles fitexactly inside a unit square mesh. This rescaling accounts for thedifference of scale which might exist between the 2 axis. Default(and recommended) value is True.

Returns:

new_mask : array-like of booleans

Mask to apply to encapsulated triangulation.All the initially masked triangles remain masked in thenew_mask.

Notes

The rationale behind this function is that a Delaunaytriangulation - of an unstructured set of points - sometimes containsalmost flat triangles at its border, leading to artifacts in plots(especially for high-resolution contouring).Masked with computednew_mask, the encapsulatedtriangulation would contain no more unmasked border triangleswith a circle ratio belowmin_circle_ratio, thus improving themesh quality for subsequent plots or interpolation.

Examples

Please refer to the following illustrating example:

(Source code,png,pdf)

../_images/tricontour_smooth_delaunay1.png
scale_factors

Factors to rescale the triangulation into a unit square.

Returnsk, tuple of 2 scale factors.

Returns:

k : tuple of 2 floats (kx, ky)

Tuple of floats that would rescale the triangulation :[triangulation.x*kx,triangulation.y*ky]fits exactly inside a unit square.

© Copyright 2002 - 2012 John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the Matplotlib development team; 2012 - 2016 The Matplotlib development team. Last updated on Feb 20, 2017. Created usingSphinx 1.5.2.

[8]ページ先頭

©2009-2026 Movatter.jp