lattice-sub 1.2.2__py3-none-any.whl → 1.3.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lattice-sub
3
- Version: 1.2.2
3
+ Version: 1.3.1
4
4
  Summary: Lattice subtraction for cryo-EM micrographs - removes periodic crystal signals to reveal non-periodic features
5
5
  Author-email: George Stephenson <george.stephenson@colorado.edu>, Vignesh Kasinath <vignesh.kasinath@colorado.edu>
6
6
  License: MIT
@@ -94,7 +94,17 @@ lattice-sub batch input_folder/ output_folder/ --pixel-size 0.56
94
94
  lattice-sub batch input_folder/ output_folder/ --pixel-size 0.56 --vis comparisons/
95
95
  ```
96
96
 
97
- This creates side-by-side PNG images showing before/after/difference for each micrograph.
97
+ This creates 4-panel PNG comparison images for each micrograph showing:
98
+ 1. **Original** - Input micrograph
99
+ 2. **Subtracted** - Lattice-removed result
100
+ 3. **Difference** - What was removed (5x amplified)
101
+ 4. **Threshold Curve** - Threshold vs lattice removal efficacy
102
+
103
+ **Limit the number of visualizations:**
104
+ ```bash
105
+ # Generate visualizations for first 10 images only
106
+ lattice-sub batch input_folder/ output_folder/ -p 0.56 --vis comparisons/ -n 10
107
+ ```
98
108
 
99
109
  ---
100
110
 
@@ -105,6 +115,8 @@ This creates side-by-side PNG images showing before/after/difference for each mi
105
115
  | `-p, --pixel-size` | **Required.** Pixel size in Ångstroms |
106
116
  | `-o, --output` | Output file path (default: `sub_<input>`) |
107
117
  | `-t, --threshold` | Peak detection sensitivity (default: **auto** - optimized per image) |
118
+ | `--vis DIR` | Generate 4-panel comparison PNGs in DIR |
119
+ | `-n, --num-vis N` | Limit visualizations to first N images |
108
120
  | `--cpu` | Force CPU processing (GPU is used by default) |
109
121
  | `-q, --quiet` | Hide the banner and progress messages |
110
122
  | `-v, --verbose` | Show detailed processing information |
@@ -207,7 +219,7 @@ lattice-sub batch input/ output/ -p 0.56
207
219
 
208
220
  **Output:**
209
221
  ```
210
- Phase-preserving FFT inpainting for cryo-EM | v1.2.2
222
+ Phase-preserving FFT inpainting for cryo-EM | v1.3.0
211
223
 
212
224
  Configuration
213
225
  -------------
@@ -1,7 +1,7 @@
1
- lattice_sub-1.2.2.dist-info/licenses/LICENSE,sha256=2kPoH0cbEp0cVEGqMpyF2IQX1npxdtQmWJB__HIRSb0,1101
2
- lattice_subtraction/__init__.py,sha256=UkIWBvAFMQ3YgK1t8DwHaGqufsArImuHhBAp5iCBC2E,1737
1
+ lattice_sub-1.3.1.dist-info/licenses/LICENSE,sha256=2kPoH0cbEp0cVEGqMpyF2IQX1npxdtQmWJB__HIRSb0,1101
2
+ lattice_subtraction/__init__.py,sha256=KL12LDW3dzz_JSBMGIo6UJ3_9vw7oooF7z7EG5P3i4Y,1737
3
3
  lattice_subtraction/batch.py,sha256=zJzvUnr8dznvxE8jaPKDLJ7AcJg8Cbfv5nVo0FzZz1I,20891
4
- lattice_subtraction/cli.py,sha256=fWZ3ueahQXPQ_ApzS345AdslsMF0-6HIAIvan2IFHkk,23597
4
+ lattice_subtraction/cli.py,sha256=W99XQClUMKaaFQxle0W-ILQ6UuYRFXZVJWD4qXpcIj4,24063
5
5
  lattice_subtraction/config.py,sha256=uzwKb5Zi3phHUk2ZgoiLsQdwFdN-rTiY8n02U91SObc,8426
6
6
  lattice_subtraction/core.py,sha256=VzcecSZHRuBuHUc2jHGv8LalINL75RH0aTpABI708y8,16265
7
7
  lattice_subtraction/io.py,sha256=uHku6rJ0jeCph7w-gOIDJx-xpNoF6PZcLfb5TBTOiw0,4594
@@ -9,9 +9,9 @@ lattice_subtraction/masks.py,sha256=HIamrACmbQDkaCV4kXhnjMDSwIig4OtQFLig9A8PMO8,
9
9
  lattice_subtraction/processing.py,sha256=tmnj5K4Z9HCQhRpJ-iMd9Bj_uTRuvDEWyUenh8MCWEM,8341
10
10
  lattice_subtraction/threshold_optimizer.py,sha256=yEsGM_zt6YjgEulEZqtRy113xOFB69aHJIETm2xSS6k,15398
11
11
  lattice_subtraction/ui.py,sha256=Sp_a-yNmBRZJxll8h9T_H5-_KsI13zGYmHcbcpVpbR8,9176
12
- lattice_subtraction/visualization.py,sha256=pMZKcz6Xgs98lLaZbvGjoMIyEYA_MLRracVxpQStC3w,5935
13
- lattice_sub-1.2.2.dist-info/METADATA,sha256=u8Fy9n7k3bXazhftD4Zl4_yPgY3Aki9Jv3Sm4EjzBUk,14419
14
- lattice_sub-1.2.2.dist-info/WHEEL,sha256=qELbo2s1Yzl39ZmrAibXA2jjPLUYfnVhUNTlyF1rq0Y,92
15
- lattice_sub-1.2.2.dist-info/entry_points.txt,sha256=o8PzJR8kFnXlKZufoYGBIHpiosM-P4PZeKZXJjtPS6Y,61
16
- lattice_sub-1.2.2.dist-info/top_level.txt,sha256=BOuW-sm4G-fQtsWPRdeLzWn0WS8sDYVNKIMj5I3JXew,20
17
- lattice_sub-1.2.2.dist-info/RECORD,,
12
+ lattice_subtraction/visualization.py,sha256=noRhBXi_Xd1b5deBfVo0Bk0f3d2kqlf3_SQwAPJC0E0,12032
13
+ lattice_sub-1.3.1.dist-info/METADATA,sha256=qN0VzkEJyNbBe_AN5tKcUXh4VjDzaL1COQCk0W83ZiM,14901
14
+ lattice_sub-1.3.1.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
15
+ lattice_sub-1.3.1.dist-info/entry_points.txt,sha256=o8PzJR8kFnXlKZufoYGBIHpiosM-P4PZeKZXJjtPS6Y,61
16
+ lattice_sub-1.3.1.dist-info/top_level.txt,sha256=BOuW-sm4G-fQtsWPRdeLzWn0WS8sDYVNKIMj5I3JXew,20
17
+ lattice_sub-1.3.1.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (80.10.1)
2
+ Generator: setuptools (80.10.2)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -19,7 +19,7 @@ Example:
19
19
  >>> result.save("output.mrc")
20
20
  """
21
21
 
22
- __version__ = "1.2.2"
22
+ __version__ = "1.3.1"
23
23
  __author__ = "George Stephenson & Vignesh Kasinath"
24
24
 
25
25
  from .config import Config
@@ -153,9 +153,12 @@ def main():
153
153
  # Batch process directory (GPU handles parallelism)
154
154
  lattice-sub batch input_dir/ output_dir/ --pixel-size 0.56
155
155
 
156
- # Batch with visualizations
156
+ # Batch with visualizations (4-panel with threshold curve)
157
157
  lattice-sub batch input_dir/ output_dir/ -p 0.56 --vis viz_dir/
158
158
 
159
+ # Batch with limited visualizations (only first 10)
160
+ lattice-sub batch input_dir/ output_dir/ -p 0.56 --vis viz_dir/ -n 10
161
+
159
162
  # CPU batch with parallel workers (use -j only with --cpu)
160
163
  lattice-sub batch input_dir/ output_dir/ -p 0.56 --cpu -j 8
161
164
 
@@ -502,6 +505,12 @@ def process(
502
505
  default=None,
503
506
  help="Generate comparison visualizations in this directory",
504
507
  )
508
+ @click.option(
509
+ "-n", "--num-vis",
510
+ type=int,
511
+ default=None,
512
+ help="Number of visualizations to generate (default: all)",
513
+ )
505
514
  @click.option(
506
515
  "-v", "--verbose",
507
516
  is_flag=True,
@@ -528,6 +537,7 @@ def batch(
528
537
  config: Optional[str],
529
538
  recursive: bool,
530
539
  vis: Optional[str],
540
+ num_vis: Optional[int],
531
541
  verbose: bool,
532
542
  quiet: bool,
533
543
  cpu: bool,
@@ -617,7 +627,8 @@ def batch(
617
627
 
618
628
  # Generate visualizations if requested
619
629
  if vis:
620
- logger.info(f"Generating visualizations in: {vis}")
630
+ limit_msg = f" (limit: {num_vis})" if num_vis else ""
631
+ logger.info(f"Generating visualizations in: {vis}{limit_msg}")
621
632
  viz_success, viz_total = generate_visualizations(
622
633
  input_dir=input_dir,
623
634
  output_dir=output_dir,
@@ -625,6 +636,8 @@ def batch(
625
636
  prefix=prefix,
626
637
  pattern=pattern,
627
638
  show_progress=True,
639
+ limit=num_vis,
640
+ config=cfg,
628
641
  )
629
642
  logger.info(f"Visualizations: {viz_success}/{viz_total} created")
630
643
 
@@ -2,12 +2,12 @@
2
2
  Visualization utilities for lattice subtraction results.
3
3
 
4
4
  This module provides functions to create comparison visualizations
5
- showing original, processed, and difference images.
5
+ showing original, processed, difference images, and threshold optimization curves.
6
6
  """
7
7
 
8
8
  import logging
9
9
  from pathlib import Path
10
- from typing import Optional, Tuple
10
+ from typing import Optional, Tuple, List
11
11
 
12
12
  import numpy as np
13
13
 
@@ -22,6 +22,56 @@ logging.getLogger('PIL.PngImagePlugin').setLevel(logging.WARNING)
22
22
  logger = logging.getLogger(__name__)
23
23
 
24
24
 
25
+ def compute_threshold_curve(
26
+ image: np.ndarray,
27
+ config,
28
+ n_points: int = 21,
29
+ ) -> Tuple[np.ndarray, np.ndarray, float, float]:
30
+ """
31
+ Compute quality scores across a range of thresholds.
32
+
33
+ Args:
34
+ image: Original image array
35
+ config: Config object with processing parameters
36
+ n_points: Number of threshold points to evaluate
37
+
38
+ Returns:
39
+ Tuple of (thresholds, quality_scores, optimal_threshold, optimal_quality)
40
+ """
41
+ from .threshold_optimizer import ThresholdOptimizer
42
+
43
+ optimizer = ThresholdOptimizer(config)
44
+
45
+ # Prepare FFT data once
46
+ subtracted, radial_mask, box_size = optimizer._prepare_fft_data(image)
47
+
48
+ # Evaluate across threshold range
49
+ thresholds = np.linspace(
50
+ optimizer.min_threshold,
51
+ optimizer.max_threshold,
52
+ n_points
53
+ )
54
+
55
+ # Use GPU batch if available
56
+ if optimizer.use_gpu:
57
+ qualities, peak_counts = optimizer._compute_quality_batch_gpu(
58
+ subtracted, radial_mask, thresholds
59
+ )
60
+ else:
61
+ qualities = []
62
+ for t in thresholds:
63
+ q, _ = optimizer._compute_quality(subtracted, radial_mask, t)
64
+ qualities.append(q)
65
+ qualities = np.array(qualities)
66
+
67
+ # Find optimal
68
+ best_idx = np.argmax(qualities)
69
+ optimal_threshold = thresholds[best_idx]
70
+ optimal_quality = qualities[best_idx]
71
+
72
+ return thresholds, qualities, optimal_threshold, optimal_quality
73
+
74
+
25
75
  def create_comparison_figure(
26
76
  original: np.ndarray,
27
77
  processed: np.ndarray,
@@ -81,19 +131,108 @@ def create_comparison_figure(
81
131
  return fig
82
132
 
83
133
 
134
+ def create_comparison_figure_with_threshold(
135
+ original: np.ndarray,
136
+ processed: np.ndarray,
137
+ thresholds: np.ndarray,
138
+ quality_scores: np.ndarray,
139
+ optimal_threshold: float,
140
+ optimal_quality: float,
141
+ title: str = "Lattice Subtraction Comparison",
142
+ figsize: Tuple[int, int] = (14, 12),
143
+ dpi: int = 150,
144
+ ):
145
+ """
146
+ Create a 4-panel comparison figure with threshold optimization curve.
147
+
148
+ Layout (2x2 grid):
149
+ [Original] [Subtracted]
150
+ [Difference] [Threshold Curve]
151
+
152
+ Args:
153
+ original: Original image array
154
+ processed: Processed (lattice-subtracted) image array
155
+ thresholds: Array of threshold values tested
156
+ quality_scores: Array of quality scores for each threshold
157
+ optimal_threshold: The optimal threshold that was selected
158
+ optimal_quality: Quality score at optimal threshold
159
+ title: Figure title
160
+ figsize: Figure size in inches (width, height)
161
+ dpi: Resolution for saving
162
+
163
+ Returns:
164
+ matplotlib Figure object
165
+ """
166
+ import matplotlib.pyplot as plt
167
+
168
+ # Compute difference
169
+ difference = original - processed
170
+
171
+ # Create figure with 4 panels (2 rows, 2 columns)
172
+ fig, axes = plt.subplots(2, 2, figsize=figsize)
173
+
174
+ # Contrast limits from original
175
+ vmin, vmax = np.percentile(original, [1, 99])
176
+
177
+ # Panel 1 (top-left): Original
178
+ axes[0, 0].imshow(original, cmap='gray', vmin=vmin, vmax=vmax)
179
+ axes[0, 0].set_title(f'Original\n{original.shape}')
180
+ axes[0, 0].axis('off')
181
+
182
+ # Panel 2 (top-right): Lattice Subtracted
183
+ axes[0, 1].imshow(processed, cmap='gray', vmin=vmin, vmax=vmax)
184
+ axes[0, 1].set_title(f'Lattice Subtracted\n{processed.shape}')
185
+ axes[0, 1].axis('off')
186
+
187
+ # Panel 3 (bottom-left): Difference (removed lattice)
188
+ diff_std = np.std(difference)
189
+ axes[1, 0].imshow(
190
+ difference,
191
+ cmap='RdBu_r',
192
+ vmin=-diff_std * 3,
193
+ vmax=diff_std * 3
194
+ )
195
+ axes[1, 0].set_title('Difference (Removed Lattice)')
196
+ axes[1, 0].axis('off')
197
+
198
+ # Panel 4 (bottom-right): Threshold vs Quality Score curve
199
+ axes[1, 1].plot(thresholds, quality_scores, 'b-', linewidth=2, label='Quality Score')
200
+ axes[1, 1].axvline(x=optimal_threshold, color='r', linestyle='--', linewidth=2,
201
+ label=f'Optimal: {optimal_threshold:.3f}')
202
+ axes[1, 1].scatter([optimal_threshold], [optimal_quality], color='r', s=100, zorder=5)
203
+ axes[1, 1].set_xlabel('Threshold', fontsize=11)
204
+ axes[1, 1].set_ylabel('Lattice Removal Efficacy', fontsize=11)
205
+ axes[1, 1].set_title(f'Threshold Optimization\nOptimal = {optimal_threshold:.3f}')
206
+ axes[1, 1].legend(loc='best', fontsize=9)
207
+ axes[1, 1].grid(True, alpha=0.3)
208
+ axes[1, 1].set_xlim(thresholds.min(), thresholds.max())
209
+
210
+ # Title
211
+ plt.suptitle(title, fontsize=14)
212
+ plt.tight_layout()
213
+
214
+ return fig
215
+
216
+
84
217
  def save_comparison_visualization(
85
218
  original_path: Path,
86
219
  processed_path: Path,
87
220
  output_path: Path,
221
+ config = None,
88
222
  dpi: int = 150,
89
223
  ) -> None:
90
224
  """
91
- Create and save a comparison visualization for a single image pair.
225
+ Create and save a 4-panel comparison visualization for a single image pair.
226
+
227
+ Includes threshold optimization curve showing how the optimal threshold
228
+ was selected based on lattice removal efficacy.
92
229
 
93
230
  Args:
94
231
  original_path: Path to original MRC file
95
232
  processed_path: Path to processed MRC file
96
233
  output_path: Path for output PNG file
234
+ config: Config object for threshold computation (optional, will use defaults)
235
+ dpi: Resolution for output images
97
236
  """
98
237
  import matplotlib.pyplot as plt
99
238
  import mrcfile
@@ -106,11 +245,32 @@ def save_comparison_visualization(
106
245
 
107
246
  # Create title
108
247
  name = original_path.name
109
- short_name = name[:60] + "..." if len(name) > 60 else name
110
- title = f"Lattice Subtraction Comparison: {short_name}"
248
+ short_name = name[:50] + "..." if len(name) > 50 else name
249
+ title = f"Lattice Subtraction: {short_name}"
250
+
251
+ # Try to compute threshold curve if config available
252
+ try:
253
+ if config is None:
254
+ # Create default config for threshold computation
255
+ from .config import Config
256
+ config = Config(pixel_ang=0.56) # Default K3 pixel size
257
+
258
+ # Compute threshold optimization curve
259
+ thresholds, quality_scores, optimal_threshold, optimal_quality = \
260
+ compute_threshold_curve(original, config)
261
+
262
+ # Create 4-panel figure with threshold curve
263
+ fig = create_comparison_figure_with_threshold(
264
+ original, processed,
265
+ thresholds, quality_scores,
266
+ optimal_threshold, optimal_quality,
267
+ title=title, dpi=dpi
268
+ )
269
+ except Exception as e:
270
+ # Fallback to 3-panel if threshold computation fails
271
+ logger.debug(f"Could not compute threshold curve: {e}, using 3-panel view")
272
+ fig = create_comparison_figure(original, processed, title=title, dpi=dpi)
111
273
 
112
- # Create and save figure
113
- fig = create_comparison_figure(original, processed, title=title, dpi=dpi)
114
274
  output_path.parent.mkdir(parents=True, exist_ok=True)
115
275
  fig.savefig(output_path, dpi=dpi, bbox_inches='tight')
116
276
  plt.close(fig)
@@ -124,9 +284,11 @@ def generate_visualizations(
124
284
  pattern: str = "*.mrc",
125
285
  dpi: int = 150,
126
286
  show_progress: bool = True,
287
+ limit: Optional[int] = None,
288
+ config = None,
127
289
  ) -> Tuple[int, int]:
128
290
  """
129
- Generate comparison visualizations for all processed images in a directory.
291
+ Generate comparison visualizations for processed images in a directory.
130
292
 
131
293
  Args:
132
294
  input_dir: Directory containing original MRC files
@@ -136,6 +298,8 @@ def generate_visualizations(
136
298
  pattern: Glob pattern for finding processed files
137
299
  dpi: Resolution for output images
138
300
  show_progress: Show progress bar
301
+ limit: Maximum number of visualizations to generate (None = all)
302
+ config: Config object for threshold computation (optional)
139
303
 
140
304
  Returns:
141
305
  Tuple of (successful_count, total_count)
@@ -152,6 +316,12 @@ def generate_visualizations(
152
316
  logger.warning(f"No processed files found matching '{prefix}{pattern}' in {output_dir}")
153
317
  return 0, 0
154
318
 
319
+ # Apply limit if specified
320
+ total_available = len(output_files)
321
+ if limit is not None and limit > 0:
322
+ output_files = output_files[:limit]
323
+ logger.info(f"Limiting to {limit} visualizations (of {total_available} available)")
324
+
155
325
  successful = 0
156
326
  total = len(output_files)
157
327
 
@@ -184,11 +354,12 @@ def generate_visualizations(
184
354
  successful += 1
185
355
  continue
186
356
 
187
- # Generate visualization
357
+ # Generate visualization with 4-panel layout
188
358
  save_comparison_visualization(
189
359
  original_path=input_path,
190
360
  processed_path=processed_path,
191
361
  output_path=viz_path,
362
+ config=config,
192
363
  dpi=dpi,
193
364
  )
194
365
  successful += 1