genepy3d.obj package

Submodules

genepy3d.obj.curves module

class genepy3d.obj.curves.Curve(coors, curve_id=None, curve_name=None)[source]

Bases: object

Curve in 3D. Also work with 2D curve. Check the documentation of each function to see if it supports 2D. We assumme that curve is a parametric function g(t) = (x(t),y(t),z(t)). If 2D points are passed then we consider as X and Y coordinates and set Z = 0.

coors

list of 3d points.

  • if array is given, then each column is the x, y, z coordinates of a specific point.

  • if tuple is given, then the items are the three arrays of x, y and z coordinates.

Type

array | tuple

curve_id

curve ID (optional).

Type

int

curve_name

curve name (optional).

Type

str

compute_curvature()[source]

Curvatures of curve.

Support 2D and 3D.

Returns

array of float.

compute_derivative(deg, dt=1)[source]

Derivative using np.gradient.

Support 2D and 3D. If in 2D, then return 0 for the derivative of Z.

Parameters
  • deg (int) – derivative degree.

  • dt (float) – delta t.

Returns

array of float where each row is the derivative in x, y and z at a specific point.

compute_length()[source]

Length of curve.

Support 2D and 3D.

Returns

float.

compute_local_3d_scale(r_lst, eps_seg_len=None, eps_crv_len=None, sig_step=1, eps_kappa=0.01, eps_tau=0.01, return_dim_results=False)[source]

Computing local 3d scale of curve. [1]

Local 3D scale: scale at which point transforms from 3D to 2D/1D.

[1] https://doi.org/10.1101/2020.06.01.127035

This function is DEPRECATED. Use compute_local_3d_scale_radius().

Parameters
  • r_lst (list (float)) – list of radii of curvatures.

  • eps_seg_len (float) – segment length threshold.

  • eps_crv_len (float) – curve length threshold.

  • sig_step (int) – scale step within the searching region.

  • eps_kappa (float) – curvature threshold.

  • eps_tau (float) – torsion threshold.

  • return_dim_results (bool) – if True, then return intrinsic dim estimation of r_lst

Returns

list of local 3d scales for every points on curve.

compute_local_3d_scale_radius(r_lst, eps_seg_len=None, eps_crv_len=None, sig_step=1, eps_kappa=0.01, eps_tau=0.01, return_dim_results=False)[source]

Computing local 3d scale of curve from the list of radius of curvatures.

Local 3D scale: scale at which point transforms from 3D to 2D/1D.

Parameters
  • r_lst (list (float)) – list of radii of curvatures.

  • eps_seg_len (float) – segment length threshold.

  • eps_crv_len (float) – curve length threshold.

  • sig_step (int) – scale step within the searching region.

  • eps_kappa (float) – curvature threshold.

  • eps_tau (float) – torsion threshold.

  • return_dim_results (bool) – if True, then return intrinsic dim estimation of r_lst

Returns

list of local 3d scales for every points on curve.

compute_local_3d_scale_sigma(sig_lst, delta_sig=0, sig_step=1, eps_seg_len=None, eps_crv_len=None, eps_kappa=0.01, eps_tau=0.01, return_dim_results=False)[source]

Computing local 3d scale of curve from the list of sigma i.e stdev of Gaussian function.

Local 3D scale: scale at which point transforms from 3D to 2D/1D.

Parameters
  • sig_lst (list (float)) – list of sigma values.

  • delta_sig (float) – width of the searching interval.

  • sig_step (int|float) – scale step within the searching region.

  • eps_seg_len (float) – segment length threshold.

  • eps_crv_len (float) – curve length threshold.

  • eps_kappa (float) – curvature threshold.

  • eps_tau (float) – torsion threshold.

  • return_dim_results (bool) – if True, then return intrinsic dim estimation of r_lst

Returns

list of local 3d scales for every points on curve.

compute_orientation(u=None)[source]

Orientation vectors and angles w.r.t. a vector u for every point on the curve.

Parameters

u (array (float)) – vector used to compute angles. If None then return angles with three x, y and z axes.

compute_torsion()[source]

Torsions of curve.

Only in 3D.

Returns

array of float.

compute_tortuosity()[source]

Tortuosity of curve.

Same as compute_wiggliness()

Tortuosity = Length / Distance

Returns

array of float.

compute_wiggliness()[source]

Wiggliness of curve.

Support 2D and 3D.

Wiggliness = Length / Distance

Returns

array of float.

convolve_gaussian(sigma, mo='nearest', kerlen=4.0)[source]

Get curve at a specific scale sigma by Gaussian convolution.

Support 2D and 3D.

Parameters
  • sigma (float or list of floats) – scale.

  • mo (str) – mode used to treat the border effect (see gaussian_filter1d() for detail).

  • kerlen (float) – specify the length of Gaussian kernel (see gaussian_filter1d() for detail).

Returns

Curve.

decompose_intrinsicdim(sig_c, delta_sig=None, eps_seg_len=None, eps_crv_len=None, sig_step=1, eps_kappa=0.01, eps_tau=0.01)[source]

Decompose curve into multiscale hierarchichal intrinsic segments.

Parameters
  • sig_c (float) – central scale of the searching region.

  • delta_sig (float) – width of the searching interval.

  • sig_step (int) – scale step within the searching region.

  • eps_kappa (float) – curvature threshold.

  • eps_tau (float) – torsion threshold.

  • eps_seg_len (float) – segment length threshold.

  • eps_crv_len (float) – curve length threshold.

Returns

list of segment indices specifying line, plane+line.

denoise(return_std=False)[source]

Automatically denoise a curve assuming Gaussian noise. Noise variance acrooss the three dimensions is estimated using the beta-sigma method implemented in PyAstronomy [1].

[1] https://www.aanda.org/articles/aa/pdf/2018/01/aa30618-17.pdf

Parameters

return_std (bool) – return the estimated sigma as well (default: False)

Returns

denoised curve (if return_std is False) (denoised curve, estimated sigma) (if return_std is True)

classmethod from_csv(filepath, column_names=['x', 'y', 'z'], scales=(1.0, 1.0, 1.0), args={})[source]

Constructor from csv file.

Parameters
  • filepath (str) – csv file.

  • column_names (list of str) – coordinates columns in csv file.

  • scales (tuple of float) – scales in x, y and z.

  • args (dict) – overried parameters of pandas.read_csv().

Returns

Points.

classmethod from_text(filepath)[source]

Read from text-liked file (.txt, .xyz).

Note

Assuming the first three columns correspond to x, y, z coordinates.

main_turns(nbscales=None, search_step=5, eps_kappa=None, ridgelength_thr=0.1, angle_thr=20, min_dist=None)[source]

Compute the main turns of curve.

Parameters
  • nbscales (int) – number of scales used to check the curve evolution.

  • search_step (int) – number of up-scale levels to search for the next point of ridge.

  • eps_kappa (float) – curvature threshold.

  • ridgelength_thr (float) – ridge length threshold (percentage compared to the longest ridge).

  • angle_thr (float) – angle threshold in degree.

  • min_dist (float) – minimal distance between two main turns.

Returns

indices of main turns.

plot(ax, projection='3d', scales=(1.0, 1.0, 1.0), show_root=True, root_args={'color': 'red'}, line_args={'c': 'blue', 'lw': 1}, point_args=None)[source]

Plot curve.

plot_decomposed_table(ax, show_selection=True, show_scales=True, aspect=3, xdiv=50, ydiv=10)[source]

Display decomposed intrinsic table.

This is only used after running decompose_intrinsicdim().

Parameters
  • ax – plot axis.

  • show_selection (bool) – if True, then display selection interval.

  • show_scales (bool) – if True, display scale range in y axis.

  • aspect (int) – aspect ratio between x and y axes.

  • xdiv (int) – to calculate xticks.

  • ydiv (int) – to calculate yticks.

plot_intrinsicdim(ax, projection='3d', scales=(1.0, 1.0, 1.0), root_args={'c': 'blue', 's': 100}, dim1d_args={'alpha': 1.0, 'c': 'magenta', 'lw': 1}, dim2d_args={'alpha': 0.7, 'c': 'yellow', 'lw': 3}, dim3d_args={'alpha': 0.7, 'c': 'green', 'lw': 3}, plane_color='yellow', overrided_curve=None)[source]

Display curve superimposed by estimated intrinsic dimensions.

This is only used after running decompose_intrinsicdim().

Parameters
  • ax – plot axis.

  • projection (str) – support 3d, xy, xz, yz modes.

  • scales (tuple of float) – specify x, y, z scales.

  • overrided_curve (Curve) –

    superimpose estimated intrinsic dimensions on the overrided_curve.

    if None, then a scaled curve computed from decompose_intrinsicdim() is used as default.

plot_ridge_map(ax, show_scales=True)[source]

Display ridge finding from principal turns computation.

This is only used after running main_turns().

Parameters
  • ax – plot axis.

  • show_scales (bool) – if True, display scale range in y axis.

resample(npoints=None, unit_length=None, spline_order=1, return_interp_param=False)[source]

Resample the curve using spline interpolation.

Support 2D and 3D.

Parameters
  • npoints (int) – number of resampled points.

  • unit_length (float) – if not None, then npoints is calculated from it.

  • spline_order (uint) – 1 means linear interpolation.

  • return_interp_param (bool) – if True then return interpolation parameters.

Returns

Curve() resampled curve.

scale_space(scale_range, features={'curvature', 'line', 'planeline', 'ridge', 'torsion', 'valley'}, eps_kappa=0.01, eps_tau=0.01, eps_seg=10, mo='nearest', kerlen=4.0)[source]

Compute features of a curve across scales, i.e. a scale space of gaussian convolution.

Can compute various features at one time.

Parameters
  • scale_range (array of float) – range of scales (sigma of gaussian convolutions).

  • features (dic) – list of features (detail see below).

  • eps_kappa (float) – curvature threshold. (for planeline feature)

  • eps_tau (float) – torsion threshold. (for line and planeline feature)

  • eps_seg (float) – segment length threshold (in number of points).

Returns

dictionary whose each item is a scale space matrix of a specific feature, where rows are the scale range and columns are the curve indices.

Note

we support following features

  • curvature: curvature scale space.

  • torsion: torsion scale space.

  • ridge: local maxima of curvature

  • valley: local minima of curvature

  • planeline: plane+line scale space.

  • line: line scale space.

to_points()[source]

Convert Curve object to Points object.

transform(phi=0, theta=0, psi=0, dx=0, dy=0, dz=0, zx=1, zy=1, zz=1)[source]

Apply rigid transformation to every point of the curve.

Parameters
  • phi (float) – rotation in x.

  • theta (float) – rotation in y.

  • psi (float) – rotation in z.

  • dx (float) – translation in x.

  • dy (float) – translation in y.

  • dz (float) – translation in z.

  • zx (float) – zoom in x.

  • zy (float) – zoom in y.

  • zz (float) – zoom in z.

Returns

Curve.

class genepy3d.obj.curves.RadiusScaleMap(l=1, rmin=1, rmax=100, smin=0, smax=200, mo='nearest', kerlen=4.0, save_circles=False)[source]

Bases: object

Compute mapping between curvature radius and scale.

This class is used to estimate a scale of interest for a given curvature radius. The scale of interest is then used in decompose_intrinsicdim() of Curve to estimate the intrinsic segments.

l

sampled unit length.

Type

int

rmin

min radius.

Type

int

rmax

max radius.

Type

int

smin

min scale.

Type

int

smax

max scale.

Type

int

mo

method used in gaussian convolution to treat the extreme values.

Type

str

kerlen

gaussian kernel length.

Type

float

save_circles

if True, then save the scaled circle for each scale.

Type

bool

Note

This class is DEPRECATED.

get_scale(r)[source]

Estimate the scale of interest corresponding to given curvature radius.

Parameters

r (float) – curvature radius.

Returns

A tuple including
  • sig_c (float): scale of interest.

  • delta_c (float): parameter specifying searching region around sig_c.

  • rmask (array of float): binary mask of radius-scale map.

class genepy3d.obj.curves.RadiusScaleTable(crv, r, mo=None, kerlen=None)[source]

Bases: object

Compute scales table of a curve from given radius of curvature.

crv

curve to compute radius scale table.

Type

Curve

r

reference radius of curvature.

Type

float

mo

method used in gaussian convolution to treat the extreme values.

Type

str

kerlen

gaussian kernel length.

Type

float

build_scales_from_radius(max_iter=None)[source]

Compute scales range from given reference radius.

Support func of intrinsic dimensions decomposition.

Parameters

max_iter (int) – number of convolution iteration. If None, it will be set = haft of number of points.

Retuns:

kappa_tbl (array (float)): curvature table.

compute_scales_from_radius(r=None)[source]

Compute scales range from given reference radius.

Support func of intrinsic dimensions decomposition.

Parameters

r (float) – reference radius.

Retuns:

sig_c (float): central value of sigma delta_sig (float): std value of sigma

class genepy3d.obj.curves.SimuIntrinsic(seg_lbl=[0, 1, 2], npoints=1000, sigma=1.0, random_state=None, params={}, max_seg=None, nb_seg=None, remove_zero_replica=True, spline_order=1)[source]

Bases: object

Generate curve in 3D with random intrinsic dimension segments.

The process is simulated based on 2D and 3D Brownian motion.

seg_lbl

list of intrinsic dimensions, 0 for 3d, 1 for 2d, 2 for 1d.

Type

array of int

npoints

number of points on simulated curve.

Type

int

sigma

for adding gaussian noise.

Type

float

params

simulation parameters.

Type

array of dic | dic

random_state

seed number used to memorize the simulated curve.

Type

int

max_seg

maximal number of segments. if this is set, then number of simulated intrinsic segments will be <= max_seg.

Type

int

nb_seg

number of segments. if this is set, then number of simulated intrinsic segments will be fixed at nb_seg.

Type

int

remove_zero_replica

if True, then replace the ‘0,0,..’ sequence into only one ‘0’.

Type

bool

Note

specify either seg_lbl, max_seg or nb_seg whose priority order is seg_lbl, then max_seg and then nb_seg.

add_noise(sigma)[source]

Add Gaussian noise to curve.

Parameters

sigma (float) – std of Gaussian kernel.

Returns

itself.

evaluate(pred_line_ids, pred_plane_ids, metric='f1')[source]

Evaluate accuracies of intrinsic dimension estimation.

Parameters
  • pred_line_ids (list) – list of predicted lines indices.

  • pred_plane_ids (list) – list of predicted planes indices.

  • metric (str) – accuracy metric, we support: f1, jaccard, balanced as in scikit learn.

Returns

A tuple including
  • [line_acc, line_pre, line_rec]: line accuracy, precision and recall.

  • [plane_acc, plane_pre, plane_rec]: plane accuracy, precision and recall.

  • [nonplane_acc, nonplane_pre, nonplane_rec]: 3D accuracy, precision and recall.

gen()[source]

Simulate a 3D curve with random intrinsic lines, planes and 3D.

Returns

itself.

Note

generated curve for noiseless case can contain duplicata points.

get_curve(noisy=True)[source]

Return curve with/without noise.

Parameters

noisy (bool) – if True, then return noisy curve, and False otherwise.

Returns

Curve

plot(ax, projection='3d', noisy=True, scales=(1.0, 1.0, 1.0), show_interpoints=False)[source]

Plot simulated curve with its intrinsic segments.

Parameters
  • ax – plot axis.

  • projection (str) – support 3d, xy, xz, yz modes.

  • noisy (bool) – plot noisy curve or noiseless curve.

  • scales (tuple of float) – specify x, y and z scales.

  • show_interpoints (bool) – if True, points in between intrinsic segments are displayed.

genepy3d.obj.curves.align(target, ref)[source]

Align target curve to reference curve.

This func is used to align two curves that minimize their spatial differences.

The func is useful as a preparation before computing the distance between the two curves. E.g. we provided emd() in Points class to compute the Earth Mover’s Distance between two point clouds.

Parameters
  • target (Curve) – target curve.

  • ref (Curve) – reference curve.

Returns

aligned target curve.

genepy3d.obj.curves.decompose_intrinsicdim_sequential(p, eps_line, eps_plane, eps_seg)[source]

Decompose sequentially intrinsic segments with priority line to plane to 3d.

from paper of Jianyu Yang: https://www.sciencedirect.com/science/article/pii/S1047320316300438. This method was selected to compare with our decompose_intrinsicdim().

Parameters
  • p (array of float) – list of 3D points on curve.

  • eps_line (float) – line threshold.

  • eps_plane (float) – plane_threshold.

  • eps_seg (float) – segment length threshold.

Returns

list of line and plane indices.

genepy3d.obj.points module

class genepy3d.obj.points.Points(_coors)[source]

Bases: object

Points cloud in 3D.

coors

list of 3d points.

Type

2d array

size

number of points

Type

int

append(other)[source]

Append a point cloud to another :param other: another Points object :type other: Points

Returns

nothing, works in place

center()[source]

Center the cloud to the mean of each coordinates.

export_to_VTK(filepath)[source]

exprt to VTK file format

Parameters

filepath (str) – full path of file to save, without extention.

fit_plane()[source]

Fit plane.

Returns

Tuple containing
  • c (float): intercept scalar.

  • normal (1d array): normal vector.

classmethod from_csv(filepath, column_names=['x', 'y', 'z'], scales=(1.0, 1.0, 1.0), args={})[source]

Constructor from csv file.

Parameters
  • filepath (str) – csv file.

  • column_names (list of str) – coordinates columns in csv file.

  • scales (tuple of float) – scales in x, y and z.

  • args (dict) – overried parameters of pandas.read_csv().

Returns

Points.

classmethod from_text(filepath)[source]

Read from text file (.txt, .xyz).

Note

Assuming the first three columns correspond to x, y, z coordinates.

kmeans(**kwargs)[source]

Clustering points cloud using kmeans in scikitlearn.

Link: https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html

Parameters

**kwargs – kmeans arguments (read scikitlearn docs).

Returns

Tuple containing
  • labels (1d array): the integer label of each sample’s point.

  • centers (2d array): the center of each cluster.

Examples

>>> kmeans(n_clusters=2) # run kmeans with 2 clusters
pca()[source]

Compute principal components analysis.

Returns

Tuple containing
  • (1d array): empirical mean of points cloud.

  • (2d array): component vectors sorted by explained variance.

  • (2d array): explained variance.

plot(ax, **kwds)[source]

Plot points cloud.

Parameters
  • ax – axis to be plotted.

  • projection (str) – support ‘3d’|’xy’|’xz’|’yz’ plot.

  • point_args (dic) – matplotlib arguments for plotting points.

  • equal_aspect (bool) – make equal aspect for both axes.

property size
test_isotropy(n_iter=100)[source]

Isotropic test using bootstraping.

Parameters

n_iter (int) – number of bootstraping iterations.

Returns

p_value.

to_curve()[source]

Convert to Curve under the assumption that the points are listed in order

Returns

a Curve object

to_surface_alphashape(alpha=None)[source]

Convert to Surface by computing the alpha shape, i.e. the ‘concave up to concavities of size alpha’ hull. Assume a relatively homogeneous repartition of the points.

Returns

a Surface object

to_surface_qhull()[source]

Convert to Surface by computing the convex hull.

Returns

a Surface object

transform(phi=0, theta=0, psi=0, dx=0, dy=0, dz=0, zx=1, zy=1, zz=1)[source]

Make transformation.

Parameters
  • phi (float) – rotation in x.

  • theta (float) – rotation in y.

  • psi (float) – rotation in z.

  • dx (float) – translation in x.

  • dy (float) – translation in y.

  • dz (float) – translation in z.

  • zx (float) – zoom in x.

  • zy (float) – zoom in y.

  • zz (float) – zoom in z.

Returns

Points.

genepy3d.obj.points.emd(ps1, ps2, return_flows=False)[source]

Compute Earth Mover’s Distance (EMD) between two point clouds ps1, ps2 of equal size.

Parameters
  • ps1 (Points) – point cloud.

  • ps2 (Points) – point cloud.

  • return_flows (bool) – if True then return maching flows between ps1 and ps2.

Returns

EMD distance between ps1 and ps2 and if return_flows is True, then return array of matching flows.

genepy3d.obj.points.gen_blobs(**kwargs)[source]

Generate isotropic gaussian blobs for clustering. Convenience function around sklearn.

Parameters

**kwargs – make_blobs keyword agruments in scikitlearn.

Returns

Tuple containing
  • Points.

  • labels (array) : point label.

genepy3d.obj.points.gen_ellipsoid(axes_length=[1.0, 1.0, 1.0], n=100)[source]

Generate random point cloud on the surface of an ellipsoid.

Parameters
  • axes_length (list of float) – half length of the main axis along the three axes ([1.,1.,1.])

  • n (int) – number of point (100)

Returns

Points.

genepy3d.obj.points.gen_gaussian_points(n=1000, center=[0, 0, 0], scales=[1.0, 1.0, 1.0], orientation=[0, 1.5707963267948966])[source]

Generate point cloud by Gaussian sampling.

Parameters
  • n (int) – sample’s size.

  • center (list of float) – center of points cloud.

  • scales (float | array of float) – standard deviations along the three main axis.

  • orientation (array) – spherical coordinates of the first axis.

Returns

Points.

genepy3d.obj.points.gen_sphere(n=1000, rho=1)[source]

Generate random uniform point cloud on a sphere.

Parameters
  • n (int) – sample’s size.

  • rho (int or float) – sphere’s radius.

Returns

Points.

genepy3d.obj.surfaces module

class genepy3d.obj.surfaces.Surface(vertices=None, faces=None, face_normals=None, vertex_normals=None, face_colors=None, vertex_colors=None, face_attributes=None, vertex_attributes=None, metadata=None, process=True, validate=False, merge_tex=None, merge_norm=None, use_embree=True, initial_cache=None, visual=None, **kwargs)[source]

Bases: Trimesh

Triangulated surface in 3D; inherits from Trimesh and thus is triangulated upon creation if the mesh is not a triangulation.

vertices

vertices coordinates.

Type

2d numpy array (float)

faces

index of the vertices of each of the simplices.

Type

2d numpy array (float)

export_to_VTK(filepath, kind='PolyData')[source]

export surface in VTK fileformat, either as PolyData or unstructuredGrid

Parameters
  • filepath (string) – path to export the file to, with no extention

  • kind (string) – one of ‘PolyData’ or ‘UnstructuredGrid’ (default:’PolyData’)

classmethod from_STL(afile, xy2zratio=None, center=False)[source]

Create surface object from STL file. Does no check on the loaded mesh.

Parameters
  • afile (string) – path to load

  • xy2zratio (float) – in case of anisotromic measurement, ratio to apply to z coordinates w.r.t. x and y

  • center (bool) – center the mesh

Returns

a Surface object

classmethod from_points_alpha_shape(points, alpha)[source]

Create surface object from point cloud via the alpha-shape algorithms. The result is the set triangles part of tetrahedrals with a circumsphere of radius less that alpha that face outward. !! There is no guarenty on the topology of the resulting mesh.

Python implementation from https://stackoverflow.com/questions/26303878/alpha-shapes-in-3d

Args:

points (nx3 array of float): coordinates of point cloud alpha (float): value of alpha

Returns:

a Surface object

classmethod from_points_qhull(points)[source]

Create surface object from point cloud via the convex hull algorithms.

Parameters

points (nx3 array of float) – coordinates of point cloud

Returns

a Surface object

classmethod from_volume(vol, lbl, spacing=(1.0, 1.0, 1.0), step_size=1, level=0.5, opening=False, fillholes=False)[source]

Create isosurface from 3D volume by marching cubes.

Parameters
  • vol (3D numpy array) – 3D volume.

  • lbl (int) – voxel label.

  • spacing (tuple (float)) – voxel spacing using in marching cubes.

  • step_size (int) – parameter defining the mesh resolution (higher step_size yields coarser mesh).

  • level (float) – between 0 and 1, determine proportion between background (0.) and foreground (1.) in volume.

  • opening (bool) – preprocess volumne by morphology opening.

  • fillholes (bool) – preprocess volumne by morphology fillholes.

Returns

Surface.

plot(ax, **kwds)[source]

Plot outline in 3d or 2d (xy, xz and yz).

Args

ax: axis to be plotted. projection (str): support ‘3d’|’xy’|’xz’|’yz’. scales: (tuples [float]): scales in x y and z. args_3d (dic): matplotlib arguments to plot 3d boundary (set of 3d polygons). args_2d (dic): matplotlib arguments to plot 2d boundary. equal_aspect (bool): make equal aspect for both axes.

split()[source]

Override split() by casting Trimesh to Surface.

to_points()[source]

Convert to Points

Returns

a Points object, consisting of the vertices of the mesh

genepy3d.obj.trees module

class genepy3d.obj.trees.Tree(_nodes, _id=0, _name='GeNePy3D')[source]

Bases: object

Tree in 3D. Uses the anytree package for may underlying representation and functions.

nodes

structure of tree nodes.

Type

anytree

id

tree ID (optional).

Type

int

name

tree name (optional).

Type

str

static build_treenodes(nodes_tbl, connectors_tbl)[source]

Building tree object using anytree package.

Parameters
  • nodes_tbl (pandas dataframe) – tree nodes table.

  • connectors_tbl (pandas dataframe) – connectors table.

compute_length(nodeid=None, rootid=None)[source]

Return length of the tree of part of it. If nodeid is none, compute length of the whole tree. Else compute the length of the given set of nodes, assuming they are contiguous and ordered.

Parameters

nodeid (list[int]) – list of node IDs or None. (default None)

Returns

int.

compute_local_3d_scale(r_lst, dim_param=None, decomposed_method='leaf', rootid=None)[source]

Compute 3d local scale of neuron.

This function is DEPRECATED. Use compute_local_3d_scale_radius().

Parameters
  • r_lst (list) – list of scales (radius of curvature)

  • dim_param (dic) – parameters for dimension decomposition

  • decomposed_method (str) – “leaf”, “spine” or “branching”, method for cutting neuronal trace

  • rootid (int) – ID of root

Returns

Pandas dataframe containing local 3D scale, 1D, 2D, 3D flags, curvature and torsion

compute_local_3d_scale_radius(r_lst, dim_param=None, decomposed_method='leaf', rootid=None)[source]

Compute 3d local scale of neuron from a list of radius of curvatures.

Parameters
  • r_lst (list) – list of scales (radius of curvature)

  • dim_param (dic) – parameters for dimension decomposition

  • decomposed_method (str) – “leaf”, “spine” or “branching”, method for cutting neuronal trace

  • rootid (int) – ID of root

Returns

Pandas dataframe containing local 3D scale, 1D, 2D, 3D flags, curvature and torsion

compute_local_3d_scale_sigma(sig_lst, dim_param=None, decomposed_method='leaf', rootid=None)[source]

Compute 3d local scale of neuron from a list of sigma of Gaussian.

Parameters
  • sig_lst (list) – list of sigma values of Gaussian.

  • dim_param (dic) – parameters for dimension decomposition

  • decomposed_method (str) – “leaf”, “spine” or “branching”, method for cutting neuronal trace

  • rootid (int) – ID of root

Returns

Pandas dataframe containing local 3D scale, 1D, 2D, 3D flags, curvature and torsion

compute_orientation(decomposed_method='leaf', sigma=0, rootid=None)[source]

Return orientation vector and angles with x, y and z axes.

Parameters
  • decomposed_method (str) – “leaf”, “spine” or “branching”, method for cutting neuronal trace

  • sigma (float) – sigma used in Gaussian filter for smoothing tree branches

  • rootid (int) – ID of root

Returns

Pandas dataframe containing vectors and angles at every nodes.

compute_spine(rootid=None)[source]

Return spine node IDs (longest branch from root).

Returns

list of int.

compute_strahler_order(nodeid=None, rootid=None)[source]

Return strahler order for given node IDs.

Parameters

nodeid (int|list[int]) – list of node IDs.

Returns

Pandas serie whose indices are node IDs and values are corresponding strahler orders.

copy(rootid=None)[source]

Copy tree.

decompose_leaves(rootid=None)[source]

Decompose tree into segments starting from root to every leaf.

Returns

dictionary whose keys are leaf IDs and values are list of node IDs from root to leaf.

decompose_segments(rootid=None)[source]

Decompose tree in segments separating by branching nodes.

Returns

dictionary whose each item is a list of nodes IDs specifying indices of a segment.

decompose_spines(rootid=None)[source]

Decompose tree into list of spines starting from root node.

Returns

list whose each item is an array of nodes IDs specifying a specific spine.

extract_subtrees(nodeid, to_children=True, separate_children=False, rootid=None)[source]

Extract a sub tree from the given node.

Parameters
  • nodeid (int) – node ID that becomes new root node in the sub tree.

  • to_children (bool) – if False, then extract upper subtree, else lower subtrees are extracted.

  • separate_children (bool) – if True, then different subtrees are extracted from children. Only available if to_children = True.

  • rootid (int) – ID of root.

Returns

list of Tree objects.

classmethod from_catmaid_server(catmaid_host, token, project_id, neuron_id)[source]

Build tree from CATMAID.

Parameters
  • catmaid_host (str) – address of CATMAID server

  • token (str) – authenticated string

  • project_id (int) – project ID

  • neuron_id (int) – neuron ID

classmethod from_eswc(filepath)[source]

Build tree from ESWC file. The ESWC is used e.g. Vaa3D.

Parameters

filepath (str) – path to eswc file.

classmethod from_swc(filepath)[source]

Build tree from SWC file.

Parameters

filepath (str) – path to swc file.

classmethod from_table(nodes_tbl, connectors_tbl=None, tree_id=0, tree_name='genepy3d')[source]

Build tree from Pandas dataframes.

Parameters
  • nodes_tbl (pandas dataframe) – tree nodes table.

  • connectors_tbl (pandas dataframe) – connector table.

  • tree_id (int) – tree ID.

  • tree_name (str) – tree name.

get_branchingnodes(rootid=None)[source]

Return branching node IDs.

Returns

list of int.

get_children(nodeid)[source]

Return children ids of nodeid.

get_connectors(rootid=None)[source]

Return list of connector node IDs.

Returns

Pandas dataframe whose indices are node IDs and values are corresponding connector types, connector ids.

get_coordinates(nodeid=None, rootid=None)[source]

Return coordinates of given nodes.

Parameters

nodes (int | list of int) – list of node IDs.

Returns

Pandas dataframe whose indices are node IDs and values are corresponding coordinates.

get_leaves(rootid=None)[source]

Return list of leaf node IDs.

Returns

list of int.

get_nodes_number(rootid=None)[source]

Return the number of nodes in tree.

get_parent(nodeid)[source]

Return parent id of node id.

get_preorder_nodes(rootid=None)[source]

Return list of nodes in tree.

get_root()[source]

Return root node ID.

Returns

int.

path(target, source=None, rootid=None)[source]

Find list of nodes going from source node to target node.

Parameters
  • target (int) – target node ID.

  • source (int) – source node ID.

Returns

list of traveled node IDs included source and target node IDs.

plot(ax, projection='3d', rootid=None, spine_only=False, show_root=True, show_leaves=True, show_branchingnodes=True, show_connectors=True, root_args={}, leaves_args={}, branchingnodes_args={}, connectors_args={}, weights=None, weights_display_type='c', point_args={}, show_cbar=False, cbar_args={}, line_args={}, scales=(1.0, 1.0, 1.0), equal_axis=True)[source]

Plot tree.

Parameters
  • ax – plot axis.

  • projection (str) – we support 3d, xy, xz, yz modes.

  • spine_only (bool) – if True, then only plot tree spine.

  • show_root (bool) – if True, then display root node.

  • show_leaves (bool) – if True, then display leaves nodes.

  • show_branchingnodes (bool) – if True, then display branching nodes.

  • show_connectors (bool) – if True, then display connector nodes.

  • root_args (dic) – plot params for root node.

  • leaves_args (dic) – plot params for leaves nodes.

  • branchingnodes_args (dic) – plot params for branching nodes.

  • connectors_args (dic) – plot params for connectors nodes.

  • weights (pandas serie) – serie indexed by node ID and contains corresponding weights

  • weights_display_type (str) – “s” for point size or “c” for point color.

  • point_args (dic) – point plot params.

  • line_args (dic) – line plot params.

  • scales (tuple of float) – use to set x, y and z scales.

  • equal_axis (bool) – fix equal axes.

Note

spine_only should be removed. We can consider it as a curve.

prune_leaves(nodeid=None, length=None, rootid=None)[source]

Prune leaf branching based on its length.

Parameters
  • nodeid (list [int]) – list of leaves IDs to be pruned. If None, then take all leaves into account.

  • length (float) – length threshold for pruning leaf branching from leaves given by nodeid.

  • rootid (int) – ID of root.

Returns

new Tree after pruning.

resample(unit_length=None, rootid=None, spline_order=1, smooth_spline=False, decompose_method='branching')[source]

Resampling tree.

Parameters
  • rootid (int) – id of root node.

  • unit_length (float) – if not None, then npoints is calculated from it.

  • spline_order (uint) – 1 means linear interpolation.

Returns

Tree() resampled tree.

summary()[source]

Return a brief summary of tree.

Returns

pandas serie.

to_curve(nodeid=None)[source]

Convert a segment of tree given by nodeid list to Curve.

to_points(nodeid=None)[source]

Convert to Points.

Module contents