Please check the documentation of each function to see if it supports 2D curve.
We assumme that curve is a parametric function g(t) = (x(t),y(t),z(t)).
If 2D points are passed then we consider only X and Y coordinates and set Z = 0.
The Curve is assumed open and with no duplicated positions.
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
Examples
importnumpyasnpfromgenepy3d.obj.curvesimportCurve# Curve from array inputcoors=np.array([[1,2,3],[1,2,3],[1,2,3]])crv=Curve(coors)# Curve from tuple inputcoors=([1,1,1],[2,2,2],[3,3,3])crv=Curve(coors)
Compute the angle (directional change) at a give point and its orientation (CW or CCW).
Assume three points A => B => C. The direction change at B is the angle between two vectors
(A->B) and (B->C). The sign of angle indicates CW (negative) or CCW (positive) rotation (only work in 2D).
importnumpyasnpfromgenepy3d.objimportcurves# 3D curve from a helixt=np.arange(50)a=1.b=1.x=a*np.cos(t/5)y=a*np.sin(t/5)z=b*tcrv=curves.Curve((x,y,z))# Angles w.r.t. x-vectorcrv.compute_direction_change()
Angle between two vectors from two nearby points of a given point.
The first and last points are not counted.
Assumming three consecutive nodes A, B, C, the angle at node B is the angle between two vector (B=>A) and (B=>C).
Support 2D: YES.
Returns:
Array of angles.
Examples
importnumpyasnpfromgenepy3d.objimportcurves# 3D curve from a helixt=np.arange(50)a=1.b=1.x=a*np.cos(t/5)y=a*np.sin(t/5)z=b*tcrv=curves.Curve((x,y,z))# Angles w.r.t. x-vectorcrv.compute_angles()
Angles between vector at a node on the curve and a vector u.
Assuming two consecutive nodes A, B, the angle at the node A is the angle between vector (A=>B) and vector u.
Parameters:
u (array (float)) – vector used to compute angles. If None, then return angles with three x, y and z axes.
Returns:
Array of angles.
Examples
importnumpyasnpfromgenepy3d.objimportcurves# 3D curve from a helixt=np.arange(50)a=1.b=1.x=a*np.cos(t/5)y=a*np.sin(t/5)z=b*tcrv=curves.Curve((x,y,z))# Angles w.r.t. x-vectorcrv.compute_angles_vector(np.array([1.,0.,0.]))# Angles w.r.t. three axes x, y and z# Return array with 3 columns for angles in x, y and z respectivelycrv.compute_angles_vector()
Due to the side effect when computing the derivative, the curvature can be not very accurate at the extremal points of the curve.
The number of points affected at each of the two extremes is 2.
Due to the side effect when computing the derivative, the torsion can be not very accurate at the extremal points of the curve.
The number of points affected at each of the two extremes is 3.
Apply the same rigid transformation to every point on the curve.
Parameters:
phi (float) – rotation in x in radian.
theta (float) – rotation in y in radian.
psi (float) – rotation in z in radian.
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:
a Curve object.
Examples
importnumpyasnpfromgenepy3d.objimportcurvesimportmatplotlib.pyplotasplt# 3D curve from a helixt=np.arange(50)a=1.b=1.x=a*np.cos(t/5)y=a*np.sin(t/5)z=b*tcrv=curves.Curve((x,y,z))# Plot the curvefig=plt.figure()ax=fig.add_subplot(111,projection='3d')crv.plot(ax);# Rotate by 90 degree around x# Then, shift by 10 in ycrv_transformed=crv.transform(phi=np.pi/2.,dy=10)# Plot the transformed curvefig=plt.figure()ax=fig.add_subplot(111,projection='3d')crv_transformed.plot(ax);
Get curve at a specific scale sigma by Gaussian convolution.
Also support 2D.
Parameters:
sigma (float or list of floats) – scale.
mo (str) – mode used to treat the border effect (see gaussian_filter1d() in scipy for detail).
kerlen (float) – specify the length of Gaussian kernel (see gaussian_filter1d() in scipy for detail).
Returns:
Curve object.
Examples
importnumpyasnpfromgenepy3d.objimportcurvesimportmatplotlib.pyplotasplt# 3D curve from a helixt=np.arange(50)a=1.b=1.x=a*np.cos(t/5)y=a*np.sin(t/5)z=b*tcrv=curves.Curve((x,y,z))# Plot the curvefig=plt.figure()ax=fig.add_subplot(111,projection='3d')crv.plot(ax);sigma=5crv_gauss=crv.convolve_gaussian(sigma)# Plot the smoothed curvefig=plt.figure()ax=fig.add_subplot(111,projection='3d')crv_gauss.plot(ax);
unit_length (float) – sampling length. If None, then the curve is resampled from the input npoints.
npoints (int) – number of resampled points. If None, then the number of resampled points is equal to the current number of points on the curve (i.e. before resampling).
spline_order (uint) – if it equal 1, then the linear interpolation is used. Otherwise, spline interpolation is used. Please see interpolate.splprep() in scipy for more detail.
return_interp_param (bool) – if True then return interpolation parameters.
Returns:
Curve object.
Notes
Only choose to resample the curve by either the unit_length or npoints.
The resampling can be failed in some cases due to the spline interpolation constraints. Please see interpolate.splprep() in scipy for more detail.
Examples
importnumpyasnpfromgenepy3d.objimportcurvesimportmatplotlib.pyplotasplt# 3D curve from a helixt=np.arange(20)a=1.b=1.x=a*np.cos(t/5)y=a*np.sin(t/5)z=b*tcrv=curves.Curve((x,y,z))# Plot the curvefig=plt.figure()ax=fig.add_subplot(111,projection='3d')crv.plot(ax,point_args={"c":"r"});# set point_args to display the points on the curve# Resample by 50 pointscrv_resampled=crv.resample(npoints=50)# Plot the resampled curvefig=plt.figure()ax=fig.add_subplot(111,projection='3d')crv_resampled.plot(ax,point_args={"c":"r"});
Noise variances across x, y and z axes of the curve are estimated using the beta-sigma algorithm implemented in PyAstronomy [1].
The curve is then denoised by Gaussian convolution of an initial sigma = sigma_step.
We repeat the denoising process by increasing sigma_step until the stdev between the denoised curve and the noisy curve approaches the estimated noise variances.
The process will be also stopped if the number of iteration >= max_iter.
Parameters:
sigma_step (float) – initial sigma of Gaussian used to smooth the curve.
max_iter (int) – maximal number of iteration. If None, then max_iter = number of points on the curve.
return_sigma (bool) – if True, then return the estimated sigmas in x, y and z.
Returns:
a denoised Curve object and list of estimated sigmas if return_sigma is True. If failed, then return None.
References
Notes
We assume noise follows the normal distribution. The denoising can be ineffecient if noise follows another distribution.
The denoise() cannot guarantee an optimal noise removal, especially when the noise level is high.
Examples
importnumpyasnpfromgenepy3d.objimportcurvesimportmatplotlib.pyplotasplt# 3D curve from a helixn=200# number of pointst=np.arange(n)a=1.b=1.sigma=0.2# sigma of noise to add into the curvex=a*np.cos(t/5)+np.random.normal(0,sigma,n)y=a*np.sin(t/5)+np.random.normal(0,sigma,n)z=b*t+np.random.normal(0,sigma,n)crv=curves.Curve((x,y,z))# Plot the noisy curvefig=plt.figure()ax=fig.add_subplot(111,projection='3d')crv.plot(ax,point_args={"c":"r"});# set point_args to display the points on the curve# Denoised the curvecrv_denoised,sigma_est=crv.denoise(return_sigma=True)print(sigma_est)# Plot the denoised curvefig=plt.figure()ax=fig.add_subplot(111,projection='3d')crv_denoised.plot(ax,point_args={"c":"r"});
We compute e.g. the curvatures, torsions, etc of a curve convolved by Gaussian of a given sigma.
The process repeats over increasing sigma and produce finally a feature-scale space of the curve.
Parameters:
scale_range (array of float) – range of scales (sigma of Gaussian).
features (dic) – list of features (detail see below).
eps_tau (float) – torsion threshold. (for line and planeline features)
eps_seg (float) – segment length threshold (in number of points, for line and planeline features).
Returns:
dictionary whose each item is a scale space matrix of a specific feature,
the rows of matrix 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.
The line and planeline scale space were used to compute the local 3d scale of the curve. See compute_local_3d_scale_sigma() for detail.
The curvature scale space was used to compute the main turns of the curve. See main_turns() for detail.
Examples
importnumpyasnpfromgenepy3d.objimportcurvesimportmatplotlib.pyplotasplt# 3D curve from a helixt=np.arange(100)a=1.b=1.x=a*np.cos(t/5)y=a*np.sin(t/5)z=b*tcrv=curves.Curve((x,y,z))# Plot the curvefig=plt.figure()ax=fig.add_subplot(111,projection='3d')crv.plot(ax);scale_range=np.arange(0,50.,1)# sigma rangesfeatures=crv.scale_space(scale_range,features={'curvature'})# curvature scale spacekappa_space=features['curvature']# Plot the curvature scale spacefig=plt.figure()ax=fig.add_subplot(111)pl=ax.imshow(kappa_space)ax.invert_yaxis();fig.colorbar(pl)
Decompose curve into multiscale hierarchichal intrinsic segments at a given sigma sig_c.
The function decomposes the curve into portions of 1D lines, 2D planes or 3D at a given scale sig_c.
The decomposition is hierarchichal, i.e. 1D lines can be detected from a 2D plane portion.
The detail of algorithm can be found [1].
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.
References
Notes
The decomposition can be visualized using plot_decomposed_table() and plot_intrinsicdim().
Display curve superimposed by estimated intrinsic dimensions.
It 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.
Local 3D scale: scale at which point transforms from 3D to 2D/1D.
This function is DEPRECATED. Use compute_local_3d_scale_radius() or compute_local_3d_scale_sigma().
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.
Main turns are the positions on the curve showing important changes of orientation.
We calculate the curvature scale space of the curve across a range of sigmas (Gaussian func).
Then, track the change of curvatures of points on the curve within the curvature scale space.
Finally, select the points as the main turns based on some criteria.
Parameters:
sig_lst (list (float)) – list of sigma values used to compute curvature scale space.
search_step (int) – number of neighboring points that are grouped to find the main turns.
eps_kappa (float) – curvature threshold.
The points whose curvatures are larger than the eps_kappa are taken as the candidates to find the main turns.
If None, then it is set relatively to the maximal curvature of the curve.
ridgelength_thr (float) – ridge length threshold (in % compared to the longest ridge).
ridge is a track of a point in the curvature scale space. The point whose ridge length is larger than the ridgelength_thr is considered as main turn.
angle_thr (float) – angle threshold in degree. Remove position whose angle is smaller than the angle_thr.
min_dist (float) – minimal distance between two main turns. Make sure that the distance between two main turns is not smaller than min_dist.
Main turns are the positions on the curve showing important changes of orientation.
We calculate the curvature scale space of the curve across a range of sigmas (Gaussian func).
Then, track the change of curvatures of points on the curve within the curvature scale space.
Finally, select the points as the main turns based on some criteria.
The sigmas are defined from ``nbscales` input. sigmas = [0, 1, …, nbscales]
This function is DEPRECATED. Please refer to main_turns().
Parameters:
nbscales (int) – number of scales used to compute the curvature scale space. If None, then it is set as halft of number of points of the curve.
search_step (int) – number of neighboring points that are grouped to find the main turns.
eps_kappa (float) – curvature threshold.
The points whose curvatures are larger than the eps_kappa are taken as the candidates to find the main turns.
If None, then it is set relatively to the maximal curvature of the curve.
ridgelength_thr (float) – ridge length threshold (in % compared to the longest ridge).
ridge is a track of a point in the curvature scale space. The point whose ridge length is larger than the ridgelength_thr is considered as main turn.
angle_thr (float) – angle threshold in degree. Remove position whose angle is smaller than the angle_thr.
min_dist (float) – minimal distance between two main turns. Make sure that the distance between two main turns is not smaller than min_dist.
projection (str) – support ‘3d’, ‘xy’, ‘xz’ and ‘yz’.
scales (tuple) – scale in x, y and z.
show_root (bool) – If True, then show the root position (the first point).
root_args (dic) – Pass this to the scatter() in matplotlib.
line_args (dic) – Pass this to the plot() in matplotlib.
point_args (dic) – Pass this to the scatter() in matplotlib.
Examples
importnumpyasnpfromgenepy3d.objimportcurvesimportmatplotlib.pyplotasplt# 3D curve from a helixn=200# number of pointst=np.arange(n)a=1.b=1.x=a*np.cos(t/5)y=a*np.sin(t/5)z=b*tcrv=curves.Curve((x,y,z))# Plot the noisy curvefig=plt.figure()ax=fig.add_subplot(111,projection='3d')crv.plot(ax,point_args={"c":"r"});# set point_args to display the points on the curve
Generate curve in 3D with random intrinsic dimension segments.
The process is simulated based on 2D and 3D Brownian motion.
See active_brownian_2d() and active_brownian_3d() in genepy3d.util.geo module for the generation of Brownian motion.
if True, then replace the ‘0,0,..’ sequence into only one ‘0’.
Type:
bool
Notes
specify either seg_lbl, max_seg or nb_seg whose priority order is seg_lbl first, then max_seg and nb_seg.
Examples
fromgenepy3d.objimportcurvesimportmatplotlib.pyplotasplt# Create a simulator to generate curve consists of 3D=>1D=>3D=>2D=>1D=>3D segments.simulator=curves.SimuIntrinsic(seg_lbl=[0,2,0,1,2,0]).gen()print("Number of points:",simulator.npoints)print("Line indices:",simulator.line_ids)print("Plane indices:",simulator.plane_ids)# Plot the simulated curvefig=plt.figure()ax=fig.add_subplot(111,projection='3d')simulator.plot(ax)
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 the Points class to compute the Earth Mover’s Distance between two point clouds.
if array is given, then each column is the x, y, z coordinates.
if tuple is given, then the items are the three arrays of x, y and z coordinates.
Type:
array | tuple
Examples
fromgenepy3d.objimportpointsfromsklearn.datasetsimportmake_blobsimportmatplotlib.pyplotasplt# Generate two clusters of 3D pointscoors,_=make_blobs(n_features=3,centers=[(0,0,0),(5,5,5)])# Create Points objectpnts=points.Points(coors)# Plotfig=plt.figure()ax=fig.add_subplot(111,projection='3d')pnts.plot(ax)
Create Points object from x, y and z coordinates in the csv file.
Parameters:
filepath (str) – path of the csv file.
column_names (list of str) – coordinates columns in the csv file.
scales (tuple of float) – scales in x, y and z.
args (dict) – overried parameters of pandas.read_csv().
Returns:
A Points object.
Examples
fromgenepy3d.objimportpointsfilepath="path/to/your/csv/file.csv"# Create Points object from column "x", "y", "z" in the given csv filepnts=points.Points.from_csv(filepath)
Append a new points cloud to the current points cloud.
Parameters:
new_points (Points) – a Points object to be appended.
Notes
The coordinates of the current Points object will be updated.
Examples
fromgenepy3d.objimportpointsfromsklearn.datasetsimportmake_blobsimportmatplotlib.pyplotasplt# Create Points object from blob cluster centered at (0,0,0)coors,_=make_blobs(n_features=3,centers=[(0,0,0)])pnts_1=points.Points(coors)# Plot the pnts_1fig=plt.figure()ax=fig.add_subplot(111,projection='3d')pnts_1.plot(ax)# Create Points object from blob cluster centered at (5,5,5)coors,_=make_blobs(n_features=3,centers=[(5,5,5)])pnts_2=points.Points(coors)# Append pnts_2 into pnts_1pnts_1.append(pnts_2)# Plot the pnts_1 after appending the pnts_2fig=plt.figure()ax=fig.add_subplot(111,projection='3d')pnts_1.plot(ax)
importnumpyasnpfromgenepy3d.objimportpointsfromsklearn.datasetsimportmake_blobsimportmatplotlib.pyplotasplt# Generate 3D points cloud contains two clusterscoors,_=make_blobs(n_features=3,centers=[(0,0,0),(5,5,5)])pnts=points.Points(coors)# Plot the points cloudfig=plt.figure()ax=fig.add_subplot(111,projection='3d')pnts.plot(ax)# Rotate points cloud around z by 90 degrees.pnts_transformed=pnts.transform(psi=np.pi/2.)# Plot the rotated pointspnts_transformed.plot(ax,point_args={'color':'r'})
fromgenepy3d.objimportpointsfromsklearn.datasetsimportmake_blobsimportmatplotlib.pyplotasplt# Generate 3D points cloud contains two clusterscoors,_=make_blobs(n_features=3,centers=[(0,0,0),(5,5,5)])pnts=points.Points(coors)# Plotfig=plt.figure()ax=fig.add_subplot(111,projection='3d')pnts.plot(ax)# Compute the z-intercept and the normal vector of the hyperplane that fit the point cloudz0,normal=pnts.fit_plane()
Compute principal components analysis from the points cloud.
Returns:
Tuple containing
(1d array): empirical mean of points cloud.
(2d array): component vectors sorted by explained variances.
(2d array): explained variances.
Examples
fromgenepy3d.objimportpointsimportmatplotlib.pyplotasplt# Generate random points on the surface of a 3D ellipsoidpnts=points.gen_ellipsoid(axes_length=(1.5,1.,0.5),n=500)# PCAmeans,components,variances=pnts.pca()# Plotfig=plt.figure()ax=fig.add_subplot(111,projection='3d')pnts.plot(ax,point_args={"alpha":0.3})ax.quiver(means[0],means[1],means[2],components[0,0],components[0,1],components[0,2],length=2*variances[0],color='red')ax.quiver(means[0],means[1],means[2],components[1,0],components[1,1],components[1,2],length=2*variances[1],color='red')ax.quiver(means[0],means[1],means[2],components[2,0],components[2,1],components[2,2],length=2*variances[2],color='red')
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.
Please see surfaces.Surface.from_points_alpha_shape().
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.
References
Examples
importnumpyasnpfromgenepy3d.objimportpointsimportmatplotlib.pyplotasplt# Generate two points cloudsx=np.arange(10)y=xz=np.zeros(10)pnt1=points.Points((x,y,z))pnt2=pnt1.transform(dx=20)# translate in x# EMDdist,flows=points.emd(pnt1,pnt2,return_flows=True)print(dist)print(flows)# Plotfig=plt.figure()ax=fig.add_subplot(111,projection='3d')pnt1.plot(ax)pnt2.plot(ax)
Generate random uniform points cloud on the surface of an ellipsoid.
Parameters:
axes_length (list of float) – half lengths of the major, median and minor axis.
n (int) – number of points to be generated.
Returns:
A Points object.
Examples
fromgenepy3d.objimportpointsimportmatplotlib.pyplotasplt# Generate random points on the surface of 3D ellipsoidpnts=points.gen_ellipsoid(axes_length=(1.5,1.,0.5),n=500)# Plotfig=plt.figure()ax=fig.add_subplot(111,projection='3d')pnts.plot(ax)
fromgenepy3d.objimportpointsimportmatplotlib.pyplotasplt# Generate random points on the surface of 3D spherepnts=points.gen_sphere(r=1,n=500)# Plotfig=plt.figure()ax=fig.add_subplot(111,projection='3d')pnts.plot(ax)
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.
Examples
importnumpyasnpfromgenepy3d.objimportsurfacesimportmatplotlib.pyplotasplt# coors = np.array(...): array whose columns are x, y and z coordinatessurf=surfaces.Surface.from_points_qhull(coors)# surface from convex hullfig=plt.figure()ax=fig.add_subplot(111,projection='3d')surf.plot(ax);
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.
Parameters:
points (nx3 array of float) – coordinates of point cloud.
alpha (float) – value of alpha.
Returns:
a Surface instace.
Notes
There is no guarantee on the topology of the resulting mesh.
Examples
importnumpyasnpfromgenepy3d.objimportsurfacesfromgenepy3d.utilimportgeoimportmatplotlib.pyplotasplt# coors = np.array(...): array whose columns are x, y and z coordinates# Diagonal distance of the bounding box of the point cloud# Alpha value can be set relatively to this distance# Larger value of alpha produces surface closer to the convex hullmin_coors=np.min(coors,axis=0)max_coors=np.max(coors,axis=0)diadst=geo.l2(min_coors,max_coors)# diagonal distancealpha=diadst/3.# alpha value# Surface from the alpha shapesurf=surfaces.Surface.from_points_alpha_shape(coors,alpha)fig=plt.figure()ax=fig.add_subplot(111,projection='3d')surf.plot(ax)
Create isosurface of a 3D voxels volume from image stack using marching cubes.
We assume that the image stack contains multiple volumic objects specified by integer labels.
This function extracts the volume of a given label, then estimates the outlined surface using marching cubes from scikit-image.
Parameters:
vol (3D ndarray) – 3D volume.
lbl (int) – voxel label of the volume to be extracted from the image stack.
spacing (tuple (float)) – voxel spacing using in marching cubes.
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:
a Surface object.
Examples
importnumpyasnpfromgenepy3d.objimportsurfacesimportmatplotlib.pyplotaspltstack=np.zeros((100,100,100))# an image stack of size 100x100x100stack[20:40,20:40,20:40]=1# a volume of label = 1surf=surfaces.Surface.from_volume(stack,1)# outline surface of volumefig=plt.figure()ax=fig.add_subplot(111,projection='3d')surf.plot(ax);
where minor, median and major are lengths of the elliposoid fitting the surface.
These lengths can be found from the orient bounding box of the surface.
Assuming the surface has a paraboloid form. This function estimate the centroid lying on the surface.
It’s not similar to the centroid computed by averaging faces positions.
It needs at least nodes_tbl to create the tree object.
The nodes_tbl stores information of nodes and their linked parent-nodes.
It is the same as in the SWC file specification. Please see this [1] for more detail.
The column names must include:
treenode_id: ID of node
structure_id: ID of node structure (see the column Structure Identifier in [1] for the meaning).
x, y, z: coordinates of node
r: radius of node
parent_treenode_id: ID of parent node
The table connectors_tbl is optional.
It is used to describe the synaptic connection between neuronal trees. It is the same as connector table in CATMAID [2].
It must consist of columns:
connector_id: ID of a connector
treenode_id: ID of a treenode from a neuronal tree object
relation_id: connectomic relation, must be ‘presynaptic_to’ or ‘postsynaptic_to’ (see [3] to understand about connectomic relation in CATMAID)
References
Examples
importpandasaspdfromgenepy3d.objimporttreesimportmatplotlib.pyplotasplt# Generate a dummy nodes datadata=[[0,0,0.,0.,0.,1.,-1],[1,0,1.,2.,3.,1.,0],[2,0,4.,5.,6.,1.,1]]# Dataframe from nodes datanode_tbl=pd.DataFrame(data,columns=['treenode_id','structure_id','x','y','z','r','parent_treenode_id'])# Create a dummy neuron from node_tblneuron=trees.Tree.from_table(node_tbl)# Plot itfig=plt.figure()ax=fig.add_subplot(111,projection='3d')neuron.plot(ax)
fromgenepy3d.objimporttreesimportmatplotlib.pyplotasplt# An example of swc file can be downloaded from:# https://neuromorpho.org/neuron_info.jsp?neuron_name=AD1202-PMC-L-4201-fiber129swc_path="file/to/swc/file"neu=trees.Tree.from_swc(swc_path)fig=plt.figure()ax=fig.add_subplot(111,projection='3d')neu.plot(ax)
Build tree from ESWC file. The ESWC is used e.g. in Vaa3D-Neuron software [1].
ESWC is an extension of SWC with additional columns ‘segment_id’, ‘level’, ‘mode’, ‘timestamp’, ‘featureval’.
Parameters:
filepath (str) – path to eswc file.
Returns:
A Tree object.
Notes
ESWC has extended columns compared to default SWC file, but we don’t pass these extended columns into the Tree object.
We only pass the similar columns to the Tree object as in the SWC file.
References
Examples
Reading ESWC should be the same as reading SWC. Please see example from from_swc().
This function queries from the CATMAID server a neuronal trace given by a project_id and neuron_id.
The neuronal trace data is fetched using CATMAID API [2].
Parameters:
catmaid_host (str) – address of CATMAID server
token (str) – authenticated string
project_id (int) – project ID
neuron_id (int) – neuron ID
Returns:
A Tree object.
References
Examples
fromgenepy3d.objimporttrees# Replace these fake values with your owncatmaid_host='https://your-catmaid-host.com'token="9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b"project_id=1neuron_id=1# Retreive neuronal tree from from CATMAID hostneuron=trees.Tree.from_catmaid_server(catmaid_host,token,project_id,neuron_id)
Return the total length of the tree or subpart of the tree.
Parameters:
nodeid (list[int]) – list of node IDs. If None, then return the total length of the entire tree.
rootid (int) – root node ID. If None, then the first rootid will be taken.
Returns:
int.
Notes
If you provide a list of nodes. We consider it as a curve, then we return the curve length.
Examples
importpandasaspdfromgenepy3d.objimporttreesimportmatplotlib.pyplotasplt# Generate a dummy nodes datadata=[[0,0,0.,0.,0.,1.,-1],[1,0,1.,2.,3.,1.,0],[2,0,4.,5.,6.,1.,1],[3,0,5.,5.,5.,1.,1]]# Dataframe from nodes datanode_tbl=pd.DataFrame(data,columns=['treenode_id','structure_id','x','y','z','r','parent_treenode_id'])# Create a dummy neuron from node_tblneuron=trees.Tree.from_table(node_tbl)# Plot itfig=plt.figure()ax=fig.add_subplot(111,projection='3d')neuron.plot(ax)plt.tight_layout();# Total length of the entire neurontotal_length=neuron.compute_length()print(total_length)# Get a segment from root to the first branching pointsegment_lst=neuron.decompose_segments()print(segment_lst)segment=segment_lst['0_1']# Length of that segmentsegment_length=neuron.compute_length(segment)print(segment_length)
Find list of nodes going from source node to target node.
Parameters:
target (int) – target node ID.
source (int) – source node ID. If None, then we take root as the source.
rootid (int) – root node ID. If None, then the first rootid will be taken.
Returns:
list of traveled node IDs included source and target node IDs.
Examples
importpandasaspdfromgenepy3d.objimporttreesimportmatplotlib.pyplotasplt# Generate a dummy nodes datadata=[[0,0,0.,0.,0.,1.,-1],[1,0,1.,2.,3.,1.,0],[2,0,4.,5.,6.,1.,1],[3,0,5.,5.,5.,1.,1]]# Dataframe from nodes datanode_tbl=pd.DataFrame(data,columns=['treenode_id','structure_id','x','y','z','r','parent_treenode_id'])# Create a dummy neuron from node_tblneuron=trees.Tree.from_table(node_tbl)# Get ID of a leafleaf_node=neuron.get_leaves()[0]print(leaf_node)# Path from root to the leafprint(neuron.path(leaf_node))
nodeid (int) – node ID from that we extract the subtree. It becomes new root node in the subtree.
to_children (bool) – if False, then extract upper subtree (toward parent). Otherwise, lower subtrees are extracted (toward children).
separate_children (bool) – if True, then each subtree is extracted for each child. This parameter only works when setting to_children=True.
rootid (int) – root node ID. If None, then the first rootid will be taken.
Returns:
list of Tree objects.
Examples
importpandasaspdfromgenepy3d.objimporttreesimportmatplotlib.pyplotasplt# Generate a dummy nodes datadata=[[0,0,0.,0.,0.,1.,-1],[1,0,1.,2.,3.,1.,0],[2,0,4.,5.,6.,1.,1],[3,0,7.,2.,2.,1.,1],[4,0,6.,6.,6.,1.,2]]# Dataframe from nodes datanode_tbl=pd.DataFrame(data,columns=['treenode_id','structure_id','x','y','z','r','parent_treenode_id'])# Create a dummy neuron from node_tblneuron=trees.Tree.from_table(node_tbl)# Plot itfig=plt.figure()ax=fig.add_subplot(111,projection='3d')neuron.plot(ax)plt.tight_layout();# Get a branching nodebrnode=neuron.get_branchingnodes()[0]print(brnode)# Extract a subtree from the branching node toward its childrensubtree=neuron.extract_subtrees(brnode,to_children=True,separate_children=False)# Plot itfig=plt.figure()ax=fig.add_subplot(111,projection='3d')subtree.plot(ax)plt.tight_layout();# Extract list of subtress from the branching node toward its children# Each subtree is extracted from each childsubtree_lst=neuron.extract_subtrees(brnode,to_children=True,separate_children=True)# Plot first subtreefig=plt.figure()ax=fig.add_subplot(111,projection='3d')subtree_lst[0].plot(ax)plt.tight_layout();# Plot second subtreefig=plt.figure()ax=fig.add_subplot(111,projection='3d')subtree_lst[1].plot(ax)plt.tight_layout();
Decompose tree in segments separating by the branching nodes.
Parameters:
rootid (int) – root node ID. If None, then the first rootid will be taken.
Returns:
A dictionary whose each item is a decomposed segment, where
key is a string represents the first node and the last node of the decomposed segment.
value is a list of nodes IDs of the decomposed segment.
Examples
importpandasaspdfromgenepy3d.objimporttreesimportmatplotlib.pyplotasplt# Generate a dummy nodes datadata=[[0,0,0.,0.,0.,1.,-1],[1,0,1.,2.,3.,1.,0],[2,0,4.,5.,6.,1.,1],[3,0,7.,2.,2.,1.,1],[4,0,6.,6.,6.,1.,2],[5,0,3.,7.,6.,1.,2],[6,0,5.,5.,9.,1.,5]]# Dataframe from nodes datanode_tbl=pd.DataFrame(data,columns=['treenode_id','structure_id','x','y','z','r','parent_treenode_id'])# Create a dummy neuron from node_tblneuron=trees.Tree.from_table(node_tbl)# Plot neuronfig=plt.figure()ax=fig.add_subplot(111,projection='3d')neuron.plot(ax)# Plot node IDcoors=neuron.get_coordinates()fornodeidincoors.index:tmp=coors.loc[nodeid]ax.text(tmp.x-0.5,tmp.y+0.1,tmp.z+0.1,nodeid,fontsize=12)ax.axis('off');plt.tight_layout();# Decompose into segments separating by branching nodesprint(neuron.decompose_segments())# The output should be as follows:# {'2_4': [2, 4], '2_6': [2, 5, 6], '1_3': [1, 3], '0_1': [0, 1], '1_2': [1, 2]}
Decompose tree into segments starting from root to every leaf.
Parameters:
rootid (int) – root node ID. If None, then the first rootid will be taken.
Returns:
A dictionary whose each item is a decomposed segment, where
key is a string represents the leaf node of the decomposed segment.
value is a list of nodes IDs of the decomposed segment.
Examples
importpandasaspdfromgenepy3d.objimporttreesimportmatplotlib.pyplotasplt# Generate a dummy nodes datadata=[[0,0,0.,0.,0.,1.,-1],[1,0,1.,2.,3.,1.,0],[2,0,4.,5.,6.,1.,1],[3,0,7.,2.,2.,1.,1],[4,0,6.,6.,6.,1.,2],[5,0,3.,7.,6.,1.,2],[6,0,5.,5.,9.,1.,5]]# Dataframe from nodes datanode_tbl=pd.DataFrame(data,columns=['treenode_id','structure_id','x','y','z','r','parent_treenode_id'])# Create a dummy neuron from node_tblneuron=trees.Tree.from_table(node_tbl)# Plot neuronfig=plt.figure()ax=fig.add_subplot(111,projection='3d')neuron.plot(ax)# Plot node IDcoors=neuron.get_coordinates()fornodeidincoors.index:tmp=coors.loc[nodeid]ax.text(tmp.x-0.5,tmp.y+0.1,tmp.z+0.1,nodeid,fontsize=12)ax.axis('off');plt.tight_layout();# Decompose into segments from root to every leavesprint(neuron.decompose_leaves())# The output should be as follows:# {4: [0, 1, 2, 4], 6: [0, 1, 2, 5, 6], 3: [0, 1, 3]}
Decompose tree into list of spines (longest branches) starting from the root node.
We first extract the longest branch from the root to a leaf.
Then for every branching node on that longest branch, we extract the subtree from that, and repeat the process by extracting the longest branch of that subtree.
The process is repeated until no branch can be extracted.
Parameters:
rootid (int) – root node ID. If None, then the first rootid will be taken.
Returns:
A dictionary whose each item is a decomposed segment, where
key is a string represents the first node and the last node of the decomposed segment.
value is a list of nodes IDs of the decomposed segment.
Examples
importpandasaspdfromgenepy3d.objimporttreesimportmatplotlib.pyplotasplt# Generate a dummy nodes datadata=[[0,0,0.,0.,0.,1.,-1],[1,0,1.,2.,3.,1.,0],[2,0,4.,5.,6.,1.,1],[3,0,7.,2.,2.,1.,1],[4,0,6.,6.,6.,1.,2],[5,0,3.,7.,6.,1.,2],[6,0,5.,5.,9.,1.,5]]# Dataframe from nodes datanode_tbl=pd.DataFrame(data,columns=['treenode_id','structure_id','x','y','z','r','parent_treenode_id'])# Create a dummy neuron from node_tblneuron=trees.Tree.from_table(node_tbl)# Plot neuronfig=plt.figure()ax=fig.add_subplot(111,projection='3d')neuron.plot(ax)# Plot node IDcoors=neuron.get_coordinates()fornodeidincoors.index:tmp=coors.loc[nodeid]ax.text(tmp.x-0.5,tmp.y+0.1,tmp.z+0.1,nodeid,fontsize=12)ax.axis('off');plt.tight_layout();# Decompose into segments of longest branchesprint(neuron.decompose_spines())# The output should be as follows:# {'0_6': [0, 1, 2, 5, 6], '1_3': [1, 3], '2_4': [2, 4]}
Resample the tree by a given sampling length. Spline interpolation is used for resampling.
The tree is first decomposed into segments either by “branching” (decompose_segments()) or by “spine” (decompose_spines()).
Then, each segment is resampled by the given sampling length.
Parameters:
sampling_length (float) – sampling length. If None, then we resample the tree by the same number of nodes.
rootid (int) – root node ID. If None, then the first rootid will be taken.
spline_order (uint) – Spline order. value of 1 means linear interpolation.
spline_smoothness (float or None) – Parameter to control the smoothness of spline interpolation. The parameter is similar to the s parameter from this [1].
decompose_method (str) – choose the mode of decomposition: “branching” or “spine”.
Returns:
A new Tree object with resampled nodes.
References
Examples
importpandasaspdfromgenepy3d.objimporttreesimportmatplotlib.pyplotasplt# Generate a dummy nodes datadata=[[0,0,0.,0.,0.,1.,-1],[1,0,1.,2.,3.,1.,0],[2,0,4.,5.,6.,1.,1],[3,0,7.,2.,2.,1.,1],[4,0,6.,6.,6.,1.,2],[5,0,3.,7.,6.,1.,2],[6,0,5.,5.,9.,1.,5]]# Dataframe from nodes datanode_tbl=pd.DataFrame(data,columns=['treenode_id','structure_id','x','y','z','r','parent_treenode_id'])# Create a dummy neuron from node_tblneuron=trees.Tree.from_table(node_tbl)# Plot neuron, only showing the node pointsfig=plt.figure()ax=fig.add_subplot(111,projection='3d')neuron.plot(ax,show_nodes=True,show_leaves=False,show_root=False,show_branchingnodes=False)print("Nb. of nodes before resampling:",neuron.get_number_nodes())# Resampling by sampling length = 1 micronneuron_resampled=neuron.resample(sampling_length=1)# Plot resampled neuron, only showing the node pointsfig=plt.figure()ax=fig.add_subplot(111,projection='3d')neuron_resampled.plot(ax,show_nodes=True,show_leaves=False,show_root=False,show_branchingnodes=False)print("Nb. of nodes after resampling:",neuron_resampled.get_number_nodes())
The tree is decomposed into segments. Then, the angle of node N is the angle between two vectors (N => N-1) and (N => N+1).
One node can have multiple angle values depending on the decomposition mode.
Parameters:
decomposed_method (str) – “leaf”, “spine” or “branching”, method for decomposing the neuronal trace.
sigma (float) – sigma used in Gaussian function for smoothing the tree branches.
rootid (int) – root node ID. If None, then the first rootid will be taken.
Returns:
Pandas dataframe containing angles at every nodes.
Examples
importpandasaspdfromgenepy3d.objimporttreesimportmatplotlib.pyplotasplt# Generate a dummy nodes datadata=[[0,0,0.,0.,0.,1.,-1],[1,0,1.,2.,3.,1.,0],[2,0,4.,5.,6.,1.,1],[3,0,7.,2.,2.,1.,1],[4,0,6.,6.,6.,1.,2],[5,0,3.,7.,6.,1.,2],[6,0,5.,5.,9.,1.,5]]# Dataframe from nodes datanode_tbl=pd.DataFrame(data,columns=['treenode_id','structure_id','x','y','z','r','parent_treenode_id'])# Create a dummy neuron from node_tblneuron=trees.Tree.from_table(node_tbl)# Plot neuron, only showing the node pointsfig=plt.figure()ax=fig.add_subplot(111,projection='3d')neuron.plot(ax,show_nodes=True,show_leaves=False,show_root=False,show_branchingnodes=False)# Plot node IDcoors=neuron.get_coordinates()fornodeidincoors.index:tmp=coors.loc[nodeid]ax.text(tmp.x-0.5,tmp.y+0.1,tmp.z+0.1,nodeid,fontsize=12)plt.tight_layout();# Compute the node angles with x, y and z axes# The default decomposition is "branching"neuron.compute_angle()
Return angles of each tree node with x, y and z axes.
Angle at at a node N is the angle between vector (N => N + 1) and three unit vectors of x, y and z axes.
The tree is decomposed into segments. Then, the angles of nodes on each segment are computed.
One node can have multiple angle values depending on the decomposition mode.
Parameters:
decomposed_method (str) – “leaf”, “spine” or “branching”, method for decomposing the neuronal trace.
sigma (float) – sigma used in Gaussian function for smoothing the tree branches.
rootid (int) – root node ID. If None, then the first rootid will be taken.
Returns:
Pandas dataframe containing angles at every nodes.
Examples
importpandasaspdfromgenepy3d.objimporttreesimportmatplotlib.pyplotasplt# Generate a dummy nodes datadata=[[0,0,0.,0.,0.,1.,-1],[1,0,1.,2.,3.,1.,0],[2,0,4.,5.,6.,1.,1],[3,0,7.,2.,2.,1.,1],[4,0,6.,6.,6.,1.,2],[5,0,3.,7.,6.,1.,2],[6,0,5.,5.,9.,1.,5]]# Dataframe from nodes datanode_tbl=pd.DataFrame(data,columns=['treenode_id','structure_id','x','y','z','r','parent_treenode_id'])# Create a dummy neuron from node_tblneuron=trees.Tree.from_table(node_tbl)# Plot neuron, only showing the node pointsfig=plt.figure()ax=fig.add_subplot(111,projection='3d')neuron.plot(ax,show_nodes=True,show_leaves=False,show_root=False,show_branchingnodes=False)# Plot node IDcoors=neuron.get_coordinates()fornodeidincoors.index:tmp=coors.loc[nodeid]ax.text(tmp.x-0.5,tmp.y+0.1,tmp.z+0.1,nodeid,fontsize=12)plt.tight_layout();# Compute the node angles with x, y and z axes# The default decomposition is "branching"neuron.compute_angle_axes()
Compute local 3d scale of neuron from a list of sigma of Gaussian.
The tree is decomposed into segments. Then, local 3d scale is computed for each segment.
Each segment is considered as a Curve object. Please see compute_local_3d_scale_sigma() from Curve class for more detail.
One node can have multiple local 3d scales due to the decomposition. You can specify the postprocess to return e.g. the mean local 3d scale of the node.
Parameters:
sig_lst (list of float) – list of sigma values of Gaussian.
dim_param (dic) – parameters for dimension decomposition. If None, default parameters are used. See parameters of compute_local_3d_scale_sigma() from Curve class for the meaning.
decomposed_method (str) – “leaf”, “spine” or “branching”, method for decomposing the neuronal tree.
rootid (int) – root node ID. If None, then the first rootid will be taken.
postprocess (str) – support “mean”, “std”, “max”, “min” or None.
Returns:
1D, 2D, 3D flags, curvature and torsion.
Return type:
Pandas dataframe containing local 3D scale and additional information
Notes
If postprocess=None, then a Pandas dataframe containing local 3d scale and additional features (curvature, torsion, etc) of each decomposed segment is returned.
Otherwise, a Pandas serie containing only the local 3d scale of each node is returned.
Examples
importpandasaspdfromgenepy3d.objimporttreesimportmatplotlib.pyplotasplt# Generate a dummy nodes datadata=[[0,0,0.,0.,0.,1.,-1],[1,0,1.,2.,3.,1.,0],[2,0,4.,5.,6.,1.,1],[3,0,7.,2.,2.,1.,1],[4,0,6.,6.,6.,1.,2],[5,0,3.,7.,6.,1.,2],[6,0,5.,5.,9.,1.,5]]# Dataframe from nodes datanode_tbl=pd.DataFrame(data,columns=['treenode_id','structure_id','x','y','z','r','parent_treenode_id'])# Create a dummy neuron from node_tblneuron=trees.Tree.from_table(node_tbl)# Resample the neuron with sampling length = 1 simply to get more pointsneuron=neuron.resample(sampling_length=1)# Plot neuron, only showing the node pointsfig=plt.figure()ax=fig.add_subplot(111,projection='3d')neuron.plot(ax,show_nodes=True,show_leaves=False,show_root=False,show_branchingnodes=False)plt.tight_layout();# Averaged local 3D scale of each node for sigma from 0 => 100l3ds_tbl=neuron.compute_local_3d_scale_sigma(sig_lst=np.arange(100),postprocess='mean');# Plot neuron whose nodes are colored by the local 3d scalefig=plt.figure()ax=fig.add_subplot(111,projection='3d')neuron.plot(ax,weights=l3ds_tbl,show_cbar=True,point_args={"cmap":"rainbow"},show_nodes=False,show_leaves=False,show_root=False,show_branchingnodes=False)plt.tight_layout();
Compute local 3d scale of neuron from a list of radius of curvatures.
This is the advanced approach to compute the local 3d scale. Please see this [1] for more detail.
The tree is decomposed into segments. Then, local 3d scale is computed for each segment.
Each segment is considered as a Curve object. Please see compute_local_3d_scale_radius() from Curve class for more detail.
One node can have multiple local 3d scales due to the decomposition. You can specify the postprocess to return e.g. the mean local 3d scale of the node.
Parameters:
r_lst (list of float) – list of radius of curvatures. The radius must be > 0.
dim_param (dic) – parameters for dimension decomposition. If None, default parameters are used. See parameters of compute_local_3d_scale_radius() from Curve class for the meaning.
decomposed_method (str) – “leaf”, “spine” or “branching”, method for decomposing the neuronal tree.
rootid (int) – root node ID. If None, then the first rootid will be taken.
postprocess (str) – support “mean”, “std”, “max”, “min” or None.
Returns:
1D, 2D, 3D flags, curvature and torsion.
Return type:
Pandas dataframe containing local 3D scale and additional information
Notes
If postprocess=None, then a Pandas dataframe containing local 3d scale and additional features (curvature, torsion, etc) of each decomposed segment is returned. Otherwise, a Pandas serie containing only the local 3d scale of each node is returned.
Running this method is much longer than compute_local_3d_scale_sigma().