Search code examples
matplotlibphysicscontourtopology

are contour data (X,Y) ordered in a connected clockwise path in matplotlib?


As in the title:

pl = plt.contour(X,Y,Z,levels=[0]) 
paths = pl.allsegs

I wonder how are the data points in paths ordered. Specifically is it oriented clockwise, counterclockwise w.r.t. a guiding center?

The reason I am asking is because matplotlib.pyplot is unaware of torus topology, where edges are identified as the same. connected paths on a torus can look disconnected on an open ended 2D space. I would like to make use of the path datasets to glue together seemingly disconnected segments onto a torus manifold.


Solution

  • I resolved this problem by the following steps:

    1. make use of the torus structure, i.e., Z[0,:] = Z[N,:], Z[:,0] = Z[:,M], where (N,M) are linear dimensions of the matrix.

    2. find allsegs from contour plot for a given level z0:

      pl = plt.contour(X,Y,Z,levels=[z0]) segs = pl.allsegs[0]

    3. segs[i] contains the coordinates of a given contour whose two end points either: (1) are the same, then segs[i] is a closed contour in the domain set by X and Y. (2) are different and therefore must terminate at either of the four edges of the domain. In this case, there must exist at least another open contour whose end points pair-up with the current open contour. This pair identification is achieved by calculating their distance on a torus, which is defined as the smallest of |r1-r2|, |r1-r2 +/- period_along_x|, |r1-r2 +/- period_along_y|

    4. ultimately the numerical algorithm boils down to identifying closed contours as well as identifying pairs of matching end points satisfying torus topology.

    Three example solutions are shown in the attached figure.

    Four open contours, but it is one contour on a torus, where end points are identified as pairs by color

    Two closed contours, where two end points of each contour are identical