This repository was archived by the owner on Sep 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAMi_Image_Analysis.py
More file actions
executable file
·2359 lines (2072 loc) · 95.5 KB
/
AMi_Image_Analysis.py
File metadata and controls
executable file
·2359 lines (2072 loc) · 95.5 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 27 13:57:18 2019
@author: ludovic
"""
from gui import Ui_MainWindow
import os
import sys
import datetime
import json
import re
import csv
import math
import numpy as np
from pathlib import Path
import multiprocessing
import time
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPixmap, QKeySequence
from PyQt5.QtWidgets import (QTableWidgetItem, QFileDialog, QSplashScreen,
QMessageBox, QGridLayout, QStyleFactory,
QProgressDialog, QInputDialog, QLineEdit,
QTableView)
from utils import (ensure_directory, initProject, _RAWIMAGES, Ext,rows,
cols, open_XML, utilViewer)
from shutil import copyfile
import pdf_writer
import HeatMap_Grid
from MARCO_Results_Analysis import MARCO_Results
import PlateOverview
import StatisticsDialog
from tools import Merge_Zstack
import ReadScreen
import ExternalViewer
import preferences as pref
import subprocess
import pandasModel
import pandas as pd
import glob
QtWidgets.QApplication.setAttribute(
QtCore.Qt.AA_EnableHighDpiScaling, True) # enable highdpi scaling
QtWidgets.QApplication.setAttribute(
QtCore.Qt.AA_UseHighDpiPixmaps, True) # use highdpi icons
QtWidgets.QApplication.setAttribute(
QtCore.Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
__version__ = "1.2.5.3"
__author__ = "Ludovic Pecqueur (ludovic.pecqueur \at college-de-france.fr)"
__date__ = "08-04-2024"
__license__ = "New BSD http://www.opensource.org/licenses/bsd-license.php"
#Dictionnary used to update color of labelVisuClassif. Definition in preferences.py
ClassificationColor = pref.ClassificationColor
def Citation():
print(f'''
Program written by
Ludovic Pecqueur
Laboratoire de Chimie des Processus Biologiques
Collège de France.
Please acknowledge the use of this program and give
the following link:
https://github.com/LP-CDF/AMi_Image_Analysis
licence: %s
2019-{datetime.date.today().year}
''' % __license__)
class ViewerModule(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
# print("self.app_path ", self.app_path)
self.SplashScreen(2000)
self.ui = Ui_MainWindow()
self.setupUi(self)
self.setWindowTitle(f"AMi Image Analysis version {__version__}")
self._nsre = re.compile('([0-9]+)') # used to sort alphanumerics
content_widget = QtWidgets.QWidget()
self.scrollAreaPlate.setWidget(content_widget)
self._lay = QGridLayout(content_widget)
timeline_widget = QtWidgets.QWidget()
self.scrollArea_Timeline.setWidget(timeline_widget)
self._timlay = QGridLayout(timeline_widget)
self.os = sys.platform # Name of the OS
self.files = [] # Full path of Z-stacked images
self.well_images = [] # Only names of well images
self.wells=[] #Only names of well
self.reservoirs = [] # Only names of reservoir
self.directory = str
self.data_json = None
self.rootDir = str # Full path where folders at different times are
self.imageDir = str # Full path where images at a given time are
self.project = str # Name of the project
self.target = str # Name of the protein within the project
self.plate = str # Name of the plate
self.date = str # Date of images
# self.timed = str # Time of images
self.prepdate = str # Date of plate preparation
self.classifications = {} # Dictionnary in memory containing well:classif
self.scores = {} # Dictionnary in memory containing well:score
self.WellHasNotes = {} # Dictionnary in memory containing well:True/False
self.previousWell = None
self.currentWell = None
self.currentButtonIndex = None
self.VisiblesIdx = [] # list in memory with index of visible well widgets
self.InitialNotes = None
self.InitialClassif = None
self.InitialScore = None
# Name of the directory containing individual Z-focus images
self.rawimages = _RAWIMAGES
self.TimelineInspector = None
self.MARCO = None # Automated_Marco Predictor object
self.Predicter = None # Automated_Marco predicter
self.ScreenDatabase=dict() #Database of Screens
self.database=dict() # data
self.currentScreen=None
self.pixmap=None
self.ScreenTable=None
self.StatisticsWindow=None
self.idx=None
self.prep_date_path=None
self.current_image=None
self.imageP=None #Image in Project Viewer
self.pixmapP=None #Image in Project Viewer
self.df_filtered=None
#If using the QGraphics view, use open_image
#If not comment the next five lines and use
#function LoadWellImage
self.ImageViewer=utilViewer(self.ImageViewer_1)
#Project Tab
self.ProjectInspector = utilViewer(self.ImageViewer_2)
self.Notes_TextEdit_2.setReadOnly(True)
self.dfgrouped=None #grouped panda Dataframe
#To see all autoMARCO results windows create a dict subwell:object
self.MARCO_window = {}
#To see all Plates windows create a dict subwell:object
self.PLATE_window = {}
#Create a dict with all crystallization cocktails
self.CreateScreenDictDatabase()
#Populate comboBoxes
self.comboBoxScreen.addItem(None)
for _key,_value in self.ScreenDatabase.items():
self.comboBoxScreen.addItem(_key)
self.comboBoxScore.addItem(None)
if pref.USESCORECLASS is True:
for _i in range(1,len(pref.scoreclass)+1):
self.comboBoxScore.addItem(str(_i) + str(f' ({pref.scoreclass[_i-1]})'))
else:
for _i in range(1,11):
self.comboBoxScore.addItem(str(_i))
#Enable, disable GUI items
self.openFile.setEnabled(False)
self.EnableDisableGUI(False)
self.initUI()
def SplashScreen(self, ms):
'''ms is the time in ms to show splash screen'''
_image = Path(self.app_path).joinpath("SplashScreen.png")
self.splash = QSplashScreen(QPixmap(str(_image)))
self.splash.show()
QtCore.QTimer.singleShot(ms, self.splash.close)
def EnableDisableGUI(self,_var)->bool:
'''Enable / Disable several GUI options'''
self.actionAutomated_Annotation_MARCO.setEnabled(_var)
self.actionAutoMARCO_current_image.setEnabled(_var)
self.actionCalculate_Statistics.setEnabled(_var)
self.comboBoxScreen.setEnabled(_var)
self.actionDisplay_Heat_Map.setEnabled(_var)
self.pushButton_CopyToNotes.setEnabled(_var)
self.pushButton_DisplayHeatMap.setEnabled(_var)
self.pushButton_ExportToPDF.setEnabled(_var)
self.menuShow_autoMARCO_Grid.setEnabled(_var)
self.actionChange_Preparation_date.setEnabled(_var)
self.comboBoxProject.setEnabled(_var)
self.actionHistogram_Manual_Scores.setEnabled(_var)
self.action_SavePlateDatabase.setEnabled(_var)
self.pushExportCSV.setEnabled(_var)
self.pushButtonResetProject.setEnabled(_var)
self.actionPropagate_Screen_Reservoirs.setEnabled(_var)
def EnableDisableautoMARCO(self,_var)->bool:
'''Enable / Disable several GUI options'''
self.actionAutomated_Annotation_MARCO.setEnabled(_var)
self.actionAutoMARCO_current_image.setEnabled(_var)
self.menuShow_autoMARCO_Grid.setEnabled(_var)
self.pushButton_Evaluate.setEnabled(_var)
def initUI(self):
self.MaxCol = 6
#Shortcut definitions
# self.exportPDFshortcut=QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+E"), self)
# self.exportPDFshortcut.activated.connect(self.export_pdf)
#Set Icons
icon_path= Path(self.app_path).joinpath("icons")
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(f'{Path(icon_path).joinpath("reset-update-icon.svg")}'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButtonResetProject.setIcon(icon)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(f'{Path(icon_path).joinpath("csv-icon-red.svg")}'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushExportCSV.setIcon(icon)
#Setup Menu
self.openFile.triggered.connect(self.openFileNameDialog)
self.openDir.triggered.connect(lambda: self.openDirDialog(dialog=True))
self.action_SavePlateDatabase.triggered.connect(lambda: self.writetojson(self.database, f'data_{self.date}.json'))
self.actionAutoCrop.triggered.connect(self.AutoCrop)
self.actionAutoMerge.triggered.connect(self.AutoMerge)
self.actionAutomated_Annotation_MARCO.triggered.connect(
self.autoAnnotation)
self.actionAutoMARCO_current_image.triggered.connect(
self.annotateCurrent)
self.actionDisplay_Heat_Map.triggered.connect(self.show_HeatMap)
self.actionExport_to_PDF.triggered.connect(self.export_pdf)
self.actionDelete_Folder_rawimages.triggered.connect(
lambda: self.DeleteFolder(self.imageDir, self.rawimages))
self.actionDelete_Folder_cropped.triggered.connect(
lambda: self.DeleteFolder(self.imageDir, "cropped"))
self.actionautoMARCO_subwell_a.triggered.connect(
lambda: self.show_autoMARCO("a"))
self.actionautoMARCO_subwell_b.triggered.connect(
lambda: self.show_autoMARCO("b"))
self.actionautoMARCO_subwell_c.triggered.connect(
lambda: self.show_autoMARCO("c"))
self.actionautoMARCO_no_subwell.triggered.connect(
lambda: self.show_autoMARCO(""))
self.actionChange_Preparation_date.triggered.connect(
self.editdate_updateGUI)
self.actionPlateSubwell_a.triggered.connect(
lambda: self.show_Plates("a"))
self.actionPlateSubwell_b.triggered.connect(
lambda: self.show_Plates("b"))
self.actionPlateSubwell_c.triggered.connect(
lambda: self.show_Plates("c"))
self.actionPlateno_subwell.triggered.connect(
lambda: self.show_Plates(""))
self.PlateScreenshot_subwell_a.triggered.connect(
lambda: self.take_plate_screenshot("a"))
self.PlateScreenshot_subwell_b.triggered.connect(
lambda: self.take_plate_screenshot("b"))
self.PlateScreenshot_subwell_c.triggered.connect(
lambda: self.take_plate_screenshot("c"))
self.PlateScreenshot_no_subwell.triggered.connect(
lambda: self.take_plate_screenshot(""))
#Crystallization Screens
#Nextal
self.actionNextal_MbClassII_Suite.triggered.connect(
lambda: self.show_xmlScreen("Nextal-MbClassII-Suite"))
self.actionNeXtal_Ammonium_Sulfate_Suite.triggered.connect(
lambda: self.show_xmlScreen("NeXtal-Ammonium_Sulfate-Suite"))
self.actionNextal_Classics_Suite.triggered.connect(
lambda: self.show_xmlScreen("Nextal-Classics-Suite"))
self.actionNextal_ClassicsII_Suite.triggered.connect(
lambda: self.show_xmlScreen("Nextal-ClassicsII-Suite"))
self.actionNextal_PEGII_Suite.triggered.connect(
lambda: self.show_xmlScreen("NeXtal-PEGs-II-Suite"))
self.actionNeXtal_Protein_Complex_Suite.triggered.connect(
lambda: self.show_xmlScreen("NeXtal-Protein-Complex-Suite"))
self.actionNeXtal_Nucleix_Suite.triggered.connect(
lambda: self.show_xmlScreen("NeXtal-Nucleix-Suite"))
self.actionNextal_Cryos.triggered.connect(
lambda: self.show_xmlScreen("NeXtal-Cryos-Suite"))
#Jena
self.actionJena_JCSG_Plus_Plus.triggered.connect(
lambda: self.show_xmlScreen("JBScreen-JCSG-Plus-Plus"))
self.actionJBScreen_Classic_HTS_I.triggered.connect(
lambda: self.show_xmlScreen("JBScreen_Classic_HTS_I"))
self.actionJBScreen_Classic_HTS_II.triggered.connect(
lambda: self.show_xmlScreen("JBScreen_Classic_HTS_II"))
self.actionJBScreen_Classic_1_4.triggered.connect(
lambda: self.show_csvScreen("JBScreen_Classic_1-4"))
self.actionJBScreen_Classic_5_8.triggered.connect(
lambda: self.show_csvScreen("JBScreen_Classic_5-8"))
self.actionXP_Screen.triggered.connect(
lambda: self.show_xmlScreen("JBScreen-XP-Screen"))
self.actionPi_PEG_HTS.triggered.connect(
lambda: self.show_xmlScreen("JBScreen_Pi-PEG_HTS"))
#Hampton
self.action_Additive_screen_HT.triggered.connect(
lambda: self.show_xmlScreen("HR-AdditiveScreen_HT"))
self.actionPeg_Rx1Rx2.triggered.connect(
lambda: self.show_xmlScreen("HR-PEGRx_HT_screen"))
self.actionSaltRx.triggered.connect(
lambda: self.show_xmlScreen("HR-SaltRx_HT_screen"))
self.action_Cryo_HT.triggered.connect(
lambda: self.show_xmlScreen("HR-Cryo_HT_screen"))
#MD
self.actionMD_PGA.triggered.connect(
lambda: self.show_xmlScreen("MD-PGA"))
self.actionMD_PACT_Premier.triggered.connect(
lambda: self.show_xmlScreen("MD_PACT_Premier"))
self.actionNextal_JCSG_Plus.triggered.connect(
lambda: self.show_xmlScreen("NeXtal-JCSG-Plus-Suite"))
self.actionMD_MIDAS.triggered.connect(
lambda: self.show_xmlScreen("MD_MIDAS"))
self.actionMD_BCS_Screen.triggered.connect(
lambda: self.show_xmlScreen("MD_BCS_Screen"))
self.actionMD_MORPHEUS_Fusion.triggered.connect(
lambda: self.show_xmlScreen("MD_MORPHEUS_FUSION"))
self.actionimport_RockMaker_XML.triggered.connect(self.openXMLDialog)
self.actionQuit_2.triggered.connect(self.on_exit)
self.actionCalculate_Statistics.triggered.connect(self.show_Statistics)
self.actionShortcuts.triggered.connect(self.ShowShortcuts)
self.actionAbout.triggered.connect(self.ShowAbout)
self.actionManual.triggered.connect(self.ShowManual)
self.actionHistogram_Manual_Scores.triggered.connect(lambda: self.showBinGraph(self.scores))
self.actionPropagate_Screen_Reservoirs.triggered.connect(lambda:self.PropagateCrystCocktail(self.currentScreen))
self.label_ProjectDetails.setFont(
QtGui.QFont("Arial", 12, QtGui.QFont.Black))
self.ImageViewer_1.setStyleSheet(
"""background-color:transparent;border: 1px solid black;""")
self.labelVisuClassif.setStyleSheet(
"""background-color:yellow;color:black;""")
#Setup Filtering Options
self.radioButton_All.toggled.connect(
lambda: self.FilterClassification(self._lay, "All"))
self.radioButton_Crystal.toggled.connect(
lambda: self.FilterClassification(self._lay, "Crystal"))
self.radioButton_Clear.toggled.connect(
lambda: self.FilterClassification(self._lay, "Clear"))
self.radioButton_Other.toggled.connect(
lambda: self.FilterClassification(self._lay, "Other"))
self.radioButton_Precipitate.toggled.connect(
lambda: self.FilterClassification(self._lay, "Precipitate"))
self.radioButton_PhaseSep.toggled.connect(
lambda: self.FilterClassification(self._lay, "PhaseSep"))
self.radioButton_Unsorted.toggled.connect(
lambda: self.FilterClassification(self._lay, "Unknown"))
self.radioButton_HasNotes.toggled.connect(
lambda: self.FilterNotes(self._lay))
self.radioButton_Subwella.toggled.connect(
lambda: self.FilterSubwell(self._lay, "a"))
self.radioButton_Subwellb.toggled.connect(
lambda: self.FilterSubwell(self._lay, "b"))
self.radioButton_Subwellc.toggled.connect(
lambda: self.FilterSubwell(self._lay, "c"))
#Stylesheet scrollAreaPlate and some Qlabel
self.scrollAreaPlate.setStyleSheet(
"""background-color: rgb(220,220,220);""")
self.label_LastSaved.setStyleSheet(
"""background-color: rgb(230,230,230);""")
#Change Some Styles in Scoring Section
self.label_2.setFont(QtGui.QFont("Arial", 12, QtGui.QFont.Black))
self.label_4.setFont(QtGui.QFont("Arial", 12, QtGui.QFont.Black))
self.label_Timeline.setFont(
QtGui.QFont("Arial", 12, QtGui.QFont.Black))
self.label_CurrentWell.setFont(
QtGui.QFont("Arial", 12, QtGui.QFont.Black))
self.label_CurrentWell.setStyleSheet("""color: blue;""")
self.radioButton_ScoreClear.setStyleSheet("""color: black;""")
self.radioButton_ScorePrecipitate.setStyleSheet("""color: red;""")
self.radioButton_ScoreCrystal.setStyleSheet("""color: green;""")
self.radioButton_ScorePhaseSep.setStyleSheet("""color: orange;""")
self.radioButton_ScoreOther.setStyleSheet("""color: magenta;""")
self.radioButton_ScoreUnknown.setStyleSheet("""color: black;""")
#Listen Scoring RadioButtons
self.radioButton_ScoreClear.toggled.connect(
lambda: self.SetDropClassif(self.radioButton_ScoreClear, self.currentWell))
self.radioButton_ScorePrecipitate.toggled.connect(lambda: self.SetDropClassif(
self.radioButton_ScorePrecipitate, self.currentWell))
self.radioButton_ScoreCrystal.toggled.connect(
lambda: self.SetDropClassif(self.radioButton_ScoreCrystal, self.currentWell))
self.radioButton_ScorePhaseSep.toggled.connect(
lambda: self.SetDropClassif(self.radioButton_ScorePhaseSep, self.currentWell))
self.radioButton_ScoreOther.toggled.connect(
lambda: self.SetDropClassif(self.radioButton_ScoreOther, self.currentWell))
self.radioButton_ScoreUnknown.toggled.connect(
lambda: self.SetDropClassif(self.radioButton_ScoreUnknown, self.currentWell))
#Listen Display Heat Map and export to pdf buttons, other push buttons
self.pushButton_DisplayHeatMap.clicked.connect(self.show_HeatMap)
self.pushButton_ExportToPDF.clicked.connect(self.export_pdf)
self.pushButton_Evaluate.clicked.connect(self.annotateCurrent)
self.pushButton_CopyToNotes.clicked.connect(lambda: self.copytoNotes(self.currentScreen,self.currentWell))
#Show shortcut in GUI for class selection
self.label_ShortcutClear.setText(
"(%s)" % QKeySequence(pref.Shortcut.Clear).toString())
self.label_ShortcutPrec.setText(
"(%s)" % QKeySequence(pref.Shortcut.Precipitate).toString())
self.label_ShortcutCrystal.setText(
"(%s)" % QKeySequence(pref.Shortcut.Crystal).toString())
self.label_ShortcutPhaseSep.setText(
"(%s)" % QKeySequence(pref.Shortcut.PhaseSep).toString())
self.label_ShortcutOther.setText(
"(%s)" % QKeySequence(pref.Shortcut.Other).toString())
#Listen comboBoxes
self.comboBoxScreen.activated.connect(self.setScreen)
self.comboBoxScore.activated.connect(lambda: self.setScore(self.currentWell))
#Project Tab
classes=['Clear',
'Crystal',
'Precipitate',
'PhaseSep',
'Other',
'Unknown'
]
self.comboBoxProject.addItem(None)
for i in classes:
self.comboBoxProject.addItem(i)
self.comboBoxProject.setCurrentIndex(0)
self.comboBoxProject.activated.connect(lambda: self.searchClassifProject())
self.pushButtonResetProject.clicked.connect(self.resetProject)
self.pushExportCSV.clicked.connect(lambda: self.ExportSummaryCSV(
self.df_filtered,
Path(*self.rootDir.parts[:self.rootDir.parts.index(self.project)+1]),
f'{self.project}_{self.comboBoxProject.currentText()}.csv',
header=['Target', 'Plate', 'well', 'Human Score', 'Notes'])
)
# self.comboBoxTargetFilter.activated.connect(lambda: self.filterTable(self.comboBoxTargetFilter.currentText(),
# self.tableViewProject))
self.comboBoxTargetFilter.activated.connect(lambda: self.filterQTableView(self.comboBoxTargetFilter.currentText()))
self.show()
def show_HeatMap(self):
''' Create window and map results on a grid'''
if len(self.classifications) == 0:
self.handle_error("No data yet!!!")
return False
self.heatmap_window = HeatMap_Grid.HeatMapGrid()
self.heatmap_window.setWindowTitle(
"Heat Map: %s (%s)" % (self.plate, self.date))
self.heatmap_window.well_images = self.well_images
self.heatmap_window.classifications = self.classifications
self.heatmap_window.score = self.scores
self.heatmap_window.notes = self.WellHasNotes
self.heatmap_window.pushButton_ExportImage.clicked.connect(lambda: self.take_screenshot(
self.heatmap_window, "HeatMap_Grid_%s_%s" % (self.plate, self.date)))
self.heatmap_window.pushButton_Close.clicked.connect(
self.heatmap_window.close)
self.heatmap_window.show()
def show_csvScreen(self, Screen):
'''Screen is taken from key ScreenFile dictionnary in ReadScreen.py '''
self.ScreenTable = ReadScreen.MyTable(10, 10)
self.ScreenTable.setWindowTitle("%s" % Screen)
data = self.ScreenTable.open_sheet(Screen)
# self.ScreenTable.setColumnWidth(0, 100)
self.ScreenTable.resize(1000, 500)
if data is True:
header = self.ScreenTable.horizontalHeader()
header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
self.ScreenTable.show()
else:
self.handle_error("WARNING: File %s not found in database" %
ReadScreen.ScreenFile[Screen])
def show_xmlScreen(self, fileName):
path = Path(fileName)
self.ScreenTable = ReadScreen.MyTable(10, 10)
self.ScreenTable.setWindowTitle(path.stem)
if path.stem in self.ScreenDatabase:
data = self.ScreenDatabase[path.stem]
else:
data = open_XML(fileName)
if data is None:
self.handle_error(
"WARNING: unexpected format for file %s" % fileName)
return
else:
self.ScreenTable.create_table(data)
self.ScreenTable.resize(1000, 500)
header = self.ScreenTable.horizontalHeader()
header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
self.ScreenTable.show()
def CreateScreenDictDatabase(self):
'''Create a dict of dict containing all screens and crystallization
conditions
only load .xml formatted screens'''
ScreenFile=ReadScreen.ScreenFile
for _screen in ScreenFile.keys():
path=Path(self.app_path).joinpath("Screen_Database", ScreenFile[_screen])
if Path(path).suffix=='.xml':
self.ScreenDatabase[_screen]=open_XML(str(path))
# for i,j in self.ScreenDatabase.items(): print(i,j)
def FindCrystCocktail(self,screen,well):
'''If screen in database find crystallization cocktail
and return a list else returns False'''
if screen not in self.ScreenDatabase.keys():
return False
if well[-1] in ['a', 'b', 'c']:
well=well[:-1]
for i,j in self.ScreenDatabase[screen].items():
if j[0]==well:
cocktail=j
break
return cocktail
def PropagateCrystCocktail(self, screen):
if screen not in self.ScreenDatabase.keys():
error=''' Screen not set or not in database!!! \n Set the screen via the list or import RockMaker XML file'''
self.handle_error(error)
return False
for well in self.database[self.plate]["Wells"].keys():
txt=list(self.FindCrystCocktail(screen, well))
txt[0]="Crystallization Mix:"
self.UpdateDatabase(well, text=txt)
def show_autoMARCO(self, subwell):
''' Create window and map results on a grid'''
if len(self.classifications) == 0:
self.handle_error(
"Please choose a directory containing the images first")
return
_file = Path(self.rootDir).joinpath(
"Image_Data", self.date, "auto_MARCO.log")
if Path(_file).exists():
with open(_file, 'r') as f:
data = f.readlines()
else:
self.handle_error("File %s not found" % _file)
return
autoMARCO_data = []
for line in data:
autoMARCO_data.append(line.split())
#delete HEADER from list
del autoMARCO_data[0]
self.MARCO_window[subwell] = MARCO_Results()
self.MARCO_window[subwell].subwell = subwell
self.MARCO_window[subwell].setWindowTitle(
"autoMARCO results for subwell %s" % subwell)
self.MARCO_window[subwell].autoMARCO_data = autoMARCO_data
#Define Legend
self.MARCO_window[subwell].label_Crystal.setStyleSheet(
"""background-color:rgb(0, 255, 0)""")
self.MARCO_window[subwell].label_Other.setStyleSheet(
"""background-color:rgb(255, 0, 255); color:rgb(255, 255, 255)""")
self.MARCO_window[subwell].label_Precipitate.setStyleSheet(
"""background-color:rgb(255, 0, 0); color:rgb(255, 255, 255)""")
self.MARCO_window[subwell].label_Clear.setStyleSheet(
"""background-color:rgb(0, 0, 0); color:rgb(255, 255, 255)""")
self.MARCO_window[subwell].show()
del autoMARCO_data
def show_Plates(self, subwell):
''' Create window and map results on a grid'''
#TODO: deal with permissions issues when creating Miniatures
if len(self.classifications) == 0:
self.handle_error(
"Please choose a directory containing the images first")
return
#check Miniatures is present or can be created
_f=ensure_directory(Path(self.rootDir).joinpath(
"Image_Data", self.date, "Miniatures"))
if _f is not None: # if issue stops
self.handle_error(_f)
return
if subwell in self.PLATE_window:
self.PLATE_window[subwell].UpdateBorder(
self.files, self.classifications)
self.PLATE_window[subwell].show()
else:
self.PLATE_window[subwell] = PlateOverview.Plate(
9, 13, self.rootDir, self.date, self.files)
self.PLATE_window[subwell].subwell = subwell
self.PLATE_window[subwell].setWindowTitle(
f"Plate Overview: {self.plate} ({self.date}) | subwell {subwell}")
self.PLATE_window[subwell].create_table(
self.files, self.classifications)
self.PLATE_window[subwell].setStyleSheet(
"""background-color: rgb(240,240,240)""")
self.PLATE_window[subwell].resize(1520, 810)
self.PLATE_window[subwell].show()
self.PLATE_window[subwell].testSignal.connect(lambda: self.ShowPlateSel(subwell))
QtGui.QPixmapCache.clear()
def ShowPlateSel(self, subwell):
'''Show well selected in Plate Overview in the main window'''
well,path=self.PLATE_window[subwell].CLICKED, self.PLATE_window[subwell].RETURNPATH
self.open_image(path)
self.currentWell=well
self.dothings(well)
def show_Statistics(self):
'''Calculate statistics on the plate'''
#Check data before going further
if len(self.classifications) == 0:
self.handle_error("No data yet!!!")
return False
self.StatisticsWindow = QtWidgets.QDialog()
ui = StatisticsDialog.Ui_Dialog()
ui.setupUi(self.StatisticsWindow)
results = self.Calculate_Statistics()
positions = [(i, j) for i in range(6) for j in range(4)]
# print("positions ", positions)
for pos in positions:
if pos[0] == 0:
value = results[pos[1]]['Clear']
elif pos[0] == 1:
value = results[pos[1]]['Precipitate']
elif pos[0] == 2:
value = results[pos[1]]['Crystal']
elif pos[0] == 3:
value = results[pos[1]]['PhaseSep']
elif pos[0] == 4:
value = results[pos[1]]['Other']
else:
value = results[pos[1]]['Unknown']
ui.StatisticsTable.setItem(
pos[0], pos[1], QTableWidgetItem(str(value)))
self.StatisticsWindow.show()
ui.pushButton_Export.clicked.connect(
lambda: self.export_statistics(results))
def export_statistics(self, _list):
filename = Path(self.rootDir).joinpath(
"Image_Data", "Statistics_%s_%s.csv" % (self.plate, self.date))
with open(filename, 'w', newline='') as f:
fieldnames = ["Classification", "Subwell_a",
"Subwell_b", "Subwell_c", "No_Subwell"]
writer = csv.DictWriter(
f, fieldnames, delimiter=',', quoting=csv.QUOTE_ALL, dialect="excel")
writer.writeheader()
writer.writerow({'Classification': 'Clear', 'Subwell_a': _list[0]['Clear'], 'Subwell_b': _list[
1]['Clear'], 'Subwell_c': _list[2]['Clear'], 'No_Subwell': _list[3]['Clear']})
writer.writerow({'Classification': 'Precipitate', 'Subwell_a': _list[0]['Precipitate'], 'Subwell_b': _list[
1]['Precipitate'], 'Subwell_c': _list[2]['Precipitate'], 'No_Subwell': _list[3]['Precipitate']})
writer.writerow({'Classification': 'Crystal', 'Subwell_a': _list[0]['Crystal'], 'Subwell_b': _list[
1]['Crystal'], 'Subwell_c': _list[2]['Crystal'], 'No_Subwell': _list[3]['Crystal']})
writer.writerow({'Classification': 'Phase Separation', 'Subwell_a': _list[0]['PhaseSep'], 'Subwell_b': _list[
1]['PhaseSep'], 'Subwell_c': _list[2]['PhaseSep'], 'No_Subwell': _list[3]['PhaseSep']})
writer.writerow({'Classification': 'Other', 'Subwell_a': _list[0]['Other'], 'Subwell_b': _list[
1]['Other'], 'Subwell_c': _list[2]['Other'], 'No_Subwell': _list[3]['Other']})
writer.writerow({'Classification': 'Unsorted', 'Subwell_a': _list[0]['Unknown'], 'Subwell_b': _list[
1]['Unknown'], 'Subwell_c': _list[2]['Unknown'], 'No_Subwell': _list[3]['Unknown']})
message = "File saved to:\n %s" % filename
self.informationDialog(message)
def AutoCrop(self):
if len(self.files) == 0:
self.handle_error(
"Please choose a directory containing the images first!!!")
return
try:
import cv2
import autocrop
if cv2.__version__ < '4.0.1':
self.handle_error(
"openCV version %s not supported" % cv2.__version__)
return
except ModuleNotFoundError:
self.handle_error("module cv2 not found")
return False
path = Path(self.imageDir).joinpath("cropped")
_f = ensure_directory(path)
if _f is not None: # if Permission issue
self.handle_error(
f"> {_f}\n\nYou must change the permissions to continue")
return
errors, error_list = 0, []
count, size = 0, len(self.files)
progress = QProgressDialog("Processing files...", "Abort", 0, size)
progress.setWindowTitle("AutoCrop")
progress.setMinimumWidth(300)
progress.setModal(True)
for _file in self.files:
progress.setValue(count+1)
img = cv2.imread(_file, cv2.IMREAD_COLOR)
well = os.path.splitext(os.path.basename(_file))[0]
output = autocrop.crop_ROI(img, self.imageDir, well)
if output is False:
errors += 1
error_list.append(well)
del img, output
count += 1
if progress.wasCanceled():
break
log = Path(path).joinpath("autocrop.log")
with open(log, 'w') as f:
if errors != 0:
f.write("File(s) that could not be processed correctly \n")
for err in error_list:
f.write(err+"\n")
else:
f.write("All Files could be processed.")
if errors != 0:
self.handle_error('''
%s file(s) were not processed.
For more information check log file %s
you can use the tool Check_Circle_detection.py filename to check
and modify detection parameters.
''' % (errors, log))
#INFORM USER TO RELOAD images from cropped if needed
self.informationDialog(
"You need to load the images from the directory \"cropped\" to use the cropped images")
def AutoMerge(self):
# from utils import _RAWIMAGES
self.informationDialog(f'''
Please open the directory {_RAWIMAGES} !!!
The GUI will not be responsive during processing.
You can check progress in the terminal window.
''')
self.openDirDialog()
if len(self.files) == 0:
return
nproc = multiprocessing.cpu_count()
#To Fix multiprocessing issue with OSX Catalina
if self.os == 'darwin' and multiprocessing.get_start_method() != 'forkserver':
multiprocessing.set_start_method('forkserver', force=True)
# rows = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
# cols = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
wells = ['a', 'b', 'c']
total_wells = [row + str(col) + str(well)
for row in rows for col in cols for well in wells]
path = str(Path(self.imageDir).parent)
if self.well_images[0].split('_')[0][-1] in ['a', 'b', 'c']:
SUBWELL = True
else:
SUBWELL = False
if SUBWELL == False:
filtered = []
for i in range(len(total_wells)):
if total_wells[i][:-1] not in filtered:
filtered.append(total_wells[i][:-1])
total_wells = filtered
args = []
for well in total_wells:
arg = well, self.well_images, self.imageDir, path
args.append(arg)
njobs = len(args)
MAX_CPU = pref.MAX_CPU
if MAX_CPU is not None:
try:
int(MAX_CPU)
if int(MAX_CPU) >= nproc:
MAX_CPU = nproc-1
except:
self.handle_error(
f"ABORTING, MAX_CPU not set properly, you must edit the value of MAX_CPU in:\n{self.app_path}/preferences.py \nand restart the GUI")
return
if nproc == 1:
number_processes = 1
elif njobs >= nproc and nproc != 1:
if MAX_CPU is None:
number_processes = nproc-1
else:
number_processes = int(MAX_CPU)
print("Number of CORES = ", nproc,
"Number of processes= ", number_processes)
time_start = time.perf_counter()
pool = multiprocessing.Pool(number_processes)
results = [pool.apply_async(
Merge_Zstack.MERGE_Zstack2, arg) for arg in args]
pool.close()
pool.join()
time_end = time.perf_counter()
self.informationDialog(f'''
Operation performed in {time_end - time_start:0.2f} seconds.
Merged images were automatically loaded from : \n {path}''')
last = self.well_images[-1].split("_")[0]+".jpg"
if Path(path).joinpath(last).is_file():
with open(str(Path(path).joinpath("DONE")), 'w'):
pass
#Clean up
for i in total_wells:
del i
del results, total_wells
#autoLoad Merged
self.openDirDialog(dialog=False, directory=path)
def ShowShortcuts(self):
shortcut = pref.Shortcut()
BoxShortCuts = QMessageBox()
text = '''
Well navigation shortcuts:
MoveUp= %s
MoveDown= %s
MoveLeft= %s
MoveRight= %s
Scoring shortcuts:
Clear= %s
Precipitate= %s
Crystal= %s
Phase Separation= %s
Other= %s
''' % (QKeySequence(shortcut.MoveUp).toString(),
QKeySequence(shortcut.MoveDown).toString(),
QKeySequence(shortcut.MoveLeft).toString(),
QKeySequence(shortcut.MoveRight).toString(),
QKeySequence(shortcut.Clear).toString(),
QKeySequence(shortcut.Precipitate).toString(),
QKeySequence(shortcut.Crystal).toString(),
QKeySequence(shortcut.PhaseSep).toString(),
QKeySequence(shortcut.Other).toString())
BoxShortCuts.information(self, "Shortcuts", text)
del shortcut
def ShowAbout(self):
about = QMessageBox()
text = f'''
AMi Image Analysis version {__version__}
Program written For Python 3 and PyQt5
by:
Ludovic Pecqueur
Chimie des Processus Biologiques
College de France
Paris, France
https://www.college-de-france.fr/site/en-chemistry-of-biological-processes/index.htm
Released under licence:
%s
2019-{datetime.date.today().year}
GitHub repository:
https://github.com/LP-CDF/AMi_Image_Analysis
''' % __license__
about.information(self, "About", text)
def ShowManual(self):
path = Path(self.app_path).joinpath("Manual_AMi_Image_Analysis.pdf")
if self.os == 'linux':
import webbrowser
webbrowser.open(str(path))
else:
from subprocess import run
run(['open', path], check=True)
def openXMLDialog(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getOpenFileName(
self, "Open File", "", "XML Files (*.xml *.XML)", options=options)
if fileName:
self.show_xmlScreen(fileName)
#Import temporarily Screen into database
self.ScreenDatabase[Path(fileName).stem]=open_XML(fileName)
#Update comboBoxScreen List if item not present
if self.comboBoxScreen.findText(Path(fileName).stem) == -1:
self.comboBoxScreen.addItem(Path(fileName).stem)
def openFileNameDialog(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getOpenFileName(
self, "Open File", "", "All Files (*);;Image Files (*.tiff *.tif *.jpg *.jpeg *.png *.PNG)", options=options)
if fileName:
print(fileName)
if fileName:
self.open_image(fileName)
#Next line to activate zoom capability
self.previousWell = self.extract_WellLabel(fileName)
def Initialise(self, directory):
'''directory is pathlib.Path object'''
PATHS = initProject(directory)
self.rawimages = PATHS.rawimages
self.rootDir = PATHS.rootDir
self.project = PATHS.project
self.date = PATHS.date
# self.timed = PATHS.timed
self.target = PATHS.target
self.plate = PATHS.plate
self.prep_date_path = PATHS.prep_date_path
self.imageDir = str(Path.resolve(directory))
self.label_LastSaved.setText("")
if self.rootDir is not None:
if Path(self.prep_date_path).exists():
with open(self.prep_date_path) as file:
self.prepdate = file.read().strip("\n")
else:
text, okPressed = QInputDialog.getText(
self, "File prep_date.txt not found", "Preparation date (format: YYYYMMDD) ", QLineEdit.Normal, "")
if okPressed and text != '':
try:
datetime.datetime.strptime(text, '%Y%m%d')
with open(self.prep_date_path, 'w') as f:
f.write(text)
self.prepdate = text
except:
self.handle_error(
f"Input date \"{text}\" not with correct format, skipping calculation of number of days")
self.prepdate = "None"
else:
self.prepdate = "None"
def writetojson(self, data, filename):
path = Path(self.rootDir).joinpath(
"Image_Data", self.date, filename)
try:
with open(path, "w") as f:
json.dump(data, f, indent=4)
except Exception as e:
self.handle_error(str(e))
def loadjson(self, filename):
with open(filename) as f:
_database = json.load(f)
return _database
def Reset(self):
'''reset file list and more when changing folder and reset layout grid'''
self.classifications.clear()
self.scores.clear()
self.WellHasNotes.clear()
self.rootDir = None
self.database.clear()
self.data_json = None
self.previousWell = None
self.currentWell = None
self.currentScreen = None
self.comboBoxScreen.setCurrentIndex(0)
self.comboBoxScore.setCurrentIndex(0)
self.currentButtonIndex = None
self.idx = None