polylx package

Submodules

polylx.core module

Python module to visualize and analyze digitized 2D microstructures.

@author: Ondrej Lexa

Examples:
>>> from polylx import *
>>> g = Grains.from_shp()
>>> b = g.boundaries()
class polylx.core.Boundaries(shapes, classification=None)

Bases: polylx.core.PolySet

Class to store set of Boundaries objects

class polylx.core.Boundary(shape, name='None-None', fid=0)

Bases: polylx.core.PolyShape

Boundary class to store polyline boundary geometry

A two-dimensional linear ring.

chaikin(**kwargs)

Chaikin corner-cutting smoothing algorithm.

Keywords:
repeat: Number of repetitions. Default 2
copy()
cov()

shape_method: cov

Short and long axes are calculated from eigenvalue analysis of coordinate covariance matrix.

maxferet()

shape_method: maxferet

Long axis is defined as the maximum caliper of the polyline. Short axis correspond to caliper orthogonal to long axis. Center coordinates are set to centroid of polyline.

plot(**kwargs)

View Boundary geometry on figure.

regularize(**kwargs)

Boundary vertices regularization.

Returns Boundary object defined by vertices regularly distributed along original Boundary.

Keywords:
N: Number of vertices. Default 128. length: approx. length of segments. Default None
show(**kwargs)

Show plot of Boundary objects.

vw(**kwargs)

Visvalingam-Whyatt simplification.

The Visvalingam-Whyatt algorithm eliminates points based on their effective area. A points effective area is defined as the change in total area of the polygon by adding or removing that point.

Keywords:
threshold: Allowed total boundary length change in percents. Default 1
hull

Returns array of vertices on convex hull of boundary geometry.

xy

Returns array of vertex coordinate pair.

class polylx.core.Grain(shape, name='None', fid=0)

Bases: polylx.core.PolyShape

Grain class to store polygonal grain geometry

A two-dimensional grain bounded by a linear ring with non-zero area. It may have one or more negative-space “holes” which are also bounded by linear rings.

Properties:
shape: shapely.geometry.polygon.Polygon object name: string with phase name. Default “None” fid: feature id. Default 0 shape_method: Method to calculate axes and orientation
chaikin(**kwargs)

Chaikin corner-cutting smoothing algorithm.

Keywords:
repeat: Number of repetitions. Default 2
copy()
cov()

shape_method: cov

Short and long axes are calculated from eigenvalue analysis of coordinate covariance matrix. Center coordinates are set to centroid of exterior.

direct()

shape_method: direct

Short, long axes and centre coordinates are calculated from direct least-square ellipse fitting. If direct fitting is not possible silently fallback to moment. Center coordinates are set to centre of fitted ellipse.

classmethod from_coords(x, y, name='None', fid=0)

Create Grain from coordinate arrays

Example:
>>> g=Grain.from_coords([0,0,2,2],[0,1,1,0])
>>> g.xy
array([[ 0.,  0.,  2.,  2.,  0.],
       [ 0.,  1.,  1.,  0.,  0.]])
maee()

shape_method: maee

Short and long axes are calculated from minimum volume enclosing ellipse. The solver is based on Khachiyan Algorithm, and the final solution is different from the optimal value by the pre-specified amount of tolerance of EAD/100. Center coordinates are set to centre of fitted ellipse.

maxferet()

shape_method: maxferet

Long axis is defined as the maximum caliper of the polygon. Short axis correspond to caliper orthogonal to long axis. Center coordinates are set to centroid of exterior.

minbox()

shape_method: minbox

Short and long axes are claculated as widht and height of smallest area enclosing box. Center coordinates are set to centre of box.

minferet()

shape_method: minferet

Short axis is defined as the minimum caliper of the polygon. Long axis correspond to caliper orthogonal to short axis. Center coordinates are set to centroid of exterior.

moment()

shape_method: moment

Short and long axes are calculated from area moments of inertia. Center coordinates are set to centroid. If moment fitting failed silently fallback to maxferet. Center coordinates are set to centroid.

plot(**kwargs)

Plot Grain geometry on figure.

Note that plotted ellipse reflects actual shape method

regularize(**kwargs)

Grain vertices regularization.

Returns Grain object defined by vertices regularly distributed along boundaries of original Grain.

Keywords:
N: Number of vertices. Default 128. length: approx. length of segments. Default None
shape_vector(**kwargs)

Returns shape (feature) vector.

Shape (feature) vector is calculated from Fourier descriptors (FD) to index the shape. To achieve rotation invariance, phase information of the FDs are ignored and only the magnitudes |FDn| are used. Scale invariance is achieved by dividing the magnitudes by the DC component, i.e., |FD0|. Since centroid distance is a real value function, only half of the FDs are needed to index the shape.

Keywords:
N: number of points to regularize shape. Default 128
Routine return N/2 of FDs
show(**kwargs)

Show plot of Grain objects.

spline(**kwargs)

Spline based smoothing of grains.

Keywords:
densify: factor for geometry densification. Default 5
vw(**kwargs)

Visvalingam-Whyatt simplification.

The Visvalingam-Whyatt algorithm eliminates points based on their effective area. A points effective area is defined as the change in total area of the polygon by adding or removing that point.

Keywords:
threshold: Allowed total boundary length change in percents. Default 1
cdir

Returns centroid-vertex directions of grain exterior

cdist

Returns centroid-vertex distances of grain exterior

ead

Returns equal area diameter of grain

hull

Returns array of vertices on convex hull of grain geometry.

interiors

Returns list of arrays of vertex coordinate pair of interiors.

nholes

Returns number of holes (shape interiors)

xy

Returns array of vertex coordinate pair.

Note that only vertexes from exterior boundary are returned. For interiors use interiors property.

class polylx.core.Grains(shapes, classification=None)

Bases: polylx.core.PolySet

Class to store set of Grains objects

boundaries(T=None)

Create Boundaries from Grains.

Example:
>>> g = Grains.from_shp()
>>> b = g.boundaries()
classmethod from_shp(filename='/home/docs/checkouts/readthedocs.org/user_builds/polylx/checkouts/develop/polylx/example/sg2.shp', phasefield='phase', phase='None')

Create Grains from ESRI shapefile.

Args:

filename: filename of shapefile. Default sg2.shp from examples phasefield: name of attribute in shapefile that

holds names of grains or None. Default “phase”.

phase: value used for grain phase when phasefield is None

shape_vector(**kwargs)

Returns array of shape (feature) vectors.

Keywords:
N: number of points to regularize shape. Default 128
Routine return N/2 of FDs
ead

Returns array of equal area diameters of grains

nholes

Returns array of number of holes (shape interiors)

class polylx.core.PolySet(shapes, classification=None)

Bases: object

Base class to store set of Grains or Boundaries objects

Properties:
polys: list of objects extent: tuple of (xmin, ymin, xmax, ymax)
affine_transform(matrix)

Returns a transformed geometry using an affine transformation matrix. The matrix is provided as a list or tuple with 6 items: [a, b, d, e, xoff, yoff] which defines the equations for the transformed coordinates: x’ = a * x + b * y + xoff y’ = d * x + e * y + yoff

agg(*pairs)

Returns concatenated result of multiple aggregations (different aggregation function for different attributes) based on actual classification. For single aggregation function use directly pandas groups, e.g. g.groups(‘lao’, ‘sao’).agg(circular.mean)

Example:
>>> g.agg('area', np.sum, 'ead', np.mean, 'lao', circular.mean)
                area       ead        lao
class
ksp         2.443733  0.089710  76.875488
pl          1.083516  0.060629  94.197847
qtz         1.166097  0.068071  74.320337
barplot(val, **kwargs)

Plot seaborn swarmplot.

bootstrap(num=100, size=None)

Bootstrap random sample generator.

Args:
num: number of boostraped samples. Default 100 size: size of bootstraped samples. Default number of objects.
Examples:
>>> bsmean = np.mean([gs.ead.mean() for gs in g.bootstrap()])
boundary_segments()

Create Boundaries from object boundary segments.

Example:
>>> g = Grains.from_shp()
>>> b = g.boundary_segments()
boxplot(val, **kwargs)

Plot seaborn boxplot.

class_iter()
classify(*args, **kwargs)

Define classification of objects.

When no aruments are provided, default unique classification based on name attribute is used.

Args:
vals: name of attribute (str) used for classification
or array of values
Keywords:

label: used as classification label when vals is array k: number of classes for continuous values rule: type of classification

‘unique’: unique value mapping (for discrete values) ‘equal’: k equaly spaced bins (for continuos values) ‘user’: bins edges defined by array k (for continuos values) ‘natural’: natural breaks. Default rule.

(beware not always unique solution)

‘jenks’: fischer jenks scheme

cmap: matplotlib colormap. Default ‘viridis’

Examples:
>>> g.classify('name', rule='unique')
>>> g.classify('ar', rule='jenks', k=5)
clip(other)
clipstrap(num=100, f=0.3)

Bootstrap random rectangular clip generator.

Args:
num: number of boostraped samples. Default 100 f: area fraction clipped from original shape. Default 0.3
Examples:
>>> csmean = np.mean([gs.ead.mean() for gs in g.clipstrap()])
countplot(**kwargs)

Plot seaborn countplot.

df(*attrs)

Returns pandas.DataFrame of object attributes.

Example:
>>> g.df('ead', 'ar')
feret(angle=0)

Returns array of feret diameters for given angle.

Args:
angle: Caliper angle. Default 0
get(attr)

Returns pandas.Series of object attribute.

Example:
>>> g.get('ead')
get_class(key)
getindex(name)

Return the indices of the objects with given name.

gridsplit(m=1, n=1)

Rectangular split generator.

Args:
m, n: number of rows and columns to split.
Examples:
>>> smean = np.mean([gs.ead.mean() for gs in g.gridsplit(6, 8)])
groups(*attrs)

Returns pandas.GroupBy of object attributes.

Note that grouping is based on actual classification.

Example:
>>> g.classify('ar', 'natural')
>>> g.groups('ead').mean()
                      ead
class
1.01765-1.31807  0.067772
1.31807-1.5445   0.076042
1.5445-1.83304   0.065900
1.83304-2.36773  0.073338
2.36773-12.1571  0.084016
nndist(**kwargs)
paror(angles=range(0, 180), normalized=True)

Returns paror function values. When normalized maximum value is 1 and correspond to max feret.

Args:
angles: iterable angle values. Defaut range(180) normalized: whether to normalize values. Defaut True
plot(**kwargs)

Plot set of Grains or Boundaries objects.

Keywords:
show: If True matplotlib show is called. Default True alpha: transparency. Default 0.8 pos: legend position “top”, “right” or “none”. Defalt “auto” ncol: number of columns for legend. legend: Show legend. Default True show_fid: Show FID of objects. Default False show_index: Show index of objects. Default False

When show=False, returns matplotlib axes object.

proj(angle=0)

Returns array of cumulative projection of object for given angle. Args:

angle: angle of projection line
regularize(**kwargs)
rose(**kwargs)

Plot polar histogram of Grains or Boundaries orientations

Keywords:
show: If True matplotlib show is called. Default True attr: property used for orientation. Default ‘lao’ bins: number of bins weights: if provided histogram is weighted density: True for probability density otherwise counts grid: True to show grid

When show=False, returns matplotlib axes object.

rotate(angle, **kwargs)

Returns a rotated geometry on a 2D plane. The angle of rotation can be specified in either degrees (default) or radians by setting use_radians=True. Positive angles are counter-clockwise and negative are clockwise rotations. The point of origin can be a keyword ‘center’ for the object bounding box center (default), ‘centroid’ for the geometry’s centroid, or coordinate tuple (x0, y0) for fixed point.

savefig(**kwargs)

Save grains or boudaries plot to file.

Args:
filename: file to save figure. Default “figure.png” dpi: DPI of image. Default 150 See plot for other kwargs
scale(**kwargs)

Returns a scaled geometry, scaled by factors along each dimension. The point of origin can be a keyword ‘center’ for the object bounding box center (default), ‘centroid’ for the geometry’s centroid, or coordinate tuple (x0, y0) for fixed point. Negative scale factors will mirror or reflect coordinates.

simplify(method='vw', **kwargs)
skew(**kwargs)

Returns a skewed geometry, sheared by angles ‘xs’ along x and ‘ys’ along y direction. The shear angle can be specified in either degrees (default) or radians by setting use_radians=True. The point of origin can be a keyword ‘center’ for the object bounding box center (default), ‘centroid’ for the geometry’s centroid, or a coordinate tuple (x0, y0) for fixed point.

smooth(method='chaikin', **kwargs)
surfor(angles=range(0, 180), normalized=True)

Returns surfor function values. When normalized maximum value is 1 and correspond to max feret.

Args:
angles: iterable angle values. Defaut range(180) normalized: whether to normalize values. Defaut True
swarmplot(val, **kwargs)

Plot seaborn swarmplot.

translate(**kwargs)

Returns a translated geometry shifted by offsets ‘xoff’ along x and ‘yoff’ along y direction.

ar

Returns array of axial ratios

Note that axial ratio is calculated from long and short axes calculated by actual shape method.

area

Return array of areas of the objects. For boundary returns 0.

centroid

Returns the 2D array of geometric centers of the objects

class_names
extent

Returns minimum bounding region (minx, miny, maxx, maxy) of all objects

fid

Return array of fids of objects.

height

Returns height of extent.

la

Return array of long axes of objects according to shape_method.

lao

Return array of long axes of objects according to shape_method

length

Return array of lengths of the objects.

ma

Returns mean axis

Return array of mean axes calculated by actual shape method.

name

Return list of names of the objects.

names

Returns list of unique object names.

representative_point

Returns a 2D array of cheaply computed points that are guaranteed to be within the objects.

sa

Return array of long axes of objects according to shape_method

sao

Return array of long axes of objects according to shape_method

shape

Return list of shapely objects.

shape_method

Set or returns shape methods of all objects.

width

Returns width of extent.

class polylx.core.PolyShape(shape, name, fid)

Bases: object

Base class to store polygon or polyline

Properties:
shape: shapely.geometry object name: name of polygon or polyline. fid: feature id

Note that all properties from shapely.geometry object are inherited.

affine_transform(matrix)

Returns a transformed geometry using an affine transformation matrix. The matrix is provided as a list or tuple with 6 items: [a, b, d, e, xoff, yoff] which defines the equations for the transformed coordinates: x’ = a * x + b * y + xoff y’ = d * x + e * y + yoff

boundary_segments()

Create Boundaries from object boundary segments.

Example:
>>> g = Grains.from_shp()
>>> b = g.boundaries()
>>> bs1 = g[10].boundary_segments()
>>> bs2 = b[10].boundary_segments()
contains(other)

Returns True if the geometry contains the other, else False

crosses(other)

Returns True if the geometries cross, else False

difference(other)

Returns the difference of the geometries

disjoint(other)

Returns True if geometries are disjoint, else False

distance(other)

Unitless distance to other geometry (float)

dp(**kwargs)

Douglas–Peucker simplification.

Keywords:
tolerance: All points in the simplified object will be within the tolerance distance of the original geometry. Default Auto
equals(other)

Returns True if geometries are equal, else False

equals_exact(other, tolerance)

Returns True if geometries are equal to within a specified tolerance

feret(angle=0)

Returns the ferret diameter for given angle.

Args:
angle: angle of caliper rotation
intersection(other)

Returns the intersection of the geometries

intersects(other)

Returns True if geometries intersect, else False

overlaps(other)

Returns True if geometries overlap, else False

paror(angles=range(0, 180), normalized=True)

Returns paror function values. When normalized maximum value is 1 and correspond to max feret.

Args:
angles: iterable angle values. Defaut range(180) normalized: whether to normalize values. Defaut True
proj(angle=0)

Returns the cumulative projection of object for given angle.

Args:
angle: angle of projection line
relate(other)

Returns the DE-9IM intersection matrix for the two geometries (string)

rotate(angle, **kwargs)

Returns a rotated geometry on a 2D plane. The angle of rotation can be specified in either degrees (default) or radians by setting use_radians=True. Positive angles are counter-clockwise and negative are clockwise rotations. The point of origin can be a keyword ‘center’ for the object bounding box center (default), ‘centroid’ for the geometry’s centroid, or coordinate tuple (x0, y0) for fixed point.

scale(**kwargs)

Returns a scaled geometry, scaled by factors along each dimension. The point of origin can be a keyword ‘center’ for the object bounding box center (default), ‘centroid’ for the geometry’s centroid, or coordinate tuple (x0, y0) for fixed point. Negative scale factors will mirror or reflect coordinates.

skew(**kwargs)

Returns a skewed geometry, sheared by angles ‘xs’ along x and ‘ys’ along y direction. The shear angle can be specified in either degrees (default) or radians by setting use_radians=True. The point of origin can be a keyword ‘center’ for the object bounding box center (default), ‘centroid’ for the geometry’s centroid, or a coordinate tuple (x0, y0) for fixed point.

surfor(angles=range(0, 180), normalized=True)

Returns surfor function values. When normalized maximum value is 1 and correspond to max feret.

Args:
angles: iterable angle values. Defaut range(180) normalized: whether to normalize values. Defaut True
symmetric_difference(other)

Returns the symmetric difference of the geometries (Shapely geometry)

touches(other)

Returns True if geometries touch, else False

translate(**kwargs)

Returns a translated geometry shifted by offsets ‘xoff’ along x and ‘yoff’ along y direction.

union(other)

Returns the union of the geometries (Shapely geometry)

within(other)

Returns True if geometry is within the other, else False

ar

Returns axial ratio

Note that axial ratio is calculated from long and short axes calculated by actual shape method.

area

Area of the shape. For boundary returns 0.

bounds

Returns minimum bounding region (minx, miny, maxx, maxy)

centroid

Returns the geometric center of the object

length

Unitless length of the geometry (float)

ma

Returns mean axis

Mean axis is calculated as square root of long axis multiplied by short axis. Both axes are calculated by actual shape method.

representative_point

Returns a cheaply computed point that is guaranteed to be within the object.

shape_method

Returns shape method in use

class polylx.core.Sample(name='')

Bases: object

Class to store both Grains and Boundaries objects

Properties:
g: Grains object b: Boundaries.objects T. networkx.Graph storing grain topology
bids(idx, name=None)
classmethod from_grains(grains, name='')
classmethod from_shp(filename='/home/docs/checkouts/readthedocs.org/user_builds/polylx/checkouts/develop/polylx/example/sg2.shp', phasefield='phase', name='')
neighbors(idx, name=None, inc=False)

Returns array of indexes of neighbouring grains.

If name keyword is provided only neighbours with given name are returned.

neighbors_dist(show=False, name=None)

Return array of nearest neighbors distances.

If name keyword is provided only neighbours with given name are returned. When keyword show is True, plot is produced.

plot(**kwargs)

Plot overlay of Grains and Boundaries of Sample object.

Args:
alpha: Grains transparency. Default 0.8 pos: legend position “top” or “right”. Defalt Auto ncol: number of columns for legend. show_fid: Show FID of objects. Default False show_index: Show index of objects. Default False

Returns matplotlib axes object.

show(**kwargs)

Show plot of Sample objects.

triplets()

polylx.reports module

Generate simple pdf reports. Need rst2pdf tool (https://code.google.com/p/rst2pdf) to be installed.

Created on Wed Feb 5 21:42:54 2014

@author: Ondrej Lexa

Example:

from polylx import * from polylx.reports import Report

g = Grains.from_shp()

fig, ax = plt.subplots() x = np.linspace(-8,8,200) ax.plot(x,np.sin(x))

r = Report(‘Test report’) r.add_chapter(‘Things will start here’) r.savefig(fig, width=‘75%’) r.table([[1,2,120],[2,6,213],[3,4,118]],

title=’Table example’, header=[‘No’,’Val’,’Age’])

r.grainmap(g, width=‘75%’) r.write_pdf()

class polylx.reports.Report(title='Report')

Bases: object

add_chapter(title)
add_section(title)
add_subsection(title)
dataframe(df, title='Table', header=None, format=None, stub_columns=None, widths=None)
figure(filename, width=None, height=None)
fin()
matplotlib_fig(fig, width=None, height=None, bbox_inches='tight', dpi=150)
pagebreak()
plot(g, legend=None, loc='auto', alpha=0.8, dpi=150, width=None, height=None)
table(rows, title='Table', header=None, format=None, stub_columns=None, widths=None)
transition()
write_pdf(file='report.pdf')
write_rst(file='report.rst')

polylx.shapefile module

polylx.utils module

Created on Wed Feb 5 21:42:54 2014

@author: Ondrej Lexa

Example:

from polylx.utils import optimize_colormap g.plot(cmap=optimize_colormap(‘jet’))

# use circular statistics for agg g.groups(‘lao’).agg(circular.csd)

class polylx.utils.Classify(vals, **kwargs)

Bases: object

Class to store classification and colortable for legend

color(key)
set_colortable(cmap)

Create color table for actual classification.

Args:
cmap: matplotlib ListedColormap
sns2cmap(palette)

Create matplotlib ListedColormap from seaborn pallete

Args:
palette: name of seaborn palette or list of colors
labels
class polylx.utils.circular

Bases: object

static R(x)

Length of mean resultant vector

static angdev(x)

Angular deviation

static angskew(x)

Angular skewness

static circdist(x, y)

Pairwise difference around the circle

static circmoment(x, p=1)

Complex centered p-th moment

static csd(x)

Circular standard deviation

static mean(x)

Mean direction

static mean_conf(x, cl=0.95)

Confidence limit on mean

cl confidence on mean between mu-conf..mu+conf

static rho(x)

Mean resultant vector as complex number

static sas(x)

Standardized angular skewness

static var(x)

Circular variance

class polylx.utils.deg

Bases: object

static acos(x)
static asin(x)
static atan(x)
static atan2(x1, x2)
static cos(x)
static sin(x)
static tan(x)
polylx.utils.PolygonPath(polygon)

Constructs a compound matplotlib path from a Shapely object modified from descartes https://pypi.python.org/pypi/descartes

polylx.utils.densify(x, y, repeat=1)
polylx.utils.find_ellipse(x, y)
polylx.utils.fisher_jenks(values, k=5)

Our own version of Jenks Optimal (Natural Breaks) algorithm implemented in Python. The implementation follows the original procedure described in the book, which is a two-phased approach. First phase aims at calculating the variance matrix between the ith and jth element in the data array; Second phase runs iteratively to construct the optimal K-partition from results of K-1 - partitions. Sergio J. Rey Copyright (c) 2009-10 Sergio J. Rey

polylx.utils.fixratio(x, y)
polylx.utils.fixzero(x)
polylx.utils.inertia_moments(x, y, xc, yc)
polylx.utils.natural_breaks(values, k=5, itmax=1000)

natural breaks helper function Sergio J. Rey Copyright (c) 2009-10 Sergio J. Rey

polylx.utils.optimize_colormap(name)

Module contents

class polylx.Grain(shape, name='None', fid=0)

Bases: polylx.core.PolyShape

Grain class to store polygonal grain geometry

A two-dimensional grain bounded by a linear ring with non-zero area. It may have one or more negative-space “holes” which are also bounded by linear rings.

Properties:
shape: shapely.geometry.polygon.Polygon object name: string with phase name. Default “None” fid: feature id. Default 0 shape_method: Method to calculate axes and orientation
chaikin(**kwargs)

Chaikin corner-cutting smoothing algorithm.

Keywords:
repeat: Number of repetitions. Default 2
copy()
cov()

shape_method: cov

Short and long axes are calculated from eigenvalue analysis of coordinate covariance matrix. Center coordinates are set to centroid of exterior.

direct()

shape_method: direct

Short, long axes and centre coordinates are calculated from direct least-square ellipse fitting. If direct fitting is not possible silently fallback to moment. Center coordinates are set to centre of fitted ellipse.

classmethod from_coords(x, y, name='None', fid=0)

Create Grain from coordinate arrays

Example:
>>> g=Grain.from_coords([0,0,2,2],[0,1,1,0])
>>> g.xy
array([[ 0.,  0.,  2.,  2.,  0.],
       [ 0.,  1.,  1.,  0.,  0.]])
maee()

shape_method: maee

Short and long axes are calculated from minimum volume enclosing ellipse. The solver is based on Khachiyan Algorithm, and the final solution is different from the optimal value by the pre-specified amount of tolerance of EAD/100. Center coordinates are set to centre of fitted ellipse.

maxferet()

shape_method: maxferet

Long axis is defined as the maximum caliper of the polygon. Short axis correspond to caliper orthogonal to long axis. Center coordinates are set to centroid of exterior.

minbox()

shape_method: minbox

Short and long axes are claculated as widht and height of smallest area enclosing box. Center coordinates are set to centre of box.

minferet()

shape_method: minferet

Short axis is defined as the minimum caliper of the polygon. Long axis correspond to caliper orthogonal to short axis. Center coordinates are set to centroid of exterior.

moment()

shape_method: moment

Short and long axes are calculated from area moments of inertia. Center coordinates are set to centroid. If moment fitting failed silently fallback to maxferet. Center coordinates are set to centroid.

plot(**kwargs)

Plot Grain geometry on figure.

Note that plotted ellipse reflects actual shape method

regularize(**kwargs)

Grain vertices regularization.

Returns Grain object defined by vertices regularly distributed along boundaries of original Grain.

Keywords:
N: Number of vertices. Default 128. length: approx. length of segments. Default None
shape_vector(**kwargs)

Returns shape (feature) vector.

Shape (feature) vector is calculated from Fourier descriptors (FD) to index the shape. To achieve rotation invariance, phase information of the FDs are ignored and only the magnitudes |FDn| are used. Scale invariance is achieved by dividing the magnitudes by the DC component, i.e., |FD0|. Since centroid distance is a real value function, only half of the FDs are needed to index the shape.

Keywords:
N: number of points to regularize shape. Default 128
Routine return N/2 of FDs
show(**kwargs)

Show plot of Grain objects.

spline(**kwargs)

Spline based smoothing of grains.

Keywords:
densify: factor for geometry densification. Default 5
vw(**kwargs)

Visvalingam-Whyatt simplification.

The Visvalingam-Whyatt algorithm eliminates points based on their effective area. A points effective area is defined as the change in total area of the polygon by adding or removing that point.

Keywords:
threshold: Allowed total boundary length change in percents. Default 1
cdir

Returns centroid-vertex directions of grain exterior

cdist

Returns centroid-vertex distances of grain exterior

ead

Returns equal area diameter of grain

hull

Returns array of vertices on convex hull of grain geometry.

interiors

Returns list of arrays of vertex coordinate pair of interiors.

nholes

Returns number of holes (shape interiors)

xy

Returns array of vertex coordinate pair.

Note that only vertexes from exterior boundary are returned. For interiors use interiors property.

class polylx.Boundary(shape, name='None-None', fid=0)

Bases: polylx.core.PolyShape

Boundary class to store polyline boundary geometry

A two-dimensional linear ring.

chaikin(**kwargs)

Chaikin corner-cutting smoothing algorithm.

Keywords:
repeat: Number of repetitions. Default 2
copy()
cov()

shape_method: cov

Short and long axes are calculated from eigenvalue analysis of coordinate covariance matrix.

maxferet()

shape_method: maxferet

Long axis is defined as the maximum caliper of the polyline. Short axis correspond to caliper orthogonal to long axis. Center coordinates are set to centroid of polyline.

plot(**kwargs)

View Boundary geometry on figure.

regularize(**kwargs)

Boundary vertices regularization.

Returns Boundary object defined by vertices regularly distributed along original Boundary.

Keywords:
N: Number of vertices. Default 128. length: approx. length of segments. Default None
show(**kwargs)

Show plot of Boundary objects.

vw(**kwargs)

Visvalingam-Whyatt simplification.

The Visvalingam-Whyatt algorithm eliminates points based on their effective area. A points effective area is defined as the change in total area of the polygon by adding or removing that point.

Keywords:
threshold: Allowed total boundary length change in percents. Default 1
hull

Returns array of vertices on convex hull of boundary geometry.

xy

Returns array of vertex coordinate pair.

class polylx.Grains(shapes, classification=None)

Bases: polylx.core.PolySet

Class to store set of Grains objects

boundaries(T=None)

Create Boundaries from Grains.

Example:
>>> g = Grains.from_shp()
>>> b = g.boundaries()
classmethod from_shp(filename='/home/docs/checkouts/readthedocs.org/user_builds/polylx/checkouts/develop/polylx/example/sg2.shp', phasefield='phase', phase='None')

Create Grains from ESRI shapefile.

Args:

filename: filename of shapefile. Default sg2.shp from examples phasefield: name of attribute in shapefile that

holds names of grains or None. Default “phase”.

phase: value used for grain phase when phasefield is None

shape_vector(**kwargs)

Returns array of shape (feature) vectors.

Keywords:
N: number of points to regularize shape. Default 128
Routine return N/2 of FDs
ead

Returns array of equal area diameters of grains

nholes

Returns array of number of holes (shape interiors)

class polylx.Boundaries(shapes, classification=None)

Bases: polylx.core.PolySet

Class to store set of Boundaries objects

class polylx.Sample(name='')

Bases: object

Class to store both Grains and Boundaries objects

Properties:
g: Grains object b: Boundaries.objects T. networkx.Graph storing grain topology
bids(idx, name=None)
classmethod from_grains(grains, name='')
classmethod from_shp(filename='/home/docs/checkouts/readthedocs.org/user_builds/polylx/checkouts/develop/polylx/example/sg2.shp', phasefield='phase', name='')
neighbors(idx, name=None, inc=False)

Returns array of indexes of neighbouring grains.

If name keyword is provided only neighbours with given name are returned.

neighbors_dist(show=False, name=None)

Return array of nearest neighbors distances.

If name keyword is provided only neighbours with given name are returned. When keyword show is True, plot is produced.

plot(**kwargs)

Plot overlay of Grains and Boundaries of Sample object.

Args:
alpha: Grains transparency. Default 0.8 pos: legend position “top” or “right”. Defalt Auto ncol: number of columns for legend. show_fid: Show FID of objects. Default False show_index: Show index of objects. Default False

Returns matplotlib axes object.

show(**kwargs)

Show plot of Sample objects.

triplets()
class polylx.deg

Bases: object

static acos(x)
static asin(x)
static atan(x)
static atan2(x1, x2)
static cos(x)
static sin(x)
static tan(x)
class polylx.circular

Bases: object

static R(x)

Length of mean resultant vector

static angdev(x)

Angular deviation

static angskew(x)

Angular skewness

static circdist(x, y)

Pairwise difference around the circle

static circmoment(x, p=1)

Complex centered p-th moment

static csd(x)

Circular standard deviation

static mean(x)

Mean direction

static mean_conf(x, cl=0.95)

Confidence limit on mean

cl confidence on mean between mu-conf..mu+conf

static rho(x)

Mean resultant vector as complex number

static sas(x)

Standardized angular skewness

static var(x)

Circular variance