Tomotree class reference guide
Tomotree module
This module is intended as a tool for processing data from acoustic tomography of trees.
The EBSI method is a modification of the method proposed by Du et al. (2015). “Stress wave tomography,” BioResources 10(3), 3948-3962.
The ERSM method is an extension of the method proposed by Du et al. Image Reconstruction of Internal Defects in Wood Based on Segmented Propagation Rays of Stress Waves, Appl. Sci. 2018, 8, 1778; doi:10.3390/app8101778
The reconstruction and two case studies are described in the paper … TODO: submitted, insert final reference here after publication
- class tomotree.Cell(grid, id)
Bases:
objectLightweight view on a single cell of a
Grid.The tomogram is stored in the parent
Gridas a set of plain numeric numpy matrices (velocity, velocity without boundary, status). ACelldoes not own any of this data; it only remembers the grid it belongs to and its position. All attributes are exposed as properties which read from (and write to) the underlying grid matrices, so the originalcell.velocity/cell.statusAPI keeps working while the heavy per-cell Python objects are gone.Cells of a grid are cached in
Grid.all_cells; a given cell is always represented by the same object, therefore identity based operations (sets,in,==) behave exactly as before.- Parameters:
id (int)
- id
Index of the cell in
Grid.all_cells. Runs over the x-axis first, i.e.id == ix * (ny - 1) + iy.- Type:
int
- ix, iy
Column/row index of the cell in the grid matrices.
- Type:
int
- x, y
Coordinates of the bottom left corner of the cell.
- Type:
float
- dx, dy
The width and height of the cell.
- Type:
float
- velocity
The velocity of the cell (
nanoutside the tomogram boundary).- Type:
float
- velocity_no_boundary
The velocity of the cell ignoring the tomogram boundary. Used by the EBSI and ERSM methods.
- Type:
float
- status
Cell status used for binary classification.
nanif not set.- Type:
float
- rays
List of rays passing through the cell.
- Type:
list
- boundary_points
Points on the cell boundary, shape
(4 * n_cell_boundary_points, 2). Computed on demand; useful when testing if a cell is inside an ellipse.- Type:
numpy.ndarray
- property boundary_points: ndarray
- property dx: float
- property dy: float
- property rays: list
- property status: float
- property velocity: float
- property velocity_no_boundary: float
- property x: float
- property y: float
- class tomotree.Grid(xlim=(0, 10), nx=11, ylim=(0, 10), ny=11)
Bases:
objectClass representing a grid in a tomogram.
The tomogram is stored as plain numeric numpy matrices (
velocity,velocity_no_boundaryandstatus) of shape(nx - 1, ny - 1). A[ix, iy]entry describes the cell whose bottom-left corner is at(x[ix], y[iy]). Storing numbers instead of PythonCellobjects keeps the reconstruction fast and memory friendly.For convenience the cells are still accessible as
Cellobjects throughGrid.all_cellsandget_cell(); those objects are only lightweight views which read from and write to the matrices above.- x
Array containing the x-coordinates of the grid lines.
- Type:
numpy.ndarray
- y
Array containing the y-coordinates of the grid lines.
- Type:
numpy.ndarray
- dx, dy
Cell size along the x and y axis.
- Type:
float
- ncx, ncy
Number of cells along the x and y axis (
nx - 1andny - 1).- Type:
int
- velocity
Matrix of cell velocities, shape
(ncx, ncy).nanoutside the tomogram boundary or where the velocity is undefined.- Type:
numpy.ndarray
- velocity_no_boundary
Matrix of cell velocities ignoring the tomogram boundary.
- Type:
numpy.ndarray
- status
Matrix of cell statuses used for binary classification.
nanif unset.- Type:
numpy.ndarray
- min_velocity
The minimal velocity in the grid.
- Type:
float
- max_velocity
The maximal velocity in the grid.
- Type:
float
- cell_centers()
Return the coordinates of the cell centers, shape
(ncells, 2).The rows are ordered by cell id (x-axis first).
- Return type:
ndarray
- cells_boundary_points(N=5)
Return boundary points of every cell, shape
(ncells, 4 * N, 2).The cells are ordered by cell id. This replaces the per-cell
Cell.boundary_pointsattribute and is used to test which cells are influenced by a ray in the EBSI and ERSM methods.- Parameters:
N (int)
- Return type:
ndarray
- get_cell(x, y)
Retrieves a cell from the grid based on its coordinates.
- Parameters:
x (float) – The x-coordinate of the cell.
y (float) – The y-coordinate of the cell.
- Returns:
The cell object located at the specified coordinates. None:
If the coordinates are outside the grid boundaries.
- Return type:
- property max_velocity
Return the maximal velocity in the grid.
- property min_velocity
Return the minimal velocity in the grid.
- plot(ax=None, cax=None, speed_min=0, speed_max=2000, shading='flat', use_contourf=False, status=False, plot_colorbar=True, discrete_colorbar=False, n_intervals=6, discrete_colorbar_palette=<matplotlib.colors.LinearSegmentedColormap object>, function=<function Grid.<lambda>>, colorbar_kwds=None, plot_data='velocity', reference=None, colorbar_units='m/s', **kwds)
Plot a heatmap of the grid velocities using pcolormesh or contourf.
If status is True, the cell status (0 or 1) is plotted instead of the velocity. In this case minimal and maximal limits are set automatically.
- Parameters:
ax (matplotlib.axes.Axes, optional) – The axes object to plot on. If None, a new figure and axes are created.
cax (matplotlib.axes.Axes, optional) – The axes object for the colorbar. If None, the colorbar is added to the main axes.
speed_min (float, optional) – The minimum speed value for the color scale. Default is 0.
speed_max (float, optional) – The maximum speed value for the color scale. Default is 2000.
shading (str, optional) – The shading method for pcolormesh. Options are ‘flat’ or ‘auto’. Default is ‘flat’.
use_contourf (bool, optional) – If True, use contourf for plotting instead of pcolormesh. Default is False.
status (bool, optional) – If True, plot the cell status (0 or 1) instead of velocity. Default is False.
plot_colorbar (bool, optional) – If True, display the colorbar. Default is True.
discrete_colorbar (bool, optional) – If True, use a discrete colorbar with specified number of intervals. Default is False.
n_intervals (int, optional) – The number of intervals for the discrete colorbar. Default is 6.
discrete_colorbar_palette (matplotlib.colors.Colormap, optional) – The colormap to use for the discrete colorbar. Default is discrete_cmap.
function (callable, optional) – A function to apply to the data before plotting. Default is the identity function.
colorbar_kwds (dict, optional) – Additional keyword arguments to pass to the colorbar.
plot_data (str, optional) – The type of data to plot. Options are ‘velocity’ or ‘velocity_no_boundary’.
reference (float, optional) – Reference velocity (e.g. sound wood velocity) for the colorbar in %.
colorbar_units (str, optional) – ‘m/s’ (default), ‘percent’ (the colorbar in % of
reference) or ‘both’ (% and value), seetomotree.colorbar.add_percent_axis().
- Returns:
The axes object containing the heatmap plot.
- plot_optimalized(ax=None, cax=None, speed_min=0, speed_max=2000, shading='flat', use_contourf=False, status=False, plot_colorbar=True, discrete_colorbar=False, n_intervals=6, discrete_colorbar_palette=None, function=<function Grid.<lambda>>, colorbar_kwds=None, plot_data='velocity', **kwds)
- Parameters:
use_contourf (bool)
- set_cell_status_from_threshold(limit, nan_as_zero=False, function=<function Grid.<lambda>>, mapping=<function Grid.<lambda>>, mapping_lb=None)
Set cell velocity to 0 if the velocity is below the limit or undefined. Otherwise set the velocity to 1. The function is useful for binary classification of cells.
- Parameters:
limit (float) – The threshold value for classification.
nan_as_zero (bool) – If True, NaN is used rather than 0. This is useful for plotting the status, because NaN is not shown in the plot.
function (callable) – A function to apply to the cell velocity before comparison with the limit. Identity by default.
mapping (callable) – A function to map the cell velocity to the status value when the velocity is above the limit. By default, it maps any value to 1.
mapping_lb (callable or None) – A function to map the cell velocity to the status value when the velocity is below the limit. If None, the status is set to 0 or np.nan, depending on the value of nan_as_zero. By default, it is None.
- set_cell_velocity_from_ray_means()
Update cell velocities. Takes list of rays through the cell. The velocities of the rays from this list are used and the new cell velocity is calculated as mean of the velocities of the rays.
- class tomotree.Node(coordinates, number, active=True, bark=0.0, pith=None)
Bases:
objectClass for tomogram nodes. The node stores information on coordinates, rays from the node, rays to the node and the node number.
Parameters:
- coordinatesnumpy.ndarray
coordinates
- numberint
Node number.
- bark: real number
the bark thickness, default is 0, the node is shifted by this amount in the pith direction
- pith: numpy.ndarray
the pith position
- coordinates
A tuple representing the coordinates of the node.
- Type:
numpy.ndarray
- raw_coordinates
The original coordinates of the node before any bark adjustments.
- Type:
numpy.ndarray
- rays_from
A set of rays originating from this node.
- Type:
set
- rays_to
A set of rays targeting this node.
- Type:
set
- number
Node number.
- Type:
int
- get_ray_to
A dictionary mapping target node numbers to rays.
- Type:
dict
- active
Indicates whether the node is active.
- Type:
bool
- Parameters:
coordinates (ndarray)
number (int)
- class tomotree.Ray(start, end, speed=None, time=None, pith=array([0, 0]))
Bases:
objectRay in the acoustic tomography.
When initialized, the ray is added to the
rays_fromandrays_toattributes of the node at the start and at the end.- speed
The speed of the ray. If not provided, it will be calculated based on the distance between start and end nodes and the given time.
- Type:
float, optional
- time
The time taken for the ray to travel from start to end. Only used if speed is not provided.
- Type:
float, optional
- segments
The list of segments for the segmented method.
- Type:
list
- angle_from_radial
The angle between the ray and the radial direction.
- Type:
float
- signed_angle_from_radial
The signed angle between the ray and the radial direction.
- Type:
float
- length
The length of the ray.
- Type:
float
- ori_time
The original time of the ray before any adjustments.
- Type:
float
- ori_speed
The original speed of the ray before any adjustments.
- Type:
float
- class tomotree.Tomo(nodes=None, speeds=None, times=None, nx=21, ny=21, symmetric=False, eps=0.05, pith=None, include_only=None, boundary='spline', bark=0, boundary_nodes=None, x_positive='right', reaction_time=0.0)
Bases:
_TomoReconstructionMixin,_TomoCellsMixin,_TomoAnalysisMixin,_TomoPlotMixinClass for constructing and displaying a tomogram or generally for processing the output from a tomograph.
The arguments are a list of vertices and a table with speeds.
By default, there are 12 points evenly distributed on a circle.
- Parameters:
nodes (list, optional) – List of pairs
[[x1, y1], [x2, y2], ...]representing coordinates of nodes. IfNone, nodes are generated regularly on a circle. The default isNone.speeds (np.ndarray, optional) – The table with speeds. The times are calculated from speeds and lengths. The data from each source is in a column. The data arriving to sensors are in the rows. The table is square table with NaN in main diagonal. The default is None.
times (np.ndarray, optional) – The table with times if speeds are not given. The speeds are calculated from the times and lengths. The default is None. The format (source/receiver) is the same as for speeds.
nx (int) – The number of grid points along horizontal axis (at least 2). The grid has
nx - 1cells in this direction.ny (int) – The number of grid points along vertical axis (at least 2). The grid has
ny - 1cells in this direction.symmetric (bool) – If True, the ray speed on each ray is an average of speeds in both directions. This allows to speed up the processing when the method is symmetric. The default is False.
eps (float) – The gap between the lefmost (rightmost, top bottom) node and the grid boundary. Should be nonzero for SIRT.
include_only (list, optional) – List of node numbers which should be included in the tomogram. If None, all nodes are included. The default is None.
pith (np.ndarray, optional) – Coordinates of the pith. If not given, the pith is calculated as the centroid of the polygon from node coordinates. The default is None.
boundary (optional) – either None or ‘polygon’ or ‘spline’. Default is ‘spline’.
boundary_nodes (array-like, optional) – Independent scan outline, N by 2, in the same units and coordinate system as nodes. Uses this polygon for the domain and plotting while preserving sensor numbering and ray distances.
bark (float | list) – The bark width. If a list is provided, it should have the same length as the number of nodes. The default is 0.
reaction_time (float) – Reaction time of the device in seconds, subtracted from all measured times before anything else (also before the anisotropy correction).
ori_time/ori_speedof the rays keep the measured values.tomotree.analysis.estimate_reaction_time()estimates it from the data. The default is 0.
- nodes
The list of nodes in the tomogram.
- Type:
list
- rays
The list of rays in the tomogram.
- Type:
list
- tangential_rays
The list of tangential rays (one node between end and start, i.e. 1-3, 2-4, …)
- speeds
The speed table.
- times
The table of times.
- get_node_by_number
Dictionary which allows to access the node by a number of the node.
- Type:
dict
- n
The number of vertices
- grid
The grid for the tomogram
- polygon
The boundary of the tomogram. Polygon with vertices in nodes.
- get_node_by_number
Dict which allows to access nodes in tomogram by their numbers.
- info
String or dictionary with basic info on the tomogram.
- pith
Coordinates of the pith. If not given, the pith is calculated as the mean of the node coordinates.
- Type:
np.ndarray
- data_source
Either ‘speeds’ or ‘times’ depending on how the tomogram was created.
- Type:
str
- boundary
either None or ‘polygon’ or ‘spline’. Default is ‘spline’.
- Type:
str
- plot :
Plot the tomogram grid as a heatmap.
- __str__ :
Return a string representation of the tomogram.
- speeds :
Return the speed table as a pandas DataFrame.
- times :
Return the time table as a pandas DataFrame.
- allsegments :
Return the list of all segments in the tomogram.
- tangential_rays :
Return the list of tangential rays (one node between end and start, i.e. 1-3, 2-4, …).
- property allsegments
Return list of all segments in the tomogram.
- Return type:
list
- cells_velocity_statistics()
Return basic statistics on cell velocities in the tomogram.
- Returns:
Dictionary with keys min, max, mean, median, std, percentile_90, percentile_10.
- Return type:
dict
- check_triangle_inequality()
Check if the direct route is shorter (smaller time) than the route via another node.
- compute_inside_mask(points)
Compute mask of points inside the tomogram boundary.
Test if the points are inside the polygon defined by the nodes. If the boundary is set to ‘spline’, also test if the points are inside the spline defined boundary.
The mask is remembered for the same points and boundary, one reconstruction asks for the mask of the cell centers several times.
- correct_with_FBP(damping=1.0, ray_width='auto', ray_width_ratio=0.12, speed_max=None, speed_min=None, iterations=1, threshold=0.0)
Correct the current tomogram (e.g. EBSI or ERSM) by the filtered back projection.
The current cell velocities are the initial model
x0(slownesses; cells without a velocity get the mean slowness) and one step of the filtered back projection fits them to the measured times of flight:x = x0 + A^T (A A^T + mu I)^(-1) (b - A x0), mu = damping * trace(A A^T) / m,
see
do_FBP_method(). Unlike the linear “Rescale speeds” (optimize_back_tomogram()), the correction changes the cells individually, so it corrects also the shape and the position of defects. Where the data do not tell anything, the initial model is kept.Only the cell velocities change; the rays and their segments (speeds of the method, e.g. ERSM segments) are kept. The measured times are taken from
ray.time, so the correction may followoptimize_back_tomogram(), which rescales also the ray speeds. The velocities are clipped tospeed_minandspeed_max(default 0.5 times the minimal measured ray speed, at least 340 m/s, and the maximal measured ray speed).- Parameters:
damping (float) – Damping
lambdaof the filter. Small values fit the times closely (overshoots possible), large values keep the tomogram closer to the initial model. Default 1.ray_width – Width of fat rays, see
do_SIRT_method(). Default'auto', 12 % of the tree diameter.ray_width_ratio (float) – Width of fat rays, see
do_SIRT_method(). Default'auto', 12 % of the tree diameter.speed_max (float) – Bounds for the cell velocities, None for the bounds from the ray speeds.
speed_min (float) – Bounds for the cell velocities, None for the bounds from the ray speeds.
iterations (int) – Number of correction steps, each starting from the result of the previous one. Default 1 (one step).
threshold (float) – Soft threshold of each step, as a fraction of its largest change of the slowness: every change is shrunk by
threshold * max|change|towards zero (sign(d) * max(|d| - tau, 0)), so small changes (streaks from the few rays) are dropped and large ones (defects) stay. Default 0 (no threshold). After Wu et al., A Novel Filtered Backprojection-Based Algorithm for Sparse View CT Image Reconstruction; on a synthetic tree 3 iterations with threshold 0.2 classify sound and decayed cells better than one step, on real data it has not been confirmed yet.
- Returns:
Report on the correction.
- Return type:
str
- do_EBSI_method(fix_velocity_EBSI_function=<function _TomoReconstructionMixin.<lambda>>, silent=True, power_EBSI_weighting=1)
Do the EBSI method on tomogram. The tomogram object is updated.
The method EBSI reconstruction is performed as follows:
Clear the
velocities_listof cells. This removes any data from previous methods, if any.Fix the velocity of tangent rays, if required and if not done before. This fixes the fact that the speed depends on the angle between the ray and the radial direction. Divide the speed of each ray by the value $(1-0.2theta^2)$, where $theta$ is the angle between the ray and the radial direction.
For each ray get the list of cells influenced by the ray. Use points on cell boundaries and ellipse defined by the ray and eccentricity to check, if the cell is influenced by the ray.
For each cell influenced by the ray add the ray speed to the velocities_list of the cell.
Update cell velocities as mean of the values from
velocities_listfrom the previous step. Use weighted mean, the weights are lengths of segments.The cells outside the boundary are ignored.
- Parameters:
fix_velocity_EBSI_function –
Allows to set the function f(speed,angle) which describes how to fix the rays having declination angle from radial direction. The default
lambda x,y: x/(1-0.2*np.abs(y**2))setting is from the paper Du et al. (2015). “Stress wave tomography,” BioResources 10(3), 3948-3962.silent (bool) – If False, the function returns a dictionary where keys are rays and values are lists of cells influenced by the ray. Default is True, i.e. no output.
power_EBSI_weighting (float) – Power for weighting in EBSI method. The weight is calculated as 1/(ray.length**power_EBSI_weighting). Default is 1.
- Returns:
A dictionary where keys are rays and values are lists of cells influenced by the ray. Only if
silentis False.- Return type:
dict
- do_ERSM_method(fix_velocity_EBSI_function=<function _TomoReconstructionMixin.<lambda>>, e_segmentation=0.98, e_interpolation=0.99, n=2, mean=<function _TomoReconstructionMixin.<lambda>>, silent=True, max_segments=10)
Do the ERSM method on tomogram.
Clear the
velocities_listof cells. This removes any relicts from previous methods.Fix the velocity of tangent rays if required. This fixes the fact that the speed in radial direction is maximal.
Do the ray segmentation.
For each segment on ray find the cells affected by the segment, i.e. get the cells inside the ellipse around the ray such that the orthogonal projection to major axis is in the segment. Then store the segment speed to the
velocities_listin the cell.For each ray get the list of cells influenced by the ray and then update the
velocities_listUpdate cell velocities as mean of the values from
velocities_listfrom the previous stepThe cells outside the polygon are ignored.
We set the eccentricity values for both ray segmentation and spatial interpolation. We use eccentricity rather than the quotient of minor and major axes, the value
cvalue in Du (2018). The conversion is by the formulae=sqrt(1-c**2).- Parameters:
fix_velocity_EBSI_function –
Allows to set the function f(speed,angle) which describes how to fix the rays having declination angle from radial direction. The default
lambda x,y: x/(1-0.2*np.abs(y**2))setting is from the paper Du et al. (2015). “Stress wave tomography,” BioResources 10(3), 3948-3962.e_segmentation (float) – Eccentricity for ray segmentation algorithm. This eccentricity is used when setting the velocities of the ray segments. Du suggests c value for this step between 0.65 and 0.8 which is eccentricity between 0.76 and 0.60.
e_interpolation (float) – Eccentricity for spatial interpolation by segmented ellipse. Du suggests c value between 0.85 and 0.95 which is e between 0.53 and 0.31.
n – The shortest ray is divided into
nsegments. The other rays are divided into similar lengths.silent (bool) – No output if silent is True. If False, the function returns a dictionary with keys
allsegmentsandspeeds_on_segments.max_segments (int) – Maximum number of segments on one ray. Default is 10.
- do_FBP_method(filtered=True, damping=1.0, ray_width='auto', ray_width_ratio=0.12, speed_max=None, speed_min=None)
Do the (filtered) back projection on tomogram. The tomogram object is updated.
Classical filtered back projection needs a sinogram densely sampled on a regular grid of angles and ray positions, which a few sensors on a tree do not give. The method therefore uses the algebraic form, valid for any sensor positions. With
Athe matrix of ray lengths in cells (thin or fat rays, seedo_SIRT_method()),bthe times of flight ands0the mean slowness (homogeneous model):plain back projection (
filtered=False): every cell gets the mean slowness of the rays through the cell weighted by their lengths in the cell,x = (A^T (b / L)) / (A^T 1). Cells without rays stay undefined. The image is blurred and the contrast is low.filtered back projection (
filtered=True):x = s0 + A^T (A A^T + mu I)^(-1) (b - A s0), mu = damping * trace(A A^T) / m,
with
mrays. The matrix(A A^T)^(-1)plays the role of the ramp filter of the classical method (the ramp filter is the continuous counterpart of(R R*)^(-1),Rthe Radon transform); the data are filtered first and then projected back. The result is the minimum-norm solution ofA x = bnears0.dampingsuppresses the noise; small values give overshoots, large values blur the image. Thin rays give streaks along the rays, fat rays withdampingabout 1 give a smooth image.
The velocities are clipped to
speed_minandspeed_max; the report gives the number of cells clipped to each bound. Many cells at the maximum are usual (sound wood has about the speed of the fastest ray), cells at the minimum point to overshoots or wrong times.- Parameters:
filtered (bool) – If False, plain back projection,
dampingis ignored.damping (float) – Damping
lambdaof the filter, relative to the mean diagonal ofA A^T. Default 1.ray_width – Width of fat rays, see
do_SIRT_method(). Default'auto', 12 % of the tree diameter.ray_width_ratio (float) – Width of fat rays, see
do_SIRT_method(). Default'auto', 12 % of the tree diameter.speed_max (float) – Bounds for the cell velocities. If None, the maximal ray speed and 0.5 times the minimal ray speed, but at least 340 m/s (speed of sound in air), is used. A cell slower than 340 m/s is an artifact: the wave goes around an air-filled cavity through the wood.
speed_min (float) – Bounds for the cell velocities. If None, the maximal ray speed and 0.5 times the minimal ray speed, but at least 340 m/s (speed of sound in air), is used. A cell slower than 340 m/s is an artifact: the wave goes around an air-filled cavity through the wood.
- Returns:
Report on the reconstruction.
- Return type:
str
- do_Rays_method(ray_width=None, ray_width_ratio=0.12)
Cell velocity as the mean of the speeds of the rays through the cell.
Uses the current ray speeds, i.e. after
fix_velocity_EBSI()(anisotropy correction), if it has been called.thin rays (
ray_width=None): the plain mean of the speeds of the rays crossing the cell; cells without a ray stay undefined. The same as the tomogram computed when theTomoobject is created.fat rays: the mean weighted by
exp(-(d / w)**2),dthe distance of the cell center from the ray andwthe ray width; only rays closer than2.5 wcount. Cells outside the tomogram boundary stay undefined. Fat rays fill the cells between the rays and remove the streaks along the rays; small defects are blurred.
- Parameters:
ray_width – None for thin rays,
'auto'forray_width_ratiotimes the largest distance between the nodes (the tree diameter), or the width in m.ray_width_ratio (float) – Width of fat rays relative to the tree diameter for
ray_width='auto'. Default 12 %.
- Returns:
Report on the reconstruction.
- Return type:
str
- do_SIRT_method(speed_max=None, speed_min=None, smoothing=10.0, iterations=2000, relaxation=1.5, tol=None, fix_velocity_EBSI_function=None, ray_width='auto', ray_width_ratio=0.12)
Do the regularized SIRT method on tomogram. The tomogram object is updated.
SIRT (Simultaneous Iterative Reconstruction Technique) as described in van der Sluis, van der Vorst (1990). “SIRT- and CG-type methods for the iterative solution of sparse linear least-squares problems,” Linear Algebra and its Applications 130, 257-302.
Rays are split to segments at the cell boundaries. The unknowns are the slownesses of all cells inside the tomogram boundary (and of the cells crossed by a ray). The system is
A x = b, whereAholds the lengths of the ray segments in cells andbthe times of flight.With
ray_widththe rays are “fat”: the length of a ray is spread over the cells near the ray with the Gaussian weightexp(-(d / ray_width)**2)of the distancedof the cell center from the ray (cells farther than2.5 * ray_widthare ignored). The wave is sensitive to a zone around the straight line, and fat rays suppress the star-shaped artifacts along the rays. The price is lower resolution, small defects are blurred.With few sensors the system is strongly underdetermined. Therefore the Laplace operator
D(4 neighbours) is appended,[A; alpha D] x = [b; 0](Tikhonov regularization). This smooths the tomogram and fills the cells not crossed by any ray.The iterations start from the homogeneous model (mean slowness) and keep the velocities between
speed_minandspeed_max.The times are those of the rays, the reaction time of the device (
Tomo(reaction_time=...)) is already subtracted.
- Parameters:
speed_max (float) – Bounds for the cell velocities. If None, the maximal ray speed and 0.5 times the minimal ray speed, but at least 340 m/s (speed of sound in air), is used.
speed_min (float) – Bounds for the cell velocities. If None, the maximal ray speed and 0.5 times the minimal ray speed, but at least 340 m/s (speed of sound in air), is used.
smoothing (float) – Weight
alphaof the regularization. Larger values give smoother tomograms and larger residuals. The value 0 gives the classical SIRT without regularization (cells without rays stay undefined).iterations (int) – Maximal number of SIRT iterations. With smoothing the iterations converge slowly; 2000 iterations with
relaxation=1.5give velocities within a few m/s of the limit.relaxation (float) – Relaxation parameter of SIRT, between 0 and 2.
tol (float) – If not None, stop when the relative residual changes between two iterations less than
tol.fix_velocity_EBSI_function – If not None, the ray velocities are fixed by
fix_velocity_EBSI()with this function before reconstruction.ray_width – Width of fat rays in the units of node coordinates.
'auto'isray_width_ratiotimes the tree diameter (the largest distance between nodes), None or 0 gives thin rays (segment lengths in cells).ray_width_ratio (float) – Ray width as a fraction of the tree diameter, used if
ray_widthis'auto'. Default 0.12.
- Returns:
Report on the reconstruction.
- Return type:
str
- estimate_sound_wood_speed(include=None, exclude=None, set_status=False, e=0.995, mean=<function nanmean>, verbose_output=False)
Estimate the average speed of sound in wood from the tangential rays.
The average is calculated from the cells affected by the tangential rays. The cells affected by the ray are those which have at least one boundary point inside the ellipse defined by the ray and eccentricity 0.995.
- Parameters:
include – If not None, it is a list of sets of node numbers defining the rays to be included in the calculation. Example: [{1,7},{2,8}] includes only rays between nodes 1 and 7 and between nodes 2 and 8.
exclude – If not None, it is a list of sets of node numbers defining the rays to be excluded from the calculation. Example: [{1,7},{2,8}] excludes rays between nodes 1 and 7 and between nodes 2 and 8.
set_status – If True, the status of the cells used in the calculation is set to 1.
e – Eccentricity of the ellipse used to determine the cells affected by the ray. Default is 0.995.
mean – Function used to calculate the average speed. Default is np.nanmean. Another alternative is median.
verbose_output – If True, outputs detailed data about the calculation. Default is False, which returns only the average speed.
- Returns:
The average speed of sound in wood if verbose_output is False. If verbose_output is True, returns a dictionary with keys: ‘speed’ - the average speed of sound in wood, ‘cells’ - the set of cells used in the calculation, ‘rays’ - the list of rays used in the calculation, ‘cells_per_ray’ - a dictionary where keys are rays and values are sets of cells affected by the ray.
- Return type:
float or dict
Notes
The function is used to estimate the sound speed in wood. The method is based on the fact that the wood degradation occurs typically in the center of the tree or log, while the tangential rays pass through the outer part of the log. The average speed of sound in wood is then
- fix_velocity_EBSI(function=<function _TomoReconstructionMixin.<lambda>>)
Fix the velocities as described in EBSI in the paper Du et al. (2015). “Stress wave tomography,” BioResources 10(3), 3948-3962.
The function used to fix the velocities can be customized, if necessary. The default is
lambda x,y: x/(1-0.2*np.abs(y**2).The function does not allow to be called twice on the same tomogram. Prints a friendly notice if the user attempts to call is for the second time. The variable
self.velocities_EBSI_fixedis set toTrue.
- get_ray(start, end)
Get the ray between two nodes.
- Input:
start: The starting node or its number. end: The ending node or its number.
- Output:
The ray object or a list of rays if multiple exist.
- limit_cell_plot_velocities(fraction=0.1)
Find limits suitable for tomogram plot.
- Parameters:
self – Tomogram to be potted
fraction (float) – Fraction of the total number of cells, which should have maximal and minimal colors. The value 0.1 ensures that 10 percent of the cells will have minimal color and 10 percent maximal color.
- Returns:
Return dictionary with keys speed_min and speed max.
The author is expected to pass this dictionary to the plot method of the tomograf.
- Return type:
dict
- optimize_back(**kwargs)
Wrapper for optimize_back methods.
- optimize_back_tomogram(do_optimization=True, maxiter=300, zero=340.0)
Optimize the tomogram by rescaling the cell velocities with the linear transformation
v' = max(zero, k v + q)to match the measured times of flight.The time of flight of a ray is the integral of the slowness along the ray, i.e.
L * mean(1 / v)over points sampled on the ray (the harmonic mean of the velocities). The constantskandqminimize the sum of the squared differences between these times and the measured times.The objective is not smooth (the lower bound
zeromakes kinks and flat regions) and each of Nelder-Mead andleast_squaressometimes stops away from the minimum, in different cases. Both run from the same start, the better result is taken and refined by a restarted Nelder-Mead.- Input:
- do_optimization: If False, no optimization is done, only (k, q)
= (1, 0) is applied.
- maxiter: Maximum number of iterations of each Nelder-Mead run and
of function evaluations of
least_squares.
zero: Lower bound of the rescaled velocities (speed of sound in air).
- Output:
A dictionary;
convergedis False when the restarted Nelder-Mead still improved the objective noticeably,ansis the result of the last run,solverthe method that found the start of the refinement andobjectivesthe objective of each run.
- Parameters:
do_optimization (bool)
maxiter (int)
- property ori_speeds
- property ori_times
- plot(speed_min=None, speed_max=None, figsize=(6, 6), grid=True, rays=True, ax=None, shift_ray=0.01, title=None, shading='flat', use_contourf=False, filter_rays=<function _TomoPlotMixin.<lambda>>, lw=2, plot_colorbar=True, boundary=False, discrete_colorbar=False, n_intervals=5, discrete_colorbar_palette=<matplotlib.colors.LinearSegmentedColormap object>, function=<function _TomoPlotMixin.<lambda>>, colorbar_kwds={}, reference=None, colorbar_units='m/s', **kwds)
Plot the tomogram.
- Parameters:
speed_min (float) – Minimal speed for color scale. If None, the minimal ray speed from the tomogram is used.
speed_max (float) – Maximal speed for color scale. If None, the maximal ray speed from the tomogram is used.
figsize (tuple) – Figure size.
grid (bool) – If True, plot the grid with cell velocities.
rays (bool) – If True, plot the rays.
ax (matplotlib.axes.Axes) – Axes to plot on. If None, a new figure and axes are created.
shift_ray (float) – Shift of the rays from the center for better visibility.
title (str) – Title of the plot.
shading (str) – Shading for the grid plot. See Grid.plot for details.
use_contourf (bool) – If True, use contourf for grid plot. See Grid.plot for details.
filter_rays (function) – Function which takes speed as input and returns True if the ray should be plotted.
lw (float) – Line width for rays.
plot_colorbar (bool) – If True, plot colorbar for the grid.
colorbar_kwds (dict) – Additional keywords passed to colorbar plotting function.
boundary (bool or str) – If True, plot the boundary of the tomogram as a smooth curve. If ‘polygon’, plot the boundary as polygon.
discrete_colorbar (bool) – If True, use discrete colorbar for the grid plot. See Grid.plot for details.
n_intervals (int) – Number of intervals for discrete colorbar. See Grid.plot for details.
function (function) – Function to transform the speeds before plotting.
reference (float) – Reference velocity (e.g. the sound wood velocity) for the colorbar in %;
function(reference)is 100 %.colorbar_units (str) – ‘m/s’ (default), ‘percent’ (colorbar in % of
reference) or ‘both’ (% and the value in brackets); the ticks are at round percentages.**kwds –
Additional keywords passed to Grid.plot (used only with
grid=True), e.g.- caxmatplotlib.axes.Axes
Axes for the colorbar (e.g. a narrow axes next to
ax). If None, the colorbar takes space fromax.- statusbool
If True, plot the cell status (0 or 1, binary tomogram) instead of velocity.
- Returns:
The axes with the tomogram (
axif given).- Return type:
matplotlib.axes.Axes
- plot_angular_dependence(ax=None, figsize=None, subplots=False, plotly=False)
- plot_bokeh(*args, **kwds)
Plot the tomogram using Bokeh.
- plot_plotly(*args, **kwds)
Plot the tomogram using Plotly.
- plot_sinogram(imshow={})
Vykreslení grafu. Předpokládá 12 snímačů pravidelně do kruhu. TODO: opravit.
- ray_segments(filter_rays=<function _TomoPlotMixin.<lambda>>, shift_ray=0.01)
Ray segments as drawn by
plot():(lines, speeds), lines of shape (N, 2, 2).Each segment is shifted by
shift_rayto the left of its direction (not for a symmetric tomogram), so the two directions of a ray are both visible.- Parameters:
shift_ray (float)
- ray_time(ray_index, k=1, q=0, n=100, velocities=None)
Compute the travel time of a ray by numerical integration.
The time of flight is the integral of the slowness along the ray,
L * mean(1 / v)over equally spaced points (the harmonic mean of the velocities): the wave spends more time in slow parts. Points in cells without a velocity are skipped.- Parameters:
ray_index (int) – Index of the ray in the tomogram’s ray list.
n (int) – Number of points to use in the numerical integration.
k (float) – Scaling factor for velocities.
q (float) – Shift factor for velocities.
velocities (np.array) – If provided, use these velocities instead of computing them from the tomogram.
- Returns:
Travel time of the ray in seconds (NaN if no point has a velocity).
- Return type:
float
- ray_time_comparison(n=100)
Compare the travel times of rays computed from the tomogram with the measured travel times. :param n: Number of points to use in the numerical integration. :type n: int
- Returns:
DataFrame with columns ‘computed’, ‘measured’, ‘difference’, ‘abs_difference’. The index is the ray endpoints in the format ‘start<->end’. The DataFrame is sorted by ‘abs_difference’ in descending order.
- Return type:
pd.DataFrame
- property speeds
- speeds_at_angles_3Dplot()
- speeds_at_angles_table(highlight=False)
Vytiskne tabulku, kde jsou rychlosti z jednotlivych bodu v zavislosti na odchylce od radialniho smeru. Vystupem je tabulka pandas. Parametr highlight umožní vybarvit nejvyšší a nejnižší hodnoty
Předpokládá 12 snímačů pravidelně do kruhu. TODO: opravit.
- Parameters:
highlight (bool)
- property tangential_rays
Return list of all tangential rays in the tomogram.
The tangential rays in tomogram with 12 nodes are 1-3, 1-11, 2-4, 2-12, 3-5, 4-6, 5-7, 6-8, 7-9, 8-10, 9-11, 10-12.
Only active nodes are considered. The tangential rays are collected from the node to the node two positions ahead in the list of active nodes. Rays left out of the tomogram (disabled, or without a finite speed) are not returned.
- Return type:
list of rays
- property times
- update_segments_from_cells()
Split rays to segments. The boundary between segments is at the cell boundaries. The speed is determined by the cell velocity. If the cell velocity is undefined (may appear near the boundary), the average speed on the ray is used.
- velocities_on_ray(ray_index, n=100)
Get the velocities at n points along the ray.
- Parameters:
ray_index (int) – Index of the ray in the tomogram’s ray list.
n (int) – Number of points to sample along the ray.
- Returns:
Array of velocities at the sampled points along the ray.
- Return type:
np.array
- tomotree.get_boundary_points(N=5, dx=1, dy=1, posunx=0, posuny=0)
The function get_boundary_points is designed to generate points on the boundary of a rectangle. This can be useful for testing if a cell is within an elliptical domain of a given ray.
- Parameters:
N (int) – The number of points to generate on each side of the rectangle. The default value is 5.
dx (float) – The length of the rectangle in the x-direction. The default value is 1.
dy (float) – The length of the rectangle in the y-direction. The default value is 1.
posunx (float) – The x-coordinate of the bottom-left corner of the rectangle. The default value is 0.
posuny (float) – The y-coordinate of the bottom-left corner of the rectangle. The default value is 0.
- Return type:
ndarray
The function returns a 2D numpy array with shape (2, 4*N). The first row of the array contains the x-coordinates of the points, and the second row contains the y-coordinates. The points are ordered counterclockwise, starting from the bottom-left corner of the rectangle.
- tomotree.is_point_inside_ellipse(point, start, end, eccentricity=0.9, distance_from_vertex=False)
Test if a point is inside the ellipse. The ellipse is defined by the start and end point of the main axis and eccentricity. If
distance_from_vertexis true, returns also the length of the distance between the points and the start vertex measured in the direction of the major axis. (Useful for spatial interpolation by the segmented ellipse.)- Parameters:
point (ndarray) – Point or an array of points to be tested. The last axis of the array is supposed to have length 2.
start (float) – One of the ends of the major axis.
end (float) – The second ends of te major axis.
eccentricity (float) – Ellipse eccentricity. The default is 0.9.
distance_from_vertex (bool) – If true, return also distance from vertex, i.e. return pair [boolean, distance from minor]
- Returns:
bool – Returns bool or array of bools if
distance_from_vertexisFalse.list – Returns a pair of bool and float if
distance_from_vertexisTrue.
- Return type:
ndarray
- tomotree.perp(v=<class 'numpy.ndarray'>)
Return vector perpendicular to the argument.
- Return type:
ndarray
- tomotree.speed2color(speed, max=None, min=None, speed_min=None, speed_max=None, extend=True)
Convert speed to color. Return black, if the speed is outside minimal and maximal value. Otherwise return a color according to the colormap scheme.
Parameters
minandmaxset the minimal and maximal value.If the values are not given, values
speed_minandspeed_maxare used.If none of these values are given, set
min=0andmax=1.
- Parameters:
speed (float) – Speed to be converted to color
max (float) – Maximal value, the speed corresponding to the fastest color
min (float) – Minimal value, the speed corresponding to the color with smallest velocity.
speed_min (float) – The values speed_min and speed_max are used if min and max are not set.
speed_max (float)
extend (bool) – If True, extend the colormap beyond the min and max values. If false, return black for values outside the min-max range.
- class tomotree.classes.node.Node(coordinates, number, active=True, bark=0.0, pith=None)
Bases:
objectClass for tomogram nodes. The node stores information on coordinates, rays from the node, rays to the node and the node number.
Parameters:
- coordinatesnumpy.ndarray
coordinates
- numberint
Node number.
- bark: real number
the bark thickness, default is 0, the node is shifted by this amount in the pith direction
- pith: numpy.ndarray
the pith position
- coordinates
A tuple representing the coordinates of the node.
- Type:
numpy.ndarray
- raw_coordinates
The original coordinates of the node before any bark adjustments.
- Type:
numpy.ndarray
- rays_from
A set of rays originating from this node.
- Type:
set
- rays_to
A set of rays targeting this node.
- Type:
set
- number
Node number.
- Type:
int
- get_ray_to
A dictionary mapping target node numbers to rays.
- Type:
dict
- active
Indicates whether the node is active.
- Type:
bool
- Parameters:
coordinates (ndarray)
number (int)
- class tomotree.classes.ray.Ray(start, end, speed=None, time=None, pith=array([0, 0]))
Bases:
objectRay in the acoustic tomography.
When initialized, the ray is added to the
rays_fromandrays_toattributes of the node at the start and at the end.- speed
The speed of the ray. If not provided, it will be calculated based on the distance between start and end nodes and the given time.
- Type:
float, optional
- time
The time taken for the ray to travel from start to end. Only used if speed is not provided.
- Type:
float, optional
- segments
The list of segments for the segmented method.
- Type:
list
- angle_from_radial
The angle between the ray and the radial direction.
- Type:
float
- signed_angle_from_radial
The signed angle between the ray and the radial direction.
- Type:
float
- length
The length of the ray.
- Type:
float
- ori_time
The original time of the ray before any adjustments.
- Type:
float
- ori_speed
The original speed of the ray before any adjustments.
- Type:
float
- class tomotree.classes.ray.Segment(ray, speed, start, end)
Bases:
objectRay segment. Properties are parent ray, the speed on the segment and the start and the end position of the segment on the ray. The start of the ray corresponds to the position 0, the end corresponds to position 1.
- speed
The speed on the segment.
- Type:
float
- start
The start position of the segment on the ray. Float from 0 to 1.
- Type:
float
- end
The end position of the segment on the ray. Float from 0 to 1.
- Type:
float
- start_coordinates
The start coordinates of the segment.
- Type:
array-like
- end_coordinates
The end coordinates of the segment.
- Type:
array-like
- length
length of the segment
- Type:
float
- property length: float
Return length of the segment
- split(n=2)
Split the segment to two or more segments. Removes the segment from the ray.segments list and adds new segments to this list.
Return the list from the new segments. This allows to adjust the speed on these new segments.
- class tomotree.classes.cell.Cell(grid, id)
Bases:
objectLightweight view on a single cell of a
Grid.The tomogram is stored in the parent
Gridas a set of plain numeric numpy matrices (velocity, velocity without boundary, status). ACelldoes not own any of this data; it only remembers the grid it belongs to and its position. All attributes are exposed as properties which read from (and write to) the underlying grid matrices, so the originalcell.velocity/cell.statusAPI keeps working while the heavy per-cell Python objects are gone.Cells of a grid are cached in
Grid.all_cells; a given cell is always represented by the same object, therefore identity based operations (sets,in,==) behave exactly as before.- Parameters:
id (int)
- id
Index of the cell in
Grid.all_cells. Runs over the x-axis first, i.e.id == ix * (ny - 1) + iy.- Type:
int
- ix, iy
Column/row index of the cell in the grid matrices.
- Type:
int
- x, y
Coordinates of the bottom left corner of the cell.
- Type:
float
- dx, dy
The width and height of the cell.
- Type:
float
- velocity
The velocity of the cell (
nanoutside the tomogram boundary).- Type:
float
- velocity_no_boundary
The velocity of the cell ignoring the tomogram boundary. Used by the EBSI and ERSM methods.
- Type:
float
- status
Cell status used for binary classification.
nanif not set.- Type:
float
- rays
List of rays passing through the cell.
- Type:
list
- boundary_points
Points on the cell boundary, shape
(4 * n_cell_boundary_points, 2). Computed on demand; useful when testing if a cell is inside an ellipse.- Type:
numpy.ndarray
- property boundary_points: ndarray
- property dx: float
- property dy: float
- property rays: list
- property status: float
- property velocity: float
- property velocity_no_boundary: float
- property x: float
- property y: float
- class tomotree.classes.grid.Grid(xlim=(0, 10), nx=11, ylim=(0, 10), ny=11)
Bases:
objectClass representing a grid in a tomogram.
The tomogram is stored as plain numeric numpy matrices (
velocity,velocity_no_boundaryandstatus) of shape(nx - 1, ny - 1). A[ix, iy]entry describes the cell whose bottom-left corner is at(x[ix], y[iy]). Storing numbers instead of PythonCellobjects keeps the reconstruction fast and memory friendly.For convenience the cells are still accessible as
Cellobjects throughGrid.all_cellsandget_cell(); those objects are only lightweight views which read from and write to the matrices above.- x
Array containing the x-coordinates of the grid lines.
- Type:
numpy.ndarray
- y
Array containing the y-coordinates of the grid lines.
- Type:
numpy.ndarray
- dx, dy
Cell size along the x and y axis.
- Type:
float
- ncx, ncy
Number of cells along the x and y axis (
nx - 1andny - 1).- Type:
int
- velocity
Matrix of cell velocities, shape
(ncx, ncy).nanoutside the tomogram boundary or where the velocity is undefined.- Type:
numpy.ndarray
- velocity_no_boundary
Matrix of cell velocities ignoring the tomogram boundary.
- Type:
numpy.ndarray
- status
Matrix of cell statuses used for binary classification.
nanif unset.- Type:
numpy.ndarray
- all_cells
List of
Cellviews, one per cell, ordered by cell id.- Type:
list
- min_velocity
The minimal velocity in the grid.
- Type:
float
- max_velocity
The maximal velocity in the grid.
- Type:
float
- cell_centers()
Return the coordinates of the cell centers, shape
(ncells, 2).The rows are ordered by cell id (x-axis first).
- Return type:
ndarray
- cells_boundary_points(N=5)
Return boundary points of every cell, shape
(ncells, 4 * N, 2).The cells are ordered by cell id. This replaces the per-cell
Cell.boundary_pointsattribute and is used to test which cells are influenced by a ray in the EBSI and ERSM methods.- Parameters:
N (int)
- Return type:
ndarray
- get_cell(x, y)
Retrieves a cell from the grid based on its coordinates.
- Parameters:
x (float) – The x-coordinate of the cell.
y (float) – The y-coordinate of the cell.
- Returns:
The cell object located at the specified coordinates. None:
If the coordinates are outside the grid boundaries.
- Return type:
- property max_velocity
Return the maximal velocity in the grid.
- property min_velocity
Return the minimal velocity in the grid.
- plot(ax=None, cax=None, speed_min=0, speed_max=2000, shading='flat', use_contourf=False, status=False, plot_colorbar=True, discrete_colorbar=False, n_intervals=6, discrete_colorbar_palette=<matplotlib.colors.LinearSegmentedColormap object>, function=<function Grid.<lambda>>, colorbar_kwds=None, plot_data='velocity', reference=None, colorbar_units='m/s', **kwds)
Plot a heatmap of the grid velocities using pcolormesh or contourf.
If status is True, the cell status (0 or 1) is plotted instead of the velocity. In this case minimal and maximal limits are set automatically.
- Parameters:
ax (matplotlib.axes.Axes, optional) – The axes object to plot on. If None, a new figure and axes are created.
cax (matplotlib.axes.Axes, optional) – The axes object for the colorbar. If None, the colorbar is added to the main axes.
speed_min (float, optional) – The minimum speed value for the color scale. Default is 0.
speed_max (float, optional) – The maximum speed value for the color scale. Default is 2000.
shading (str, optional) – The shading method for pcolormesh. Options are ‘flat’ or ‘auto’. Default is ‘flat’.
use_contourf (bool, optional) – If True, use contourf for plotting instead of pcolormesh. Default is False.
status (bool, optional) – If True, plot the cell status (0 or 1) instead of velocity. Default is False.
plot_colorbar (bool, optional) – If True, display the colorbar. Default is True.
discrete_colorbar (bool, optional) – If True, use a discrete colorbar with specified number of intervals. Default is False.
n_intervals (int, optional) – The number of intervals for the discrete colorbar. Default is 6.
discrete_colorbar_palette (matplotlib.colors.Colormap, optional) – The colormap to use for the discrete colorbar. Default is discrete_cmap.
function (callable, optional) – A function to apply to the data before plotting. Default is the identity function.
colorbar_kwds (dict, optional) – Additional keyword arguments to pass to the colorbar.
plot_data (str, optional) – The type of data to plot. Options are ‘velocity’ or ‘velocity_no_boundary’.
reference (float, optional) – Reference velocity (e.g. sound wood velocity) for the colorbar in %.
colorbar_units (str, optional) – ‘m/s’ (default), ‘percent’ (the colorbar in % of
reference) or ‘both’ (% and value), seetomotree.colorbar.add_percent_axis().
- Returns:
The axes object containing the heatmap plot.
- plot_optimalized(ax=None, cax=None, speed_min=0, speed_max=2000, shading='flat', use_contourf=False, status=False, plot_colorbar=True, discrete_colorbar=False, n_intervals=6, discrete_colorbar_palette=None, function=<function Grid.<lambda>>, colorbar_kwds=None, plot_data='velocity', **kwds)
- Parameters:
use_contourf (bool)
- set_cell_status_from_threshold(limit, nan_as_zero=False, function=<function Grid.<lambda>>, mapping=<function Grid.<lambda>>, mapping_lb=None)
Set cell velocity to 0 if the velocity is below the limit or undefined. Otherwise set the velocity to 1. The function is useful for binary classification of cells.
- Parameters:
limit (float) – The threshold value for classification.
nan_as_zero (bool) – If True, NaN is used rather than 0. This is useful for plotting the status, because NaN is not shown in the plot.
function (callable) – A function to apply to the cell velocity before comparison with the limit. Identity by default.
mapping (callable) – A function to map the cell velocity to the status value when the velocity is above the limit. By default, it maps any value to 1.
mapping_lb (callable or None) – A function to map the cell velocity to the status value when the velocity is below the limit. If None, the status is set to 0 or np.nan, depending on the value of nan_as_zero. By default, it is None.
- set_cell_velocity_from_ray_means()
Update cell velocities. Takes list of rays through the cell. The velocities of the rays from this list are used and the new cell velocity is calculated as mean of the velocities of the rays.
Reconstruction implementation
- class tomotree.classes._tomo_reconstruction._TomoReconstructionMixin
Bases:
objectMixin: reconstruction methods for EBSI, ERSM and SIRT.
This includes: - EBSI velocity fix - Ellipse-Based Spatial Interpolation (EBSI) - Extended Ray Segmentation Method (ERSM) - Simultaneous Iterative Reconstruction Technique (SIRT)
- correct_with_FBP(damping=1.0, ray_width='auto', ray_width_ratio=0.12, speed_max=None, speed_min=None, iterations=1, threshold=0.0)
Correct the current tomogram (e.g. EBSI or ERSM) by the filtered back projection.
The current cell velocities are the initial model
x0(slownesses; cells without a velocity get the mean slowness) and one step of the filtered back projection fits them to the measured times of flight:x = x0 + A^T (A A^T + mu I)^(-1) (b - A x0), mu = damping * trace(A A^T) / m,
see
do_FBP_method(). Unlike the linear “Rescale speeds” (optimize_back_tomogram()), the correction changes the cells individually, so it corrects also the shape and the position of defects. Where the data do not tell anything, the initial model is kept.Only the cell velocities change; the rays and their segments (speeds of the method, e.g. ERSM segments) are kept. The measured times are taken from
ray.time, so the correction may followoptimize_back_tomogram(), which rescales also the ray speeds. The velocities are clipped tospeed_minandspeed_max(default 0.5 times the minimal measured ray speed, at least 340 m/s, and the maximal measured ray speed).- Parameters:
damping (float) – Damping
lambdaof the filter. Small values fit the times closely (overshoots possible), large values keep the tomogram closer to the initial model. Default 1.ray_width – Width of fat rays, see
do_SIRT_method(). Default'auto', 12 % of the tree diameter.ray_width_ratio (float) – Width of fat rays, see
do_SIRT_method(). Default'auto', 12 % of the tree diameter.speed_max (float) – Bounds for the cell velocities, None for the bounds from the ray speeds.
speed_min (float) – Bounds for the cell velocities, None for the bounds from the ray speeds.
iterations (int) – Number of correction steps, each starting from the result of the previous one. Default 1 (one step).
threshold (float) – Soft threshold of each step, as a fraction of its largest change of the slowness: every change is shrunk by
threshold * max|change|towards zero (sign(d) * max(|d| - tau, 0)), so small changes (streaks from the few rays) are dropped and large ones (defects) stay. Default 0 (no threshold). After Wu et al., A Novel Filtered Backprojection-Based Algorithm for Sparse View CT Image Reconstruction; on a synthetic tree 3 iterations with threshold 0.2 classify sound and decayed cells better than one step, on real data it has not been confirmed yet.
- Returns:
Report on the correction.
- Return type:
str
- do_EBSI_method(fix_velocity_EBSI_function=<function _TomoReconstructionMixin.<lambda>>, silent=True, power_EBSI_weighting=1)
Do the EBSI method on tomogram. The tomogram object is updated.
The method EBSI reconstruction is performed as follows:
Clear the
velocities_listof cells. This removes any data from previous methods, if any.Fix the velocity of tangent rays, if required and if not done before. This fixes the fact that the speed depends on the angle between the ray and the radial direction. Divide the speed of each ray by the value $(1-0.2theta^2)$, where $theta$ is the angle between the ray and the radial direction.
For each ray get the list of cells influenced by the ray. Use points on cell boundaries and ellipse defined by the ray and eccentricity to check, if the cell is influenced by the ray.
For each cell influenced by the ray add the ray speed to the velocities_list of the cell.
Update cell velocities as mean of the values from
velocities_listfrom the previous step. Use weighted mean, the weights are lengths of segments.The cells outside the boundary are ignored.
- Parameters:
fix_velocity_EBSI_function –
Allows to set the function f(speed,angle) which describes how to fix the rays having declination angle from radial direction. The default
lambda x,y: x/(1-0.2*np.abs(y**2))setting is from the paper Du et al. (2015). “Stress wave tomography,” BioResources 10(3), 3948-3962.silent (bool) – If False, the function returns a dictionary where keys are rays and values are lists of cells influenced by the ray. Default is True, i.e. no output.
power_EBSI_weighting (float) – Power for weighting in EBSI method. The weight is calculated as 1/(ray.length**power_EBSI_weighting). Default is 1.
- Returns:
A dictionary where keys are rays and values are lists of cells influenced by the ray. Only if
silentis False.- Return type:
dict
- do_ERSM_method(fix_velocity_EBSI_function=<function _TomoReconstructionMixin.<lambda>>, e_segmentation=0.98, e_interpolation=0.99, n=2, mean=<function _TomoReconstructionMixin.<lambda>>, silent=True, max_segments=10)
Do the ERSM method on tomogram.
Clear the
velocities_listof cells. This removes any relicts from previous methods.Fix the velocity of tangent rays if required. This fixes the fact that the speed in radial direction is maximal.
Do the ray segmentation.
For each segment on ray find the cells affected by the segment, i.e. get the cells inside the ellipse around the ray such that the orthogonal projection to major axis is in the segment. Then store the segment speed to the
velocities_listin the cell.For each ray get the list of cells influenced by the ray and then update the
velocities_listUpdate cell velocities as mean of the values from
velocities_listfrom the previous stepThe cells outside the polygon are ignored.
We set the eccentricity values for both ray segmentation and spatial interpolation. We use eccentricity rather than the quotient of minor and major axes, the value
cvalue in Du (2018). The conversion is by the formulae=sqrt(1-c**2).- Parameters:
fix_velocity_EBSI_function –
Allows to set the function f(speed,angle) which describes how to fix the rays having declination angle from radial direction. The default
lambda x,y: x/(1-0.2*np.abs(y**2))setting is from the paper Du et al. (2015). “Stress wave tomography,” BioResources 10(3), 3948-3962.e_segmentation (float) – Eccentricity for ray segmentation algorithm. This eccentricity is used when setting the velocities of the ray segments. Du suggests c value for this step between 0.65 and 0.8 which is eccentricity between 0.76 and 0.60.
e_interpolation (float) – Eccentricity for spatial interpolation by segmented ellipse. Du suggests c value between 0.85 and 0.95 which is e between 0.53 and 0.31.
n – The shortest ray is divided into
nsegments. The other rays are divided into similar lengths.silent (bool) – No output if silent is True. If False, the function returns a dictionary with keys
allsegmentsandspeeds_on_segments.max_segments (int) – Maximum number of segments on one ray. Default is 10.
- do_FBP_method(filtered=True, damping=1.0, ray_width='auto', ray_width_ratio=0.12, speed_max=None, speed_min=None)
Do the (filtered) back projection on tomogram. The tomogram object is updated.
Classical filtered back projection needs a sinogram densely sampled on a regular grid of angles and ray positions, which a few sensors on a tree do not give. The method therefore uses the algebraic form, valid for any sensor positions. With
Athe matrix of ray lengths in cells (thin or fat rays, seedo_SIRT_method()),bthe times of flight ands0the mean slowness (homogeneous model):plain back projection (
filtered=False): every cell gets the mean slowness of the rays through the cell weighted by their lengths in the cell,x = (A^T (b / L)) / (A^T 1). Cells without rays stay undefined. The image is blurred and the contrast is low.filtered back projection (
filtered=True):x = s0 + A^T (A A^T + mu I)^(-1) (b - A s0), mu = damping * trace(A A^T) / m,
with
mrays. The matrix(A A^T)^(-1)plays the role of the ramp filter of the classical method (the ramp filter is the continuous counterpart of(R R*)^(-1),Rthe Radon transform); the data are filtered first and then projected back. The result is the minimum-norm solution ofA x = bnears0.dampingsuppresses the noise; small values give overshoots, large values blur the image. Thin rays give streaks along the rays, fat rays withdampingabout 1 give a smooth image.
The velocities are clipped to
speed_minandspeed_max; the report gives the number of cells clipped to each bound. Many cells at the maximum are usual (sound wood has about the speed of the fastest ray), cells at the minimum point to overshoots or wrong times.- Parameters:
filtered (bool) – If False, plain back projection,
dampingis ignored.damping (float) – Damping
lambdaof the filter, relative to the mean diagonal ofA A^T. Default 1.ray_width – Width of fat rays, see
do_SIRT_method(). Default'auto', 12 % of the tree diameter.ray_width_ratio (float) – Width of fat rays, see
do_SIRT_method(). Default'auto', 12 % of the tree diameter.speed_max (float) – Bounds for the cell velocities. If None, the maximal ray speed and 0.5 times the minimal ray speed, but at least 340 m/s (speed of sound in air), is used. A cell slower than 340 m/s is an artifact: the wave goes around an air-filled cavity through the wood.
speed_min (float) – Bounds for the cell velocities. If None, the maximal ray speed and 0.5 times the minimal ray speed, but at least 340 m/s (speed of sound in air), is used. A cell slower than 340 m/s is an artifact: the wave goes around an air-filled cavity through the wood.
- Returns:
Report on the reconstruction.
- Return type:
str
- do_Rays_method(ray_width=None, ray_width_ratio=0.12)
Cell velocity as the mean of the speeds of the rays through the cell.
Uses the current ray speeds, i.e. after
fix_velocity_EBSI()(anisotropy correction), if it has been called.thin rays (
ray_width=None): the plain mean of the speeds of the rays crossing the cell; cells without a ray stay undefined. The same as the tomogram computed when theTomoobject is created.fat rays: the mean weighted by
exp(-(d / w)**2),dthe distance of the cell center from the ray andwthe ray width; only rays closer than2.5 wcount. Cells outside the tomogram boundary stay undefined. Fat rays fill the cells between the rays and remove the streaks along the rays; small defects are blurred.
- Parameters:
ray_width – None for thin rays,
'auto'forray_width_ratiotimes the largest distance between the nodes (the tree diameter), or the width in m.ray_width_ratio (float) – Width of fat rays relative to the tree diameter for
ray_width='auto'. Default 12 %.
- Returns:
Report on the reconstruction.
- Return type:
str
- do_SIRT_method(speed_max=None, speed_min=None, smoothing=10.0, iterations=2000, relaxation=1.5, tol=None, fix_velocity_EBSI_function=None, ray_width='auto', ray_width_ratio=0.12)
Do the regularized SIRT method on tomogram. The tomogram object is updated.
SIRT (Simultaneous Iterative Reconstruction Technique) as described in van der Sluis, van der Vorst (1990). “SIRT- and CG-type methods for the iterative solution of sparse linear least-squares problems,” Linear Algebra and its Applications 130, 257-302.
Rays are split to segments at the cell boundaries. The unknowns are the slownesses of all cells inside the tomogram boundary (and of the cells crossed by a ray). The system is
A x = b, whereAholds the lengths of the ray segments in cells andbthe times of flight.With
ray_widththe rays are “fat”: the length of a ray is spread over the cells near the ray with the Gaussian weightexp(-(d / ray_width)**2)of the distancedof the cell center from the ray (cells farther than2.5 * ray_widthare ignored). The wave is sensitive to a zone around the straight line, and fat rays suppress the star-shaped artifacts along the rays. The price is lower resolution, small defects are blurred.With few sensors the system is strongly underdetermined. Therefore the Laplace operator
D(4 neighbours) is appended,[A; alpha D] x = [b; 0](Tikhonov regularization). This smooths the tomogram and fills the cells not crossed by any ray.The iterations start from the homogeneous model (mean slowness) and keep the velocities between
speed_minandspeed_max.The times are those of the rays, the reaction time of the device (
Tomo(reaction_time=...)) is already subtracted.
- Parameters:
speed_max (float) – Bounds for the cell velocities. If None, the maximal ray speed and 0.5 times the minimal ray speed, but at least 340 m/s (speed of sound in air), is used.
speed_min (float) – Bounds for the cell velocities. If None, the maximal ray speed and 0.5 times the minimal ray speed, but at least 340 m/s (speed of sound in air), is used.
smoothing (float) – Weight
alphaof the regularization. Larger values give smoother tomograms and larger residuals. The value 0 gives the classical SIRT without regularization (cells without rays stay undefined).iterations (int) – Maximal number of SIRT iterations. With smoothing the iterations converge slowly; 2000 iterations with
relaxation=1.5give velocities within a few m/s of the limit.relaxation (float) – Relaxation parameter of SIRT, between 0 and 2.
tol (float) – If not None, stop when the relative residual changes between two iterations less than
tol.fix_velocity_EBSI_function – If not None, the ray velocities are fixed by
fix_velocity_EBSI()with this function before reconstruction.ray_width – Width of fat rays in the units of node coordinates.
'auto'isray_width_ratiotimes the tree diameter (the largest distance between nodes), None or 0 gives thin rays (segment lengths in cells).ray_width_ratio (float) – Ray width as a fraction of the tree diameter, used if
ray_widthis'auto'. Default 0.12.
- Returns:
Report on the reconstruction.
- Return type:
str
- fix_velocity_EBSI(function=<function _TomoReconstructionMixin.<lambda>>)
Fix the velocities as described in EBSI in the paper Du et al. (2015). “Stress wave tomography,” BioResources 10(3), 3948-3962.
The function used to fix the velocities can be customized, if necessary. The default is
lambda x,y: x/(1-0.2*np.abs(y**2).The function does not allow to be called twice on the same tomogram. Prints a friendly notice if the user attempts to call is for the second time. The variable
self.velocities_EBSI_fixedis set toTrue.