core module

Python module to visualize and analyze digitized 2D microstructures.

@author: Ondrej Lexa

Examples

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

Bases: PolySet

Class to store set of Boundaries objects

__init__(shapes, classification=None)
accumulate(*methods)

Returns accumulated result of multiple Group methods based on actual classification.

Example

>>> g.accumulate('rms_ead', 'aw_ead', 'aw_ead_log')
        rms_ead    aw_ead  aw_ead_log
class
ksp    0.110679  0.185953    0.161449
pl     0.068736  0.095300    0.086762
qtz    0.097872  0.297476    0.210481
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(**kwargs)

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(
      total_area=['area', 'sum'],
      mean_ead =['ead', 'mean'],
      mean_orientation=['lao', circular.mean]
    )
       total_area  mean_ead  mean_orientation
class
ksp      2.443733  0.089710         76.875488
pl       1.083516  0.060629         94.197847
qtz      1.166097  0.068071         74.320337
property ar

Returns array of axial ratios

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

property area

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

barplot(val, **kwargs)

Plot seaborn swarmplot.

bootstrap(num=100, size=None)

Bootstrap random sample generator.

Parameters:
  • 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.example()
>>> b = g.boundary_segments()
boxplot(val, **kwargs)

Plot seaborn boxplot.

property centroid

Returns the 2D array of geometric centers of the objects

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

Define classification of objects.

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

Parameters:
  • vals – name of attribute (str) used for classification

  • values (or array of) –

Keyword Arguments:
  • label – used as classification label when vals is array

  • k – number of classes for continuous values

  • rule – type of classification, ‘unique’ for unique value mapping (for discrete values), ‘equal’ for k equaly spaced bins (for continuos values), ‘user’ for bins edges defined by array k (for continuous values), ‘jenks’ for k fischer-jenks bins and ‘quantile’ for k quantile based bins.

  • cmap – matplotlib colormap. Default ‘viridis’

Examples

>>> g.classify('name', rule='unique')
>>> g.classify('ar', rule='jenks', k=5)
clip(*bounds)

Clip by bounds rectangle (minx, miny, maxx, maxy) tuple (float values)

clip_by_shape(other)
clipstrap(num=100, f=0.3)

Bootstrap random rectangular clip generator.

Parameters:
  • 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.

Note: Use ‘class’ for class names.

Example

>>> g.df('ead', 'ar')
property extent

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

property features

Generator of feature records

feret(angle=0)

Returns array of feret diameters for given angle.

Keyword Arguments:

angle (float) – Caliper angle. Default 0

property fid

Return array of fids of objects.

classmethod from_file(filename, **kwargs)

Create Boudaries from geospatial file using fiona.

Parameters:

filename – filename of geospatial file.

Keyword Arguments:
  • namefield – name of attribute that holds names of boundaries or None. Default “name”.

  • name – value used for boundary name when namefield is None

  • layer – name of layer in files which support it e.g. ‘GPKG’. Default boundaries

classmethod from_shp(filename, namefield='name', name='None')

Create Boundaries from ESRI shapefile.

Parameters:

filename – filename of shapefile.

Keyword Arguments:
  • namefield – name of attribute in shapefile that holds names of boundairies or None. Default “name”.

  • name – value used for grain name when namefield is None

generalize(method='taubin', **kwargs)
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.

Parameters:
  • m – number of rows and columns to split.

  • 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', rule='natural')
>>> g.groups('ead').mean()
                 ead
class
1.02-1.32   0.067772
1.32-1.54   0.076042
1.54-1.82   0.065479
1.82-2.37   0.073690
2.37-12.16  0.084016
property height

Returns height of extent.

property la

Return array of long axes of objects according to shape_method.

property lao

Return array of long axes of objects according to shape_method

property length

Return array of lengths of the objects.

property ma

Returns mean axis

Return array of mean axes calculated by actual shape method.

property name

Return list of names of the objects.

property names

Returns list of unique object names.

nndist(**kwargs)
paror(angles=range(0, 180), normalized=True)

Returns paror function values. When normalized particle projections are normalized by maximum feret.

Note: It calculates proj() values for given angles

Keyword Arguments:
  • angles – iterable of angle values. Defaut range(180)

  • normalized (bool) – whether to normalize values. Default True

plot(**kwargs)

Plot set of Grains or Boundaries objects.

Keyword Arguments:
  • 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

  • scalebar – When True scalebar is drawn instead axes frame

  • scalebar_kwg – Dict of scalebar properties size: Default 1 label: Default 1mm loc: Default ‘lower right’ See AnchoredSizeBar for others

Returns matplotlib axes object.

proj(angle=0)

Returns array of cumulative projection of object for given angle.

Keyword Arguments:

angle (float) – angle of projection line. Default 0

regularize(**kwargs)
property representative_point

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

rose(**kwargs)

Plot polar histogram of Grains or Boundaries orientations

Keyword Arguments:
  • 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

  • color – Bars color. Default is taken classification.

  • ec – edgecolor. Default ‘#222222’

  • alpha – alpha value. Default 1

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.

Parameters:

angle (float) – angle of rotation

Keyword Arguments:
  • origin – 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.

  • use_radians (bool) – defaut False

property sa

Return array of long axes of objects according to shape_method

property sao

Return array of long axes of objects according to shape_method

savefig(**kwargs)

Save grains or boudaries plot to file.

Keyword Arguments:
  • filename – file to save figure. Default “figure.png”

  • dpi – DPI of image. Default 150

  • kwargs (See plot for other) –

scale(**kwargs)

Returns a scaled geometry, scaled by factors along each dimension.

Keyword Arguments:
  • xfact (float) – Default 1.0

  • yfact (float) – Default 1.0

  • origin – 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.

property shape

Return list of shapely objects.

property shape_method

Set or returns shape methods of all objects.

show(**kwargs)

Show of Grains or Boundaries 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.

Keyword Arguments:
  • xs (float) – Default 0.0

  • ys (float) – Default 0.0

  • origin – 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.

  • use_radians (bool) – defaut False

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

Returns surfor function values. When normalized surface projections are normalized by maximum projection.

Note: It calculates feret() values for given angles

Keyword Arguments:
  • angles – iterable of angle values. Defaut range(180)

  • normalized (bool) – whether to normalize values. Default True

swarmplot(val, **kwargs)

Plot seaborn swarmplot.

to_file(filename, **kwargs)

Save boundaries to geospatial file

Parameters:

filename – filename

Keyword Arguments:
  • driver – ‘ESRI Shapefile’, ‘GeoJSON’, ‘GPKG’ or ‘GML’. Default ‘GPKG’

  • layer – name of layer in files which support it e.g. ‘GPKG’. Default boundaries

translate(**kwargs)

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

Keyword Arguments:
  • xoff (float) – Default 1.0

  • yoff (float) – Default 1.0

violinplot(val, **kwargs)

Plot seaborn boxplot.

property width

Returns width of extent.

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

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

property ar

Returns axial ratio (eccentricity)

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

bcov()

shape_method: bcov

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

boundary_segments()

Create Boundaries from object boundary segments.

Example

>>> g = Grains.example()
>>> b = g.boundaries()
>>> bs1 = g[10].boundary_segments()
>>> bs2 = b[10].boundary_segments()
property bounds

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

catmull(**kwargs)

Smoothing using Catmull-Rom splines

Keyword Arguments:
  • alpha (float) – Tension parameter 0 <= alpha <= 1 For uniform Catmull-Rom splines, alpha=0 for centripetal Catmull-Rom splines, alpha=0.5, for chordal Catmull-Rom splines, alpha=1 Default value 0.5

  • subdivs (int) – Number of subdivisions of each polyline segment. Default value 10

property centroid

Returns the geometric center of the object

chaikin(**kwargs)

Chaikin’s Corner Cutting algorithm

Keyword Arguments:

iters (int) – Number of iterations. Default value 5

Note: algorithm (roughly) doubles the amount of nodes at each iteration, therefore care should be taken when selecting the number of iterations. Instead of the original iterative algorithm by Chaikin, this implementation makes use of the equivalent multi-step algorithm introduced by Wu et al. doi: 10.1007/978-3-540-30497-5_188

chaikin2(**kwargs)

Chaikin corner-cutting smoothing algorithm.

Keyword Arguments:

iters (int) – Number of iterations. Default value 5

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.

Keyword Arguments:

tolerance (float) – 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.

Parameters:

angle – angle of caliper rotation

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

Create Boundary from coordinate arrays

Example

>>> g=Boundary.from_coords([0,0,2,2],[0,1,1,0])
>>> g.xy
array([[ 0.,  0.,  2.,  2.],
       [ 0.,  1.,  1.,  0.]])
property hull

Returns array of vertices on convex hull of boundary geometry.

intersection(other)

Returns the intersection of the geometries

intersects(other)

Returns True if geometries intersect, else False

property length

Unitless length of the geometry (float)

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

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 particle projections are normalized by maximum feret.

Note: It calculates feret() values for given angles

Parameters:
  • angles – iterable angle values. Defaut range(180)

  • normalized – whether to normalize values. Defaut True

property pdist

Returns a cummulative along-perimeter distances.

plot(**kwargs)

View Boundary geometry on figure.

proj(angle=0)

Returns the cumulative projection of object for given angle.

Parameters:

angle – angle of projection line

regularize(**kwargs)

Boundary vertices regularization.

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

Keyword Arguments:
  • N (int) – Number of vertices. Default 128.

  • length (float) – approx. length of segments. Default None

relate(other)

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

property representative_point

Returns a cheaply computed point that is guaranteed to be within the 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.

Parameters:

angle (float) – angle of rotation

Keyword Arguments:
  • origin – 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.

  • use_radians (bool) – defaut False

scale(**kwargs)

Returns a scaled geometry, scaled by factors ‘xfact’ and ‘yfact’ along each dimension. The ‘origin’ keyword can be ‘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.

Keyword Arguments:
  • xfact (float) – Default 1.0

  • yfact (float) – Default 1.0

  • origin – 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.

property shape_method

Returns shape method in use

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.

Keyword Arguments:
  • xs (float) – Default 0.0

  • ys (float) – Default 0.0

  • origin – 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.

  • use_radians (bool) – defaut False

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

Returns surfor function values. When normalized surface projections are normalized by maximum projection.

Note: It calculates proj() values for given angles

Parameters:
  • 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)

taubin(**kwargs)

Taubin smoothing

Keyword Arguments:
  • factor (float) – How far each node is moved toward the average position of its neighbours during every second iteration. 0 < factor < 1 Default value 0.5

  • mu (float) – How far each node is moved opposite the direction of the average position of its neighbours during every second iteration. 0 < -mu < 1. Default value -0.5

  • steps (int) – Number of smoothing steps. Default value 5

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.

Keyword Arguments:
  • xoff (float) – Default 1.0

  • yoff (float) – Default 1.0

union(other)

Returns the union of the geometries (Shapely geometry)

property vertex_angles

Returns the array of vertex angles

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.

Keyword Arguments:

threshold (float) – Allowed total boundary length change in percents. Default 1

within(other)

Returns True if geometry is within the other, else False

property xy

Returns array of vertex coordinate pair.

class polylx.core.Fractnet(G, coords=None)

Bases: object

Class to store topological fracture networks

Properties:

G: networkx.Graph storing fracture network topology pos: a dictionary with nodes as keys and positions as values

property Cb

Average number of connections per branch

property Cl

Average number of connections per line

property Nb

Robust number of branches

property Ni

Number of isolated tips I-nodes

property Nl

Robust number of lines

property Nx

Number of crossing fractures X-nodes

property Ny

Number of fracture abutments Y-nodes

__init__(G, coords=None)
property area

Return minimum bounding rectangle area

branches_boundaries()
components()
property degree
edges_boundaries()
classmethod example()
classmethod from_boundaries(b)
classmethod from_file(filename, **kwargs)

Create Fractnet from geospatial file.

Parameters:

filename – filename of geospatial file.

Keyword Args are passed to fiona.open()

k_order_connectivity()

Calculation of connectivity according to Zhang et al., 1992

property n_edges
property n_nodes
property node_positions
reduce()

Remove 2 degree nodes. Usefull for connectivity calculation Zhang et al., 1992

show(**kwargs)
show_components(**kwargs)
show_nodes(**kwargs)
class polylx.core.Grain(shape, name='None', fid=0)

Bases: 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 grain 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

property ar

Returns axial ratio (eccentricity)

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

property area

Returns area of the grain.

bcov()

shape_method: bcov

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

boundary_segments()

Create Boundaries from object boundary segments.

Example

>>> g = Grains.example()
>>> b = g.boundaries()
>>> bs1 = g[10].boundary_segments()
>>> bs2 = b[10].boundary_segments()
property bounds

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

catmull(**kwargs)

Smoothing using Catmull-Rom splines

Keyword Arguments:
  • alpha (float) – Tension parameter 0 <= alpha <= 1 For uniform Catmull-Rom splines, alpha=0 for centripetal Catmull-Rom splines, alpha=0.5, for chordal Catmull-Rom splines, alpha=1 Default value 0.5

  • subdivs (int) – Number of subdivisions of each polyline segment. Default value 10

property cdir

Returns centroid-vertex directions of grain exterior

property cdist

Returns centroid-vertex distances of grain exterior

property centroid

Returns the geometric center of the object

chaikin(**kwargs)

Chaikin’s Corner Cutting algorithm

Keyword Arguments:

iters (int) – Number of iterations. Default value 5

Note: algorithm (roughly) doubles the amount of nodes at each iteration, therefore care should be taken when selecting the number of iterations. Instead of the original iterative algorithm by Chaikin, this implementation makes use of the equivalent multi-step algorithm introduced by Wu et al. doi: 10.1007/978-3-540-30497-5_188

chaikin2(**kwargs)

Chaikin corner-cutting smoothing algorithm.

Keyword Arguments:

iters (int) – Number of iterations. Default value 5

property circularity

Return circularity (also called compactness) of the object. circ = length**2/ (4 * pi * area)

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.

Keyword Arguments:

tolerance (float) – All points in the simplified object will be within the tolerance distance of the original geometry. Default Auto

property ead

Returns equal area diameter of grain

property eap

Returns equal area perimeter of grain

property epa

Returns equal perimeter area of grain

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.

Parameters:

angle – angle of caliper rotation

fourier(**kwargs)

Eliptic Fourier reconstruction.

Returns reconstructed Grain object using Fourier coefficients for characterizing closed contours.

Keyword Arguments:
  • order (int) – The order of FDC to calculate. Default 12.

  • N (int) – number of vertices for reconstructed grain. Default 128.

fourier_ellipse()

shape_method: fourier_ellipse

Short and long axes are calculated from first-order approximation of contour with a Fourier series.

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.]])
property haralick

Return Haralick’s circularity of the object. hcirc = mean(R) / std(R) where R is array of centroid-vertex distances

property hull

Returns array of vertices on convex hull of grain geometry.

property interiors

Returns list of arrays of vertex coordinate pair of interiors.

intersection(other)

Returns the intersection of the geometries

intersects(other)

Returns True if geometries intersect, else False

property length

Unitless length of the geometry (float)

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

maee()

shape_method: maee

Short and long axes are calculated from minimum area 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 width 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 calculation fallback to maxferet. Center coordinates are set to centroid.

property nholes

Returns number of holes (shape interiors)

overlaps(other)

Returns True if geometries overlap, else False

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

Returns paror function values. When normalized particle projections are normalized by maximum feret.

Note: It calculates feret() values for given angles

Parameters:
  • angles – iterable angle values. Defaut range(180)

  • normalized – whether to normalize values. Defaut True

property pdist

Returns a cummulative along-perimeter distances.

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.

Parameters:

angle – angle of projection line

regularize(**kwargs)

Grain vertices regularization.

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

Keyword Arguments:
  • N (int) – Number of vertices. Default 128.

  • length (float) – approx. length of segments. Default None

relate(other)

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

property representative_point

Returns a cheaply computed point that is guaranteed to be within the 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.

Parameters:

angle (float) – angle of rotation

Keyword Arguments:
  • origin – 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.

  • use_radians (bool) – defaut False

scale(**kwargs)

Returns a scaled geometry, scaled by factors ‘xfact’ and ‘yfact’ along each dimension. The ‘origin’ keyword can be ‘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.

Keyword Arguments:
  • xfact (float) – Default 1.0

  • yfact (float) – Default 1.0

  • origin – 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.

property shape_method

Returns shape method in use

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.

Keyword Arguments:

N (int) – number of vertices to regularize outline. Default 128 Note that number returned FDs is half of N.

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.

Keyword Arguments:
  • xs (float) – Default 0.0

  • ys (float) – Default 0.0

  • origin – 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.

  • use_radians (bool) – defaut False

spline(**kwargs)

Spline based smoothing of grains.

Keyword Arguments:

densify (int) – factor for geometry densification. Default 5

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

Returns surfor function values. When normalized surface projections are normalized by maximum projection.

Note: For polygons, the calculates proj() values are divided by factor 2

Parameters:
  • 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)

taubin(**kwargs)

Taubin smoothing

Keyword Arguments:
  • factor (float) – How far each node is moved toward the average position of its neighbours during every second iteration. 0 < factor < 1 Default value 0.5

  • mu (float) – How far each node is moved opposite the direction of the average position of its neighbours during every second iteration. 0 < -mu < 1. Default value -0.5

  • steps (int) – Number of smoothing steps. Default value 5

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.

Keyword Arguments:
  • xoff (float) – Default 1.0

  • yoff (float) – Default 1.0

union(other)

Returns the union of the geometries (Shapely geometry)

property vertex_angles

Returns the array of vertex angles

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.

Keyword Arguments:

threshold (float) – Allowed total boundary length change in percents. Default 1

within(other)

Returns True if geometry is within the other, else False

property 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: PolySet

Class to store set of Grains objects

__init__(shapes, classification=None)
accumulate(*methods)

Returns accumulated result of multiple Group methods based on actual classification.

Example

>>> g.accumulate('rms_ead', 'aw_ead', 'aw_ead_log')
        rms_ead    aw_ead  aw_ead_log
class
ksp    0.110679  0.185953    0.161449
pl     0.068736  0.095300    0.086762
qtz    0.097872  0.297476    0.210481
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(**kwargs)

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(
      total_area=['area', 'sum'],
      mean_ead =['ead', 'mean'],
      mean_orientation=['lao', circular.mean]
    )
       total_area  mean_ead  mean_orientation
class
ksp      2.443733  0.089710         76.875488
pl       1.083516  0.060629         94.197847
qtz      1.166097  0.068071         74.320337
property ar

Returns array of axial ratios

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

property area

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

areafraction_plot(**kwargs)
property aw_ead

Returns normal area weighted mean of ead

property aw_ead_log

Returns lognormal area weighted mean of ead

barplot(val, **kwargs)

Plot seaborn swarmplot.

bootstrap(num=100, size=None)

Bootstrap random sample generator.

Parameters:
  • 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.example()
>>> b = g.boundaries()
boundaries_fast(T=None)

Create Boundaries from Grains. Faster but not always safe implementation

Example

>>> g = Grains.example()
>>> b = g.boundaries_fast()
boundary_segments()

Create Boundaries from object boundary segments.

Example

>>> g = Grains.example()
>>> b = g.boundary_segments()
boxplot(val, **kwargs)

Plot seaborn boxplot.

property centroid

Returns the 2D array of geometric centers of the objects

property circularity

Return array of circularities (also called compactness) of the objects. circ = length**2/area

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

Define classification of objects.

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

Parameters:
  • vals – name of attribute (str) used for classification

  • values (or array of) –

Keyword Arguments:
  • label – used as classification label when vals is array

  • k – number of classes for continuous values

  • rule – type of classification, ‘unique’ for unique value mapping (for discrete values), ‘equal’ for k equaly spaced bins (for continuos values), ‘user’ for bins edges defined by array k (for continuous values), ‘jenks’ for k fischer-jenks bins and ‘quantile’ for k quantile based bins.

  • cmap – matplotlib colormap. Default ‘viridis’

Examples

>>> g.classify('name', rule='unique')
>>> g.classify('ar', rule='jenks', k=5)
clip(*bounds)

Clip by bounds rectangle (minx, miny, maxx, maxy) tuple (float values)

clip_by_shape(other)
clipstrap(num=100, f=0.3)

Bootstrap random rectangular clip generator.

Parameters:
  • 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.

Note: Use ‘class’ for class names.

Example

>>> g.df('ead', 'ar')
property ead

Returns array of equal area diameters of grains

property eap

Returns array of equal area perimeters of grains

property epa

Returns array of equal perimeter areas of grains

classmethod example()

Return example grains

property extent

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

property features

Generator of feature records

feret(angle=0)

Returns array of feret diameters for given angle.

Keyword Arguments:

angle (float) – Caliper angle. Default 0

property fid

Return array of fids of objects.

classmethod from_file(filename, **kwargs)

Create Grains from geospatial file.

Parameters:

filename – filename of geospatial file.

Keyword Arguments:
  • namefield – name of attribute that holds names of grains or None. Default “name”.

  • name – value used for grain name when namefield is None

  • layer – name of layer in files which support it e.g. ‘GPKG’. Default grains

classmethod from_shp(filename, namefield='name', name='None')

Create Grains from ESRI shapefile.

Parameters:

filename – filename of shapefile.

Keyword Arguments:
  • namefield – name of attribute in shapefile that holds names of grains or None. Default “name”.

  • name – value used for grain name when namefield is None

generalize(method='taubin', **kwargs)
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.

grainsize_plot(areaweighted=True, **kwargs)
gridsplit(m=1, n=1)

Rectangular split generator.

Parameters:
  • m – number of rows and columns to split.

  • 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', rule='natural')
>>> g.groups('ead').mean()
                 ead
class
1.02-1.32   0.067772
1.32-1.54   0.076042
1.54-1.82   0.065479
1.82-2.37   0.073690
2.37-12.16  0.084016
property haralick

Return array of Haralick’s circularities of the objects. hcirc = mean(R) / std(R) where R is array of centroid-vertex distances

property height

Returns height of extent.

property la

Return array of long axes of objects according to shape_method.

property lao

Return array of long axes of objects according to shape_method

property length

Return array of lengths of the objects.

property ma

Returns mean axis

Return array of mean axes calculated by actual shape method.

property name

Return list of names of the objects.

property names

Returns list of unique object names.

property nholes

Returns array of number of holes (shape interiors)

nndist(**kwargs)
paror(angles=range(0, 180), normalized=True)

Returns paror function values. When normalized particle projections are normalized by maximum feret.

Note: It calculates proj() values for given angles

Keyword Arguments:
  • angles – iterable of angle values. Defaut range(180)

  • normalized (bool) – whether to normalize values. Default True

plot(**kwargs)

Plot set of Grains or Boundaries objects.

Keyword Arguments:
  • 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

  • scalebar – When True scalebar is drawn instead axes frame

  • scalebar_kwg – Dict of scalebar properties size: Default 1 label: Default 1mm loc: Default ‘lower right’ See AnchoredSizeBar for others

Returns matplotlib axes object.

proj(angle=0)

Returns array of cumulative projection of object for given angle.

Keyword Arguments:

angle (float) – angle of projection line. Default 0

regularize(**kwargs)
property representative_point

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

property rms_ead

Returns root mean square of ead

rose(**kwargs)

Plot polar histogram of Grains or Boundaries orientations

Keyword Arguments:
  • 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

  • color – Bars color. Default is taken classification.

  • ec – edgecolor. Default ‘#222222’

  • alpha – alpha value. Default 1

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.

Parameters:

angle (float) – angle of rotation

Keyword Arguments:
  • origin – 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.

  • use_radians (bool) – defaut False

property sa

Return array of long axes of objects according to shape_method

property sao

Return array of long axes of objects according to shape_method

savefig(**kwargs)

Save grains or boudaries plot to file.

Keyword Arguments:
  • filename – file to save figure. Default “figure.png”

  • dpi – DPI of image. Default 150

  • kwargs (See plot for other) –

scale(**kwargs)

Returns a scaled geometry, scaled by factors along each dimension.

Keyword Arguments:
  • xfact (float) – Default 1.0

  • yfact (float) – Default 1.0

  • origin – 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.

property shape

Return list of shapely objects.

property shape_method

Set or returns shape methods of all objects.

shape_vector(**kwargs)

Returns array of shape (feature) vectors.

Keyword Arguments:

N – number of points to regularize shape. Default 128 Routine return N/2 of FDs

show(**kwargs)

Show of Grains or Boundaries 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.

Keyword Arguments:
  • xs (float) – Default 0.0

  • ys (float) – Default 0.0

  • origin – 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.

  • use_radians (bool) – defaut False

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

Returns surfor function values. When normalized surface projections are normalized by maximum projection.

Note: It calculates feret() values for given angles

Keyword Arguments:
  • angles – iterable of angle values. Defaut range(180)

  • normalized (bool) – whether to normalize values. Default True

swarmplot(val, **kwargs)

Plot seaborn swarmplot.

to_file(filename, **kwargs)

Save Boundaries to geospatial file

Parameters:

filename – filename of geospatial file

Keyword Arguments:
  • driver – ‘ESRI Shapefile’, ‘GeoJSON’, ‘GPKG’ or ‘GML’. Default ‘GPKG’

  • layer – name of layer in files which support it e.g. ‘GPKG’. Default grains

translate(**kwargs)

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

Keyword Arguments:
  • xoff (float) – Default 1.0

  • yoff (float) – Default 1.0

violinplot(val, **kwargs)

Plot seaborn boxplot.

property 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)
accumulate(*methods)

Returns accumulated result of multiple Group methods based on actual classification.

Example

>>> g.accumulate('rms_ead', 'aw_ead', 'aw_ead_log')
        rms_ead    aw_ead  aw_ead_log
class
ksp    0.110679  0.185953    0.161449
pl     0.068736  0.095300    0.086762
qtz    0.097872  0.297476    0.210481
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(**kwargs)

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(
      total_area=['area', 'sum'],
      mean_ead =['ead', 'mean'],
      mean_orientation=['lao', circular.mean]
    )
       total_area  mean_ead  mean_orientation
class
ksp      2.443733  0.089710         76.875488
pl       1.083516  0.060629         94.197847
qtz      1.166097  0.068071         74.320337
property ar

Returns array of axial ratios

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

property area

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

barplot(val, **kwargs)

Plot seaborn swarmplot.

bootstrap(num=100, size=None)

Bootstrap random sample generator.

Parameters:
  • 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.example()
>>> b = g.boundary_segments()
boxplot(val, **kwargs)

Plot seaborn boxplot.

property centroid

Returns the 2D array of geometric centers of the objects

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

Define classification of objects.

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

Parameters:
  • vals – name of attribute (str) used for classification

  • values (or array of) –

Keyword Arguments:
  • label – used as classification label when vals is array

  • k – number of classes for continuous values

  • rule – type of classification, ‘unique’ for unique value mapping (for discrete values), ‘equal’ for k equaly spaced bins (for continuos values), ‘user’ for bins edges defined by array k (for continuous values), ‘jenks’ for k fischer-jenks bins and ‘quantile’ for k quantile based bins.

  • cmap – matplotlib colormap. Default ‘viridis’

Examples

>>> g.classify('name', rule='unique')
>>> g.classify('ar', rule='jenks', k=5)
clip(*bounds)

Clip by bounds rectangle (minx, miny, maxx, maxy) tuple (float values)

clip_by_shape(other)
clipstrap(num=100, f=0.3)

Bootstrap random rectangular clip generator.

Parameters:
  • 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.

Note: Use ‘class’ for class names.

Example

>>> g.df('ead', 'ar')
property extent

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

property features

Generator of feature records

feret(angle=0)

Returns array of feret diameters for given angle.

Keyword Arguments:

angle (float) – Caliper angle. Default 0

property fid

Return array of fids of objects.

generalize(method='taubin', **kwargs)
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.

Parameters:
  • m – number of rows and columns to split.

  • 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', rule='natural')
>>> g.groups('ead').mean()
                 ead
class
1.02-1.32   0.067772
1.32-1.54   0.076042
1.54-1.82   0.065479
1.82-2.37   0.073690
2.37-12.16  0.084016
property height

Returns height of extent.

property la

Return array of long axes of objects according to shape_method.

property lao

Return array of long axes of objects according to shape_method

property length

Return array of lengths of the objects.

property ma

Returns mean axis

Return array of mean axes calculated by actual shape method.

property name

Return list of names of the objects.

property names

Returns list of unique object names.

nndist(**kwargs)
paror(angles=range(0, 180), normalized=True)

Returns paror function values. When normalized particle projections are normalized by maximum feret.

Note: It calculates proj() values for given angles

Keyword Arguments:
  • angles – iterable of angle values. Defaut range(180)

  • normalized (bool) – whether to normalize values. Default True

plot(**kwargs)

Plot set of Grains or Boundaries objects.

Keyword Arguments:
  • 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

  • scalebar – When True scalebar is drawn instead axes frame

  • scalebar_kwg – Dict of scalebar properties size: Default 1 label: Default 1mm loc: Default ‘lower right’ See AnchoredSizeBar for others

Returns matplotlib axes object.

proj(angle=0)

Returns array of cumulative projection of object for given angle.

Keyword Arguments:

angle (float) – angle of projection line. Default 0

regularize(**kwargs)
property representative_point

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

rose(**kwargs)

Plot polar histogram of Grains or Boundaries orientations

Keyword Arguments:
  • 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

  • color – Bars color. Default is taken classification.

  • ec – edgecolor. Default ‘#222222’

  • alpha – alpha value. Default 1

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.

Parameters:

angle (float) – angle of rotation

Keyword Arguments:
  • origin – 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.

  • use_radians (bool) – defaut False

property sa

Return array of long axes of objects according to shape_method

property sao

Return array of long axes of objects according to shape_method

savefig(**kwargs)

Save grains or boudaries plot to file.

Keyword Arguments:
  • filename – file to save figure. Default “figure.png”

  • dpi – DPI of image. Default 150

  • kwargs (See plot for other) –

scale(**kwargs)

Returns a scaled geometry, scaled by factors along each dimension.

Keyword Arguments:
  • xfact (float) – Default 1.0

  • yfact (float) – Default 1.0

  • origin – 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.

property shape

Return list of shapely objects.

property shape_method

Set or returns shape methods of all objects.

show(**kwargs)

Show of Grains or Boundaries 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.

Keyword Arguments:
  • xs (float) – Default 0.0

  • ys (float) – Default 0.0

  • origin – 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.

  • use_radians (bool) – defaut False

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

Returns surfor function values. When normalized surface projections are normalized by maximum projection.

Note: It calculates feret() values for given angles

Keyword Arguments:
  • angles – iterable of angle values. Defaut range(180)

  • normalized (bool) – whether to normalize values. Default True

swarmplot(val, **kwargs)

Plot seaborn swarmplot.

translate(**kwargs)

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

Keyword Arguments:
  • xoff (float) – Default 1.0

  • yoff (float) – Default 1.0

violinplot(val, **kwargs)

Plot seaborn boxplot.

property 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

property ar

Returns axial ratio (eccentricity)

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

boundary_segments()

Create Boundaries from object boundary segments.

Example

>>> g = Grains.example()
>>> b = g.boundaries()
>>> bs1 = g[10].boundary_segments()
>>> bs2 = b[10].boundary_segments()
property bounds

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

catmull(**kwargs)

Smoothing using Catmull-Rom splines

Keyword Arguments:
  • alpha (float) – Tension parameter 0 <= alpha <= 1 For uniform Catmull-Rom splines, alpha=0 for centripetal Catmull-Rom splines, alpha=0.5, for chordal Catmull-Rom splines, alpha=1 Default value 0.5

  • subdivs (int) – Number of subdivisions of each polyline segment. Default value 10

property centroid

Returns the geometric center of the object

chaikin(**kwargs)

Chaikin’s Corner Cutting algorithm

Keyword Arguments:

iters (int) – Number of iterations. Default value 5

Note: algorithm (roughly) doubles the amount of nodes at each iteration, therefore care should be taken when selecting the number of iterations. Instead of the original iterative algorithm by Chaikin, this implementation makes use of the equivalent multi-step algorithm introduced by Wu et al. doi: 10.1007/978-3-540-30497-5_188

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.

Keyword Arguments:

tolerance (float) – 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.

Parameters:

angle – angle of caliper rotation

intersection(other)

Returns the intersection of the geometries

intersects(other)

Returns True if geometries intersect, else False

property length

Unitless length of the geometry (float)

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

overlaps(other)

Returns True if geometries overlap, else False

property pdist

Returns a cummulative along-perimeter distances.

proj(angle=0)

Returns the cumulative projection of object for given angle.

Parameters:

angle – angle of projection line

relate(other)

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

property representative_point

Returns a cheaply computed point that is guaranteed to be within the 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.

Parameters:

angle (float) – angle of rotation

Keyword Arguments:
  • origin – 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.

  • use_radians (bool) – defaut False

scale(**kwargs)

Returns a scaled geometry, scaled by factors ‘xfact’ and ‘yfact’ along each dimension. The ‘origin’ keyword can be ‘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.

Keyword Arguments:
  • xfact (float) – Default 1.0

  • yfact (float) – Default 1.0

  • origin – 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.

property shape_method

Returns shape method in use

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.

Keyword Arguments:
  • xs (float) – Default 0.0

  • ys (float) – Default 0.0

  • origin – 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.

  • use_radians (bool) – defaut False

symmetric_difference(other)

Returns the symmetric difference of the geometries (Shapely geometry)

taubin(**kwargs)

Taubin smoothing

Keyword Arguments:
  • factor (float) – How far each node is moved toward the average position of its neighbours during every second iteration. 0 < factor < 1 Default value 0.5

  • mu (float) – How far each node is moved opposite the direction of the average position of its neighbours during every second iteration. 0 < -mu < 1. Default value -0.5

  • steps (int) – Number of smoothing steps. Default value 5

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.

Keyword Arguments:
  • xoff (float) – Default 1.0

  • yoff (float) – Default 1.0

union(other)

Returns the union of the geometries (Shapely geometry)

within(other)

Returns True if geometry is within the other, else False

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)

Return array of indexes of boundaries creating grain idx

If name keyword is provided only boundaries with grains of given name are returned.

dissolve()
classmethod example()

Returns example Sample

classmethod from_grains(grains, name='')
get_cluster(idx, name=None)

Return array of indexes of clustered grains seeded from idx.

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

get_clusters()

Return dictionary with lists of clusters for each 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.

Keyword Arguments:
  • 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()