slabify 0.6.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- slabify/__init__.py +5 -0
- slabify/boundary_mask_auto.py +157 -0
- slabify/cli.py +231 -0
- slabify/slabify.py +69 -0
- slabify/stopgap_tm.py +61 -0
- slabify/utils/__init__.py +12 -0
- slabify/utils/utils.py +239 -0
- slabify-0.6.1.dist-info/METADATA +116 -0
- slabify-0.6.1.dist-info/RECORD +12 -0
- slabify-0.6.1.dist-info/WHEEL +4 -0
- slabify-0.6.1.dist-info/entry_points.txt +2 -0
- slabify-0.6.1.dist-info/licenses/LICENSE +28 -0
slabify/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"""CLI init function."""
|
|
2
|
+
# These imports are necessary to register CLI commands. Do not remove!
|
|
3
|
+
from .boundary_mask_auto import create_boundary_mask_auto # noqa: F401
|
|
4
|
+
from .slabify import slabify # noqa: F401
|
|
5
|
+
from .stopgap_tm import sg_tm_create_boundary_mask # noqa: F401
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from sklearn.linear_model import RANSACRegressor
|
|
3
|
+
|
|
4
|
+
from slabify.utils import (
|
|
5
|
+
distance_of_points_to_plane,
|
|
6
|
+
make_boundary_mask,
|
|
7
|
+
plane_equation_Z_from_XY,
|
|
8
|
+
sample_points,
|
|
9
|
+
variance_at_points,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def create_boundary_mask_auto(
|
|
14
|
+
tomo: np.ndarray,
|
|
15
|
+
N: int = 50000,
|
|
16
|
+
boxsize: int = 32,
|
|
17
|
+
z_min: int = 1,
|
|
18
|
+
z_max: int = None,
|
|
19
|
+
z_offset: float = 0.0,
|
|
20
|
+
simple: bool = False,
|
|
21
|
+
thickness: int = None,
|
|
22
|
+
var_percentile: float = 95,
|
|
23
|
+
percentile_thresholds: tuple = (10, 20, 80, 90),
|
|
24
|
+
r: float = 0.0,
|
|
25
|
+
seed: int = 42,
|
|
26
|
+
verbose: bool = False,
|
|
27
|
+
write_points: bool = False,
|
|
28
|
+
points_file: str = "slabify_points.txt",
|
|
29
|
+
) -> np.ndarray:
|
|
30
|
+
"""
|
|
31
|
+
Automatically create a slab (boundary) mask by fitting one or two planes to enclose the points with high variance.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
tomo (np.ndarray): The tomogram array.
|
|
35
|
+
N (int, optional): Number of points to sample. Defaults to 50000.
|
|
36
|
+
boxsize (int, optional): Box size in pixels to analyze variance around each sampled point. Defaults to 32.
|
|
37
|
+
z_min (int, optional): Minimum Z slice to sample, starting from 1. Defaults to 1.
|
|
38
|
+
z_max (int, optional): Maximum Z slice to sample. Defaults to None, which corresponds to the highest slice.
|
|
39
|
+
z_offset (float, optional): Offset in the Z direction for the mask. Defaults to 0.0.
|
|
40
|
+
simple (bool, optional): Whether to use the simple masking method (single plane). Defaults to False.
|
|
41
|
+
thickness (int, optional): Total thickness of the lamella in pixels (used in simple mode). Defaults to None.
|
|
42
|
+
iterations (int, optional): Number of iterations for plane fitting. Defaults to 3.
|
|
43
|
+
var_percentile (float, optional): Percentile of highest variance locations to use for fitting. Defaults to 95.
|
|
44
|
+
percentile_thresholds (tuple, optional): Percentiles for defining the thresholds for above and below points. Defaults to (10, 20, 80, 90).
|
|
45
|
+
r (float, optional): Regularization factor, between 0.0 and 1.0. A value of 0.0 means no regularization, top and bottom planes are fully independent. A value of 1.0 means top and bottom planes are identical to the central plane, except for the Z offset. Defaults to 0.0.
|
|
46
|
+
seed (int, optional): Random seed for reproducibility. Defaults to 42.
|
|
47
|
+
verbose (bool, optional): Whether to print verbose output (number of points at each iteration). Defaults to False.
|
|
48
|
+
write_points (bool, optional): Whether to write the sampled points to a file. Defaults to False.
|
|
49
|
+
points_file (str, optional): Path to the file where sampled points will be written. Defaults to "slabify_points.txt".
|
|
50
|
+
Returns
|
|
51
|
+
-------
|
|
52
|
+
mask (np.ndarray): Binary mask representing the lamella slab.
|
|
53
|
+
"""
|
|
54
|
+
dims = tomo.shape
|
|
55
|
+
# Sample N points at random:
|
|
56
|
+
Z_rand, Y_rand, X_rand = sample_points(
|
|
57
|
+
mask_size=dims, N=N, boxsize=boxsize, z_min=z_min, z_max=z_max, seed=seed
|
|
58
|
+
)
|
|
59
|
+
# Calculate the variance around each point:
|
|
60
|
+
variances = variance_at_points(
|
|
61
|
+
tomo=tomo, Z=Z_rand, Y=Y_rand, X=X_rand, N=N, boxsize=boxsize
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
variance_thr = np.percentile(variances, var_percentile)
|
|
65
|
+
idx = variances[:] > variance_thr
|
|
66
|
+
idx = idx.squeeze()
|
|
67
|
+
if verbose:
|
|
68
|
+
print(f"Number of points above threshold: {np.sum(idx)}")
|
|
69
|
+
# We now threshold to only work with variances and coordinates for points above the threshold:
|
|
70
|
+
# Hopefully this represents points with "interesting" density, i.e. within the lamella:
|
|
71
|
+
variances = variances[idx]
|
|
72
|
+
Z_rand, Y_rand, X_rand = Z_rand[idx], Y_rand[idx], X_rand[idx]
|
|
73
|
+
|
|
74
|
+
# Robust linear fit using RANSAC:
|
|
75
|
+
fit = RANSACRegressor()
|
|
76
|
+
fit.fit(np.transpose([X_rand, Y_rand]), Z_rand)
|
|
77
|
+
n_central = np.array([fit.estimator_.coef_[0], fit.estimator_.coef_[1], -1])
|
|
78
|
+
p_central = np.array([0, 0, fit.estimator_.intercept_])
|
|
79
|
+
n_top = n_bottom = np.zeros(n_central.shape) # Initialize
|
|
80
|
+
p_top = p_bottom = np.zeros(p_central.shape) # Initialize
|
|
81
|
+
|
|
82
|
+
X, Y = np.meshgrid(np.arange(dims[2]), np.arange(dims[1]))
|
|
83
|
+
|
|
84
|
+
if simple:
|
|
85
|
+
# Fit a single plane through the ~center of the lamella slab:
|
|
86
|
+
if not thickness:
|
|
87
|
+
thickness = float(dims[0]) / 2
|
|
88
|
+
half_thickness = thickness / 2
|
|
89
|
+
# The top and bottom planes are now defined
|
|
90
|
+
Z_top = plane_equation_Z_from_XY(
|
|
91
|
+
X=X, Y=Y, n=n_central, p=p_central, z_offset=half_thickness + z_offset
|
|
92
|
+
)
|
|
93
|
+
Z_bottom = plane_equation_Z_from_XY(
|
|
94
|
+
X=X, Y=Y, n=n_central, p=p_central, z_offset=-half_thickness - z_offset
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
else:
|
|
98
|
+
# Fit two planes to the high-variance points: one for the top and one for the bottom.
|
|
99
|
+
|
|
100
|
+
D = distance_of_points_to_plane(x=X_rand, y=Y_rand, z=Z_rand, n=n_central, p=p_central)
|
|
101
|
+
|
|
102
|
+
# 'above' and 'below' definitions must be inverted because of internal coordinate conventions:
|
|
103
|
+
|
|
104
|
+
above_thr_max = np.percentile(D, percentile_thresholds[1])
|
|
105
|
+
above_thr_min = np.percentile(D, percentile_thresholds[0])
|
|
106
|
+
below_thr_min = np.percentile(D, percentile_thresholds[2])
|
|
107
|
+
below_thr_max = np.percentile(D, percentile_thresholds[3])
|
|
108
|
+
|
|
109
|
+
# above = D < above_thr
|
|
110
|
+
# below = D > below_thr
|
|
111
|
+
|
|
112
|
+
above = np.logical_and(D < above_thr_max, D > above_thr_min)
|
|
113
|
+
below = np.logical_and(D > below_thr_min, D < below_thr_max)
|
|
114
|
+
|
|
115
|
+
n_above = np.sum(above)
|
|
116
|
+
n_below = np.sum(below)
|
|
117
|
+
print(
|
|
118
|
+
f"{n_above} points above, {n_below} points below the plane."
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
if write_points:
|
|
122
|
+
l = np.zeros((X_rand.shape[0],), dtype=int)
|
|
123
|
+
l[above] = 1
|
|
124
|
+
l[below] = 2
|
|
125
|
+
A = np.array([X_rand, Y_rand, Z_rand, variances, D, l])
|
|
126
|
+
fmt = "%d", "%d", "%d", "%.3f", "%.3f", "%d"
|
|
127
|
+
np.savetxt(points_file, A.T, fmt=fmt, delimiter="\t", header="# X Y Z variance distance label: 0=none, 1=top, 2=bottom")
|
|
128
|
+
|
|
129
|
+
X_above, Y_above, Z_above = X_rand[above], Y_rand[above], Z_rand[above]
|
|
130
|
+
X_below, Y_below, Z_below = X_rand[below], Y_rand[below], Z_rand[below]
|
|
131
|
+
|
|
132
|
+
fit_top = RANSACRegressor()
|
|
133
|
+
fit_top.fit(np.transpose([X_above, Y_above]), Z_above)
|
|
134
|
+
fit_bottom = RANSACRegressor()
|
|
135
|
+
fit_bottom.fit(np.transpose([X_below, Y_below]), Z_below)
|
|
136
|
+
n_top = np.array(
|
|
137
|
+
[fit_top.estimator_.coef_[0], fit_top.estimator_.coef_[1], -1]
|
|
138
|
+
)
|
|
139
|
+
p_top = np.array([0, 0, fit_top.estimator_.intercept_])
|
|
140
|
+
n_bottom = np.array(
|
|
141
|
+
[fit_bottom.estimator_.coef_[0], fit_bottom.estimator_.coef_[1], -1]
|
|
142
|
+
)
|
|
143
|
+
p_bottom = np.array([0, 0, fit_bottom.estimator_.intercept_])
|
|
144
|
+
|
|
145
|
+
# Regularization: make the top and bottom planes more similar to the central plane:
|
|
146
|
+
n_top = (1.0 - r) * n_top + r * n_central
|
|
147
|
+
n_bottom = (1.0 - r) * n_bottom + r * n_central
|
|
148
|
+
Z_top = plane_equation_Z_from_XY(
|
|
149
|
+
X=X, Y=Y, n=n_top, p=p_top, z_offset=+z_offset
|
|
150
|
+
)
|
|
151
|
+
Z_bottom = plane_equation_Z_from_XY(
|
|
152
|
+
X=X, Y=Y, n=n_bottom, p=p_bottom, z_offset=-z_offset
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
mask = make_boundary_mask(mask_size=dims, Z_top=Z_top, Z_bottom=Z_bottom)
|
|
156
|
+
|
|
157
|
+
return mask
|
slabify/cli.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import sys
|
|
3
|
+
|
|
4
|
+
import mrcfile
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from slabify import slabify
|
|
8
|
+
from slabify.utils import measure_thickness
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def parse_args() -> argparse.Namespace:
|
|
12
|
+
"""
|
|
13
|
+
Parses command-line arguments for the lamella boundary mask generator.
|
|
14
|
+
|
|
15
|
+
Returns
|
|
16
|
+
-------
|
|
17
|
+
argparse.Namespace: Parsed command-line arguments.
|
|
18
|
+
"""
|
|
19
|
+
parser = argparse.ArgumentParser(
|
|
20
|
+
description="Lamella boundary mask generator.",
|
|
21
|
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
general_opts = parser.add_argument_group(title="General options")
|
|
25
|
+
general_opts.add_argument(
|
|
26
|
+
"-i",
|
|
27
|
+
"--input",
|
|
28
|
+
type=str,
|
|
29
|
+
help="Path to input tomogram in MRC format.",
|
|
30
|
+
required=True,
|
|
31
|
+
)
|
|
32
|
+
general_opts.add_argument(
|
|
33
|
+
"-o",
|
|
34
|
+
"--output",
|
|
35
|
+
type=str,
|
|
36
|
+
help="Path to output mask in MRC format.",
|
|
37
|
+
required=True,
|
|
38
|
+
)
|
|
39
|
+
general_opts.add_argument(
|
|
40
|
+
"--output-masked",
|
|
41
|
+
"--output_masked",
|
|
42
|
+
type=str,
|
|
43
|
+
help="Path to output masked volume in MRC format.",
|
|
44
|
+
)
|
|
45
|
+
general_opts.add_argument(
|
|
46
|
+
"--border", type=int, default=0, help="Voxels to exclude from the border in XY."
|
|
47
|
+
)
|
|
48
|
+
general_opts.add_argument(
|
|
49
|
+
"--offset",
|
|
50
|
+
type=int,
|
|
51
|
+
default=0,
|
|
52
|
+
help="Voxels to offset from the border along Z, i.e. to make a thicker (positive value) or thinner (negative value) slab mask.",
|
|
53
|
+
)
|
|
54
|
+
general_opts.add_argument(
|
|
55
|
+
"--angpix", type=float, help="Pixel size (in Angstroms) for output mask."
|
|
56
|
+
)
|
|
57
|
+
general_opts.add_argument(
|
|
58
|
+
"--measure",
|
|
59
|
+
default=False,
|
|
60
|
+
action="store_true",
|
|
61
|
+
help="Measure thickness of the lamella slab mask at the center of the tomogram.",
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
manual_opts = parser.add_argument_group(
|
|
65
|
+
title="Manual masking options (using model with points to define the boundary)"
|
|
66
|
+
)
|
|
67
|
+
manual_opts.add_argument(
|
|
68
|
+
"--points",
|
|
69
|
+
type=str,
|
|
70
|
+
help="Path to IMOD model containing boundary control points. Both .mod and .txt formats are accepted, but if a .mod file is supplied, IMOD is expected to be present in your $PATH.",
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
auto_opts = parser.add_argument_group(
|
|
74
|
+
title="Automatic masking options (using local analysis of variance)"
|
|
75
|
+
)
|
|
76
|
+
auto_opts.add_argument(
|
|
77
|
+
"--n-samples",
|
|
78
|
+
"--n_samples",
|
|
79
|
+
type=int,
|
|
80
|
+
default=50000,
|
|
81
|
+
help="Number of points to sample at random within the tomogram.",
|
|
82
|
+
)
|
|
83
|
+
auto_opts.add_argument(
|
|
84
|
+
"--boxsize",
|
|
85
|
+
type=int,
|
|
86
|
+
default=24,
|
|
87
|
+
help="Box size (in pixels) to analyze variance around each sampled point.",
|
|
88
|
+
)
|
|
89
|
+
auto_opts.add_argument(
|
|
90
|
+
"--z-min",
|
|
91
|
+
"--z_min",
|
|
92
|
+
type=int,
|
|
93
|
+
default=1,
|
|
94
|
+
help="Minimum Z slice to consider in variance analysis, starting from 1. If not specified, will use the first slice.",
|
|
95
|
+
)
|
|
96
|
+
auto_opts.add_argument(
|
|
97
|
+
"--z-max",
|
|
98
|
+
"--z_max",
|
|
99
|
+
type=int,
|
|
100
|
+
default=None,
|
|
101
|
+
help="Maximum Z slice to consider in variance analysis. If not specified, will use the last slice.",
|
|
102
|
+
)
|
|
103
|
+
auto_opts.add_argument(
|
|
104
|
+
"--simple",
|
|
105
|
+
default=False,
|
|
106
|
+
action="store_true",
|
|
107
|
+
help="Fit a single plane through the center of the lamella and assume fixed lamella thickness.",
|
|
108
|
+
)
|
|
109
|
+
auto_opts.add_argument(
|
|
110
|
+
"--thickness",
|
|
111
|
+
type=int,
|
|
112
|
+
help="Total lamella thickness (in pixels) when doing simple automatic boundary masking. By default the program will use half the tomogram size in Z.",
|
|
113
|
+
)
|
|
114
|
+
auto_opts.add_argument(
|
|
115
|
+
"-p","--percentile","--var-percentile",
|
|
116
|
+
type=float,
|
|
117
|
+
default=95,
|
|
118
|
+
help="Percentile of highest variance locations to select for fitting.",
|
|
119
|
+
)
|
|
120
|
+
auto_opts.add_argument(
|
|
121
|
+
"--percentile-thresholds",
|
|
122
|
+
nargs=4,
|
|
123
|
+
type=float,
|
|
124
|
+
default=(10, 20, 80, 90),
|
|
125
|
+
help="Percentile thresholds for defining the thresholds for above and below points.",
|
|
126
|
+
)
|
|
127
|
+
auto_opts.add_argument(
|
|
128
|
+
"-r","--regularization",
|
|
129
|
+
type=float,
|
|
130
|
+
default=0.5,
|
|
131
|
+
help="Regularization factor, between 0.0 and 1.0. A value of 0.0 means no regularization, top and bottom planes are fully independent. A value of 1.0 means top and bottom planes are identical to the central plane of the lamella except for the Z offset.",
|
|
132
|
+
)
|
|
133
|
+
auto_opts.add_argument("--seed", type=int, default=4056, help="Random seed.")
|
|
134
|
+
auto_opts.add_argument(
|
|
135
|
+
"--verbose",
|
|
136
|
+
default=False,
|
|
137
|
+
action="store_true",
|
|
138
|
+
help="Print verbose output during plane fitting.",
|
|
139
|
+
)
|
|
140
|
+
auto_opts.add_argument(
|
|
141
|
+
"--write-points",
|
|
142
|
+
default=False,
|
|
143
|
+
action="store_true",
|
|
144
|
+
help="Write the sampled points to a file.",
|
|
145
|
+
)
|
|
146
|
+
auto_opts.add_argument(
|
|
147
|
+
"--points-file",
|
|
148
|
+
type=str,
|
|
149
|
+
default="slabify_points.txt",
|
|
150
|
+
help="Path to the file where sampled points will be written.",
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
if len(sys.argv) == 1:
|
|
154
|
+
parser.print_help(sys.stderr)
|
|
155
|
+
sys.exit(1)
|
|
156
|
+
|
|
157
|
+
return parser.parse_args()
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def main():
|
|
161
|
+
"""Main function to generate the lamella boundary mask based on the parsed arguments."""
|
|
162
|
+
args = parse_args()
|
|
163
|
+
input = args.input
|
|
164
|
+
output = args.output
|
|
165
|
+
output_masked = args.output_masked
|
|
166
|
+
points = args.points
|
|
167
|
+
border = args.border
|
|
168
|
+
offset = args.offset
|
|
169
|
+
n_samples = args.n_samples
|
|
170
|
+
boxsize = args.boxsize
|
|
171
|
+
z_min = args.z_min
|
|
172
|
+
z_max = args.z_max
|
|
173
|
+
simple = args.simple
|
|
174
|
+
measure = args.measure
|
|
175
|
+
thickness = args.thickness
|
|
176
|
+
var_percentile = args.percentile
|
|
177
|
+
percentile_thresholds = args.percentile_thresholds
|
|
178
|
+
r = args.regularization
|
|
179
|
+
seed = args.seed
|
|
180
|
+
angpix = args.angpix
|
|
181
|
+
verbose = args.verbose
|
|
182
|
+
write_points = args.write_points
|
|
183
|
+
points_file = args.points_file
|
|
184
|
+
|
|
185
|
+
if r < 0.0 or r > 1.0:
|
|
186
|
+
raise ValueError(
|
|
187
|
+
f"Regularization factor r must be between 0.0 and 1.0, but got {r}."
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
inmrc = mrcfile.open(input, permissive=True)
|
|
191
|
+
tomo = np.array(inmrc.data)
|
|
192
|
+
|
|
193
|
+
bmask = slabify(
|
|
194
|
+
tomo=tomo,
|
|
195
|
+
points=points,
|
|
196
|
+
border=border,
|
|
197
|
+
offset=offset,
|
|
198
|
+
n_samples=n_samples,
|
|
199
|
+
boxsize=boxsize,
|
|
200
|
+
z_min=z_min,
|
|
201
|
+
z_max=z_max,
|
|
202
|
+
simple=simple,
|
|
203
|
+
thickness=thickness,
|
|
204
|
+
var_percentile=var_percentile,
|
|
205
|
+
percentile_thresholds=percentile_thresholds,
|
|
206
|
+
r=r,
|
|
207
|
+
seed=seed,
|
|
208
|
+
verbose=verbose,
|
|
209
|
+
write_points=write_points,
|
|
210
|
+
points_file=points_file
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
if not angpix:
|
|
214
|
+
print(
|
|
215
|
+
f"Warning: --angpix was not provided. Using the pixel size from the input tomogram's header: {inmrc.voxel_size.x:.3f}"
|
|
216
|
+
)
|
|
217
|
+
angpix = inmrc.voxel_size.x
|
|
218
|
+
|
|
219
|
+
if measure:
|
|
220
|
+
measure_thickness(mask=bmask, z_offset=offset, angpix=angpix, verbose=True)
|
|
221
|
+
|
|
222
|
+
# Save output mask:
|
|
223
|
+
with mrcfile.new(output, overwrite=True) as outmrc:
|
|
224
|
+
outmrc.set_data(bmask)
|
|
225
|
+
outmrc.voxel_size = angpix
|
|
226
|
+
|
|
227
|
+
if output_masked:
|
|
228
|
+
# Save output masked volume:
|
|
229
|
+
with mrcfile.new(output_masked, overwrite=True) as outmrc:
|
|
230
|
+
outmrc.set_data(tomo * bmask)
|
|
231
|
+
outmrc.voxel_size = angpix
|
slabify/slabify.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import subprocess
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
from slabify.boundary_mask_auto import create_boundary_mask_auto
|
|
7
|
+
from slabify.stopgap_tm import sg_tm_create_boundary_mask
|
|
8
|
+
from slabify.utils import apply_mask_border
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def slabify(
|
|
12
|
+
tomo: np.ndarray,
|
|
13
|
+
points: str = None,
|
|
14
|
+
border: int = 0,
|
|
15
|
+
offset: float = 0.0,
|
|
16
|
+
n_samples: int = 50000,
|
|
17
|
+
boxsize: int = 32,
|
|
18
|
+
z_min: int = 1,
|
|
19
|
+
z_max: int = None,
|
|
20
|
+
simple: bool = False,
|
|
21
|
+
thickness: int = None,
|
|
22
|
+
var_percentile: float = 95,
|
|
23
|
+
percentile_thresholds: tuple = (10, 20, 80, 90),
|
|
24
|
+
r: float = 0.0,
|
|
25
|
+
seed: int = 4056,
|
|
26
|
+
verbose: bool = False,
|
|
27
|
+
write_points: bool = False,
|
|
28
|
+
points_file: str = "slabify_points.txt",
|
|
29
|
+
):
|
|
30
|
+
# Check if a points file was provided:
|
|
31
|
+
if isinstance(points, str):
|
|
32
|
+
points_basename, points_ext = os.path.splitext(points)
|
|
33
|
+
|
|
34
|
+
# If the points file is provided in binary format (.mod) we call IMOD's model2point to convert it. IMOD must be already loaded for this to work:
|
|
35
|
+
if points_ext == ".mod":
|
|
36
|
+
subprocess.run(["model2point", points, points_basename + ".txt"])
|
|
37
|
+
points = points_basename + ".txt"
|
|
38
|
+
|
|
39
|
+
boundary = np.loadtxt(points)
|
|
40
|
+
|
|
41
|
+
# Create boundary mask using given points:
|
|
42
|
+
bmask = sg_tm_create_boundary_mask(
|
|
43
|
+
mask_size=tomo.shape, boundary=boundary, z_offset=offset
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
else:
|
|
47
|
+
# Create a boundary mask automatically:
|
|
48
|
+
bmask = create_boundary_mask_auto(
|
|
49
|
+
tomo=tomo,
|
|
50
|
+
N=n_samples,
|
|
51
|
+
boxsize=boxsize,
|
|
52
|
+
z_min=z_min,
|
|
53
|
+
z_max=z_max,
|
|
54
|
+
z_offset=offset,
|
|
55
|
+
simple=simple,
|
|
56
|
+
thickness=thickness,
|
|
57
|
+
var_percentile=var_percentile,
|
|
58
|
+
percentile_thresholds=percentile_thresholds,
|
|
59
|
+
r=r,
|
|
60
|
+
seed=seed,
|
|
61
|
+
verbose=verbose,
|
|
62
|
+
write_points=write_points,
|
|
63
|
+
points_file=points_file
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
# Mask out some voxels away from the border in XY:
|
|
67
|
+
bmask = apply_mask_border(mask=bmask, xy_border=border)
|
|
68
|
+
|
|
69
|
+
return bmask
|
slabify/stopgap_tm.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
from slabify.utils import affine_fit, make_boundary_mask, plane_equation_Z_from_XY
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def sg_tm_create_boundary_mask(
|
|
7
|
+
mask_size: np.ndarray, boundary: np.ndarray, z_offset: float = 0.0
|
|
8
|
+
) -> np.ndarray:
|
|
9
|
+
"""
|
|
10
|
+
Create a boundary mask for a tomogram assuming a slab geometry.
|
|
11
|
+
Reimplementation in Python of the MATLAB function:
|
|
12
|
+
https://github.com/wan-lab-vanderbilt/STOPGAP/blob/master/sg_toolbox/sg_tm_create_boundary_mask.m.
|
|
13
|
+
|
|
14
|
+
NOTE: the Python version of this function assumes volume dimensions in the mrcfile convention: [Z, Y, X].
|
|
15
|
+
|
|
16
|
+
Args:
|
|
17
|
+
mask_size (np.ndarray): The size of the tomogram to be masked in format (Z, Y, X).
|
|
18
|
+
boundary (np.ndarray): A plain-text file containing points that define the slab geometry.
|
|
19
|
+
xy_border (int, optional): Number of voxels to mask on each edge. Defaults to 0.
|
|
20
|
+
|
|
21
|
+
Returns
|
|
22
|
+
-------
|
|
23
|
+
mask (np.ndarray): The boundary mask.
|
|
24
|
+
|
|
25
|
+
Original author: William Wan
|
|
26
|
+
Converted to Python by: Ricardo D. Righetto (with some Copilot help)
|
|
27
|
+
|
|
28
|
+
"""
|
|
29
|
+
dims = mask_size
|
|
30
|
+
|
|
31
|
+
# Parse top and bottom points
|
|
32
|
+
n_points = boundary.shape[0]
|
|
33
|
+
n_sets = n_points // 4
|
|
34
|
+
if n_points % 4 != 0:
|
|
35
|
+
raise ValueError("Input boundary coordinates must be supplied in sets of 4")
|
|
36
|
+
|
|
37
|
+
top = np.zeros((n_sets * 2, 3))
|
|
38
|
+
bottom = np.zeros((n_sets * 2, 3))
|
|
39
|
+
|
|
40
|
+
# Parse point list:
|
|
41
|
+
for i in range(n_sets):
|
|
42
|
+
top[2 * i] = boundary[4 * i]
|
|
43
|
+
top[2 * i + 1] = boundary[4 * i + 1]
|
|
44
|
+
bottom[2 * i] = boundary[4 * i + 2]
|
|
45
|
+
bottom[2 * i + 1] = boundary[4 * i + 3]
|
|
46
|
+
|
|
47
|
+
# Generate boundaries
|
|
48
|
+
X, Y = np.meshgrid(np.arange(dims[2]), np.arange(dims[1]))
|
|
49
|
+
|
|
50
|
+
n_1, _, p_1 = affine_fit(top)
|
|
51
|
+
n_2, _, p_2 = affine_fit(bottom)
|
|
52
|
+
|
|
53
|
+
Z_top = plane_equation_Z_from_XY(X=X, Y=Y, n=n_1, p=p_1, z_offset=z_offset)
|
|
54
|
+
Z_bottom = plane_equation_Z_from_XY(X=X, Y=Y, n=n_2, p=p_2, z_offset=-z_offset)
|
|
55
|
+
|
|
56
|
+
Z_top[Z_top > dims[0]] = dims[0]
|
|
57
|
+
Z_bottom[Z_bottom < 0] = 0
|
|
58
|
+
|
|
59
|
+
mask = make_boundary_mask(mask_size=dims, Z_top=Z_top, Z_bottom=Z_bottom)
|
|
60
|
+
|
|
61
|
+
return mask
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""CLI init function."""
|
|
2
|
+
# These imports are necessary to register CLI commands. Do not remove!
|
|
3
|
+
from .utils import ( # noqa: F401
|
|
4
|
+
affine_fit,
|
|
5
|
+
apply_mask_border,
|
|
6
|
+
distance_of_points_to_plane,
|
|
7
|
+
make_boundary_mask,
|
|
8
|
+
measure_thickness,
|
|
9
|
+
plane_equation_Z_from_XY,
|
|
10
|
+
sample_points,
|
|
11
|
+
variance_at_points,
|
|
12
|
+
)
|
slabify/utils/utils.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def measure_thickness(
|
|
5
|
+
mask: np.ndarray,
|
|
6
|
+
yx_coords: tuple[int, int] = None,
|
|
7
|
+
z_offset: float = 0.0,
|
|
8
|
+
angpix: float = None,
|
|
9
|
+
verbose=False,
|
|
10
|
+
) -> tuple[float, float]:
|
|
11
|
+
"""
|
|
12
|
+
Measure thickness in Z of binary slab mask at given point.
|
|
13
|
+
|
|
14
|
+
Args:
|
|
15
|
+
mask (np.ndarray): The lamella slab mask.
|
|
16
|
+
yx_coords (tuple, optional): the y,x coordinates where to measure the Z thickness.
|
|
17
|
+
z_offset (float, optional): Offset in the Z direction for the mask. Defaults to 0.0.
|
|
18
|
+
angpix (float, optional): The pixel size in Angstroms for displaying the measured thickness, only relevant if verbose is True.
|
|
19
|
+
verbose (bool, optional): Whether to print the measured thickness with and without Z offset to the screen.
|
|
20
|
+
|
|
21
|
+
Returns
|
|
22
|
+
-------
|
|
23
|
+
tuple: Slab mask thickness with and without Z offset.
|
|
24
|
+
"""
|
|
25
|
+
# If no coordinates are passed, we use the center of the volume:
|
|
26
|
+
if not yx_coords:
|
|
27
|
+
yx_coords = [
|
|
28
|
+
mask.shape[1] // 2,
|
|
29
|
+
mask.shape[2] // 2,
|
|
30
|
+
] # Remember mrcfile convention is [Z, Y, X]
|
|
31
|
+
|
|
32
|
+
t_with_offset = np.sum(mask[:, yx_coords[0], yx_coords[1]])
|
|
33
|
+
t_no_offset = t_with_offset - 2 * z_offset
|
|
34
|
+
|
|
35
|
+
if verbose:
|
|
36
|
+
if not angpix:
|
|
37
|
+
units = "px"
|
|
38
|
+
else:
|
|
39
|
+
units = "Å"
|
|
40
|
+
t_with_offset *= angpix
|
|
41
|
+
t_no_offset *= angpix
|
|
42
|
+
|
|
43
|
+
print(f"Slab mask thickness with Z offset: {t_with_offset:.2f} {units}")
|
|
44
|
+
print(f"Slab mask thickness without Z offset: {t_no_offset:.2f} {units}")
|
|
45
|
+
|
|
46
|
+
return t_with_offset, t_no_offset
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def sample_points(
|
|
50
|
+
mask_size: np.ndarray,
|
|
51
|
+
N: int = 50000,
|
|
52
|
+
boxsize: int = 32,
|
|
53
|
+
z_min: int = 1,
|
|
54
|
+
z_max: int = None,
|
|
55
|
+
seed: int = 42,
|
|
56
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
57
|
+
"""
|
|
58
|
+
Sample points at random within the tomogram, staying away from the borders.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
mask_size (np.ndarray): The dimensions of the tomogram.
|
|
62
|
+
N (int, optional): Number of points to sample. Defaults to 50000.
|
|
63
|
+
boxsize (int, optional): Box size in pixels around each sampled point. Defaults to 32.
|
|
64
|
+
z_min (int, optional): Minimum Z slice to sample, starting from 1. Defaults to 1.
|
|
65
|
+
z_max (int, optional): Maximum Z slice to sample. Defaults to None, which corresponds to the highest slice.
|
|
66
|
+
seed (int, optional): Random seed for reproducibility. Defaults to 42.
|
|
67
|
+
|
|
68
|
+
Returns
|
|
69
|
+
-------
|
|
70
|
+
tuple: Arrays of sampled Z, Y, X coordinates.
|
|
71
|
+
"""
|
|
72
|
+
dims = mask_size
|
|
73
|
+
half_box = boxsize // 2
|
|
74
|
+
if not z_max:
|
|
75
|
+
z_max = dims[0]
|
|
76
|
+
|
|
77
|
+
np.random.seed(seed=seed)
|
|
78
|
+
Z_rand = np.random.randint(z_min + half_box - 1, z_max - half_box, size=(N,))
|
|
79
|
+
Y_rand = np.random.randint(half_box, dims[1] - half_box, size=(N,))
|
|
80
|
+
X_rand = np.random.randint(half_box, dims[2] - half_box, size=(N,))
|
|
81
|
+
|
|
82
|
+
return Z_rand, Y_rand, X_rand
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def variance_at_points(
|
|
86
|
+
tomo: np.ndarray,
|
|
87
|
+
Z: np.ndarray,
|
|
88
|
+
Y: np.ndarray,
|
|
89
|
+
X: np.ndarray,
|
|
90
|
+
N: int = 50000,
|
|
91
|
+
boxsize: int = 32,
|
|
92
|
+
) -> np.ndarray:
|
|
93
|
+
"""
|
|
94
|
+
Calculate the variance around each sampled point within the specified box size.
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
tomo (np.ndarray): The tomogram array.
|
|
98
|
+
Z (np.ndarray): Array of sampled Z coordinates.
|
|
99
|
+
Y (np.ndarray): Array of sampled Y coordinates.
|
|
100
|
+
X (np.ndarray): Array of sampled X coordinates.
|
|
101
|
+
N (int, optional): Number of sampled points. Defaults to 50000.
|
|
102
|
+
boxsize (int, optional): Box size in pixels around each sampled point. Defaults to 32.
|
|
103
|
+
|
|
104
|
+
Returns
|
|
105
|
+
-------
|
|
106
|
+
variances (np.ndarray): Array containing the variance at each sampled point.
|
|
107
|
+
"""
|
|
108
|
+
half_box = boxsize // 2
|
|
109
|
+
|
|
110
|
+
variances = np.zeros((N,))
|
|
111
|
+
|
|
112
|
+
for i in np.arange(N):
|
|
113
|
+
x, y, z = X[i], Y[i], Z[i]
|
|
114
|
+
x_min, x_max = x - half_box, x + half_box
|
|
115
|
+
y_min, y_max = y - half_box, y + half_box
|
|
116
|
+
z_min, z_max = z - half_box, z + half_box
|
|
117
|
+
|
|
118
|
+
box = tomo[z_min:z_max, y_min:y_max, x_min:x_max]
|
|
119
|
+
|
|
120
|
+
variances[i] = np.var(box)
|
|
121
|
+
|
|
122
|
+
return variances
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def make_boundary_mask(mask_size: np.ndarray, Z_top: np.ndarray, Z_bottom: np.ndarray):
|
|
126
|
+
"""
|
|
127
|
+
Creates the boundary mask volume given the top and bottom planes.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
mask_size (np.ndarray): The dimensions of the tomogram.
|
|
131
|
+
Z_top (np.ndarray): Volume containing the Z value of each voxel, according to top plane equation.
|
|
132
|
+
Z_bottom (np.ndarray): Volume containing the Z value of each voxel, according to bottom plane equation.
|
|
133
|
+
|
|
134
|
+
Returns
|
|
135
|
+
-------
|
|
136
|
+
mask (np.ndarray): The binary boundary mask, with value of 1 within the boundary and 0 outside.
|
|
137
|
+
"""
|
|
138
|
+
dims = mask_size
|
|
139
|
+
|
|
140
|
+
# Generate mask
|
|
141
|
+
mask = np.zeros(dims, dtype=np.int8)
|
|
142
|
+
|
|
143
|
+
# Loop over X,Y and fill each column in Z with the mask where appropriate:
|
|
144
|
+
for i in range(dims[2]): # Loop over X
|
|
145
|
+
for j in range(dims[1]): # Loop over Y
|
|
146
|
+
z1 = int(round(Z_top[j, i]))
|
|
147
|
+
z2 = int(round(Z_bottom[j, i]))
|
|
148
|
+
mask[z2:z1, j, i] = 1
|
|
149
|
+
|
|
150
|
+
return mask
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def apply_mask_border(mask: np.ndarray, xy_border: int = 0) -> np.ndarray:
|
|
154
|
+
"""
|
|
155
|
+
Applies a border exclusion to the mask.
|
|
156
|
+
|
|
157
|
+
Args:
|
|
158
|
+
mask (np.ndarray): The binary mask to be adjusted.
|
|
159
|
+
xy_border (int, optional): Number of pixels to exclude from the XY border. Defaults to 0.
|
|
160
|
+
|
|
161
|
+
Returns
|
|
162
|
+
-------
|
|
163
|
+
mask (np.ndarray): The adjusted binary mask.
|
|
164
|
+
"""
|
|
165
|
+
if xy_border > 0:
|
|
166
|
+
border = np.zeros(mask.shape, dtype=np.int8)
|
|
167
|
+
border[:, xy_border:-xy_border, xy_border:-xy_border] = 1
|
|
168
|
+
mask *= border
|
|
169
|
+
|
|
170
|
+
return mask
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def affine_fit(X: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
174
|
+
"""
|
|
175
|
+
Computes the plane that best fits a set of sample points.
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
X (np.ndarray): N by 3 matrix where each row is a sample point.
|
|
179
|
+
|
|
180
|
+
Returns
|
|
181
|
+
-------
|
|
182
|
+
tuple: (n, V, p), where
|
|
183
|
+
n (np.ndarray): Unit vector normal to the plane.
|
|
184
|
+
V (np.ndarray): 3 by 2 matrix with orthonormal basis vectors of the plane.
|
|
185
|
+
p (np.ndarray): A point belonging to the plane.
|
|
186
|
+
"""
|
|
187
|
+
# Compute mean of samples
|
|
188
|
+
p = np.mean(X, axis=0)
|
|
189
|
+
|
|
190
|
+
# Reduce samples
|
|
191
|
+
R = X - p
|
|
192
|
+
|
|
193
|
+
# Compute principal directions
|
|
194
|
+
V, _, _ = np.linalg.svd(R.T)
|
|
195
|
+
n = V[:, -1]
|
|
196
|
+
V = V[:, 0:-1]
|
|
197
|
+
|
|
198
|
+
return n, V, p
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def plane_equation_Z_from_XY(
|
|
202
|
+
X: np.ndarray, Y: np.ndarray, n: np.ndarray, p: np.ndarray, z_offset: float = 0
|
|
203
|
+
) -> np.ndarray:
|
|
204
|
+
"""
|
|
205
|
+
Calculates the Z-coordinate of a plane given X and Y coordinates and plane coefficients.
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
X (np.ndarray): Array of X-coordinates.
|
|
209
|
+
Y (np.ndarray): Array of Y-coordinates.
|
|
210
|
+
coeffs (np.ndarray): Coefficients of the plane equation.
|
|
211
|
+
intercept (float): Intercept of the plane equation.
|
|
212
|
+
|
|
213
|
+
Returns
|
|
214
|
+
-------
|
|
215
|
+
Z (np.ndarray): The Z-coordinate values corresponding to the input X and Y coordinates.
|
|
216
|
+
"""
|
|
217
|
+
return -(n[0] * X + n[1] * Y - np.dot(n, p)) / n[2] + z_offset
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def distance_of_points_to_plane(
|
|
221
|
+
x: np.ndarray, y: np.ndarray, z: np.ndarray, n: np.ndarray, p: np.ndarray
|
|
222
|
+
) -> np.ndarray:
|
|
223
|
+
"""
|
|
224
|
+
Calculates the distance of points to a plane.
|
|
225
|
+
|
|
226
|
+
Args:
|
|
227
|
+
points (np.ndarray): Array of points.
|
|
228
|
+
coeffs (np.ndarray): Coefficients of the plane equation.
|
|
229
|
+
intercept (float): Intercept of the plane equation.
|
|
230
|
+
|
|
231
|
+
Returns
|
|
232
|
+
-------
|
|
233
|
+
D (np.ndarray): The distances of the points from the plane.
|
|
234
|
+
"""
|
|
235
|
+
d = -np.dot(n, p)
|
|
236
|
+
|
|
237
|
+
return (n[2] * z + n[1] * y + n[0] * x + d) / np.sqrt(
|
|
238
|
+
n[2] ** 2 + n[1] ** 2 + n[0] ** 2
|
|
239
|
+
)
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: slabify
|
|
3
|
+
Version: 0.6.1
|
|
4
|
+
Summary: lamella slab segmentation for cryo-et
|
|
5
|
+
Project-URL: homepage, https://github.com/CellArchLab/slabify-et
|
|
6
|
+
Project-URL: repository, https://github.com/CellArchLab/slabify-et
|
|
7
|
+
Author-email: Ricardo Diogo Righetto <ricardo.righetto@unibas.ch>
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: License :: OSI Approved :: BSD License
|
|
11
|
+
Classifier: Natural Language :: English
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Image Processing
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.8
|
|
21
|
+
Requires-Dist: mrcfile
|
|
22
|
+
Requires-Dist: numpy
|
|
23
|
+
Requires-Dist: scikit-learn
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: black; extra == 'dev'
|
|
26
|
+
Requires-Dist: ipython; extra == 'dev'
|
|
27
|
+
Requires-Dist: mkdocs-material; extra == 'dev'
|
|
28
|
+
Requires-Dist: pdbpp; extra == 'dev'
|
|
29
|
+
Requires-Dist: pre-commit; extra == 'dev'
|
|
30
|
+
Requires-Dist: pytest; extra == 'dev'
|
|
31
|
+
Requires-Dist: pytest-cov; extra == 'dev'
|
|
32
|
+
Requires-Dist: rich; extra == 'dev'
|
|
33
|
+
Requires-Dist: ruff; extra == 'dev'
|
|
34
|
+
Provides-Extra: test
|
|
35
|
+
Requires-Dist: pytest-cov; extra == 'test'
|
|
36
|
+
Requires-Dist: pytest>=6.0; extra == 'test'
|
|
37
|
+
Description-Content-Type: text/markdown
|
|
38
|
+
|
|
39
|
+
# Slabify
|
|
40
|
+
A CLI tool to automatically segment the lamella slab in cryo-ET volumes
|
|
41
|
+
|
|
42
|
+
[](https://doi.org/10.5281/zenodo.13941081)
|
|
43
|
+

|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# Overview
|
|
47
|
+
Slabify is a Python command-line tool to automatically segment the lamella slab from cellular cryo-electron tomography (cryo-ET) volumes. The program analyzes the local variance around random points inside the tomogram to find where the "interesting" density is. There are three modes of operation:
|
|
48
|
+
1. Find the lamella boundaries by fitting two planes to the top and bottom sides of the slab (default).
|
|
49
|
+
2. Fit a single plane through the center of the lamella, then expand a slab mask of the given `--thickness` in Z. This mode is enabled by the `--simple` flag, and tends to work better in "difficult" cases.
|
|
50
|
+
3. If all else fails, you can still manually define the lamella boundaries by clicking a few points (12, to be precise) in IMOD and have `slabify` fit two planes defining the top and bottom sides of the slab. See [instructions](https://github.com/CellArchLab/slabify-et/wiki/How-to-manually-create-a-lamella-boundary-mask-using-IMOD) for details.
|
|
51
|
+
|
|
52
|
+
The first two modes employ robust fitting through the [RANSAC](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.RANSACRegressor.html) algorithm to prevent outliers from perturbing the boundary estimation too much.
|
|
53
|
+
|
|
54
|
+
## Applications
|
|
55
|
+
A lamella slab mask can be useful in different scenarios when processing cellular cryo-ET data, for example:
|
|
56
|
+
|
|
57
|
+
* Removing obvious false positives outside the lamella in particle picking (e.g. by template matching)
|
|
58
|
+
* Speeding up template matching by avoiding searches in the void, as implemented in [STOPGAP](https://github.com/wan-lab-vanderbilt/STOPGAP), [GAPSTOP](https://gitlab.mpcdf.mpg.de/bturo/gapstop_tm) and [pytom-match-pick](https://github.com/SBC-Utrecht/pytom-match-pick)
|
|
59
|
+
* Clipping segmentations
|
|
60
|
+
* Selecting only "interesting" subtomograms for training denoising networks, as in [IsoNet](https://github.com/IsoNet-cryoET/IsoNet) and [DeepDeWedge](https://github.com/MLI-lab/DeepDeWedge)
|
|
61
|
+
* Assessing particle distribution within the lamella
|
|
62
|
+
|
|
63
|
+
# Installation
|
|
64
|
+
|
|
65
|
+
1. Create a conda environment (or use an existing one if you prefer):
|
|
66
|
+
```bash
|
|
67
|
+
conda create -n slabify python=3.12
|
|
68
|
+
```
|
|
69
|
+
2. Activate the environment:
|
|
70
|
+
```bash
|
|
71
|
+
conda activate slabify
|
|
72
|
+
```
|
|
73
|
+
3. Install Slabify from PyPI:
|
|
74
|
+
```bash
|
|
75
|
+
pip install slabify
|
|
76
|
+
```
|
|
77
|
+
Or, for the latest development version, install from the repo:
|
|
78
|
+
```bash
|
|
79
|
+
git clone https://github.com/CellArchLab/slabify-et.git
|
|
80
|
+
cd slabify-et
|
|
81
|
+
pip install .
|
|
82
|
+
```
|
|
83
|
+
Now, you should be able to run the `slabify` command.
|
|
84
|
+
|
|
85
|
+
## Optional dependencies
|
|
86
|
+
* [IMOD](https://bio3d.colorado.edu/imod/): if you want to be able to create slab masks from IMOD models in `.mod` format directly, you should have IMOD installed and activated in your session.
|
|
87
|
+
|
|
88
|
+
# Usage
|
|
89
|
+
Using Slabify is straightforward:
|
|
90
|
+
```bash
|
|
91
|
+
slabify -i tomogram.mrc -o tomogram_slab_mask.mrc
|
|
92
|
+
```
|
|
93
|
+
You may want to turn a few knobs to fine tune your results of course. Type `slabify --help` to see all options. See also the [FAQ](https://github.com/CellArchLab/slabify#faq) below.
|
|
94
|
+
|
|
95
|
+
# FAQ
|
|
96
|
+
### What tomogram dimensions are good for Slabify?
|
|
97
|
+
The following tomogram sizes have been tested:
|
|
98
|
+
|
|
99
|
+
* 1024 x 1024 x 512, 7.84 Å/px (bin4, Falcon4i detector)
|
|
100
|
+
* 1024 x 1440 x 256, 10.74 Å/px (bin4, K3 detector)
|
|
101
|
+
|
|
102
|
+
Anything in this range of tomogram dimensions and pixel sizes should work well. The `--boxsize` and `--n-samples` options might need to be adjusted if you have something very different.
|
|
103
|
+
|
|
104
|
+
### What kind of filtering should I apply to my tomograms?
|
|
105
|
+
While Slabify should work on any tomogram, high-contrast and "clean" tomos tend to give the best results. These can be obtained by applying a denoising tool such as [DeepDeWedge](https://github.com/MLI-lab/DeepDeWedge), [ICECREAM](https://github.com/swing-research/icecream) or [IsoNet2](https://github.com/IsoNet-cryoET/IsoNet2) to your data before running Slabify. For a quicker alternative, the deconvolution filter from [Warp](https://doi.org/10.1038/s41592-019-0580-y) also works well for our purposes. See [here](https://github.com/CellArchLab/slabify-et/wiki/How-to-deconvolve-a-tomogram-using-IMOD) for how to apply it using the IMOD implementation.
|
|
106
|
+
|
|
107
|
+
### The estimated slab is too thin, how can I improve it?
|
|
108
|
+
It is known that Slabify can be quite conservative in its estimation of the lamella boundaries. This is desirable in most cases, as you probably want to exclude the damage layer from FIB milling on both sides of the lamella. However, there are a few tips you can try to get thicker slab masks:
|
|
109
|
+
* The easiest way is to use the `--offset` option to arbitrarily grow your slab mask in the Z direction. Note that a negative value can be provided to make the slab *thinner*!
|
|
110
|
+
* You can increase the number of `--iterations`. 3 to 5 iterations are usually good.
|
|
111
|
+
* You can slightly decrease the `--percentile` of highest variance points in order to capture more information, say from 95 to 94.
|
|
112
|
+
* Tweaking the `--n-samples` and `--boxsize` values can be beneficial in some cases (needs more testing).
|
|
113
|
+
* Finally, the `--simple` mode with an arbitrary slab `--thickness` is generally a safe option.
|
|
114
|
+
|
|
115
|
+
# Acknowledgments
|
|
116
|
+
The manual boundary masking is based on code from Will Wan for [STOPGAP](https://github.com/wan-lab-vanderbilt/STOPGAP). Thanks to Caitie McCafferty and Philippe Van der Stappen for discussions and feature suggestions.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
slabify/__init__.py,sha256=Qjcygu-VTBR3WpUXEgYQOdt8bvaYuggCRJsMui5xEyE,276
|
|
2
|
+
slabify/boundary_mask_auto.py,sha256=UhBreCNPWo365Knnsf0q-oJnQS48ODiU0YVVidADmwA,7245
|
|
3
|
+
slabify/cli.py,sha256=UaqWKXbHb5XxhQRCTXdC2TaDQfiLRbgU5VQVJ0bK2mw,7208
|
|
4
|
+
slabify/slabify.py,sha256=UXv1xEjrsXmjJmWDtDBknlwhEdfpIc-A0W5N4eFI3cA,2073
|
|
5
|
+
slabify/stopgap_tm.py,sha256=-pOFf0GgUaQYUatBKMjcxwwv48WXMcWdGKNnDEZp5w8,2068
|
|
6
|
+
slabify/utils/__init__.py,sha256=xU4QAkG9B9Z_gTco8v4IjvMfN4KeiRXO0StXujQO6Ok,325
|
|
7
|
+
slabify/utils/utils.py,sha256=8m4QzYIaeypwBLHm4FH481A-pnaL0ioe7eczn0NR4dA,7570
|
|
8
|
+
slabify-0.6.1.dist-info/METADATA,sha256=_Vg_MBiBZlm6ycSvspZoC8dbuh-qb-4P7Fp0vAXgo_A,6992
|
|
9
|
+
slabify-0.6.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
10
|
+
slabify-0.6.1.dist-info/entry_points.txt,sha256=b-zeW_fwr5e2Lqf-GroLpF9btDG6abgV0uMy_qFSta8,45
|
|
11
|
+
slabify-0.6.1.dist-info/licenses/LICENSE,sha256=up2CMYVHZDZN-wzKiMbRJdMBaFKUA-khnD4l14lQZLg,1498
|
|
12
|
+
slabify-0.6.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024, CellArchLab
|
|
4
|
+
|
|
5
|
+
Redistribution and use in source and binary forms, with or without
|
|
6
|
+
modification, are permitted provided that the following conditions are met:
|
|
7
|
+
|
|
8
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
9
|
+
list of conditions and the following disclaimer.
|
|
10
|
+
|
|
11
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
and/or other materials provided with the distribution.
|
|
14
|
+
|
|
15
|
+
3. Neither the name of the copyright holder nor the names of its
|
|
16
|
+
contributors may be used to endorse or promote products derived from
|
|
17
|
+
this software without specific prior written permission.
|
|
18
|
+
|
|
19
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
22
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
23
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
24
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
25
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
26
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
27
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
28
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|