-
Notifications
You must be signed in to change notification settings - Fork 0
/
inspection.py
3346 lines (2687 loc) · 117 KB
/
inspection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import collections
import gc
import logging
import math
import random
import threading
from multiprocessing import Pool
import concurrent.futures
import multiprocessing
from functools import partial, wraps
import random
from collections import OrderedDict
import jax
import jax.numpy as jnp
import zarr
# Set the logging level to suppress all log messages
logging.getLogger('jax').setLevel(logging.ERROR)
import platform
from pathlib import Path
from typing import (Tuple, List, FrozenSet, Set, Mapping,
Union, Dict, Any, Iterable, Optional)
import json
import matplotlib.pyplot as plt
import cv2
import glob
import skimage.io
from cv2 import phaseCorrelate
from skimage.metrics import structural_similarity
import yaml
import numpy as np
from numpy.typing import ArrayLike
from numpy import ndarray
from ruyaml import YAML
from time import time
from tqdm import tqdm
import os
from scipy.interpolate import UnivariateSpline
from scipy.stats import zscore
import inspection_utils as utils
import experiment_configs as cfg
import pyramid_levels
import s01_coarse_align_section_pairs as em_align_reg_sections
# import s01_estimate_flow_fields as em_align_est_ff
import s02_create_coarse_aligned_stack as em_align_warp_coarse_stack
#import s02_relax_meshes as em_relax
#import s03_warp_fine_aligned_sections as em_warp
from process_section_pairs import compute_sections_par
#from parameter_config import FlowFieldEstimationConfig, MeshIntegrationConfig, WarpConfig
from Section import Section, run_compute_coarse_offset, fine_align_section
from Tile import Tile
Vector2D = List[float]
Vector = Union[Tuple[int, int], Tuple[int, int, int], Union[Tuple[int], Tuple[Any, ...]]]
UniPath = Union[str, Path]
# # Set up logging
# logging.basicConfig(level=logging.DEBUG)
# logging.basicConfig(level=logging.INFO)
logging.basicConfig(level=logging.WARNING)
os.environ["XLA_PYTHON_CLIENT_PREALLOCATE"] = "false"
os.environ["XLA_PYTHON_CLIENT_ALLOCATOR"] = "platform"
os.environ["XLA_FLAGS"] = "--xla_gpu_strict_conv_algorithm_picker=false"
class Inspection:
def __init__(self, config: cfg.ExpConfig):
self.config = config
self.root = Path(config.path)
self.grid_nr = config.grid_num
self.first_sec = config.first_sec
self.last_sec = config.last_sec
self.grid_shape = config.grid_shape
self.acq_dir = utils.cross_platform_path(config.acq_dir)
self._initialize_directories()
self._initialize_paths()
self._initialize_section_data()
self._initialize_stitched_data()
def _initialize_directories(self):
self.dir_sections = self.root / 'sections'
self.dir_stitched = self.root / 'stitched-sections'
self.dir_inspect = self.root / '_inspect'
self.dir_downscaled = self.dir_inspect / 'downscaled'
self.dir_overlaps = self.dir_inspect / 'overlaps'
self.dir_outliers = self.dir_inspect / 'overlaps_outliers'
self.dir_inf_overlaps = self.dir_inspect / 'inf_overlaps'
self.dir_coarse_stacks = self.root / 'coarse-stack'
def _initialize_paths(self):
self.path_exp_notes = self.root.parent / 'exp_notes.yaml'
self.path_cxyz = self._get_inspect_path('all_offsets.npz')
self.path_id_maps = self._get_inspect_path('all_tile_id_maps.npz')
self.fp_eval_ov = self._get_overlaps_path('overlap_quality_smr.npz')
self.fp_est_ff_cfg = self.root / 'fine_align_estimate_flow_fields.config'
self.fp_missing_sections = self.root / 'missing_sections.yaml'
def _initialize_section_data(self):
self.section_dirs: Optional[List[Path]] = None
self.section_names: Optional[List[str]] = None
self.section_nums: Optional[List[int]] = None
self.section_dicts: Optional[Dict[int, str]] = None
self.section_nums_duplicates: Optional[List[str]] = None
self.section_nums_skip: Optional[List[str]] = None
self.missing_sections: Optional[List[int]] = None
def _initialize_stitched_data(self):
self.stitched_dirs: Optional[List[Path]] = None
self.stitched_names: Optional[List[str]] = None
self.stitched_nums: Optional[List[int]] = None
self.stitched_nums_valid: Optional[List[int]] = None
self.stitched_dicts: Optional[Dict[int, str]] = None
self.cross_aligned_nums: Optional[List[int]] = None
def _get_inspect_path(self, filename: str) -> Path:
return self.dir_inspect / filename
def _get_overlaps_path(self, filename: str) -> Path:
return self.dir_overlaps / filename
def get_zarr_sizes(self) -> Dict[int, int]:
"""Compute .zarr folder size in kb and return dict with sec_num as keys"""
if self.stitched_dicts is None:
self.list_all_section_dirs()
subfolder_sizes = {}
for sec_num, zarr_path in self.stitched_dicts.items():
subfolder_sizes[sec_num] = utils.get_folder_size(zarr_path)
# Sort dictionary by folder number
return dict(sorted(subfolder_sizes.items()))
@staticmethod
def list_subdirs_w_files(folder_path: UniPath, file_name: str) -> Optional[List[str]]:
folder_path = Path(folder_path).resolve()
if not folder_path.exists():
logging.warning(f'Listing files failed. Parent folder does not exist.')
return
subfolders_with_file = [
str(subfolder) for subfolder in folder_path.iterdir()
if subfolder.is_dir() and (subfolder / file_name).is_file()
]
return subfolders_with_file
@staticmethod
def create_multiscale(zarr_path: Union[str, Path], max_layer=5, num_processes=42) -> None:
zarr_path = utils.cross_platform_path(str(zarr_path))
if not Path(zarr_path).exists():
logging.warning(f'Creating multiscale .zarr failed (zarr path does not exist).')
return
logging.info(f'Creating multiscale volume: {zarr_path}')
pyramid_levels.main(zarr_path=zarr_path,
max_layer=max_layer,
num_processes=num_processes
)
return
def fix_false_offsets_trace(self,
tid_pair: [Tuple[int, int]],
align_args: dict,
inf=False,
custom_sec_nums: Optional[Iterable[int]] = None
) -> None:
sec_nums = []
# fp = self.dir_inspect / 'coarse_offset_outliers.txt'
# if inf:
# fp = self.dir_inspect / 'inf_vals.txt'
#
# if not Path(fp).exists():
# logging.warning(f'Failed to load outliers/inf values from {fp}')
# return
#
# try:
# outliers = self.load_outliers(path_outliers=fp)
# except ValueError as _:
# logging.warning(f'Empty list of outliers/inf values in {fp}')
# return
#
# sec_nums = list(outliers.keys())
if custom_sec_nums is not None:
sec_nums = custom_sec_nums
# sec_nums = [num for num in sec_nums if num in custom_sec_nums]
if not sec_nums:
logging.warning(f'Fixing false offsets: nothing to fix in specified range of section numbers and tile-pair IDs.')
return
# for sec_num in sec_nums:
# for val in set(outliers[sec_num]):
# if val == tid_pair:
# tid_a, tid_b = tid_pair
# align_tile_pair(self, sec_num, tid_a, tid_b, **align_args)
seams_scores = []
for sec_num in sec_nums:
tid_a, tid_b = tid_pair
ov_score = align_tile_pair(self, sec_num, tid_a, tid_b, **align_args)
seams_scores.append(ov_score)
# Store and plot results
mssim_tuples = [(num, score) for num, score in zip(sec_nums, seams_scores)]
dir_out = self.dir_inf_overlaps
process_eval_ov_results(mssim_tuples, tid_pair[0], tid_pair[1], dir_out, sort=False)
return
def parallel_align(self, sec_nums, tid_pair, align_args):
# TODO test parallel fix of outliers
args = [(self, sec_num, tid_pair, align_args) for sec_num in sec_nums]
with multiprocessing.Pool() as pool:
pool.map(align_wrapper, args)
return
def compute_paddings(self):
if self.stitched_dirs is None:
logging.info(f'Parsing stitched .zarr folders...')
res = utils.process_dirs(str(self.dir_stitched), utils.list_stitched)
if res is None:
logging.warning('Get paddings not performed. No .zarr sections found.')
return
self.stitched_dirs = res[0]
dirs = [str(p) for p in self.stitched_dirs]
shifts = em_align_reg_sections.load_shifts(dirs)
paddings = em_align_reg_sections.get_padding_per_section(shifts)
for i in tqdm(range(len(dirs))):
with open(os.path.join(dirs[i], "coarse_stack_padding.json"), "w") as f:
json.dump(dict(shift_y=int(paddings[i, 0]), shift_x=int(paddings[i, 1])), f)
logging.info(f'Get paddings done.')
return
def get_cross_aligned_nums(self) -> None:
fn = 'shift_to_previous.json'
cross_aligned_dirs = self.list_subdirs_w_files(self.dir_stitched, fn)
if len(cross_aligned_dirs) > 0:
nums = [int(Path(s).name.split("_")[0][1:]) for s in cross_aligned_dirs]
self.cross_aligned_nums = nums
def validate_seams(self, input_dir: Optional[UniPath] = None, num_proc: int = 5) -> None:
# Get list of overlaps folders
source_dir = Path(input_dir) if input_dir is not None else self.dir_overlaps
ov_dirs = self.list_dir_overlaps(source_dir)
ov_dirs_full = [str(source_dir / name) for name in ov_dirs]
for dir_path in ov_dirs_full:
run_par_validate_seam(dir_path, num_proc=num_proc)
def list_dir_overlaps(self, source_dir: Optional[UniPath] = None) -> List[str]:
"""Returns ov folder names within 'overlaps' folder"""
matching_folders = []
folder_path = Path(source_dir) if source_dir is not None else self.dir_overlaps
if not folder_path.exists():
logging.warning('No folders containing overlap images could be located.')
return matching_folders
# Iterate over the contents of the folder
for item in folder_path.iterdir():
# Check if the item is a directory and matches the specified pattern
if (item.is_dir() and len(item.name) == 11
and item.name.startswith("t")
and item.name[1:5].isdigit()
and item.name[5:7] == "_t"
and item.name[7:].isdigit()):
# If it matches, add it to the list of matching folders
matching_folders.append(item.name)
return sorted(matching_folders)
def get_valid_sec_nums(
self,
start: Optional[int] = None,
end: Optional[int] = None,
custom_sec_nums: Optional[Iterable[int]] = None
) -> List[int]:
"""Get valid section numbers based on specified range or custom range.
Args:
start (int, optional): The first section number to consider. Defaults to None.
end (int, optional): The last section number to consider. Defaults to None.
custom_sec_nums (Iterable[int], optional): A custom set of section numbers to consider.
Defaults to None.
Returns:
List[int]: A list of valid section numbers within the specified range or custom range.
"""
# Ensure experiment section numbers are available
if self.section_nums is None:
data = utils.process_dirs(
str(self.dir_sections), utils.filter_and_sort_sections)
if data is not None:
_, _, section_nums, _ = data
else:
return []
# Determine the set of section numbers to consider
if custom_sec_nums is None:
# Set default values for section numbers if not provided
if start is None:
start = self.section_nums[0]
if end is None:
end = self.section_nums[-1]
sec_nums = set(range(start, end + 1))
else:
sec_nums = set(custom_sec_nums)
valid_nums = list(sec_nums.intersection(self.section_nums))
valid_nums.sort()
return valid_nums
def read_exp_notes(self):
exp_notes: cfg.ExpNotes = cfg.load_exp_notes(str(self.path_exp_notes))
if exp_notes is None:
print(f'Warning: experiment notes file not found.')
return
self.section_nums_skip = exp_notes.Skip
self.section_nums_duplicates = exp_notes.Duplicates
return
def repair_inf_offsets(self,
start: Optional[int] = None,
end: Optional[int] = None,
custom_sec_nums: Optional[Iterable[int]] = None,
masking: bool = True,
store: bool = True,
num_processes: Optional[int] = 5,
refine_params: Optional[Dict] = None # TODO
) -> None:
"""Repair infinite values in offset arrays across sections using refine pyramid method.
Args:
start (int, optional): The first section number to consider. Defaults to None.
end (int, optional): The last section number to consider. Defaults to None.
custom_sec_nums : Define specific set of sections to be scanned for Inf values
masking (bool, optional): Whether to apply masking. Defaults to True.
store (bool): Save computed offset vector to cx_cy.json.
num_processes (int): Number of CPU cores to use for parallel processing
"""
# Get dict of all sections with Inf values and respective tile_id pairs
sec_nums = self.get_valid_sec_nums(start, end, custom_sec_nums)
sec_dirs = [self.section_dicts.get(n) for n in sec_nums]
all_inf = utils.locate_all_inf(sec_dirs)
if len(all_inf) == 0:
logging.warning(f'Repair Inf offsets: no Inf values to repair were found.')
return
# print(len(all_inf))
# for inf in all_inf:
# print(inf)
# Use refine method to fix infinities
arg_dicts = []
for sec_dir, tid_list in all_inf.items():
sec = Section(sec_dir)
sec.feed_section_data()
for (tid_a, tid_b) in tid_list:
logging.info(f'fixing s{utils.get_section_num(sec_dir)} t{tid_a} t{tid_b}')
args = dict(sec=sec,
tid_a=tid_a,
tid_b=tid_b,
masking=masking,
levels=3,
max_ext=24,
stride=6,
clahe=True,
store=store,
plot=True,
show_plot=False)
arg_dicts.append(args)
with multiprocessing.Pool(processes=num_processes) as pool:
pool.map(refine_trace_wrapper, arg_dicts)
return
def plot_ov_for_section(self, sec_num: int, ov_dict: dict):
# Plot overlaps
sec_dict = {sec_num: ov_dict.get(sec_num)}
self.plot_specific_ovs(sec_dict)
return
def plot_all_ovs_par(
self,
first: Optional[int] = None,
last: Optional[int] = None,
custom_range: Optional[Iterable[int]] = None,
num_processes=42
) -> None:
sec_nums = self.get_valid_sec_nums(first, last, custom_range)
if not sec_nums:
logging.warning('No valid setion numbers to plot.')
return
num_processes = min(len(sec_nums), num_processes)
if len(sec_nums) == 0:
logging.warning('plot_ovs: Nothing to plot. Invalid section range.')
return
# Create dict of all sections and all tile_id pairs
ov_dict: Dict[int, List[Tuple[int, int]]] = dict()
# Get valid tile-id neighbor pairs and add them to final dict
for num in sec_nums:
sec_path = self.section_dicts.get(num)
if sec_path is not None:
my_sec = Section(sec_path)
my_sec.read_tile_id_map()
ov_dict[num] = utils.get_neighbour_pairs(my_sec.tile_id_map)
with multiprocessing.Pool(processes=num_processes) as pool:
plot_partial = partial(self.plot_ov_for_section, ov_dict=ov_dict)
pool.map(plot_partial, sec_nums)
return
def mod_time_select(self,
sec_nums: Set[int],
min_file_age: int,
filename: str,
stitched_dir: bool = False,
store: bool = False,
store_dir: Optional[UniPath] = None
) -> Set[int]:
"""
Selects section (numbers) containing specific file older than
min_file_age (specified in hours).
Can be used in conjunction with compute coarse offsets, when one
aims to recompute only portion of cx_cy.jsons.
Args:
sec_nums (Set[int]): Set of section numbers.
min_file_age (int): Minimum file age in hours.
filename (str): Filename to be scanned for.
stitched_dir (bool): look for files in stitched sections directories otherwise in sections folder
Returns:
Set[int]: Selected section numbers.
"""
def eval_thumb_fp(sec_num) -> str:
sec_str = str(sec_num).zfill(5)
ext = f"g{self.grid_nr}_thumb_0.2.png"
thumb_name = "s" + sec_str + ext
return thumb_name
def eval_thumb_fn(sec_num) -> str:
thumb_name = f"final_flow_s{sec_num - 1}_g0_to_s{sec_num}_g0.npy"
return thumb_name
now = time()
sel_sec_nums = sec_nums.copy()
dicts = self.stitched_dicts if stitched_dir else self.section_dicts
for num in sec_nums:
try:
sec_dir = Path(dicts.get(num))
except TypeError as _:
logging.warning(f"Mod time select failed at s{num}")
sel_sec_nums.remove(num)
continue
if sec_dir is not None:
fp = sec_dir / filename
# fp = sec_dir / eval_thumb_fn(num)
# fp = sec_dir / '.zattrs'
try:
mod_time = fp.stat().st_ctime
file_age = (now - mod_time) / 3600
logging.debug(f's{num} file age: {file_age:.1f} hours')
if file_age < min_file_age:
logging.debug(f'Removing {num}')
sel_sec_nums.remove(num)
except FileNotFoundError:
logging.info(f'File {fp} not found in s{num} directory!')
# sel_sec_nums.remove(num)
if store:
if store_dir is None:
store_dir = self.dir_inspect
fp = Path(store_dir) / 'old_nums.json'
with open(fp, 'w') as json_file:
data = sorted(list(sel_sec_nums))
for number in data:
json_file.write(f"{number}\n")
logging.info(f'Number of old files: {len(sel_sec_nums)}')
return sel_sec_nums
def select_folders_wo_file(self, sec_nums: Set[int], filename: Optional[str] = None) -> Set[int]:
def eval_thumb_fn(sec_num) -> str:
sec_str = str(sec_num).zfill(5)
if filename is not None:
return filename
ext = f"g{self.grid_nr}_thumb_0.2.png"
thumb_name = "s" + sec_str + ext
return thumb_name
if self.section_dicts is None:
self.init_experiment()
sel_sec_nums = sec_nums.copy()
for num in sec_nums:
sec_dir = Path(self.section_dicts.get(num))
if sec_dir is not None:
path_cxcy = sec_dir / eval_thumb_fn(num)
if path_cxcy.exists():
sel_sec_nums.remove(num)
return sel_sec_nums
def create_masks_exp_par(self,
sec_nums: Optional[Iterable[int]] = None,
num_processes: int = 42) -> None:
"""Parallelized version of creating tile masks
num_processes: number of CPU cores requested for a job
sec_nums: Section numbers to be processed. If not provided,
all sections within sections folder will be processed
"""
if self.section_nums is None:
self.init_experiment()
if sec_nums is None:
sec_nums = self.section_nums
else:
sec_nums = [num for num in sec_nums if num in self.section_nums]
kwargs = dict(roi_thresh=20,
max_vert_ext=200,
edge_only=True,
n_lines=25,
store=True,
filter_size=50,
range_limit=170)
part_func = partial(create_masks_for_section, **kwargs)
with multiprocessing.Pool(processes=num_processes) as pool:
pool.map(part_func, sec_nums)
return
@staticmethod
def verify_single_section(section: Section) -> Optional[int]:
if not section.verify_tile_id_map(print_ids=False):
return section.section_num
return None
def verify_tile_id_maps(self) -> List[int]:
# Init experiment
if not self.section_nums:
self.init_experiment()
# Construct section objects to be aligned
section_paths = list(self.section_dirs)
sections = [Section(p) for p in section_paths]
# Create a pool of processes and map the verify_single_section function over section_nums
num_proc = min(42, len(self.section_nums))
with multiprocessing.Pool(processes=num_proc) as pool:
results = pool.map(self.verify_single_section, sections)
# Filter None results to collect failed section numbers
failed_sec_nums = [num for num in results if num is not None]
return failed_sec_nums
@staticmethod
def verify_stitched(zarr_path: Union[str, Path]) -> Optional[int]:
if not utils.check_zarr_integrity(zarr_path):
return utils.get_section_num(zarr_path)
return None
def verify_stitched_files(self) -> List[int]:
if not self.stitched_dirs:
self.init_experiment()
# Create a pool of processes and map the verify_single_section function over section_nums
num_proc = min(42, len(self.stitched_dirs))
with multiprocessing.Pool(processes=num_proc) as pool:
results = pool.map(self.verify_stitched, self.stitched_dirs)
# Filter None results to collect failed section numbers
failed_sec_nums = [num for num in results if num is not None]
return failed_sec_nums
def scan_for_missing_masks(self) -> List[int]:
"""Scans section folders of input experiment for missing tile_masks.npz files."""
if self.section_dirs is None:
self.init_experiment()
missing_nums = []
fn = 'tile_masks.npz'
for directory in self.section_dirs:
fp = (Path(directory) / fn)
if not fp.exists():
missing_nums.append(int(directory.name.split("_")[0].strip('s')))
return missing_nums
def backup_coarse_offsets(self):
"""Stores all coarse offset arrays into a .npz file within inspect directory
"""
# Collect all offsets
offsets, missing_files = utils.aggregate_coarse_offsets(self.section_dirs)
logging.debug(f'len missing files {len(missing_files)}')
for p in missing_files:
logging.debug(p)
fp_out = self.dir_inspect / "all_offsets.npz"
np.savez(fp_out, **offsets)
logging.info(f'Coarse offsets saved to: {fp_out}')
fp_out2 = fp_out.with_name("all_offsets_missing_files.txt")
with open(fp_out2, "w") as f:
f.writelines("\n".join(missing_files))
logging.info(f'Missing offsets saved to: {fp_out2}')
return
def backup_tile_id_maps(self):
# Collect all tile ID maps
tile_id_maps, missing_files = utils.aggregate_tile_id_maps(self.section_dirs)
logging.debug(f'len missing files {len(missing_files)}')
for p in missing_files:
logging.debug(p)
fp_out = self.dir_inspect / "all_tile_id_maps.npz"
np.savez(fp_out, **tile_id_maps)
logging.info(f'Tile ID maps saved to: {fp_out}')
fp_out2 = fp_out.with_name("all_missing_tile_id_maps.txt")
with open(fp_out2, "w") as f:
f.writelines("\n".join(missing_files))
logging.info(f'Missing tile ID maps saved to: {fp_out2}')
return
def run_compute_coarse_offset_trace(self,
start: int,
end: int,
tid1: int,
tid2: int,
store: bool
):
if self.section_dicts is None:
self.init_experiment()
for sec_num in range(start, end + 1):
if sec_num in self.section_nums:
print(f'Aligning s{sec_num}')
section_path = self.section_dicts[sec_num]
run_compute_coarse_offset(section_path)
return
def load_outliers(self, path_outliers: Optional[UniPath] = None
) -> Dict[int, List[Tuple[int, int]]]:
"""
Load outliers data from a text file.
:param path_outliers: Optional. Path to the file containing outliers
data. If not provided, defaults to 'coarse_offset_outliers.txt'
in the directory specified by self.dir_inspect.
:return: A dictionary where keys are slice numbers and values are
lists of tuples, each containing two integers (TileID, TileID_nn).
"""
if path_outliers is None:
# path_outliers = self.dir_inspect / 'coarse_offset_outliers.txt'
path_outliers = self.dir_inspect / 'inf_vals.txt'
outliers_data = {}
if Path(path_outliers).exists():
with open(path_outliers, 'r') as f:
# Skip the header line
next(f)
# Read data line by line
for line in f:
parts = line.strip().split('\t')
slice_num = int(parts[0])
tile_id = int(parts[-2])
tile_id_nn = int(parts[-1])
# Check if the key already exists in the dictionary
if slice_num in outliers_data:
# If the key exists, append the new outlier data to the existing list
outliers_data[slice_num].append((tile_id, tile_id_nn))
else:
# If the key does not exist, create a new list with the outlier data
outliers_data[slice_num] = [(tile_id, tile_id_nn)]
# Check if outliers_data is empty
if not outliers_data:
raise ValueError("No data found in the input file.")
return outliers_data
def plot_specific_ovs(self,
ov_dict: Dict[int, List[Tuple[int, int]]],
dir_name_out: Optional[str] = None,
refine=False,
est_vec: Optional[Vector] = None,
shift_abs_dev: Optional[float] = 15.
) -> None:
for sec_num, tid_list in ov_dict.items():
if sec_num not in self.section_nums:
continue
sec_path = self.section_dicts[sec_num]
sec = Section(sec_path)
sec.feed_section_data()
# Specify custom shift vector here
shift_vec = (None, 0)
# Specify parent dir for stored images
if dir_name_out is None:
dir_name_out = 'overlaps'
dir_out = self.dir_inspect / dir_name_out
utils.create_directory(dir_out)
# Filter duplicate tile-id pairs
seen = set()
unique_tid_list = [x for x in tid_list if x not in seen and not seen.add(x)]
# skip = [(860, 900), (941, 981)]
skip = []
# unique_tid_list = [(651, 683),] # (624, 656)
for (tid_a, tid_b) in unique_tid_list:
if (tid_a, tid_b) not in skip:
# print(f'Plotting s{sec.section_num} t{tid_a}-t{tid_b}')
# logging.info(f'Plotting s{sec.section_num} t{tid_a}-t{tid_b}')
if refine:
refine_kwargs = dict(tid_a=tid_a, tid_b=tid_b, masking=False, levels=3,
max_ext=24, stride=8, clahe=True, store=True,
plot=False, show_plot=False, est_vec=None)
shift_vec = sec.refine_pyramid(**refine_kwargs)
# print(f'refined vector: {shift_vec}')
# Verify is coarse offset is within limits, otherwise skip
axis = 1 if utils.pair_is_vertical(sec.tile_id_map, tid_a, tid_b) else 0
offset = sec.get_coarse_offset(tid_a, axis)
offset_valid, _ = utils.vector_dist_valid(offset, est_vec, shift_abs_dev)
if offset_valid:
logging.info(f's{sec.section_num} t{tid_a}-t{tid_b} coarse offset deviation within limits.')
break
args = dict(tid_a=tid_a,
tid_b=tid_b,
shift_vec=shift_vec,
dir_out=dir_out,
show_plot=False,
clahe=True,
blur=1.0)
sec.plot_ov(**args)
return
def plot_tile_overlaps(self,
sec_start: Optional[int],
sec_end: Optional[int],
tid_a: int,
tid_b: int,
dir_out: Optional[UniPath]
):
"""
Stores rendered overlap regions of range of tile-pairs and specific sections.
"""
assert tid_a != tid_b
assert any((sec_start, sec_end))
if sec_start is None:
sec_start = self.section_nums[0]
if sec_end is None:
sec_end = self.section_nums[-1]
if dir_out is None:
dir_out = self.dir_inspect / 'overlaps'
logging.info(f'plotting overlaps of tiles {tid_a, tid_b}, sections range: {sec_start, sec_end}')
for sec_num in range(sec_start, sec_end):
if sec_num in self.section_nums:
my_sec = Section(self.section_dicts[sec_num])
my_sec.feed_section_data()
# Specify custom shift vector here
shift_vec = (None, 0)
args = dict(tid_a=tid_a,
tid_b=tid_b,
shift_vec=shift_vec,
dir_out=dir_out,
show_plot=False,
clahe=True,
blur=1.2)
my_sec.plot_ov(**args)
return
def get_missing_sections(self) -> None:
"""Identify section numbers discontinuities in section folder"""
if self.section_dirs is None:
self.list_all_section_dirs()
missing_nums = []
if len(self.section_dirs) > 1 and self.section_dirs:
# first: int = utils.get_section_num(str(self.section_dirs[0]))
# last: int = utils.get_section_num(str(self.section_dirs[-1])) # TODO: implement skipped section numbers
first: int = self.first_sec
last: int = self.last_sec
section_range = set(range(first, last + 1))
missing_nums = sorted(list(section_range - set(self.section_nums)))
if len(missing_nums) > 0:
utils.write_dict_to_yaml(str(self.fp_missing_sections), missing_nums)
is_are = 'is' if len(missing_nums) == 1 else 'are'
logging.warning(f"There {is_are} {len(missing_nums)} missing sections in 'sections' folder!")
self.missing_sections = missing_nums
return
def add_missing_sections(self,
prefix_tile_name: str,
grid_shape: Tuple[int, int],
thickness_nm: int,
acquisition: str,
tile_height: int,
tile_width: int,
tile_overlap: int,
resolution_nm: float):
def create_section_folder(section_num: int) -> Path:
path_section = self.dir_sections / f's{section_num}_g{self.grid_nr}'
path_section.mkdir(parents=True, exist_ok=True)
return path_section
def create_tile_entries(tile_paths: List[Path]):
def_entry = {
'tile_id': self.grid_nr,
'path': '',
'stage_x': 0,
'stage_y': 0,
'resolution_xy': 10.0,
'unit': 'nm'}
tile_entries = []
for tp in sorted(tile_paths):
new_entry = def_entry.copy()
new_entry['tile_id'] = int(tp.parent.name[1:])
new_entry['path'] = str(tp)
new_entry['resolution_xy'] = resolution_nm
tile_entries.append(new_entry)
return tile_entries
def create_section_entries():
return {
'file_path': str(self.dir_sections / f's{sec_num}_g{self.grid_nr}' / 'section.yaml'),
'section_num': sec_num,
'tile_grid_num': self.grid_nr,
'grid_shape': self.grid_shape,
'acquisition': acquisition,
'thickness': thickness_nm,
'tile_height': tile_height,
'tile_width': tile_width,
'tile_overlap': tile_overlap,
'tiles': create_tile_entries(paths_tiles)
}
def store_tile_id_map(section_dir: Path,
tile_paths: List[Path],
grid_shape: Tuple[int, int]
):
tile_ids = [int(p.parent.name[1:]) for p in tile_paths]
tile_id_map = utils.compute_tile_id_map(tuple(grid_shape), tile_ids)
if tile_id_map is None:
logging.warning('Tile id-map could not be created')
else:
tile_id_map_list = tile_id_map.tolist()
with open(section_dir / 'tile_id_map.json', "w") as file:
json.dump(tile_id_map_list, file)
return
# Read missing_sections.yaml
with open(self.fp_missing_sections, 'r') as f:
missing_nums = yaml.safe_load(f)
if not missing_nums:
logging.warning('No missing numbers could be loaded form missing_sections.yaml!')
return
# Filter section tile-paths
dir_tiles = Path(self.acq_dir) / 'tiles' / f'g000{self.grid_nr}'
tile_folders = utils.scan_dirs(dir_tiles)
if not tile_folders:
logging.warning('Tile folders with raw EM-data not found.')
return
for sec_num in missing_nums:
paths_tiles = []
for tf in tile_folders:
tile_path = tf / f'{prefix_tile_name}g000{self.grid_nr}_{tf.name}_s{str(sec_num).zfill(5)}.tif'
if tile_path.is_file():
paths_tiles.append(tile_path)
if not paths_tiles:
logging.warning(f'No tiles paths found for section s{sec_num}')
continue
sec_dir = create_section_folder(sec_num)
data = create_section_entries()
utils.create_section_yaml_file(**data)
store_tile_id_map(Path(sec_dir), paths_tiles, grid_shape)
return
def init_experiment(self) -> None:
"""
Perform initial data processing for Inspection class
"""
self.read_exp_notes()
self.list_all_section_dirs()
self.get_missing_sections()
self.create_inspection_dirs()
def list_all_section_dirs(self, skip: Optional[bool] = False) -> None:
"""Lists all section and .zarr folders stored in 'sections' and 'stitched' folders
"""
# Sections folder
res = utils.process_dirs(str(self.dir_sections),
utils.filter_and_sort_sections)
if res is not None:
(self.section_dirs,
self.section_names,
self.section_nums,
self.section_dicts) = res
# Stitched sections folder
res = utils.process_dirs(str(self.dir_stitched),
utils.list_stitched)
if res is not None:
(self.stitched_dirs,
self.stitched_names,
self.stitched_nums,
self.stitched_dicts) = res
return
def validate_stitched(self):
if self.stitched_nums is None:
self.init_experiment()