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

__init__(shapes, classification=None)
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.Boundary(shape, name='None-None', fid=0)

Bases: polylx.core.PolyShape

Boundary class to store polyline boundary geometry

A two-dimensional linear ring.

__init__(shape, name='None-None', fid=0)

Create Boundary object

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()
chaikin(**kwargs)

Chaikin corner-cutting smoothing algorithm.

Keywords:
repeat: Number of repetitions. Default 2
contains(other)

Returns True if the geometry contains the other, else False

copy()
cov()

shape_method: cov

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

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

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.

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
plot(**kwargs)

View Boundary geometry on figure.

proj(angle=0)

Returns the cumulative projection of object for given angle.

Args:
angle: angle of projection line
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
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.

show(**kwargs)

Show plot of Boundary objects.

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)

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
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

hull

Returns array of vertices on convex hull of boundary geometry.

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

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
__init__(shape, name='None', fid=0)

Create Grain object

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()
chaikin(**kwargs)

Chaikin corner-cutting smoothing algorithm.

Keywords:
repeat: Number of repetitions. Default 2
contains(other)

Returns True if the geometry contains the other, else False

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.

crosses(other)

Returns True if the geometries cross, else False

difference(other)

Returns the difference of the geometries

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.

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
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.]])
intersection(other)

Returns the intersection of the geometries

intersects(other)

Returns True if geometries intersect, else False

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.

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
plot(**kwargs)

Plot Grain geometry on figure.

Note that plotted ellipse reflects actual shape method

proj(angle=0)

Returns the cumulative projection of object for given angle.

Args:
angle: angle of projection line
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
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.

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.

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.

spline(**kwargs)

Spline based smoothing of grains.

Keywords:
densify: factor for geometry densification. Default 5
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)

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
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)

cdir

Returns centroid-vertex directions of grain exterior

cdist

Returns centroid-vertex distances of grain exterior

centroid

Returns the geometric center of the object

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.

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.

nholes

Returns number of holes (shape interiors)

representative_point

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

shape_method

Returns shape method in use

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

__init__(shapes, classification=None)
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()])
boundaries(T=None)

Create Boundaries from Grains.

Example:
>>> g = Grains.from_shp()
>>> b = g.boundaries()
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
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

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.

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
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
ead

Returns array of equal area diameters of grains

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.

nholes

Returns array of number of holes (shape interiors)

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.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)
__init__(shapes, classification=None)
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.

__init__(shape, name, fid)
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
__init__(name='')
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()