-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloader.py
1959 lines (1620 loc) · 85 KB
/
loader.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
# IMPORTS
import copy
import json
import math
import os
import random
import sys
import threading
import time
import traceback
from concurrent.futures import ThreadPoolExecutor
from functools import cmp_to_key
from sys import platform
from typing import Union
from zipfile import ZipFile
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import patches
import mil_metrics
import r
from util import log
from util import paths
from util import utils
from util.sample_preview import z_score_to_rgb
from util.utils import gct
from util.utils import get_time_diff
from util.utils import line_print
from util.well_metadata import PlateMetadata
from util.well_metadata import TileMetadata
from util.well_metadata import extract_well_info
####
# Constants
# normalize_enum is an enum to determine normalisation as follows:
# 0 = no normalisation
# 1 = normalize every cell between 0 and 255 (8 bit)
# 2 = normalize every cell individually with every color channel independent
# 3 = normalize every cell individually with every color channel using the min / max of all three
# 4 = normalize every cell but with bounds determined by the brightest cell in the bag
# 5 = z-score every cell individually with every color channel independent
# 6 = z-score every cell individually with every color channel using the mean / std of all three
# 7 = z-score every cell individually with every color channel independent using all samples in the bag
# 8 = z-score every cell individually with every color channel using the mean / std of all three from all samples in the bag
# 9: Normalizing first, according to [4] and z-scoring afterwards according to [5]
# 10: Normalizing first, according to [4] and z-scoring afterwards according to [6]
normalize_enum_default = 1
normalize_enum_descriptions = [
' 0: No Normalisation',
' 1: Normalize samples between 0 and 255 (8 bit)',
' 2: Normalize samples individually with every color channel independent',
' 3: Normalize samples individually with every color channel using the min / max of all three',
' 4: Normalize samples but with bounds determined by the brightest cell in the bag',
' 5: z-score samples with every color channel independent',
' 6: z-score samples with combined mean / std of all three',
' 7: z-score samples with mean / std of all three over the bag',
' 8: z-score samples with combined mean / std over the bag',
' 9: Normalizing first, according to [4] and z-scoring afterwards according to [5]',
'10: Normalizing first, according to [4] and z-scoring afterwards according to [6]'
]
default_tile_constraints_none = [0, 0, 0]
default_tile_constraints_nuclei = [1, 0, 0]
default_tile_constraints_oligos = [0, 1, 0]
default_tile_constraints_neurons = [0, 0, 1]
default_well_indices_none = []
default_well_indices_all = list(range(99))
default_well_indices_early = [0, 1, 2, 3, 4]
default_well_indices_late = [7, 8, 9]
default_well_indices_very_early = [0, 1, 2, 3]
default_well_indices_very_late = [8, 9]
default_well_indices_debug_early = [0, 1, 2, 3, 4]
default_well_indices_debug_late = [5, 6, 7, 8, 9]
default_well_bmc_threshold_control = 0.7
default_well_bmc_threshold_effect = 0.3
default_channel_inclusions_all = [True, True, True]
default_channel_inclusions_no_neurites = [True, True, False]
# Default tile quartiles to be used.
# ##################################
# If you want to limit the data to be loaded to specific quartiles, a 4-element-list of booleans is used.
# Each boolean represents a quartile and can be toggled on or off, depending on if that specific quartile should be ommited from loading.
# Default: ALL TRUE
default_used_tile_quartiles = [True, True, True, True]
# Comparison parameters
compare_bag_value_weight_oligo = 0.0
compare_bag_value_weight_tile_count = 1.0
####
# Threading lock
global thread_lock
thread_lock = threading.Lock()
global plate_metadata_cache
plate_metadata_cache = {}
def load_bags_json_batch(batch_dirs: [str], max_workers: int, normalize_enum: int, include_raw: bool = True,
channel_inclusions=None, constraints_0=None, constraints_1=None,
unrestricted_experiments_override: [str] = None,
positive_z_score_scale: float = 1.0, z_score_max_kernel_size: int = 1,
used_tile_quartiles=None,
force_balanced_batch: bool = True, label_0_well_indices=None, label_1_well_indices=None):
if label_1_well_indices is None:
label_1_well_indices = default_well_indices_none
if label_0_well_indices is None:
label_0_well_indices = default_well_indices_none
if constraints_1 is None:
constraints_1 = default_tile_constraints_none
if constraints_0 is None:
constraints_0 = default_tile_constraints_none
if channel_inclusions is None:
channel_inclusions = default_channel_inclusions_all
if used_tile_quartiles is None:
used_tile_quartiles = default_used_tile_quartiles.copy()
used_tile_quartiles_enum = utils.boolean_to_integer(used_tile_quartiles[0],
used_tile_quartiles[1],
used_tile_quartiles[2],
used_tile_quartiles[3])
log.write('Looking for multiple source dirs to load json data from.')
log.write('Batch dir: ' + str(batch_dirs))
log.write('Normalization Protocol: ' + str(normalize_enum))
time.sleep(0.5)
log.write('Well indices label 0: ' + str(label_0_well_indices))
log.write('Well indices label 1: ' + str(label_1_well_indices))
time.sleep(0.5)
log.write('Tile constraints explained: Minimum number of x [Nuclei, Oligos, Neurons]')
log.write('Tile Constraints label 0: ' + str(constraints_0))
log.write('Tile Constraints label 1: ' + str(constraints_1))
log.write('Channel Inclusions: ' + str(channel_inclusions))
time.sleep(0.5)
log.write('Used Tile-Quartiles: ' + str(used_tile_quartiles_enum) + ' (Enum)')
log.write('Used Tile-Quartiles: ' + str(used_tile_quartiles))
if unrestricted_experiments_override is None:
unrestricted_experiments_override = []
else:
log.write('Unrestricted experiments override: ' + str(unrestricted_experiments_override))
X_full = None
X_raw_full = None
y_full = None
y_tiles_full = None
X_metadata_full = []
error_list = []
loaded_files_list_full = []
bag_names_full = []
experiment_names_full = []
well_names_full = []
# Checking if all the paths exist
# we do this first, as to avoid unnecessary loading just to see that a path does not exist later on
all_paths_exist = True
for i in range(len(batch_dirs)):
current_dir = batch_dirs[i]
if not os.path.exists(current_dir):
log.write('Error! Path to load does not exist: ' + current_dir)
all_paths_exist = False
assert all_paths_exist
# Now that we know that these paths do all exist, we can load them
loading_time_durations = []
for i in range(len(batch_dirs)):
current_dir = batch_dirs[i]
log.write('Considering source directory: ' + current_dir)
if os.path.isdir(current_dir):
load_start_time = datetime.now()
X, y, y_tiles, X_raw, X_metadata, bag_names, experiment_names, well_names, errors, loaded_files_list = load_bags_json(
source_dir=current_dir,
max_workers=max_workers,
normalize_enum=normalize_enum,
force_balanced_batch=force_balanced_batch,
gp_current=i + 1,
gp_max=len(batch_dirs),
channel_inclusions=channel_inclusions,
label_0_well_indices=label_0_well_indices,
label_1_well_indices=label_1_well_indices,
constraints_0=constraints_0,
constraints_1=constraints_1,
used_tile_quartiles=used_tile_quartiles,
positive_z_score_scale=positive_z_score_scale, z_score_max_kernel_size=z_score_max_kernel_size,
unrestricted_experiments_override=unrestricted_experiments_override,
include_raw=include_raw)
# Adding results to the respective lists
loaded_files_list_full.extend(loaded_files_list)
bag_names_full.extend(bag_names)
error_list.extend(errors)
well_names_full.extend(well_names)
experiment_names_full.extend(experiment_names)
X_metadata_full.extend(X_metadata)
# Deleting these results to save on RAM
if X_full is None:
X_full = X
else:
# X_full = np.concatenate((X_full, X), axis=0)
X_full.extend(X)
if X_raw_full is None:
X_raw_full = X_raw
else:
# X_raw_full = np.concatenate((X_raw_full, X_raw), axis=0)
X_raw_full.extend(X_raw)
if y is not None:
if y_full is None:
y_full = y
else:
# y_full = np.concatenate((y_full, y), axis=0)
y_full.extend(y)
if y_tiles_full is None:
y_tiles_full = y_tiles
else:
# y_tiles_full = np.concatenate((y_tiles_full, y_tiles), axis=0)
y_tiles_full.extend(y_tiles)
# Deleting references to save on RAM
del X, y, y_tiles, X_raw, X_metadata, bag_names, experiment_names, well_names, errors, loaded_files_list
# Printing current loaded overview
X_s_full = str(utils.byteSizeString(utils.listToBytes(X_full)))
X_s_raw_full = str(utils.byteSizeString(utils.listToBytes(X_raw_full)))
y_s_full = str(utils.byteSizeString(sys.getsizeof(y_full)))
log.write("X-size in memory (after " + str(i + 1) + " batches): " + str(X_s_full))
log.write("y-size in memory (after " + str(i + 1) + " batches): " + str(y_s_full))
log.write("X-size (raw) in memory (after " + str(i + 1) + " batches): " + str(X_s_raw_full))
del X_s_full, y_s_full, X_s_raw_full
load_end_time = datetime.now()
load_time_diff = load_end_time - load_start_time
loading_time_durations.append(load_time_diff)
log.write('Loading finished in ' + str(load_time_diff.seconds) + ' seconds (' + str(
int(load_time_diff.seconds / 60)) + ' min.).')
del load_start_time, load_end_time, load_time_diff
if len(loading_time_durations) > 0:
mean_loading_time = np.mean(loading_time_durations)
current_time = datetime.now()
eta_time = current_time + (mean_loading_time * (len(batch_dirs) - (i + 1)))
log.write('Loading finished ETA: ' + str(eta_time.strftime("%d/%m/%Y, %H:%M:%S")))
del mean_loading_time, current_time, eta_time
if X_full is None:
log.write('No files were loaded!')
assert False
log.write('Debug list size "X_full": ' + str(len(X_full)), print_to_console=False)
log.write('Debug list size "y_full": ' + str(len(y_full)), print_to_console=False)
log.write('Debug list size "y_tiles_full": ' + str(len(y_tiles_full)), print_to_console=False)
log.write('Debug list size "X_raw_full": ' + str(len(X_raw_full)), print_to_console=False)
log.write('Debug list size "bag_names": ' + str(len(bag_names_full)), print_to_console=False)
log.write('Debug list size "X_metadata_full": ' + str(len(X_metadata_full)), print_to_console=False)
assert len(X_full) == len(y_full)
assert len(X_full) == len(y_tiles_full)
assert len(X_full) == len(X_raw_full)
assert len(X_full) == len(bag_names_full)
assert len(X_full) == len(X_metadata_full)
experiment_names_unique = []
for experiment_name in experiment_names_full:
if experiment_name not in experiment_names_unique:
experiment_names_unique.append(experiment_name)
return X_full, y_full, y_tiles_full, X_raw_full, X_metadata_full, bag_names_full, experiment_names_full, experiment_names_unique, well_names_full, error_list, loaded_files_list_full
# Main Loading function
def load_bags_json(source_dir: str, max_workers: int, normalize_enum: int, label_0_well_indices: [int],
channel_inclusions: [bool], label_1_well_indices: [int], constraints_1: [int], constraints_0: [int],
force_balanced_batch: bool = True, unrestricted_experiments_override: [str] = None,
positive_z_score_scale: float = 1.0, z_score_max_kernel_size: int = 1,
used_tile_quartiles=None,
gp_current: int = 1, gp_max: int = 1, include_raw: bool = True):
if used_tile_quartiles is None:
used_tile_quartiles = default_used_tile_quartiles.copy()
files = os.listdir(source_dir)
log.write('[' + str(gp_current) + '/' + str(gp_max) + '] Loading from source: ' + source_dir)
loaded_files_list = []
if unrestricted_experiments_override is None:
unrestricted_experiments_override = []
terminal_columns = None
if platform == "linux" or platform == "linux2":
try:
terminal_rows, terminal_columns = os.popen('stty size', 'r').read().split()
terminal_columns = int(terminal_columns)
except Exception as e:
log.write_exception(e, print_to_console_message=True,
include_in_files_message=True,
print_to_console_stack_trace=False,
include_in_files_stack_trace=True)
log.write('Cannot display refreshing lines in this console. :(')
time.sleep(1)
terminal_columns = None
executor = ThreadPoolExecutor(max_workers=max_workers)
future_list = []
worker_verbose: bool = max_workers == 1
for file in files:
# print('Considering source file: ' + file)
filepath = source_dir + os.sep + file
if file.endswith('.json.zip'):
loaded_files_list.append(filepath + os.sep + file)
future = executor.submit(unzip_and_read_JSON,
filepath,
worker_verbose,
normalize_enum,
label_0_well_indices,
label_1_well_indices,
constraints_0,
constraints_1,
channel_inclusions,
unrestricted_experiments_override,
positive_z_score_scale,
z_score_max_kernel_size,
used_tile_quartiles,
include_raw
)
future_list.append(future)
if file.endswith('.json'):
if os.path.exists(filepath + '.zip'):
# print('A zipped version also existed. Skipping.')
continue
loaded_files_list.append(filepath + os.sep + file)
future = executor.submit(read_JSON_file,
filepath,
worker_verbose,
normalize_enum,
label_0_well_indices,
label_1_well_indices,
constraints_0,
constraints_1,
channel_inclusions,
unrestricted_experiments_override,
positive_z_score_scale,
z_score_max_kernel_size,
used_tile_quartiles,
include_raw
)
future_list.append(future)
start_time = gct(raw=True)
all_finished: bool = False
executor.shutdown(wait=False)
while not all_finished:
finished_count = 0
error_count = 0
for future in future_list:
if future.done():
finished_count = finished_count + 1
e = future.exception()
if e is not None:
error_count = error_count + 1
line_print('[' + str(gp_current) + ' / ' + str(gp_max) + '] ' + str(
max_workers) + ' Threads running. Finished: ' + str(finished_count) + '/' + str(
len(future_list)) + '. Errors: ' + str(
error_count) + '. Running: ' + get_time_diff(
start_time) + '. ' + gct(), max_width=terminal_columns, include_in_log=False)
all_finished = finished_count == len(future_list)
time.sleep(1)
experiment_name = '<unknown experiment>'
X = []
y = []
X_raw = []
X_metadata = []
bag_names = []
well_names = []
experiment_names = []
y_tiles = []
error_list = []
print('')
log.write('Parallel execution resulted in ' + str(len(future_list)) + ' futures.')
print('\n')
for i in range(len(future_list)):
future = future_list[i]
line_print('Extracting future: ' + str(i + 1) + '/' + str(len(future_list)), include_in_log=False)
e = future.exception()
if e is None:
X_f, y_f, y_f_tiles, x_f_raw, x_f_metadata_raw, bag_name, experiment_name, well_name = future.result()
if X_f is not None and y_f is not None and y_f_tiles is not None and x_f_raw is not None and len(
X_f) != 0:
X.append(X_f)
y.append(y_f)
y_tiles.append(y_f_tiles)
X_raw.append(x_f_raw)
X_metadata.append(x_f_metadata_raw)
experiment_names.append(experiment_name)
well_names.append(well_name)
bag_names.append(bag_name)
log.write('Assumed experiment name (Future #' + str(
i) + '):\n' + experiment_name + ' - ' + well_name + ' <- ' + source_dir,
print_to_console=False, include_in_files=True)
else:
log.write('\n' + gct() + 'Error extracting future results: ' + str(e) + '\n')
tb = traceback.TracebackException.from_exception(e)
for line in tb.stack:
log.write(str(line))
error_list.append(e)
print('\n')
log.write('\nFully Finished Loading Path. Files: ' + str(loaded_files_list))
# TODO assert all the same experiment name!
# Deleting the futures and the future list to immediately releasing the memory.
future_count = len(future_list)
del future_list[:]
del future_list
log.write('Debug list size "X": ' + str(len(X)))
log.write('Debug list size "y": ' + str(len(y)))
log.write('Debug list size "y_tiles": ' + str(len(y_tiles)))
log.write('Debug list size "X_raw": ' + str(len(X_raw)))
log.write('Debug list size "bag_names": ' + str(len(bag_names)))
log.write('Debug list size "bag_names": ' + str(len(X_metadata)))
bag_count_negative = len(np.where(np.asarray(y) == 0)[0])
bag_count_positive = len(np.where(np.asarray(y) == 1)[0])
log.write('Wells with label 0 from ' + experiment_name + ': ' + str(bag_count_negative) + ' / ' + str(future_count))
log.write('Wells with label 1 from ' + experiment_name + ': ' + str(bag_count_positive) + ' / ' + str(future_count))
max_tile_count = 0
max_oligo_count = 0
if bag_count_negative + bag_count_positive > 0:
max_tile_count = float(max([len(x) for x in X_metadata]))
max_oligo_count = float(max([x.count_oligos for xs in X_metadata for x in xs]))
# Overriding forcing balance!
force_balanced_batch_overwritten = False
if force_balanced_batch and experiment_name in unrestricted_experiments_override:
log.write('Forcing balance...')
log.write('... OVERWRITTEN! This experiment will not force balance!')
force_balanced_batch_overwritten = True
if force_balanced_batch and not force_balanced_batch_overwritten:
balance_difference = bag_count_positive - bag_count_negative
log.write('Forcing balance...')
if bag_count_negative == 0 and bag_count_positive > 0:
# If there are no negative bags in this batch....
# there would be no data loaded! This cannot be! So one well is selected at random.
log.write('... by keeping a single positive well. There were no negatives in this batch.')
# TODO choose, but not random
positive_indices = np.where(np.asarray(y) == 1)[0]
positive_indices = positive_indices.tolist()
random.shuffle(positive_indices)
keep_index = positive_indices[0]
keep_index = get_most_valuable_bag_index(X_metadata=X_metadata, max_tile_count=max_tile_count,
max_oligo_count=max_oligo_count, inverted=False)
# Removing all elements, except the one with the 'keep_index'
X = [X[keep_index]]
y = [y[keep_index]]
y_tiles = [y_tiles[keep_index]]
X_raw = [X_raw[keep_index]]
bag_names = [bag_names[keep_index]]
experiment_names = [experiment_names[keep_index]]
well_names = [well_names[keep_index]]
X_metadata = [X_metadata[keep_index]]
elif bag_count_positive > bag_count_negative:
log.write('... by removing ' + str(balance_difference) + ' positive wells.')
for i in range(balance_difference):
positive_indices = np.where(np.asarray(y) == 1)[0]
positive_indices = positive_indices.tolist()
random.shuffle(positive_indices)
delete_index = positive_indices[0]
delete_index = get_most_valuable_bag_index(X_metadata=X_metadata, max_tile_count=max_tile_count,
max_oligo_count=max_oligo_count, inverted=True)
# TODO select index by criterium, not randomly
metadata = X_metadata[delete_index][0]
current_experiment_name = metadata.experiment_name
current_well = metadata.get_formatted_well()
log.write('Deleting superfluous bag: ' + str(i + 1) + '/' + str(
balance_difference) + ' - ' + current_experiment_name + ' ' + current_well)
# Deleting from the loaded lists at the randomly selected index
del X[delete_index]
del y[delete_index]
del y_tiles[delete_index]
del X_raw[delete_index]
del bag_names[delete_index]
del experiment_names[delete_index]
del well_names[delete_index]
del X_metadata[delete_index]
bag_count_negative = len(np.where(np.asarray(y) == 0)[0])
bag_count_positive = len(np.where(np.asarray(y) == 1)[0])
# assert bag_count_negative == bag_count_positive
else:
log.write('No need. Batch is already perfectly balanced. As all things should be.')
# Setting the variables again
bag_count_negative = len(np.where(np.asarray(y) == 0)[0])
bag_count_positive = len(np.where(np.asarray(y) == 1)[0])
log.write('After forcing balance: label 0 from ' + experiment_name + ': ' + str(bag_count_negative))
log.write('After forcing balance: label 1 from ' + experiment_name + ': ' + str(bag_count_positive))
X_s = str(utils.byteSizeString(utils.listToBytes(X)))
X_s_raw = str(utils.byteSizeString(utils.listToBytes(X_raw)))
y_s = str(utils.byteSizeString(sys.getsizeof(y)))
log.write("X-size in memory of " + experiment_name + " alone): " + str(X_s))
log.write("y-size in memory of " + experiment_name + " alone): " + str(y_s))
log.write("X-size (raw) in memory of " + experiment_name + " alone): " + str(X_s_raw))
del X_s, X_s_raw, y_s
assert len(X) == len(y)
assert len(X) == len(y_tiles)
assert len(X) == len(X_raw)
assert len(X) == len(bag_names)
assert len(X) == len(experiment_names)
assert len(X) == len(well_names)
assert len(X) == len(X_metadata)
# In case we have a R terminal running, we should keep it busy so it does not time out
r.has_connection()
return X, y, y_tiles, X_raw, X_metadata, bag_names, experiment_names, well_names, error_list, loaded_files_list
####
def unzip_and_read_JSON(filepath, worker_verbose, normalize_enum, label_0_well_indices: [int],
label_1_well_indices: [int], constraints_0: [int], constraints_1: [int],
channel_inclusions: [bool], unrestricted_experiments_override: [str],
positive_z_score_scale: float = 1.0, z_score_max_kernel_size: int = 1,
used_tile_quartiles=None,
include_raw: bool = True):
if used_tile_quartiles is None:
used_tile_quartiles = default_used_tile_quartiles.copy()
if worker_verbose:
log.write('Unzipping and reading json: ' + filepath)
threading.current_thread().setName('Unzipping & Reading JSON: ' + filepath)
# handling the case, if a json file has been zipped
# The idea: Read the zip, unzip it in ram and parse the byte stream directly as a string!
input_zip = ZipFile(filepath)
zipped_data_name = input_zip.namelist()[0]
data = input_zip.read(zipped_data_name)
input_zip.close()
data = json.loads(data)
X, y_bag, y_tiles, X_raw, X_metadata, bag_name, experiment_name, well_name = parse_JSON(filepath,
str(zipped_data_name), data,
worker_verbose,
normalize_enum,
label_0_well_indices=label_0_well_indices,
label_1_well_indices=label_1_well_indices,
channel_inclusions=channel_inclusions,
constraints_1=constraints_1,
constraints_0=constraints_0,
z_score_max_kernel_size=z_score_max_kernel_size,
positive_z_score_scale=positive_z_score_scale,
used_tile_quartiles=used_tile_quartiles,
unrestricted_experiments_override=unrestricted_experiments_override,
include_raw=include_raw)
if worker_verbose:
log.write('File Shape: ' + filepath + ' -> ')
log.write("X-shape: " + str(np.asarray(X).shape))
log.write("y-shape: " + str(np.asarray(y_bag).shape))
return X, y_bag, y_tiles, X_raw, X_metadata, bag_name, experiment_name, well_name
####
def read_JSON_file(filepath: str, worker_verbose: bool, normalize_enum: int, label_0_well_indices: [int],
label_1_well_indices: [int], constraints_0: [int], constraints_1: [int],
channel_inclusions: [bool], unrestricted_experiments_override: [str],
positive_z_score_scale: float = 1.0, z_score_max_kernel_size: int = 1,
used_tile_quartiles=None,
include_raw: bool = True):
if used_tile_quartiles is None:
used_tile_quartiles = default_used_tile_quartiles.copy()
if worker_verbose:
log.write('Reading json: ' + filepath)
# Renaming the thread, so profilers can keep up
threading.current_thread().setName('Loading JSON: ' + filepath)
f = open(filepath)
data = json.load(f)
f.close()
return parse_JSON(filepath=filepath, zipped_data_name=filepath, worker_verbose=worker_verbose,
normalize_enum=normalize_enum, label_0_well_indices=label_0_well_indices,
label_1_well_indices=label_1_well_indices, include_raw=include_raw,
channel_inclusions=channel_inclusions, json_data=data,
positive_z_score_scale=positive_z_score_scale, z_score_max_kernel_size=z_score_max_kernel_size,
unrestricted_experiments_override=unrestricted_experiments_override,
used_tile_quartiles=used_tile_quartiles,
constraints_1=constraints_1, constraints_0=constraints_0)
####
def parse_JSON(filepath: str, zipped_data_name: str, json_data: dict, worker_verbose: bool, normalize_enum: int,
# What well indices should be label 0 or label 1
label_0_well_indices: [int], label_1_well_indices: [int],
# Constraints
constraints_1: [int], constraints_0: [int],
unrestricted_experiments_override: [str], channel_inclusions: [bool],
# Validation params for oligo morphology
positive_z_score_scale: float = 1.0, z_score_max_kernel_size: int = 1,
# Restricting the tiles used to specific quartiles
used_tile_quartiles: [bool, bool, bool, bool] = None,
# misc params
include_raw: bool = True) -> (np.ndarray, int, [int], np.ndarray, str):
# Setting up arrays and params
if used_tile_quartiles is None:
used_tile_quartiles = default_used_tile_quartiles.copy()
X = []
X_raw = []
X_metadata = []
label = None
y_tiles = None
# Somehow, if 'include_raw' is false, nothing will be loaded. Why?
# TODO FIXME
assert include_raw
assert normalize_enum is not None
if unrestricted_experiments_override is None:
unrestricted_experiments_override = []
# Renaming the thread, so profilers can keep up
preview_out_folder_name_suffix = ''
threading.current_thread().setName('Parsing JSON: ' + zipped_data_name)
assert len(channel_inclusions) == 3
assert len(constraints_1) == 3
assert len(constraints_0) == 3
inclusions_count = sum([float(channel_inclusions[i]) for i in range(len(channel_inclusions))])
# Reading JSON meta data
width = json_data['tileWidth']
height = json_data['tileHeight']
bit_depth = json_data['bit_depth']
well = json_data['well']
if 'experiment_name' in json_data.keys():
experiment_name = json_data['experiment_name']
else:
experiment_name = zipped_data_name[:zipped_data_name.find('-')]
log.write(
'Interpreting experiment name from file name: "' + zipped_data_name + '" -> "' + experiment_name + '"',
print_to_console=False, include_in_files=True)
bag_name = experiment_name + '-' + well
if experiment_name in unrestricted_experiments_override:
log.write('Experiment name in unrestricted override. Removing restrictions.')
# TODO if there are constraints later, you can adjust those here in a future version.
# Reading metadata for the well, if it exists
well_image_width: int = 5520
well_image_height: int = 5520
if 'w' in json_data.keys() and 'h' in json_data.keys():
well_image_width = int(json_data['w'])
well_image_height = int(json_data['h'])
well_letter, well_number = extract_well_info(well, verbose=worker_verbose)
# Reading metadata for the experiment
metadata_path = paths.mil_metadata_file_linux
if sys.platform == 'win32':
metadata_path = paths.mil_metadata_file_win
if not os.path.exists(metadata_path):
log.write('Failed to locate metadata file: ' + metadata_path)
assert False
log.write('Metadata path (exists: True): ' + metadata_path, print_to_console=False, include_in_files=True)
plate_metadata_out_path = os.path.dirname(filepath)
if not sys.platform == 'win32':
plate_metadata_out_path = os.path.dirname(plate_metadata_out_path)
plate_metadata_out_path = plate_metadata_out_path + os.sep + 'bmc_metadata_preview'
plate_metadata = get_experiment_metadata(metadata_path=metadata_path, experiment_name=experiment_name,
out_dir=plate_metadata_out_path)
# bit_max = np.info('uint' + str(bit_depth)).max
bit_max = pow(2, bit_depth) - 1
# Setting label to match the param
label = -1
if type(label_1_well_indices) == list and type(label_0_well_indices) == list:
# Checking if the labels are in 'List' Format. If so, those bags are assigned the specific label
# Example #1: label_1_well_indices = [0, 1, 2, 3, 4]
if well_number in label_1_well_indices:
label = 1
elif well_number in label_0_well_indices:
label = 0
elif type(label_1_well_indices) == float and type(label_0_well_indices) == float:
# Checking if the labels are in 'List' Format. If so, those bags are assigned the specific label
# Example #1: label_1_well_indices = 0.2
# First, checking if the metadata is None
if plate_metadata is None or plate_metadata.compound_oligo_diff is None:
log.write('\n\n== WARNING ==\n'
'Cannot set label based on plate BMC for: ' + zipped_data_name + '! No metadata found!')
else:
oligo_diff = plate_metadata.compound_oligo_diff[well_number - plate_metadata.well_control]
if worker_verbose:
log.write('\n\n' + zipped_data_name + ' read BMC: ' + str(oligo_diff) + '. Compare to: <=' + str(
label_1_well_indices) + ' | >=' + str(label_0_well_indices) + '\n\n')
if oligo_diff >= label_1_well_indices:
label = 1
elif oligo_diff <= label_0_well_indices:
label = 0
if label == -1:
# Labels were not set. Skipping this bag.
if worker_verbose:
log.write('This bag has no label assigned. Removing.')
return X, label, y_tiles, X_raw, X_metadata, bag_name, experiment_name, well
if worker_verbose:
log.write('Reading JSON: ' + str(width) + 'x' + str(height) + '. Bits: ' + str(bit_depth))
# Deciding on what constraints to use, based on label
used_constraints = constraints_0
if label == 1:
used_constraints = constraints_1
# Initializing "best" min / max values for every cell in the tile
best_well_min_r = bit_max
best_well_min_g = bit_max
best_well_min_b = bit_max
best_well_max_r = 0
best_well_max_g = 0
best_well_max_b = 0
# Reading tiles
json_data = json_data['tiles']
keys = list(json_data.keys())
if len(keys) == 0:
if worker_verbose:
print('The read bag is empty!')
return X, label, y_tiles, X_raw, X_metadata, bag_name, experiment_name, well
for i in range(len(keys)):
# print('Processing tile: ' + str(i + 1) + '/' + str(len(keys)))
key = keys[i]
current_tile = json_data[str(key)]
# Reading channels
r = np.array(current_tile['r'])
g = np.array(current_tile['g'])
b = np.array(current_tile['b'])
# Extracting nuclei information from the metadata
count_nuclei: int = 0
count_oligos: int = 0
count_neurons: int = 0
if 'nuclei' in current_tile.keys():
count_nuclei = int(current_tile['nuclei'])
count_oligos = int(current_tile['oligos'])
count_neurons = int(current_tile['neurons'])
# Reading metadata for the tile
pos_x = math.nan
pos_y = math.nan
if 'x' in current_tile.keys() and 'y' in current_tile.keys():
pos_x = int(current_tile['x'])
pos_y = int(current_tile['y'])
metadata = TileMetadata(experiment_name=experiment_name, well_letter=well_letter, well_number=well_number,
pos_x=pos_x, pos_y=pos_y, well_image_width=well_image_width,
count_nuclei=count_nuclei, count_oligos=count_oligos, count_neurons=count_neurons,
plate_metadata=plate_metadata,
well_image_height=well_image_height, read_from_source=True)
# Holding on to the metadata and adding it when needed
# But creating it now, for caching and preview reasons
# Checking the constraints...
if count_nuclei < used_constraints[0] or count_oligos < used_constraints[1] or count_neurons < used_constraints[
2]:
# The constraints were not met...
if worker_verbose:
log.write('Tile with label ' + str(label) + ' did not meet the constraints! My values: ' + str(
count_nuclei) + ', ' + str(count_oligos) + ', ' + str(count_neurons) + ' - ' + str(
used_constraints))
continue
# Adding metadata now.
X_metadata.append(metadata)
del metadata
if include_raw:
# Reshaping the color images to a 2 dimensional array
raw_r = np.reshape(r, (width, height))
raw_g = np.reshape(g, (width, height))
raw_b = np.reshape(b, (width, height))
# Normalizing r,g,b based on max bit depth to convert them to 8 bit int
raw_r = raw_r / bit_max * 255
raw_g = raw_g / bit_max * 255
raw_b = raw_b / bit_max * 255
# Concatenating the color images to a rgb image
raw_rgb = np.dstack((raw_r, raw_g, raw_b))
raw_rgb = raw_rgb.astype('uint8')
X_raw.append(raw_rgb)
del raw_r, raw_g, raw_b, raw_rgb
# 0 = no normalisation
# 1 = normalize every cell between 0 and 255 (8 bit)
# 2 = normalize every cell individually with every color channel independent
# 3 = normalize every cell individually with every color channel using the min / max of all three
# 4 = normalize every cell but with bounds determined by the brightest cell in the same well
# 5 = z-score every cell individually with every color channel independent
# 6 = z-score every cell individually with every color channel using the mean / std of all three
r_min = min(r)
g_min = min(g)
b_min = min(b)
r_max = max(r)
g_max = max(g)
b_max = max(b)
min_list = []
max_list = []
if channel_inclusions[0]:
min_list.append(r_min)
max_list.append(r_max)
if channel_inclusions[1]:
min_list.append(g_min)
max_list.append(g_max)
if channel_inclusions[2]:
min_list.append(b_min)
max_list.append(b_max)
rgb_min = min(min_list)
rgb_max = max(max_list)
# Updating 'best' min / max values
best_well_min_r = min(best_well_min_r, r_min)
best_well_min_g = min(best_well_min_g, g_min)
best_well_min_b = min(best_well_min_b, b_min)
best_well_max_r = max(best_well_max_r, r_max)
best_well_max_g = max(best_well_max_g, g_max)
best_well_max_b = max(best_well_max_b, b_max)
# 2 = normalize every cell individually with every color channel independent
if normalize_enum == 2:
r = normalize_np(r, r_min, r_max)
g = normalize_np(g, g_min, g_max)
b = normalize_np(b, b_min, b_max)
# 3 = normalize every cell individually with every color channel using the min / max of all three
if normalize_enum == 3:
r = normalize_np(r, rgb_min, rgb_max)
g = normalize_np(g, rgb_min, rgb_max)
b = normalize_np(b, rgb_min, rgb_max)
# 5 = z-score every cell individually with every color channel independent
if normalize_enum == 5:
r = z_score(r, axis=0)
g = z_score(g, axis=0)
b = z_score(b, axis=0)
# 6 = z-score every cell individually with every color channel using the mean / std of all three
if normalize_enum == 6:
standardize_list = []
if channel_inclusions[0]:
standardize_list.append(r)
if channel_inclusions[1]:
standardize_list.append(g)
if channel_inclusions[2]:
standardize_list.append(b)
rgb = np.concatenate(standardize_list, axis=0)
mean = np.mean(rgb)
std = np_std(rgb, axis=0, mean=mean)
r = z_score(r, axis=0, std=std, mean=mean)
g = z_score(g, axis=0, std=std, mean=mean)
b = z_score(b, axis=0, std=std, mean=mean)
del rgb, mean, std, standardize_list
# Reshaping the color images to a 2 dimensional array
r = np.reshape(r, (width, height))
g = np.reshape(g, (width, height))
b = np.reshape(b, (width, height))
# Concatenating the color images to a rgb image
rgb = np.dstack((r, g, b))
# 1 = normalize every cell between 0 and 255 (8 bit)
if normalize_enum == 1:
rgb = normalize_np(rgb, 0, bit_max)
# Appending the current tile to the list
X.append(rgb)
del r
del g
del b
del rgb
# 4 = normalize every cell individually with every color channel using the min / max of all three
# 7 = z-score every cell individually with every color channel independent using all samples in the bag
# 8 = z-score every cell individually with every color channel using the mean / std of all three from all samples in the bag
if normalize_enum == 4 or normalize_enum == 7 or normalize_enum == 8 or normalize_enum == 9 or normalize_enum == 10:
bag_mean_r = float('NaN')
bag_mean_g = float('NaN')
bag_mean_b = float('NaN')
bag_std_r = float('NaN')
bag_std_g = float('NaN')
bag_std_b = float('NaN')
bag_mean = float('NaN')
bag_std = float('NaN')
if normalize_enum == 7:
bag_mean_r, bag_std_r = get_bag_mean(X, axis=0)
bag_mean_g, bag_std_g = get_bag_mean(X, axis=1)
bag_mean_b, bag_std_b = get_bag_mean(X, axis=2)
if normalize_enum == 8:
bag_mean, bag_std = get_bag_mean(X, channel_inclusions=channel_inclusions)
for i in range(len(X)):
current_x = X[i]
current_r = current_x[:, :, 0]
current_g = current_x[:, :, 1]
current_b = current_x[:, :, 2]
if normalize_enum == 4 or normalize_enum == 9 or normalize_enum == 10:
current_r = normalize_np(current_r, best_well_min_r, best_well_max_r)
current_g = normalize_np(current_g, best_well_min_g, best_well_max_g)
current_b = normalize_np(current_b, best_well_min_b, best_well_max_b)
if normalize_enum == 9:
current_r = z_score(current_r, axis=0)
current_g = z_score(current_g, axis=0)
current_b = z_score(current_b, axis=0)
if normalize_enum == 10:
standardize_list = []
if channel_inclusions[0]:
standardize_list.append(current_r)
if channel_inclusions[1]:
standardize_list.append(current_g)
if channel_inclusions[2]:
standardize_list.append(current_b)
rgb = np.concatenate(standardize_list, axis=0)
mean = np.mean(rgb)
std = np_std(rgb, axis=0, mean=mean)
current_r = z_score(current_r, axis=0, std=std, mean=mean)
current_g = z_score(current_g, axis=0, std=std, mean=mean)
current_b = z_score(current_b, axis=0, std=std, mean=mean)
del mean, std, rgb, standardize_list
if normalize_enum == 7:
current_r = z_score(current_r, mean=bag_mean_r, std=bag_std_r)
current_g = z_score(current_g, mean=bag_mean_g, std=bag_std_g)
current_b = z_score(current_b, mean=bag_mean_b, std=bag_std_b)
if normalize_enum == 8:
current_r = z_score(current_r, mean=bag_mean, std=bag_std)
current_g = z_score(current_g, mean=bag_mean, std=bag_std)
current_b = z_score(current_b, mean=bag_mean, std=bag_std)
current_rgb = np.dstack((current_r, current_g, current_b))
del current_r
del current_g
del current_b
X[i] = current_rgb