-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlogics.py
More file actions
1329 lines (1100 loc) · 62.6 KB
/
logics.py
File metadata and controls
1329 lines (1100 loc) · 62.6 KB
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
"""
Beta-2 release for Revision of SR length measurement
v2.1.1-beta-2
update date: 20230716
"""
import os
import re
import sys
import traceback
from datetime import datetime
import cv2
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import pandas as pd
from tqdm import tqdm
import numpy as np
import math as ms
import tifffile as tiff
import imagej
from skimage import io
from skimage.morphology import disk, erosion, dilation, white_tophat, reconstruction, skeletonize, closing
from skimage.measure import label, regionprops_table
import skan
from sklearn.neighbors import NearestNeighbors
from sklearn.cluster import DBSCAN
from astropy.convolution import RickerWavelet2DKernel
from PIL import Image, UnidentifiedImageError
from scipy import ndimage
from scipy.stats import norm
import multiprocessing
from pathos.multiprocessing import ProcessingPool as Pool
from functools import partial
import psutil
import scyjava
import json
plugins_dir = os.path.join(os.path.dirname(__file__), 'Fiji.app/plugins')
scyjava.config.add_option(f'-Dplugins.dir={plugins_dir}')
class DiffractionLimitedAnalysis:
def __init__(self, data_path, parameters):
self.error = 1 # When this value is 1, no error was detected in the object.
self.path_program = os.path.dirname(__file__)
self.path_data_main = data_path
self.parameters = parameters
# Construct dirs for results
self.path_result_main = data_path + '_results' + self.parameters
if os.path.isdir(self.path_result_main) != 1:
os.mkdir(self.path_result_main)
self.path_result_raw = os.path.join(self.path_result_main, 'raw')
if os.path.isdir(self.path_result_raw) != 1:
os.mkdir(self.path_result_raw)
self.path_result_samples = os.path.join(self.path_result_main, 'samples')
if os.path.isdir(self.path_result_samples) != 1:
os.mkdir(self.path_result_samples)
naming_system = self.gather_project_info()
if naming_system == 0:
self.error = 'Invalid naming system for images. Currently supported naming systems are: XnYnRnWnCn, XnYnRnWn and Posn.'
def gather_project_info(self):
self.fov_paths = {} # dict - FoV name: path to the corresponding image
for root, dirs, files in os.walk(self.path_data_main):
for file in files:
if file.endswith(".tif"):
try:
pos = re.findall(r"X\d+Y\d+R\d+W\d+C\d+", file)[-1]
naming_system = 'XnYnRnWnCn'
except IndexError:
try:
pos = re.findall(r'X\d+Y\d+R\d+W\d+', file)[-1]
naming_system = 'XnYnRnWn'
except IndexError:
try:
pos = re.findall(r'Pos\d+', file)[-1]
naming_system = 'Posn'
except IndexError:
return 0
self.fov_paths[pos] = os.path.join(root, file)
self.wells = {} # dict - well name: list of FoV taken in the well
if naming_system == 'Posn':
for fov in self.fov_paths:
self.wells[fov] = [fov]
return naming_system
else:
for fov in self.fov_paths:
well = re.findall(r"X\d+Y\d+", fov)[-1]
if well in self.wells:
self.wells[well] += [fov]
else:
self.wells[well] = [fov]
return naming_system
def call_ComDet(self, size, threshold, progress_signal=None, IJ=None):
if progress_signal == None: #i.e. running in non-GUI mode
path_fiji = os.path.join(self.path_program, 'Fiji.app')
IJ = imagej.init(path_fiji, headless=False)
IJ.ui().showUI()
workload = tqdm(sorted(self.fov_paths)) # using tqdm as progress bar in cmd
else:
workload = sorted(self.fov_paths)
c = 0 # progress indicator
# Check if the images are stack, and choose correct macro
test_img = Image.open(list(self.fov_paths.values())[0])
if test_img.n_frames > 1:
stacked = True
else:
stacked = False
for field in workload:
imgFile = self.fov_paths[field]
saveto = os.path.join(self.path_result_raw, field)
saveto = saveto.replace("\\", "/")
img = IJ.io().open(imgFile)
IJ.ui().show(field, img)
if stacked:
macro = """
run("Z Project...", "projection=[Average Intensity]");
run("Detect Particles", "ch1i ch1a="""+str(size)+""" ch1s="""+str(threshold)+""" rois=Ovals add=Nothing summary=Reset");
selectWindow('Results');
saveAs("Results", \""""+saveto+"""_results.csv\");
close("Results");
close("Summary");
selectWindow(\"AVG_"""+field+"""\");
saveAs("tif", \""""+saveto+""".tif\");
close();
close();
"""
IJ.py.run_macro(macro)
else:
macro = """
run("Detect Particles", "ch1i ch1a="""+str(size)+""" ch1s="""+str(threshold)+""" rois=Ovals add=Nothing summary=Reset");
selectWindow('Results');
saveAs("Results", \""""+saveto+"""_results.csv\");
close("Results");
close("Summary");
selectWindow(\""""+field+"""\");
saveAs("tif", \""""+saveto+""".tif\");
close();
"""
IJ.py.run_macro(macro)
# Remove edge particles
try:
df = pd.read_csv(saveto+'_results.csv')
except pd.errors.EmptyDataError:
print('No spot found in FoV: ' + field)
else:
img_dimensions = Image.open(imgFile).size
df = df.loc[(df['X_(px)'] >= img_dimensions[0] * 0.02) & (df['X_(px)'] <= img_dimensions[0] * 0.98)]
df = df.loc[(df['Y_(px)'] >= img_dimensions[1] * 0.02) & (df['Y_(px)'] <= img_dimensions[1] * 0.98)]
# Remove particles detected in the 5% pixels from the edges
df = df.reset_index(drop=True)
df.to_csv(saveto + '_results.csv')
if progress_signal == None:
pass
else:
c += 1
progress_signal.emit(c)
if progress_signal == None:
IJ.py.run_macro("""run("Quit")""")
else:
IJ.py.run_macro("""
if (isOpen("Log")) {
selectWindow("Log");
run("Close" );
}
""")
return 1
def call_Trevor(self, bg_thres = 1, tophat_disk_size=50, progress_signal=None, erode_size = 1):
if progress_signal == None: #i.e. running in non-GUI mode
workload = tqdm(sorted(self.fov_paths)) # using tqdm as progress bar in cmd
else:
workload = sorted(self.fov_paths)
c = 0 # progress indicator
num_cpu = multiprocessing.cpu_count()
ram = psutil.virtual_memory().available
estimated_cores = int(np.round(ram/1024/1024/1024/2))
num_workers = np.minimum(num_cpu, estimated_cores)
def process_img(img_index, fov_paths, path_result_raw, workload):
field = workload[img_index]
imgFile = fov_paths[field]
saveto = os.path.join(path_result_raw, field)
saveto = saveto.replace("\\", "/")
img = io.imread(imgFile) # Read image
img = img.astype(np.float64)
if len(img.shape) == 3: # Determine if the image is a stack file with multiple slices
img = np.mean(img, axis=0) # If true, average the image
else:
pass # If already averaged, go on processing
img_size = np.shape(img)
tophat_disk_size = 50
tophat_disk = disk(tophat_disk_size) # create tophat structural element disk, diam = tophat_disk_size (typically set to 10)
tophat_img = white_tophat(img, tophat_disk) # Filter image with tophat
kernelsize = 1
ricker_2d_kernel = RickerWavelet2DKernel(kernelsize)
def convolve2D(image, kernel, padding=4, strides=1):
# Cross Correlation
kernel = np.flipud(np.fliplr(kernel))
# Gather Shapes of Kernel + Image + Padding
xKernShape = kernel.shape[0]
yKernShape = kernel.shape[1]
xImgShape = image.shape[0]
yImgShape = image.shape[1]
# Shape of Output Convolution
xOutput = int(((xImgShape - xKernShape + 2 * padding) / strides) + 1)
yOutput = int(((yImgShape - yKernShape + 2 * padding) / strides) + 1)
output = np.zeros((xOutput, yOutput))
# Apply Equal Padding to All Sides
if padding != 0:
imagePadded = np.zeros((image.shape[0] + padding*2, image.shape[1] + padding*2))
imagePadded[int(padding):int(-1 * padding), int(padding):int(-1 * padding)] = image
#print(imagePadded)
else:
imagePadded = image
# Iterate through image
for y in range(image.shape[1]):
# Exit Convolution
if y > image.shape[1] - yKernShape:
break
# Only Convolve if y has gone down by the specified Strides
if y % strides == 0:
for x in range(image.shape[0]):
# Go to next row once kernel is out of bounds
if x > image.shape[0] - xKernShape:
break
try:
# Only Convolve if x has moved by the specified Strides
if x % strides == 0:
output[x, y] = (kernel * imagePadded[x: x + xKernShape, y: y + yKernShape]).sum()
except:
break
return output
pad = np.zeros([img_size[0]+8, img_size[1]+8])
pad[4:img_size[0]+4, 4:img_size[1]+4] = tophat_img
pad_img = np.copy(pad)
output = convolve2D(pad_img, ricker_2d_kernel, padding=0)
out_img = Image.fromarray(output)
out_resize = out_img.resize(img_size)
out_array = np.array(out_resize)
mu,sigma = norm.fit(out_array)
threshold = mu + bg_thres*sigma
out_array[out_array<threshold] = 0
erode_img = erosion(out_array, disk(erode_size))
dilate_img = dilation(erode_img, disk(erode_size))
dilate_img[dilate_img>0] = 1
mask = np.copy(dilate_img)
mask[0:5, :] = 0
mask[-5:, :] = 0
mask[:, 0:5] = 0
mask[:, -5:] = 0
io.imsave(saveto + '.tif', mask) # save masked image as result
inverse_mask = 1-mask
img_bgonly = inverse_mask*img
seed_img = np.copy(img_bgonly) # https://scikit-image.org/docs/dev/auto_examples/features_detection/plot_holes_and_peaks.html
seed_img[1:-1, 1:-1] = img_bgonly.max()
seed_mask = img_bgonly
filled_img = reconstruction(seed_img, seed_mask, method='erosion')
img_nobg = abs(img - filled_img)
# Label the image to index all aggregates
labeled_img = label(mask)
# *save image
intensity_list = []
Abs_frame = []
Channel = []
Slice = []
Frame = []
# Get the number of particles
num_aggregates = int(np.max(labeled_img))
# Get profiles of labeled image
df = regionprops_table(labeled_img, intensity_image=img, properties=['label', 'area', 'centroid', 'bbox'])
df = pd.DataFrame(df)
df.columns = [' ', 'NArea', 'X_(px)', 'Y_(px)', 'xMin', 'yMin', 'xMax', 'yMax']
# Analyze each particle for integra
for j in range(0, num_aggregates):
current_aggregate = np.copy(labeled_img)
current_aggregate[current_aggregate != j + 1] = 0
current_aggregate[current_aggregate > 0] = 1
intensity = np.sum(current_aggregate * img_nobg)
intensity_list.append(intensity)
Abs_frame.append(1)
Channel.append(1)
Slice.append(1)
Frame.append(1)
df['Abs_frame'] = Abs_frame
df['Channel']= Channel
df['Slice'] = Slice
df['Frame'] = Frame
df['IntegratedInt'] = intensity_list
df.to_csv(saveto + '_results.csv', index=False) # save result.csv
img_index = list(range(len(workload)))
partial_func = partial(process_img, fov_paths=self.fov_paths, path_result_raw=self.path_result_raw, workload=workload)
pool = Pool(num_workers)
pool.map(partial_func, img_index)
pool.close()
pool.join()
if progress_signal == None:
pass
else:
c += 1
progress_signal.emit(c)
return 1
def generate_reports(self, progress_signal=None):
if progress_signal == None: #i.e. running in non-GUI mode
workload = tqdm(sorted(self.wells)) # using tqdm as progress bar in cmd
else:
workload = sorted(self.wells)
c = 0 # progress indicator
# Generate sample reports
for well in workload:
well_result = pd.DataFrame()
for fov in self.wells[well]:
try:
df = pd.read_csv(self.path_result_raw + '/' + fov + '_results.csv')
df = df.drop(columns=[' ', 'Channel', 'Slice', 'Frame'])
df['FoV'] = fov
df['IntPerArea'] = df.IntegratedInt / df.NArea
well_result = pd.concat([well_result, df])
except pd.errors.EmptyDataError:
pass
well_result.to_csv(self.path_result_samples + '/' + well + '.csv', index=False)
if progress_signal == None:
pass
else:
c += 1
progress_signal.emit(c)
# Generate summary report
summary_report = pd.DataFrame()
for well in workload:
try:
df = pd.read_csv(self.path_result_samples + '/' + well + '.csv')
df_sum = pd.DataFrame.from_dict({
'Well': [well],
'NoOfFoV': [len(self.wells[well])],
'ParticlePerFoV': [len(df.index) / len(self.wells[well])],
'MeanSize': [df.NArea.mean()],
'MeanIntegrInt': [df.IntegratedInt.mean()],
'MeanIntPerArea': [df.IntPerArea.mean()]
})
summary_report = pd.concat([summary_report, df_sum])
except pd.errors.EmptyDataError:
df_sum = pd.DataFrame.from_dict({
'Well': [well],
'NoOfFoV': [len(self.wells[well])],
'ParticlePerFoV': [0],
'MeanSize': [0],
'MeanIntegrInt': [0],
'MeanIntPerArea': [0]
})
summary_report = pd.concat([summary_report, df_sum])
if progress_signal == None:
pass
else:
c += 1
progress_signal.emit(c)
summary_report.to_csv(self.path_result_main + '/Summary.csv', index=False)
# Generate quality control report
QC_data = pd.DataFrame()
for well in workload:
try:
df = pd.read_csv(self.path_result_samples + '/' + well + '.csv')
df['Well'] = well
df = df[['Well','FoV', 'NArea', 'IntegratedInt', 'IntPerArea']]
QC_data = pd.concat([QC_data, df])
except pd.errors.EmptyDataError:
pass
if progress_signal == None:
pass
else:
c += 1
progress_signal.emit(c)
QC_data = QC_data.reset_index(drop=True)
QC_data.to_csv(self.path_result_main + '/QC.csv', index=False)
return 1
class LiposomeAssayAnalysis:
def __init__(self, data_path):
self.error = 1 # When this value is 1, no error was detected in the object.
self.path_program = os.path.dirname(__file__)
self.path_data_main = data_path
# Construct dirs for results
self.path_result_main = data_path + '_results'
if os.path.isdir(self.path_result_main) != 1:
os.mkdir(self.path_result_main)
self.path_result_raw = os.path.join(self.path_result_main, 'Samples')
if os.path.isdir(self.path_result_raw) != 1:
os.mkdir(self.path_result_raw)
self.gather_project_info()
def gather_project_info(self):
samples = [name for name in os.listdir(self.path_data_main) if os.path.isdir(os.path.join(self.path_data_main, name))]
if 'Ionomycin' in samples:
self.samples = [self.path_data_main]
else:
self.samples = [os.path.join(self.path_data_main, sample) for sample in samples]
### Create result directory
for sample in self.samples:
if not os.path.isdir(sample.replace(self.path_data_main, self.path_result_raw)):
os.mkdir((sample.replace(self.path_data_main, self.path_result_raw)))
def run_analysis(self, threshold, progress_signal=None, log_signal=None):
def extract_filename(path):
"""
walk through a directory and put names of all tiff files into an ordered list
para: path - string
return: filenames - list of string
"""
filenames = []
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith('.tif'):
filenames.append(name)
filenames = sorted(filenames)
return filenames
def average_frame(path):
"""
input 'path' for stacked tiff file and the 'number of images' contained
separate individual images from a tiff stack.
para: path - string
return: ave_img - 2D array
"""
ori_img = tiff.imread(path)
ave_img = np.mean(ori_img, axis=0)
ave_img = ave_img.astype('uint16')
return ave_img
def img_alignment(Ionomycin, Sample, Blank):
"""
image alignment based on cross-correlation
Ionomycin image is the reference image
para: Ionomycin, Sample, Blank - 2D array
return: Corrected_Sample, Corrected_Blank - 2D array
"""
centre_ = (Ionomycin.shape[0]/2, Ionomycin.shape[1]/2)
# 2d fourier transform of averaged images
FIonomycin = np.fft.fft2(Ionomycin)
FSample = np.fft.fft2(Sample)
FBlank = np.fft.fft2(Blank)
# Correlation based on Ionomycin image
FRIS = FIonomycin*np.conj(FSample)
FRIB = FIonomycin*np.conj(FBlank)
RIS = np.fft.ifft2(FRIS)
RIS = np.fft.fftshift(RIS)
RIB = np.fft.ifft2(FRIB)
RIB = np.fft.fftshift(RIB)
[i, j] = np.where(RIS == RIS.max())
[g, k] = np.where(RIB == RIB.max())
# offset values
IS_x_offset = i-centre_[1]
IS_y_offset = j-centre_[0]
IB_x_offset = g-centre_[1]
IB_y_offset = k-centre_[0]
# Correction
MIS = np.float64([[1, 0, *IS_y_offset], [0, 1, *IS_x_offset]])
Corrected_Sample = cv2.warpAffine(Sample, MIS, Ionomycin.shape)
MIB = np.float64([[1, 0, *IB_y_offset], [0, 1, *IB_x_offset]])
Corrected_Blank = cv2.warpAffine(Blank, MIB, Ionomycin.shape)
return Corrected_Sample, Corrected_Blank
def peak_locating(data, threshold):
"""
Credit to Dr Daniel R Whiten
para: data - 2D array
para: threshold - integer
return: xy_thresh - 2D array [[x1, y1], [x2, y2]...]
"""
data_max = ndimage.filters.maximum_filter(data, 3)
maxima = (data == data_max)
data_min = ndimage.filters.minimum_filter(data, 3)
diff = ((data_max - data_min) > threshold)
maxima[diff == 0] = 0
labeled, num_objects = ndimage.label(maxima)
xy = np.array(ndimage.center_of_mass(data, labeled, range(1, num_objects+1)))
xy_thresh = np.zeros((0, 2))
for row in xy:
a = row[0]
b = row[1]
if (a > 30) and (a < 480) and (b > 30) and (b < 480):
ab = np.array([np.uint16(a), np.uint16(b)])
xy_thresh = np.vstack((xy_thresh, ab))
xy_thresh = xy_thresh[1:]
return xy_thresh
def intensities(image_array, peak_coor, radius=3):
"""
When the local peak is found, extract all the coordinates of pixels in a 'radius'
para: image_array - 2D array
para: peak_coor - 2D array [[x1, y1], [x2, y2]]
para: radius - integer
return: intensities - 2D array [[I1], [I2]]
"""
x_ind, y_ind = np.indices(image_array.shape)
intensities = np.zeros((0,1))
for (x, y) in peak_coor:
intensity = 0
circle_points = ((x_ind - x)**2 + (y_ind - y)**2) <= radius**2
coor = np.where(circle_points == True)
coor = np.array(list(zip(coor[0], coor[1])))
for j in coor:
intensity += image_array[j[0], j[1]]
intensities = np.vstack((intensities, intensity))
return intensities
def influx_qc(field, peaks, influx_df):
### Remove error measurements ###
"""
if 100% < influx < 110% take as 100%
if -10% < influx < 0% take as 0
if influx calculated to be nan or <-10% or >110% count as error
"""
influx_df['Influx'] = [100 if i >= 100 and i <= 110 else i for i in influx_df['Influx']]
influx_df['Influx'] = [0 if i <= 0 and i >= -10 else i for i in influx_df['Influx']]
influx_df['Influx'] = ['error' if ms.isnan(float(i)) or i < -10 or i > 110 else i for i in influx_df['Influx']]
### Generate a dataframe which contains the result of current FoV ###
field_result = pd.concat([
pd.DataFrame(np.repeat(field, len(peaks)), columns=['Field']),
pd.DataFrame(peaks, columns=['X', 'Y']),
influx_df
],axis = 1)
### Filter out error data ###
field_result = field_result[field_result.Influx != 'error']
### Get field summary ###
try:
field_error = (influx_df.Influx == 'error').sum()
except (AttributeError, FutureWarning) as e:
field_error = 0
field_summary = pd.DataFrame({
"FoV": [field],
"Mean influx": [field_result.Influx.mean()],
"Total liposomes": [len(peaks)],
"Valid liposomes": [len(peaks)-field_error],
"Invalid liposomes": [field_error]
})
return field_result, field_summary
def pass_log(text):
if log_signal == None:
print(text)
else:
log_signal.emit(text)
def process_img(img_index, workload, threshold):
sample = workload[img_index]
sample_summary = pd.DataFrame()
# report which sample is running to log window
#pass_log('Running sample: ' + sample)
ionomycin_path = os.path.join(sample, 'Ionomycin')
sample_path = os.path.join(sample, 'Sample')
blank_path = os.path.join(sample, 'Blank')
#if not os.path.isdir(ionomycin_path):
#pass_log('Skip ' + sample + '. No data found in the sample folder.')
### Obtain filenames for fields of view ###
field_names = extract_filename(ionomycin_path)
for field in tqdm(field_names, desc=f'Processing FoVs in {sample}'):
### Average tiff files ###
ionomycin_mean = average_frame(os.path.join(ionomycin_path, field))
sample_mean = average_frame(os.path.join(sample_path, field))
blank_mean = average_frame(os.path.join(blank_path, field))
### Align blank and sample images to the ionomycin image ###
sample_aligned, blank_aligned = img_alignment(ionomycin_mean, sample_mean, blank_mean)
### Locate the peaks on the ionomycin image ###
peaks = peak_locating(ionomycin_mean, threshold)
if len(peaks) == 0:
#pass_log('Field ' + field + ' of sample ' + sample +' ignored due to no liposome located in this FoV.')
field_summary = pd.DataFrame({
"FoV": [field],
"Mean influx": [0],
"Total liposomes": [0],
"Valid liposomes": [0],
"Invalid liposomes": [0]
})
sample_summary = pd.concat([sample_summary, field_summary])
else:
### Calculate the intensities of peaks with certain radius (in pixel) ###
ionomycin_intensity = intensities(ionomycin_mean, peaks)
sample_intensity = intensities(sample_aligned, peaks)
blank_intensity = intensities(blank_aligned, peaks)
### Calculate influx of each single liposome and count errors ###
influx_df = pd.DataFrame((sample_intensity - blank_intensity)/(ionomycin_intensity - blank_intensity)*100, columns=['Influx'])
field_result, field_summary = influx_qc(field, peaks, influx_df)
field_result.to_csv(os.path.join(sample.replace(self.path_data_main, self.path_result_raw), field+".csv"))
sample_summary = pd.concat([sample_summary, field_summary])
sample_summary.to_csv(sample.replace(self.path_data_main, self.path_result_raw) + ".csv")
if progress_signal == None: #i.e. running in non-GUI mode
workload = tqdm(sorted(self.samples)) # using tqdm as progress bar in cmd
else:
workload = sorted(self.samples)
c = 0 # progress indicator
num_cpu = multiprocessing.cpu_count()
ram = psutil.virtual_memory().available
estimated_cores = int(np.round(ram/1024/1024/1024/2))
num_workers = np.minimum(num_cpu, estimated_cores)
img_index = list(range(len(workload)))
partial_func = partial(process_img, workload =workload, threshold=threshold)
pool = Pool(num_workers)
pool.map(partial_func, img_index)
pool.close()
pool.join()
# Report progress
if progress_signal != None:
c += 1
progress_signal.emit(c)
return 1
def generate_reports(self, progress_signal=None):
workload = [f for f in os.listdir(self.path_result_raw) if os.path.isfile(os.path.join(self.path_result_raw, f))]
if progress_signal == None: #i.e. running in non-GUI mode
workload = tqdm(sorted(workload)) # using tqdm as progress bar in cmd
else:
workload = sorted(workload)
c = 0 # progress indicator
summary_df = pd.DataFrame()
for file in workload:
file_path = os.path.join(self.path_result_raw, file)
df = pd.read_csv(file_path)
df['Well'] = df['FoV'].str.findall(r"X\dY\d")
df['Well'] = df['Well'].str.get(0)
df = df.groupby('Well').agg({'Mean influx': 'mean',
'Total liposomes': 'sum',
'Valid liposomes': 'sum',
'Invalid liposomes': 'sum'})
df = df.reset_index(drop=False)
df['Sample'] = file[:-4]
summary_df = pd.concat([summary_df, df])
if progress_signal != None:
c += 1
progress_signal.emit(c)
cols = summary_df.columns.tolist()
cols = cols[-1:] + cols[:-1]
summary_df = summary_df[cols]
summary_df.to_csv(self.path_result_main + '/Summary.csv', index=False)
return 1
class SuperResAnalysis:
def __init__(self, data_path):
self.error = 1 # When this value is 1, no error was detected in the object.
self.path_program = os.path.dirname(__file__)
self.path_data_main = data_path
self.gather_project_info()
def update_parameters(self, parameters):
self.parameters = parameters
def gather_project_info(self):
self.fov_paths = {} # dict - FoV name: path to the corresponding image
for root, dirs, files in os.walk(self.path_data_main):
for file in files:
if file.endswith(".tif"):
try:
pos = re.findall(r"X\d+Y\d+R\d+W\d+C\d+", file)[-1]
except IndexError:
try:
pos = re.findall(r'X\d+Y\d+R\d+W\d+', file)[-1]
except IndexError:
self.error = 'Error in the naming system of the images. Please make sure the image names contain coordinate in form of XnYnRnWnCn or XnYnRnWn.'
return 0
self.fov_paths[pos] = os.path.join(root, file)
self.wells = {} # dict - well name: list of FoV taken in the well
for fov in self.fov_paths:
well = re.findall(r"X\d+Y\d+", fov)[-1]
if well in self.wells:
self.wells[well] += [fov]
else:
self.wells[well] = [fov]
# Check if the images are stacks
try:
# Try to open image with Image
test_img = Image.open(list(self.fov_paths.values())[0])
# Get image frame number
self.img_frames = test_img.n_frames
print('Test image number of frames: ' + str(self.img_frames))
# Get image dimensions
self.dimensions = test_img.size
print('Test image dimensions: ' + str(self.dimensions))
except TypeError:
self.error = 'The metadata of the first image was damaged. Please retry without it.'
return 0
except UnidentifiedImageError:
# Open image with Tifffile
test_img = tiff.imread(list(self.fov_paths.values())[0])
# Get image frame number
self.img_frames = test_img.shape[0]
print('Test image number of frames: ' + str(self.img_frames))
# Get image dimensions
self.dimensions = test_img.shape[1:]
print('Test image dimensions: ' + str(self.dimensions))
if self.img_frames < 2:
self.error = 'The images are not stacked. Please check.'
return 0
return 1
def _compose_fiji_macro(self, field_name):
if self.parameters['method'] == 'GDSC SMLM 1':
self.macro = """
run("Peak Fit", "template=[None] config_file=["""+self.path_result_raw + '/gdsc.smlm.settings.xml' +"""] calibration="""+str(self.parameters['pixel_size'])+""" gain="""+str(self.parameters['camera_gain'])+""" exposure_time="""+str(self.parameters['exposure_time'])+""" initial_stddev0=2.000 initial_stddev1=2.000 initial_angle=0.000 smoothing=0.50 smoothing2=3 search_width=3 fit_solver=[Least Squares Estimator (LSE)] fit_function=Circular local_background camera_bias="""+str(self.parameters['camera_bias'])+""" fit_criteria=[Least-squared error] significant_digits=5 coord_delta=0.0001 lambda=10.0000 max_iterations=20 fail_limit=10 include_neighbours neighbour_height=0.30 residuals_threshold=1 duplicate_distance=0.50 shift_factor=2 signal_strength="""+str(self.parameters['signal_strength'])+""" width_factor=2 precision="""+str(self.parameters['precision'])+""" min_photons="""+str(self.parameters['min_photons'])+""" results_table=Uncalibrated image=[Localisations (width=precision)] weighted equalised image_precision=5 image_scale="""+str(self.parameters['scale'])+""" results_dir=["""+self.path_result_raw+"""] local_background camera_bias="""+str(self.parameters['camera_bias'])+""" fit_criteria=[Least-squared error] significant_digits=5 coord_delta=0.0001 lambda=10.0000 max_iterations=20 stack");
selectWindow(\""""+field_name+""" (LSE) SuperRes\");
saveAs("tif", \""""+self.path_result_raw + '/SR_' + field_name+""".tif\");
close(\"SR_"""+field_name+""".tif\");
selectWindow("Fit Results");
saveAs("Results", \""""+self.path_result_raw + '/' + field_name+"""_results.csv\");
close("Fit Results");
close("Log");
close(\""""+field_name+"""\");
"""
elif self.parameters['method'] == 'ThunderSTORM':
self.macro = """
run("Camera setup", "offset="""+str(self.parameters['camera_bias'])+""" quantumefficiency="""+str(self.parameters['quantum_efficiency'])+""" isemgain=true photons2adu=3.6 gainem="""+str(self.parameters['camera_gain'])+""" pixelsize="""+str(self.parameters['pixel_size'])+"""");
run("Run analysis", "filter=[Wavelet filter (B-Spline)] scale=2.0 order=3 detector=[Local maximum] connectivity=8-neighbourhood threshold=1.5*std(Wave.F1) estimator=[PSF: Integrated Gaussian] sigma=1.6 fitradius=3 method=[Weighted Least squares] full_image_fitting=false mfaenabled=false renderer=[Averaged shifted histograms] magnification="""+str(self.parameters['scale'])+""" colorize=false threed=false shifts=2 repaint="""+str(int(self.parameters['exposure_time']))+"""");
run("Export results", "floatprecision=5 filepath="""+self.path_result_raw + '/' + field_name+"""_results.csv fileformat=[CSV (comma separated)] sigma=true intensity=true offset=true saveprotocol=true x=true y=true bkgstd=true id=true uncertainty_xy=true frame=true");
selectWindow('Averaged shifted histograms');
saveAs("tif", \""""+self.path_result_raw + '/SR_' + field_name+""".tif\");
close(\"SR_"""+field_name+""".tif\");
close(\""""+field_name+"""\");
"""
def superRes_reconstruction(self, progress_signal=None, IJ=None):
error_fields = []
# Construct dirs for results
self.timeStamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
self.path_result_main = (self.path_data_main + '_' + self.timeStamp + '_' + self.parameters['method'])
self.path_result_main = self.path_result_main.replace("\\", "/") # fiji only reads path with /
#self.path_result_main = self.path_result_main.replace(" ", "_") # fiji only reads path with /
if os.path.isdir(self.path_result_main) != 1:
os.mkdir(self.path_result_main)
self.path_result_raw = os.path.join(self.path_result_main, 'raw')
self.path_result_raw = self.path_result_raw.replace("\\", "/")# fiji only reads path with /
if os.path.isdir(self.path_result_raw) != 1:
os.mkdir(self.path_result_raw)
with open(os.path.join(self.path_result_main, 'parameters.txt'), 'w') as js_file:
json.dump(self.parameters, js_file)
if progress_signal == None: #i.e. running in non-GUI mode
path_fiji = os.path.join(self.path_program, 'Fiji.app')
IJ = imagej.init(path_fiji, headless=False)
IJ.ui().showUI()
workload = tqdm(sorted(self.fov_paths)) # using tqdm as progress bar in cmd
else:
workload = sorted(self.fov_paths)
c = 0 # progress indicator
for field in workload:
imgFile = self.fov_paths[field]
#saveto = os.path.join(self.path_result_raw, field)
#saveto = saveto.replace("\\", "/")
try:
img = IJ.io().open(imgFile)
except: # Skip the image stack if there is an error in the image itself
error_fields.append(field)
else:
IJ.ui().show(field, img)
self._compose_fiji_macro(field)
IJ.py.run_macro(self.macro)
if progress_signal == None:
pass
else:
c += 1
progress_signal.emit(c)
if len(error_fields) != 0:
self.error = 'Failed to open image ' + ','.join(error_fields) + ' . They were skipped.'
else:
self.error = 1
return 1
def _GDSC_TS_IOadapter(self, GDSC_result=None, TS_result=None):
GDSC_df = pd.read_csv(GDSC_result) # Read file
GDSC_df = GDSC_df.sort_values(by = ['Frame']) # sort by frame number
if TS_result == None: # i.e. convert GSDC to TS
TS_df = GDSC_df[['Frame', 'X', 'Y', 'origValue']] # take out important columns
TS_df.rename(columns = {'Frame': 'frame', 'X': 'x [nm]', 'Y': 'y [nm]', 'origValue': 'intensity [photon]'}, inplace = True) # Replace column names into ThunderSTORM format
TS_df['x [nm]'] = self.parameters['pixel_size'] * TS_df['x [nm]'] # Convert between pixel and nm
TS_df['y [nm]'] = self.parameters['pixel_size'] * TS_df['y [nm]'] # Convert between pixel and nm
TS_df.to_csv(GDSC_result.replace('.csv', '_TS.csv'), index = False) # Write ThunderSTORM file for fiducial correction with FIJI
else: # i.e. Feed corrected X,Y back to GDSC file
TS_df = pd.read_csv(TS_result) # Read file
TS_df['x [nm]'] = TS_df['x [nm]'] / self.parameters['pixel_size'] # Convert between pixel and nm
TS_df['y [nm]'] = TS_df['y [nm]'] / self.parameters['pixel_size'] # Convert between pixel and nm
GDSC_corrected_df = GDSC_df.copy()
GDSC_corrected_df['X'] = TS_df['x [nm]'].values # Replace values with corrected values
GDSC_corrected_df['Y'] = TS_df['y [nm]'].values # Replace values with corrected values
GDSC_corrected_df.to_csv(TS_result.replace('_corrected_TS.csv', '_corrected.csv'), index = False)
def _fidCorr_TS_fiducialMarkers(self, field_name, IJ=None):
if self.parameters['method'] == 'ThunderSTORM':
self.macro = """
run("Import results", "detectmeasurementprotocol=true filepath="""+self.path_result_raw+ "/" +field_name+"""_results.csv fileformat=[CSV (comma separated)] livepreview=true rawimagestack= startingframe=1 append=false");
run("Visualization", "imleft=0.0 imtop=0.0 imwidth="""+str(self.dimensions[0])+""" imheight="""+str(self.dimensions[1])+""" renderer=[Averaged shifted histograms] magnification="""+str(self.parameters['scale'])+""" colorize=false threed=false shifts=2");
run("Show results table", "action=drift smoothingbandwidth=0.25 method=[Fiducial markers] ontimeratio="""+str(self.parameters['min_visibility'])+""" distancethr="""+str(self.parameters['max_distance'])+""" save=false");
run("Export results", "floatprecision=5 filepath="""+self.path_result_fid+"/"+field_name+"""_corrected.csv fileformat=[CSV (comma separated)] sigma=true intensity=true chi2=true offset=true saveprotocol=true x=true y=true bkgstd=true id=true uncertainty_xy=true frame=true");
selectWindow("Averaged shifted histograms");
saveAs("tif", \""""+self.path_result_fid+"/SR_"+field_name+"""_corrected.tif\");
close(\"SR_"""+field_name+"""_corrected.tif\");
selectWindow("Drift");
saveAs("tif",\""""+self.path_result_fid+"/"+field_name+"""_drift.tif\");
close(\""""+field_name+"""_drift.tif\");
close("Averaged shifted histograms");
"""
IJ.py.run_macro(self.macro)
elif self.parameters['method'] == 'GDSC SMLM 1':
self._GDSC_TS_IOadapter(GDSC_result=self.path_result_raw+ "/" + field_name+"_results.csv") # Convert the GDSC result to TS format and save as _TS.csv
self.macro = """
run("Import results", "detectmeasurementprotocol=true filepath="""+self.path_result_raw+ "/" +field_name+"""_results_TS.csv fileformat=[CSV (comma separated)] livepreview=true rawimagestack= startingframe=1 append=false");
run("Visualization", "imleft=0.0 imtop=0.0 imwidth="""+str(self.dimensions[0])+""" imheight="""+str(self.dimensions[1])+""" renderer=[Averaged shifted histograms] magnification="""+str(self.parameters['scale'])+""" colorize=false threed=false shifts=2");
run("Show results table", "action=drift smoothingbandwidth=0.25 method=[Fiducial markers] ontimeratio="""+str(self.parameters['min_visibility'])+""" distancethr="""+str(self.parameters['max_distance'])+""" save=false");
run("Export results", "floatprecision=5 filepath="""+self.path_result_fid+"/"+field_name+"""_corrected_TS.csv fileformat=[CSV (comma separated)] sigma=true intensity=true chi2=true offset=true saveprotocol=true x=true y=true bkgstd=true id=true uncertainty_xy=true frame=true");
selectWindow("Averaged shifted histograms");
saveAs("tif", \""""+self.path_result_fid+"/SR_"+field_name+"""_corrected.tif\");
close(\"SR_"""+field_name+"""_corrected.tif\");
selectWindow("Drift");
saveAs("tif",\""""+self.path_result_fid+"/"+field_name+"""_drift.tif\");
close(\""""+field_name+"""_drift.tif\");
close("Averaged shifted histograms");
"""
IJ.py.run_macro(self.macro)
self._GDSC_TS_IOadapter(GDSC_result=self.path_result_raw+ "/" + field_name+"_results.csv", TS_result=self.path_result_fid+ "/" + field_name+"_corrected_TS.csv") # Feed the corrected X, Y coordinates back to GDSC result file
def _fidCorr_TS_crossCorrelation(self, field_name, IJ=None):
if self.parameters['method'] == 'ThunderSTORM':
self.macro = """
run("Import results", "detectmeasurementprotocol=true filepath="""+self.path_result_raw+ "/" + field_name+"""_results.csv fileformat=[CSV (comma separated)] livepreview=false rawimagestack= startingframe=1 append=false");
run("Visualization", "imleft=0.0 imtop=0.0 imwidth="""+str(self.dimensions[0])+""" imheight="""+str(self.dimensions[1])+""" renderer=[Averaged shifted histograms] magnification="""+str(self.parameters['scale'])+""" colorize=false threed=false shifts=2");
run("Show results table", "action=drift magnification="""+str(self.parameters['magnification'])+""" method=[Cross correlation] ccsmoothingbandwidth=0.25 save=false steps="""+str(self.parameters['bin_size'])+""" showcorrelations=false");
run("Export results", "floatprecision=5 filepath="""+self.path_result_fid+"/"+field_name+"""_corrected.csv fileformat=[CSV (comma separated)] sigma=true intensity=true chi2=true offset=true saveprotocol=true x=true y=true bkgstd=true id=true uncertainty_xy=true frame=true");
selectWindow("Averaged shifted histograms");
saveAs("tif", \""""+self.path_result_fid+"/SR_"+field_name+"""_corrected.tif\");
close(\"SR_"""+field_name+"""_corrected.tif\");
selectWindow("Drift");
saveAs("tif",\""""+self.path_result_fid+"/"+field_name+"""_drift.tif\");
close(\""""+field_name+"""_drift.tif\");
close("Averaged shifted histograms");
"""
IJ.py.run_macro(self.macro)
elif self.parameters['method'] == 'GDSC SMLM 1':
self._GDSC_TS_IOadapter(GDSC_result=self.path_result_raw+ "/" + field_name+"_results.csv") # Convert the GDSC result to TS format and save as _TS.csv
self.macro = """
run("Import results", "detectmeasurementprotocol=true filepath="""+self.path_result_raw+ "/" + field_name+"""_results_TS.csv fileformat=[CSV (comma separated)] livepreview=false rawimagestack= startingframe=1 append=false");
run("Visualization", "imleft=0.0 imtop=0.0 imwidth="""+str(self.dimensions[0])+""" imheight="""+str(self.dimensions[1])+""" renderer=[Averaged shifted histograms] magnification="""+str(self.parameters['scale'])+""" colorize=false threed=false shifts=2");
run("Show results table", "action=drift magnification="""+str(self.parameters['magnification'])+""" method=[Cross correlation] ccsmoothingbandwidth=0.25 save=false steps="""+str(self.parameters['bin_size'])+""" showcorrelations=false");
run("Export results", "floatprecision=5 filepath="""+self.path_result_fid+"/"+field_name+"""_corrected_TS.csv fileformat=[CSV (comma separated)] sigma=true intensity=true chi2=true offset=true saveprotocol=true x=true y=true bkgstd=true id=true uncertainty_xy=true frame=true");
selectWindow("Averaged shifted histograms");
saveAs("tif", \""""+self.path_result_fid+"/SR_"+field_name+"""_corrected.tif\");
close(\"SR_"""+field_name+"""_corrected.tif\");
selectWindow("Drift");
saveAs("tif",\""""+self.path_result_fid+"/"+field_name+"""_drift.tif\");
close(\""""+field_name+"""_drift.tif\");
close("Averaged shifted histograms");
"""
IJ.py.run_macro(self.macro)
self._GDSC_TS_IOadapter(GDSC_result=self.path_result_raw+ "/" + field_name+"_results.csv", TS_result=self.path_result_fid+ "/" + field_name+"_corrected_TS.csv") # Feed the corrected X, Y coordinates back to GDSC result file
def _fidCorr_GDSC_autoFid(self, field_name):
if self.parameters['method'] == 'GDSC SMLM 1':
pass
def superRes_fiducialCorrection(self, progress_signal=None, IJ=None):
if progress_signal == None: #i.e. running in non-GUI mode
path_fiji = os.path.join(self.path_program, 'Fiji.app')
IJ = imagej.init(path_fiji, headless=False)
IJ.ui().showUI()
workload = tqdm(sorted(self.fov_paths)) # using tqdm as progress bar in cmd
else:
workload = sorted(self.fov_paths)
c = 0 # progress indicator