-
Notifications
You must be signed in to change notification settings - Fork 0
/
CIU2_Main.py
1923 lines (1662 loc) · 98.5 KB
/
CIU2_Main.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
"""
Main entry point for CIUSuite 2 and location of all GUI handling code, along with some
basic file operations.
CIUSuite 2 Copyright (C) 2018 Daniel Polasky and Sugyan Dixit
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
if __name__ == '__main__':
print('Loading CIUSuite 2 modules...')
import pygubu
import tkinter as tk
from tkinter import filedialog
from tkinter import simpledialog
from tkinter import messagebox
import os
import subprocess
import pickle
import sys
import multiprocessing
import logging
from logging.handlers import RotatingFileHandler
from CIU_analysis_obj import CIUAnalysisObj
import CIU_Params
import Raw_Processing
import Original_CIU
import Gaussian_Fitting
import Feature_Detection
import Classification
import Raw_Data_Import
import SimpleToolTip
# Set global matplotlib params for good figure layouts and a non-interactive backend
import matplotlib
matplotlib.rcParams.update({'figure.autolayout': True})
matplotlib.use('Agg')
# Load resource file paths, supporting both live code and code bundled by PyInstaller
if getattr(sys, 'frozen', False):
root_dir = sys._MEIPASS
program_data_dir = os.path.join(os.environ['ALLUSERSPROFILE'], 'CIUSuite2')
else:
root_dir = os.path.dirname(__file__)
program_data_dir = root_dir
# hard_params_file = os.path.join(program_data_dir, 'CIU2_param_info.csv')
hard_params_file = os.path.join(program_data_dir, 'CIU2_param_info_new.csv')
hard_twimextract_path = os.path.join(program_data_dir, 'TWIMExtract', 'jars', 'TWIMExtract.jar')
hard_file_path_ui = os.path.join(root_dir, 'UI', 'CIUSuite2.ui')
hard_crop_ui = os.path.join(root_dir, 'UI', 'Crop_vals.ui')
hard_agilent_ext_path = os.path.join(root_dir, os.path.join('Agilent_Extractor', 'MIDAC_CIU_Extractor.exe'))
hard_tooltips_file = os.path.join(root_dir, 'tooltips.txt')
help_file = os.path.join(root_dir, 'CIUSuite2_Manual.pdf')
about_file = os.path.join(root_dir, 'README.txt')
log_file = os.path.join(program_data_dir, 'ciu2.log')
class CIUSuite2(object):
"""
Primary graphical class for running CIU2 user interface. Uses PyGuBu builder to create
interface and handles associated events.
"""
def __init__(self, tk_root_window):
"""
Create a new GUI window, connect feedback to buttons, and load parameters
"""
self.tk_root = tk_root_window
# create a Pygubu builder
self.builder = builder = pygubu.Builder()
# load the UI file
builder.add_from_file(hard_file_path_ui)
# create widget using provided root (Tk) window
self.mainwindow = builder.get_object('CIU_app_top')
self.mainwindow.protocol('WM_DELETE_WINDOW', self.on_close_window)
callbacks = {
'on_button_help_clicked': self.on_button_help_clicked,
'on_button_about_clicked': self.on_button_about_clicked,
'on_button_rawfile_clicked': self.on_button_rawfile_clicked,
'on_button_analysisfile_clicked': self.on_button_analysisfile_clicked,
'on_button_vendor_raw_clicked': self.on_button_vendor_raw_clicked,
'on_button_printparams_clicked': self.on_button_printparams_clicked,
'on_button_update_param_defaults_clicked': self.on_button_update_param_defaults_clicked,
'on_button_changedir_clicked': self.on_button_changedir_clicked,
'on_button_plot_options_clicked': self.on_button_plot_options_clicked,
'on_button_oldplot_clicked': self.on_button_oldplot_clicked,
'on_button_oldcompare_clicked': self.on_button_oldcompare_clicked,
'on_button_oldavg_clicked': self.on_button_oldavg_clicked,
'on_button_crop_clicked': self.on_button_crop_clicked,
'on_button_interpolate_clicked': self.on_button_interpolate_clicked,
'on_button_restore_clicked': self.on_button_restore_clicked,
'on_button_gaussfit_clicked': self.on_button_gaussfit_clicked,
'on_button_feature_detect_clicked': self.on_button_feature_detect_clicked,
'on_button_ciu50_clicked': self.on_button_ciu50_clicked,
'on_button_gaussian_reconstruction_clicked': self.on_button_gaussian_reconstruct_clicked,
'on_button_classification_supervised_clicked': self.on_button_classification_supervised_multi_clicked,
'on_button_classify_unknown_clicked': self.on_button_classify_unknown_subclass_clicked,
'on_button_smoothing_clicked': self.on_button_smoothing_clicked
}
builder.connect_callbacks(callbacks)
self.initialize_tooltips()
# load parameter file
self.params_obj = CIU_Params.Parameters()
self.params_obj.set_params(CIU_Params.parse_params_file(hard_params_file))
self.param_file = hard_params_file
# holder for feature information in between user assessment - plan to replace with better solution eventually
self.temp_feature_holder = None
self.analysis_file_list = []
self.output_dir = root_dir
self.output_dir_override = False
def run(self):
"""
Run the main GUI loop
:return: void
"""
self.mainwindow.mainloop()
def on_close_window(self):
"""
Close (destroy) the app window and the Tkinter root window to stop the process.
:return: void
"""
self.mainwindow.destroy()
self.tk_root.destroy()
def initialize_tooltips(self):
"""
Register tooltips for all buttons/widgets that need tooltips
:return: void
"""
tooltip_dict = parse_tooltips_file(hard_tooltips_file)
for tip_key, tip_value in tooltip_dict.items():
SimpleToolTip.create(self.builder.get_object(tip_key), tip_value)
def on_button_help_clicked(self):
"""
Open the manual
:return: void
"""
subprocess.Popen(help_file, shell=True)
def on_button_about_clicked(self):
"""
Open the license/about information file
:return: void
"""
subprocess.Popen(about_file, shell=True)
def on_button_rawfile_clicked(self):
"""
Open a filechooser for the user to select raw files, then process them
:return:
"""
# clear analysis list
self.analysis_file_list = []
raw_files = self.open_files(filetype=[('_raw.csv', '_raw.csv')])
self.load_raw_files(raw_files)
def load_raw_files(self, raw_filepaths):
"""
Helper method for loading _raw.csv files. Created since the code is accessed by multiple
other methods - used for modularity
:param raw_filepaths: list of full system path strings to _raw.csv files to load
:return: void
"""
if len(raw_filepaths) > 0:
# Ask user for smoothing input
plot_keys = [x for x in self.params_obj.params_dict.keys() if 'smoothing' in x]
param_success, param_dict = self.run_param_ui('Initial Smoothing Parameters', plot_keys)
if param_success:
self.progress_started()
# run raw processing
analysis_filenames = []
for raw_file in raw_filepaths:
try:
raw_obj = Raw_Processing.get_data(raw_file)
except ValueError as err:
messagebox.showerror('Data Import Error', message='{}{}. \nProblem: {}. Press OK to continue'.format(*err.args))
continue
try:
analysis_obj = Raw_Processing.process_raw_obj(raw_obj, self.params_obj)
except ValueError:
# all 0's in raw data - skip this file an notify the user
messagebox.showerror('Empty raw data file!', 'The raw file {} is empty (no intensity values > 0) and will NOT be loaded. Press OK to continue.'.format(os.path.basename(raw_file)))
continue
analysis_filename = save_analysis_obj(analysis_obj, param_dict, os.path.dirname(raw_obj.filepath))
analysis_filenames.append(analysis_filename)
self.update_progress(raw_filepaths.index(raw_file), len(raw_filepaths))
# update the list of analysis files to display
self.display_analysis_files(analysis_filenames)
# update directory to match the loaded files
if not self.output_dir_override:
if len(self.analysis_file_list) > 0:
self.output_dir = os.path.dirname(self.analysis_file_list[0])
self.update_dir_entry()
self.progress_done()
def on_button_analysisfile_clicked(self):
"""
Open a filechooser for the user to select previously process analysis (.ciu) files
:return:
"""
analysis_files = self.open_files(filetype=[('CIU files', '.ciu')])
self.display_analysis_files(analysis_files)
# update directory to match the loaded files
try:
if not self.output_dir_override:
self.output_dir = os.path.dirname(self.analysis_file_list[0])
self.update_dir_entry()
except IndexError:
# no files selected (user probably hit 'cancel') - ignore
return
# check if parameters in loaded files match the current Parameter object
# self.check_params()
def display_analysis_files(self, files_to_display):
"""
Write analysis filenames to the main text window and update associated controls. References
self.analysis_list for filenames
:param files_to_display: list of strings (full system paths to file location)
:return: void
"""
# update the internal analysis file list
self.analysis_file_list = files_to_display
displaystring = ''
index = 1
for file in files_to_display:
displaystring += '{}: {}\n'.format(index, os.path.basename(file).rstrip('.ciu'))
index += 1
# clear any existing text, then write the list of files to the display
self.builder.get_object('Text_analysis_list').delete(1.0, tk.END)
self.builder.get_object('Text_analysis_list').insert(tk.INSERT, displaystring)
# update total file number counter
self.builder.get_object('Entry_num_files').config(state=tk.NORMAL)
self.builder.get_object('Entry_num_files').delete(0, tk.END)
self.builder.get_object('Entry_num_files').insert(0, str(len(files_to_display)))
self.builder.get_object('Entry_num_files').config(state=tk.DISABLED)
def on_button_restore_clicked(self):
"""
Restore the original dataset using the Raw_obj for each analysis object requested.
Can be used to undo cropping, delta-dt, parameter changes, etc. Differs from reprocess
in that a NEW object is created, so any gaussian fitting/etc is reset in this method.
:return: void
"""
plot_keys = [x for x in self.params_obj.params_dict.keys() if 'smoothing' in x]
param_success, param_dict = self.run_param_ui('Initial Smoothing on Restored Data', plot_keys)
if param_success:
files_to_read = self.check_file_range_entries()
output_files = []
self.progress_started()
for analysis_file in files_to_read:
# load analysis obj and print params
analysis_obj = load_analysis_obj(analysis_file)
# update parameters and re-process raw data
try:
new_obj = Raw_Processing.process_raw_obj(analysis_obj.raw_obj, self.params_obj, short_filename=analysis_obj.short_filename)
except ValueError:
# all 0's in raw data - skip this file an notify the user
messagebox.showerror('Empty raw data file!', 'The raw data in file {} is empty (no intensity values > 0) and will NOT be loaded. Press OK to continue.'.format(analysis_obj.short_filename))
continue
# new_obj = process_raw_obj(analysis_obj.raw_obj, self.params_obj, short_filename=analysis_obj.short_filename)
filename = save_analysis_obj(new_obj, param_dict, outputdir=self.output_dir)
output_files.append(filename)
self.update_progress(files_to_read.index(analysis_file), len(files_to_read))
self.display_analysis_files(output_files)
self.progress_done()
def on_button_printparams_clicked(self):
"""
print parameters from selected files (or all files) to console
:return: void
"""
# Determine if a file range has been specified
files_to_read = self.check_file_range_entries()
for file in files_to_read:
# load analysis obj and print params
analysis_obj = load_analysis_obj(file)
print('\nParameters used in file {}:'.format(os.path.basename(file)))
analysis_obj.params.print_params_to_console()
def on_button_update_param_defaults_clicked(self):
"""
Update the default parameters (in the param info csv file) to be the current settings
in self.params_obj
:return: void
"""
CIU_Params.update_param_csv(self.params_obj, hard_params_file)
self.progress_done()
def check_file_range_entries(self):
"""
Check to see if user has entered a valid range in either of the file range entries
and return the range if so, or return the default range (all files) if not.
Note: subtracts 1 from file numbers because users count from 1, not 0
:return: sublist of self.analysis_file_list bounded by ranges
"""
try:
start_file = int(self.builder.get_object('Entry_start_files').get()) - 1
except ValueError:
# no number was entered or an invalid number - use default start location (0)
start_file = 0
try:
end_file = int(self.builder.get_object('Entry_end_files').get())
except ValueError:
end_file = len(self.analysis_file_list)
files_to_read = self.analysis_file_list[start_file: end_file]
return files_to_read
def on_button_changedir_clicked(self):
"""
Open a file chooser to change the output directory and update the display
:return: void
"""
newdir = filedialog.askdirectory()
if newdir == '':
# user hit cancel - don't set directory
return
self.output_dir = newdir
self.output_dir_override = True # stop changing directory on file load if the user has specified a directory
self.update_dir_entry()
def update_dir_entry(self):
"""
Update the graphical display of the output directory
:return: void
"""
self.builder.get_object('Text_outputdir').config(state=tk.NORMAL)
self.builder.get_object('Text_outputdir').delete(1.0, tk.INSERT)
self.builder.get_object('Text_outputdir').insert(tk.INSERT, self.output_dir)
self.builder.get_object('Text_outputdir').config(state=tk.DISABLED)
def run_param_ui(self, section_title, list_of_param_keys):
"""
Run the parameter UI for a given set of parameters.
:param section_title: Title to display on the popup parameter editing window (string)
:param list_of_param_keys: List of parameter keys. All values MUST be parameter names (as in
the __init__ method of the Parameters object.
:return: void
"""
list_of_param_keys = sorted(list_of_param_keys) # keep parameter keys in alphabetical order
param_ui = CIU_Params.ParamUI(section_name=section_title,
params_obj=self.params_obj,
key_list=list_of_param_keys,
param_descripts_file=hard_params_file)
param_ui.lift()
param_ui.grab_set() # prevent users from hitting multiple windows simultaneously
param_ui.wait_window()
param_ui.grab_release()
# Only update parameters if the user clicked 'okay' (didn't click cancel or close the window)
if param_ui.return_code == 0:
return_vals = param_ui.refresh_values()
self.params_obj.set_params(return_vals)
return True, return_vals
return False, None
def on_button_plot_options_clicked(self):
"""
Update parameters object with new plot options for all methods
:return: void
"""
plot_keys = [x for x in self.params_obj.params_dict.keys() if 'plot' in x and 'override' not in x]
self.run_param_ui('Plot parameters', plot_keys)
self.progress_done()
def on_button_oldplot_clicked(self):
"""
Run old CIU plot method to generate a plot in the output directory
:return: void (saves to output dir)
"""
plot_keys = [x for x in self.params_obj.params_dict.keys() if 'ciuplot_cmap_override' in x]
param_success, param_dict = self.run_param_ui('Plot parameters', plot_keys)
if param_success:
# Determine if a file range has been specified
files_to_read = self.check_file_range_entries()
self.progress_started()
updated_filelist = []
for analysis_file in files_to_read:
analysis_obj = load_analysis_obj(analysis_file)
Original_CIU.ciu_plot(analysis_obj, self.params_obj, self.output_dir)
self.update_progress(files_to_read.index(analysis_file), len(files_to_read))
# save analysis obj to ensure that parameter changes are noted correctly
filename = save_analysis_obj(analysis_obj, param_dict, outputdir=self.output_dir)
updated_filelist.append(filename)
self.display_analysis_files(updated_filelist)
self.progress_done()
def on_button_oldcompare_clicked(self):
"""
Run old (batched) RMSD-based CIU plot comparison on selected files
:return: void (saves to output dir)
"""
# Determine if a file range has been specified
files_to_read = self.check_file_range_entries()
self.progress_started()
if len(files_to_read) == 1:
# re-open filechooser to choose a list of files to compare to this standard
newfiles = self.open_files(filetype=[('CIU files', '.ciu')])
if len(newfiles) == 0:
return
# run parameter dialog for comparison
param_keys = [x for x in self.params_obj.params_dict.keys() if 'compare_' in x and 'batch' not in x]
param_success, param_dict = self.run_param_ui('Plot parameters', param_keys)
if param_success:
rmsd_print_list = ['File 1, File 2, RMSD (%)']
# load all files and check axes for comparison
std_file = files_to_read[0]
std_obj = load_analysis_obj(std_file)
compare_objs = [load_analysis_obj(file) for file in newfiles]
all_objs = [std_obj]
all_objs.extend(compare_objs)
check_axes_and_warn(all_objs)
# compare each CIU analysis object against the standard
index = 0
updated_filelist = []
for compare_obj in compare_objs:
rmsd = Original_CIU.compare_basic_raw(std_obj, compare_obj, self.params_obj, self.output_dir)
printstring = '{},{},{:.2f}'.format(std_obj.short_filename,
compare_obj.short_filename,
rmsd)
rmsd_print_list.append(printstring)
index += 1
self.update_progress(compare_objs.index(compare_obj), len(compare_objs))
# save analysis objs to ensure that parameter changes are noted correctly
for analysis_obj in all_objs:
filename = save_analysis_obj(analysis_obj, param_dict, outputdir=self.output_dir)
updated_filelist.append(filename)
with open(os.path.join(self.output_dir, 'batch_RMSDs.csv'), 'w') as rmsd_file:
for rmsd_string in rmsd_print_list:
rmsd_file.write(rmsd_string + '\n')
self.display_analysis_files(updated_filelist)
if len(files_to_read) == 2:
# Direct compare between two files
param_keys = [x for x in self.params_obj.params_dict.keys() if 'compare_' in x and 'batch' not in x]
param_success, param_dict = self.run_param_ui('Plot parameters', param_keys)
if param_success:
ciu1 = load_analysis_obj(files_to_read[0])
ciu2 = load_analysis_obj(files_to_read[1])
updated_obj_list = check_axes_and_warn([ciu1, ciu2])
Original_CIU.compare_basic_raw(updated_obj_list[0], updated_obj_list[1], self.params_obj, self.output_dir)
# save analysis objs to ensure that parameter changes are noted correctly
updated_filelist = []
for analysis_obj in updated_obj_list:
filename = save_analysis_obj(analysis_obj, param_dict, outputdir=self.output_dir)
updated_filelist.append(filename)
self.display_analysis_files(updated_filelist)
elif len(files_to_read) > 2:
param_keys = [x for x in self.params_obj.params_dict.keys() if 'compare_' in x]
param_success, param_dict = self.run_param_ui('Plot parameters', param_keys)
if param_success:
rmsd_print_list = ['File 1, File 2, RMSD (%)']
# batch compare - compare all against all.
f1_index = 0
loaded_files = [load_analysis_obj(x) for x in files_to_read]
loaded_files = check_axes_and_warn(loaded_files)
updated_filelist = []
for analysis_obj in loaded_files:
# don't compare the file against itself
skip_index = loaded_files.index(analysis_obj)
f2_index = 0
while f2_index < len(loaded_files):
# skip either comparisons to self or reverse and self comparisons depending on parameter
if self.params_obj.compare_batch_1_both_dirs:
if f2_index == skip_index:
f2_index += 1
continue
else:
# skip reverse and self comparisons
if f2_index >= f1_index:
f2_index += 1
continue
ciu1 = analysis_obj
ciu2 = loaded_files[f2_index]
rmsd = Original_CIU.compare_basic_raw(ciu1, ciu2, self.params_obj, self.output_dir)
printstring = '{},{},{:.2f}'.format(ciu1.short_filename, ciu2.short_filename, rmsd)
rmsd_print_list.append(printstring)
f2_index += 1
filename = save_analysis_obj(analysis_obj, param_dict, outputdir=self.output_dir)
updated_filelist.append(filename)
f1_index += 1
self.update_progress(loaded_files.index(analysis_obj), len(loaded_files))
self.display_analysis_files(updated_filelist)
# print output to csv
with open(os.path.join(self.output_dir, 'batch_RMSDs.csv'), 'w') as rmsd_file:
for rmsd_string in rmsd_print_list:
rmsd_file.write(rmsd_string + '\n')
self.progress_done()
def on_button_smoothing_clicked(self):
"""
Reprocess raw data with new smoothing (and interpolation?) parameters
:return: void
"""
param_keys = [x for x in self.params_obj.params_dict.keys() if 'smoothing' in x]
param_success, param_dict = self.run_param_ui('Smoothing Parameters', param_keys)
if param_success:
files_to_read = self.check_file_range_entries()
self.progress_started()
new_file_list = []
for file in files_to_read:
analysis_obj = load_analysis_obj(file)
analysis_obj = Raw_Processing.smooth_main(analysis_obj, self.params_obj)
analysis_obj.refresh_data()
filename = save_analysis_obj(analysis_obj, param_dict, outputdir=self.output_dir)
new_file_list.append(filename)
# also save _raw.csv output if desired
if self.params_obj.output_1_save_csv:
save_path = file.rstrip('.ciu') + '_delta_raw.csv'
Original_CIU.write_ciu_csv(save_path, analysis_obj.ciu_data, analysis_obj.axes)
self.update_progress(files_to_read.index(file), len(files_to_read))
self.display_analysis_files(new_file_list)
self.progress_done()
def on_button_oldavg_clicked(self):
"""
Average several processed files into a replicate object and save it for further
replicate processing methods
:return:
"""
# Determine if a file range has been specified
files_to_read = self.check_file_range_entries()
if len(files_to_read) < 2:
messagebox.showerror('Too Few Files', 'At least 2 files must be selected to Average')
return
self.progress_started()
# Check that axes are the same across objects
analysis_obj_list = [load_analysis_obj(x) for x in files_to_read]
analysis_obj_list = check_axes_and_warn(analysis_obj_list)
# Compute averaged CIU data and generate output plots
averaged_obj, std_data = Original_CIU.average_ciu(analysis_obj_list)
# Save averaged object as a .ciu file and write the new average Raw data to _raw.csv text file
averaged_obj.filename = save_analysis_obj(averaged_obj, {}, self.output_dir)
averaged_obj.short_filename = os.path.basename(averaged_obj.filename).rstrip('.ciu')
avg_raw_path = os.path.join(self.output_dir, averaged_obj.raw_obj.filename)
Original_CIU.write_ciu_csv(avg_raw_path, averaged_obj.raw_obj.rawdata, [averaged_obj.raw_obj.dt_axis, averaged_obj.raw_obj.cv_axis])
# plot averaged object and standard deviation and save output average CSV file
pairwise_rmsds, rmsd_strings = Original_CIU.get_pairwise_rmsds(analysis_obj_list, self.params_obj)
Original_CIU.ciu_plot(averaged_obj, self.params_obj, self.output_dir)
Original_CIU.std_dev_plot(averaged_obj, std_data, pairwise_rmsds, self.params_obj, self.output_dir)
Original_CIU.save_avg_rmsd_data(analysis_obj_list, self.params_obj, averaged_obj.short_filename, self.output_dir)
self.display_analysis_files([averaged_obj.filename])
self.progress_done()
def on_button_crop_clicked(self):
"""
Open a dialog to ask user for crop inputs, then crop selected data accordingly.
NOTE: preserves parameters from original object, as no changes have been made here
:return: saves new .ciu files
"""
# run the cropping UI
if len(self.analysis_file_list) > 0:
# check axes for equality and interpolate if different
files_to_read = self.check_file_range_entries()
loaded_files = [load_analysis_obj(x) for x in files_to_read]
# Warn user if any files have features or Gaussians, as these will be erased by cropping
warned_yet_flag = False
for quick_obj in loaded_files:
if quick_obj.features_changept is not None or quick_obj.raw_protein_gaussians is not None or quick_obj.features_gaussian is not None:
if not warned_yet_flag:
messagebox.showwarning('Processing Results will be Erased', 'All processing results (feature detection, Gaussian fitting, etc.) are erased when cropping files to prevent axes errors. If you do not want this, press cancel on the next screen.')
warned_yet_flag = True
crop_vals = Raw_Processing.run_crop_ui(loaded_files[0].axes, hard_crop_ui)
if crop_vals is None:
# user hit cancel, or no values were provided
self.progress_done()
return
self.progress_started()
new_file_list = []
# for file in files_to_read:
for analysis_obj in loaded_files:
new_obj = Raw_Processing.crop(analysis_obj, crop_vals)
new_obj.refresh_data()
new_obj.crop_vals = crop_vals
newfile = save_analysis_obj(new_obj, {}, outputdir=self.output_dir)
new_file_list.append(newfile)
self.update_progress(loaded_files.index(analysis_obj), len(loaded_files))
self.display_analysis_files(new_file_list)
else:
messagebox.showwarning('No Files Selected', 'Please select files before performing cropping/interpolation')
self.progress_done()
def on_button_interpolate_clicked(self):
"""
Perform interpolation of data onto new axes using user provided parameters. Overwrites
existing objects with new objects containing new data and axes to prevent unstable
behavior if old values (e.g. features) were used after interpolation.
:return: void
"""
if len(self.analysis_file_list) > 0:
# Warn user if any files have features or Gaussians, as these will be erased by cropping
files_to_read = self.check_file_range_entries()
loaded_files = [load_analysis_obj(x) for x in files_to_read]
warned_yet_flag = False
for quick_obj in loaded_files:
if quick_obj.features_changept is not None or quick_obj.raw_protein_gaussians is not None or quick_obj.features_gaussian is not None:
if not warned_yet_flag:
messagebox.showwarning('Processing Results will be Erased', 'All processing results (feature detection, Gaussian fitting, etc.) are erased when cropping files to prevent axes errors. If you do not want this, press cancel on the next screen.')
warned_yet_flag = True
# interpolation parameters
param_keys = [x for x in self.params_obj.params_dict.keys() if 'interpolate' in x]
param_success, param_dict = self.run_param_ui('Interpolation Parameters', param_keys)
if param_success:
self.progress_started()
# determine which axis to interpolate
if self.params_obj.interpolate_1_axis == 'collision voltage':
interp_cv = True
interp_dt = False
elif self.params_obj.interpolate_1_axis == 'drift time':
interp_cv = False
interp_dt = True
else:
interp_cv = True
interp_dt = True
new_file_list = []
for file in files_to_read:
analysis_obj = load_analysis_obj(file)
# Restore the original data and interpolate from that to ensure constant level of interpolation
try:
new_obj = Raw_Processing.process_raw_obj(analysis_obj.raw_obj, self.params_obj,
short_filename=analysis_obj.short_filename)
except ValueError:
# all 0's in raw data - skip this file an notify the user
messagebox.showerror('Empty raw data file!',
'The raw data in file {} is empty (no intensity values > 0) and will NOT be loaded. Press OK to continue.'.format(
analysis_obj.short_filename))
continue
# compute new axes
new_axes = Raw_Processing.compute_new_axes(old_axes=new_obj.axes, interpolation_scaling=int(self.params_obj.interpolate_2_scaling), interp_cv=interp_cv, interp_dt=interp_dt)
if not self.params_obj.interpolate_3_onedim:
new_obj = Raw_Processing.interpolate_axes(new_obj, new_axes)
else:
# 1D interpolation mode, pass the correct axis to 1D interp method
if interp_dt:
new_obj = Raw_Processing.interpolate_axis_1d(new_obj, interp_dt, new_axes[0])
elif interp_cv:
new_obj = Raw_Processing.interpolate_axis_1d(new_obj, interp_dt, new_axes[1])
else:
messagebox.showerror('Invalid Mode', '1D interpolation can only be performed on one axis at a time. Please select 2D interpolation for both axes or select a single axis for 1D interpolation.')
break
# create a new analysis object to prevent unstable behavior with new axes
interp_obj = CIUAnalysisObj(new_obj.raw_obj, new_obj.ciu_data, new_obj.axes, self.params_obj, short_filename=new_obj.short_filename)
filename = save_analysis_obj(interp_obj, param_dict, outputdir=self.output_dir)
new_file_list.append(filename)
self.update_progress(files_to_read.index(file), len(files_to_read))
self.display_analysis_files(new_file_list)
else:
messagebox.showwarning('No Files Selected',
'Please select files before performing cropping/interpolation')
self.progress_done()
def on_button_gaussfit_clicked(self):
"""
Run Gaussian fitting on the analysis object list (updating the objects and leaving
the current list in place). Saves Gaussian diagnostics/info to file in self.output_dir
:return: void
"""
# Ask user to specify protein or nonprotein mode
t1_param_keys = [x for x in self.params_obj.params_dict.keys() if 'gauss_t1' in x]
t1_param_success, t1_param_dict = self.run_param_ui('Gaussian Fitting Mode', t1_param_keys)
if t1_param_success:
# Determine parameters for appropriate mode
if self.params_obj.gauss_t1_1_protein_mode:
t2_param_keys = [x for x in self.params_obj.params_dict.keys() if ('gaussian' in x and '_nonprot_' not in x)]
else:
t2_param_keys = [x for x in self.params_obj.params_dict.keys() if 'gaussian' in x]
# Finally, run feature detection in the appropriate mode
t2_param_success, t2_param_dict = self.run_param_ui('Gaussian Fitting Parameters', t2_param_keys)
if t2_param_success:
# Determine if a file range has been specified
files_to_read = self.check_file_range_entries()
self.progress_started()
logger.info('\n**** Starting Gaussian Fitting - THIS MAY TAKE SOME TIME - CIUSuite 2 will not respond until fitting is completed ****')
new_file_list = []
all_output = ''
all_file_gaussians = []
gauss_filenames = []
ciu_objs = []
for file in files_to_read:
analysis_obj = load_analysis_obj(file)
ciu_objs.append(analysis_obj)
# analysis_obj, csv_output, cv_gaussians = Gaussian_Fitting.main_gaussian_lmfit(analysis_obj, self.params_obj, self.output_dir)
# all_output += csv_output
# all_file_gaussians.append(cv_gaussians)
gauss_filenames.append(analysis_obj.short_filename)
ciu_objs, all_output, all_file_gaussians = Gaussian_Fitting.main_gaussian_lmfit_wrapper(ciu_objs, self.params_obj, self.output_dir)
for analysis_obj in ciu_objs:
t2_param_dict.update(t1_param_dict)
filename = save_analysis_obj(analysis_obj, t2_param_dict, outputdir=self.output_dir)
new_file_list.append(filename)
self.update_progress(ciu_objs.index(analysis_obj), len(ciu_objs))
if self.params_obj.gaussian_5_combine_outputs:
outputpath = os.path.join(self.output_dir, 'All_gaussians.csv')
all_output_append = Gaussian_Fitting.print_combined_params(all_file_gaussians, gauss_filenames)
all_output += all_output_append
try:
with open(outputpath, 'w') as output:
output.write(all_output)
except PermissionError:
messagebox.showerror('Please Close the File Before Saving',
'The file {} is being used by another process! Please close it, THEN press the OK button to retry saving'.format(
outputpath))
with open(os.path.join(outputpath, outputpath), 'w') as output:
output.write(all_output)
self.display_analysis_files(new_file_list)
# prompt the user to run feature detection in Gaussian mode
# if len(files_to_read) > 0:
# messagebox.showinfo('Success!', 'Gaussing fitting finished successfully. Please run Feature Detection in "gaussian" mode to finalize Gaussian assignments to features (this is required for CIU50 analysis, classification, and reconstruction).')
self.progress_done()
def on_button_gaussian_reconstruct_clicked(self):
"""
Create a new CIUAnalysisObj from the fitted Gaussians of selected objects. Must
have Gaussian feature detection already performed.
:return: void
"""
param_keys = [x for x in self.params_obj.params_dict.keys() if 'reconstruct' in x]
param_success, param_dict = self.run_param_ui('Gaussian Reconstruction Parameters', param_keys)
if param_success:
files_to_read = self.check_file_range_entries()
self.progress_started()
new_file_list = []
# If reading in Gaussians from template, load template files and construct Gaussians from provided information
if self.params_obj.reconstruct_1_mode == 'Load File':
template_files = filedialog.askopenfilenames(filetypes=[('Gaussian Fit CSV', '.csv')])
if len(template_files) > 0:
self.output_dir = os.path.dirname(template_files[0])
for template_file in template_files:
# load Gaussian information and generate a CIUAnalysisObj
gaussians_by_cv, axes = Gaussian_Fitting.parse_gaussian_list_from_file(template_file)
new_analysis_obj = Gaussian_Fitting.reconstruct_from_fits(gaussians_by_cv, axes, os.path.basename(template_file).rstrip('.csv'), self.params_obj)
filename = save_analysis_obj(new_analysis_obj, param_dict, outputdir=self.output_dir)
# also save an _raw.csv file with the generated data
Original_CIU.write_ciu_csv(os.path.join(self.output_dir, new_analysis_obj.short_filename + '_raw.csv'),
new_analysis_obj.ciu_data,
new_analysis_obj.axes)
new_file_list.append(filename)
self.update_progress(template_files.index(template_file), len(template_files))
else:
# use loaded .ciu files and read from the Gaussian fitting/feature detection results
for file in files_to_read:
# load file
analysis_obj = load_analysis_obj(file)
# check to make sure the analysis_obj has Gaussian data fitted
if analysis_obj.feat_protein_gaussians is None:
messagebox.showerror('Gaussian feature detection required', 'Data in file {} does not have Gaussian feature detection performed. Please run Gaussian feature detection, then try again.')
break
# If gaussian data exists, perform the analysis
final_gausslists, final_axes = Gaussian_Fitting.check_recon_for_crop(analysis_obj.feat_protein_gaussians, analysis_obj.axes)
# Save a new analysis object constructed from the fits. NOTE: saves previous objects parameter information for reference
new_obj = Gaussian_Fitting.reconstruct_from_fits(final_gausslists, final_axes, analysis_obj.short_filename, analysis_obj.params)
filename = save_analysis_obj(new_obj, param_dict, outputdir=self.output_dir)
# also save an _raw.csv file with the generated data
Original_CIU.write_ciu_csv(os.path.join(self.output_dir, new_obj.short_filename + '_raw.csv'),
new_obj.ciu_data,
new_obj.axes)
new_file_list.append(filename)
self.update_progress(files_to_read.index(file), len(files_to_read))
self.display_analysis_files(new_file_list)
self.progress_done()
def on_button_feature_detect_clicked(self):
"""
Run feature detection routine.
:return: void
"""
# Ask user to specify standard or Gaussian mode
t1_param_keys = [x for x in self.params_obj.params_dict.keys() if 'feature_t1' in x]
t1_param_success, t1_param_dict = self.run_param_ui('Feature Detection Mode', t1_param_keys)
if t1_param_success:
# Determine feature detection parameters for appropriate mode
if self.params_obj.feature_t1_1_ciu50_mode == 'standard':
t2_param_keys = [x for x in self.params_obj.params_dict.keys() if ('feature_t2' in x and '_gauss_' not in x)]
else:
t2_param_keys = [x for x in self.params_obj.params_dict.keys() if 'feature_t2' in x]
# Finally, run feature detection in the appropriate mode
t2_param_success, t2_param_dict = self.run_param_ui('Feature Detection Parameters', t2_param_keys)
if t2_param_success:
t2_param_dict.update(t1_param_dict)
files_to_read = self.check_file_range_entries()
self.progress_started()
new_file_list = []
all_outputs = 'Filename,Features Detected\n'
for file in files_to_read:
# load file
analysis_obj = load_analysis_obj(file)
if self.params_obj.feature_t1_1_ciu50_mode == 'gaussian':
# GAUSSIAN MODE
# check to make sure the analysis_obj has Gaussian data fitted if needed
if analysis_obj.raw_protein_gaussians is None:
messagebox.showwarning('Gaussian fitting required', 'Data in file {} does not have Gaussian fitting'
'performed. Please run Gaussian fitting, then try '
'again.'.format(analysis_obj.short_filename))
break
# Detect features in the appropriate mode
try:
analysis_obj = Feature_Detection.feature_detect_gaussians(analysis_obj, self.params_obj)
except ValueError:
messagebox.showerror('Uneven CV Axis', 'Error: Activation axis in file {} was not evenly spaced. Please use the "Interpolate Data" button to generate an evenly spaced axis. If using Gaussian fitting mode, Gaussian fitting MUST be redone after interpolation.'.format(analysis_obj.short_filename))
continue
features_list = analysis_obj.features_gaussian
filename = save_analysis_obj(analysis_obj, t2_param_dict, outputdir=self.output_dir)
new_file_list.append(filename)
else:
# STANDARD MODE
analysis_obj = Feature_Detection.feature_detect_col_max(analysis_obj, self.params_obj)
features_list = analysis_obj.features_changept
filename = save_analysis_obj(analysis_obj, t2_param_dict, outputdir=self.output_dir)
new_file_list.append(filename)
# save output
Feature_Detection.plot_features(features_list, analysis_obj, self.params_obj, self.output_dir)
outputpath = os.path.join(self.output_dir, analysis_obj.short_filename + '_features.csv')
if self.params_obj.feature_t2_6_ciu50_combine_outputs:
all_outputs += analysis_obj.short_filename
all_outputs += Feature_Detection.print_features_list(features_list, outputpath, mode=self.params_obj.feature_t1_1_ciu50_mode, combine=True)
else:
Feature_Detection.print_features_list(features_list, outputpath,
mode=self.params_obj.feature_t1_1_ciu50_mode, combine=False)
self.update_progress(files_to_read.index(file), len(files_to_read))
if self.params_obj.feature_t2_6_ciu50_combine_outputs:
outputpath = os.path.join(self.output_dir, '_all-features.csv')
save_existing_output_string(outputpath, all_outputs)
self.display_analysis_files(new_file_list)
self.progress_done()
def on_button_ciu50_clicked(self):
"""
Run feature detection workflow to generate CIU-50 (transition) outputs for selected
files
:return: void
"""
# Ask user to specify standard or Gaussian mode
t1_param_keys = [x for x in self.params_obj.params_dict.keys() if ('_t1_' in x and '_ciu50_' in x)]
t1_param_success, t1_param_dict = self.run_param_ui('CIU50 Mode', t1_param_keys)
if t1_param_success:
# Determine feature detection parameters for appropriate mode
if self.params_obj.feature_t1_1_ciu50_mode == 'standard':
t2_param_keys = [x for x in self.params_obj.params_dict.keys() if
('ciu50' in x and '_t2_' in x and '_gauss_' not in x)]
else:
t2_param_keys = [x for x in self.params_obj.params_dict.keys() if ('ciu50' in x and '_t2_' in x)]
# Finally, run analysis in the appropriate mode
t2_param_success, t2_param_dict = self.run_param_ui('CIU50 Parameters', t2_param_keys)
if t2_param_success:
t2_param_dict.update(t1_param_dict)
files_to_read = self.check_file_range_entries()
self.progress_started()
new_file_list = []
all_outputs = ''
short_outputs = 'Filename,CIU50 1,CIU50 2,(etc)\n'
filename = ''
combine_flag = False
gaussian_bool = False
if self.params_obj.feature_t1_1_ciu50_mode == 'gaussian':
gaussian_bool = True
for file in files_to_read:
# load file
analysis_obj = load_analysis_obj(file)
# Ensure features are detected for this file
feature_list = analysis_obj.get_features(gaussian_bool)
if feature_list is None:
# returning False means features aren't detected for the selected mode. Warn user
messagebox.showerror('No Features in File {}'.format(analysis_obj.short_filename),
message='Feature Detection has not been performed in {} mode for file {}. Please '
'perform feature detection before CIU50 analysis.'.format(self.params_obj.feature_t1_1_ciu50_mode, analysis_obj.short_filename))
continue
# run CIU50 analysis
analysis_obj = Feature_Detection.ciu50_main(feature_list, analysis_obj, self.params_obj, outputdir=self.output_dir, gaussian_bool=gaussian_bool)
filename = save_analysis_obj(analysis_obj, t2_param_dict, outputdir=self.output_dir)
new_file_list.append(filename)
# save outputs to file in combined or stand-alone modes
if not self.params_obj.feature_t2_6_ciu50_combine_outputs:
Feature_Detection.save_ciu50_outputs(analysis_obj, self.output_dir)
Feature_Detection.save_ciu50_short(analysis_obj, self.output_dir)
combine_flag = False
else:
file_string = os.path.basename(filename).rstrip('.ciu') + '\n'
all_outputs += file_string
all_outputs += Feature_Detection.save_ciu50_outputs(analysis_obj, self.output_dir, combine=True)
short_outputs += os.path.basename(filename).rstrip('.ciu')
short_outputs += Feature_Detection.save_ciu50_short(analysis_obj, self.output_dir, combine=True)
combine_flag = True
self.update_progress(files_to_read.index(file), len(files_to_read))
if combine_flag:
# save final combined output
outputpath = os.path.join(self.output_dir, os.path.basename(filename.rstrip('.ciu')) + '_ciu50s.csv')
outputpath_short = os.path.join(self.output_dir, os.path.basename(filename.rstrip('.ciu')) + '_ciu50-short.csv')
save_existing_output_string(outputpath, all_outputs)
save_existing_output_string(outputpath_short, short_outputs)