GUI_sortem.py 16.3 KB
Newer Older
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

from dearpygui.dearpygui import *
from os.path import isfile
#from execute_sortem import control_flow
import csv
from os import mkdir
from os.path import isdir,join
import subprocess

file_list = []

def callback(sender, app_data):
    paths = list(list(app_data.values())[-1].values())
 
    set_value('directories',value=' '.join(paths))


def slurm_callback(sender, app_data):
    paths = list(list(app_data.values())[-1].values())
 
    set_value('slurms',value=' '.join(paths))

def run_sortem():
    output_dir = str(get_value('OD'))
    slurm  = str(get_value('slurm'))


    num_parts  = int(get_value('nc'))
    f16        = bool(get_value('f16'))
    num_gpus   = int(get_value('num_gpus'))
    num_cpus   = int(get_value('num_cpus'))
    batch_size = int(get_value('batch_size'))
    save_model = int(get_value('sme'))
    if '.star' not in get_value('directories'):
       return print("you need to give a star file")

    star       =    str(get_value('directories'))
    p_batch_size =  int(get_value('batch_size'))
    steps =             get_value('s1to4')
    gpu_list = get_value('gpu_list').split(',')

    start_disc,end_disc,_,_ =     get_value('dval')
    start_gen,end_gen,_,_ =       get_value('gval')
    dstep               =         get_value('dstep')
    top_off         =           get_value('s5')
    if '' in gpu_list:
        gpu_list = None
    feature_size = get_value('feat_size')
    movies = get_value('pd')
    l_reg = get_value('nf')
    over_cluster = get_value('oc')
    start_disc = 10**(-start_disc)   
    end_disc = 10**(-end_disc)   
    start_gen = 10**(-start_gen)    
    end_gen = 10**(-end_gen)  
    s1,s2,s3,s4 = get_value('s1to4')
    noise = bool(get_value('noise'))
    ctf = bool(get_value('ctf'))
    vi = int(get_value('vi'))
    verbose = bool(get_value('record'))
    if not isdir(output_dir):
            mkdir(output_dir)
    if not isdir(join(output_dir,'tmp')):
            mkdir(join(output_dir,'tmp'))
    if not isdir(join(output_dir,'model')):
            mkdir(join(output_dir,'model'))
    if not isdir(join(output_dir,'results')):
            mkdir(join(output_dir,'results'))
    if not isdir(join(output_dir,'best_model')):
            mkdir(join(output_dir,'best_model'))
    model_list = []
    for i in range(num_parts):
        if not isdir(join(join(output_dir,'results'),'model_%i' %i)):
            mkdir(join(join(output_dir,'results'),'model_%i' %i))
        model_list.append(join(join(output_dir,'results'),'model_%i' %i))


    ds = '--num_gpus %i ' %num_gpus
    ds += '--num_cpus %i ' %num_cpus
    ds += '--star %s ' %star
    ds += '--batch_size %s ' %batch_size
    ds += '--p_batch_size %s ' %p_batch_size
    ds += '--o %s ' %output_dir
    if f16:
        ds += '--f16 '
    ds += '--vi %i ' %vi
    ds += '--movie_int %i ' %movies
    ds += '--save_model %i ' %save_model
    if verbose:
      ds +='--verbose '
    ds +='--num_parts %i ' %num_parts
    ds +='--lr_b_g %f ' %start_gen
    ds +='--lr_b_d %f ' %start_disc
    ds +='--lr_e_g %f ' %end_gen
    ds +='--lr_e_d %f ' %end_disc
    if ctf:
        ds +='--ctf '
    if noise:
        ds +='--noise '
    ds +='--dstep %i ' %dstep
    ds +='--s_1_steps %i ' %s1
    ds +='--s_2_steps %i ' %s2
    ds +='--s_3_steps %i ' %s3
    ds +='--s_4_steps %i ' %s4
    ds +='--top_off %i ' %top_off
    ds +='--l_reg %f ' %l_reg
    ds +='--feature_size %i ' %feature_size
    if over_cluster:
        ds +='--over_cluster '

    noise_bg = bool(get_value('noise_bg'))
    seg_mode = bool(get_value('seg_mode'))
    no_gen = bool(get_value('no_gen'))
    TD_mod = int(get_value('2D_mode'))
    Only_VAE = bool(get_value('Only_VAE'))
    if  noise_bg:
               ds +='--noise_bg '
    if  seg_mode:
               ds +='--seg_mode '
    if  no_gen:
               ds +='--no_gen '
    if  TD_mod:
               ds +='--2D_mode '
    if Only_VAE:
               ds +='--Only_VAE'


    ds = list(filter(lambda x: x !='',ds.split(' ')))        
 
    if isfile(slurm):
        with open('path/to/csv_file', 'w') as f:
            writer = csv.writer(f)
            writer.writerow(['#!/bin/bash'])
            writer.writerow(['#SBATCH -p gpu'])
            writer.writerow(['#SBATCH -o run.log'])
            writer.writerow(['#SBATCH --mem=32G'])
            writer.writerow(['python3 %s ' %ds])
            # create the csv writer
            #!/bin/bash
Jonathan Juhl's avatar
Jonathan Juhl committed
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
  
        subprocess.run('bash %s ' %slurm)
    else:   
       
        subprocess.call(['python3','main_sortem.py']+ds)
  

with file_dialog(directory_selector=False, show=False, callback=callback, id="file_dialog_id",file_count =100):
        add_file_extension(".star", color=(255, 255, 255, 255))

with file_dialog(directory_selector=False, show=False, callback=slurm_callback, id="slurm_dialog_id"):
        add_file_extension(".sh", color=(255, 255, 255, 255))

with window(label="Sortem",width=800, height=500):

    with tab_bar(label='Parameters'):
        
        with tab(label='Required Parameters'):


              add_button(label="Select star files", callback=lambda: show_item("file_dialog_id"),id='star')
              add_same_line()
              add_button(label="Slurm file", callback=lambda: show_item("slurm_dialog_id"),id='slurm')
              add_text('',id='directories') 
              add_same_line() 
              add_text('',id='slurms')  
              add_slider_int(label='Number of clusters',min_value=2,max_value=100,default_value=2,id='nc')
              add_button(label="Run", callback=run_sortem,id='run')

        with tab(label='Advanced Parameters'):

            add_checkbox(label="Use half precision",id='f16')
            add_same_line()
            add_checkbox(label="Apply CTF",id='ctf')
            add_same_line()
            add_checkbox(label="Apply noise",id='noise')
            add_same_line()
            add_checkbox(label="Record labels",id='record')
            add_same_line()
            add_checkbox(label="Over Cluster",id='oc')
            add_input_text(label="GPU list",id='gpu_list')
            add_input_text(label="Output Directory",id='OD',default_value ='results')
            add_slider_int(label='Batch Size',min_value=25,max_value=500,default_value=100,id='batch_size')
            add_slider_int(label='Prediction Batch Size',min_value=100,max_value=500,default_value=100,id='p_batch_size')
            add_slider_int(label='Number of GPUs',min_value=1,max_value=8,default_value=1,id='num_gpus')
            add_slider_int(label='Number of CPUs',min_value=1,max_value=42,default_value=8,id='num_cpus')
            add_slider_int(label='feature size',min_value=128,max_value=256,default_value=128,id='feat_size')
            add_slider_int(label='Save Model every ',min_value=100,max_value=1000,default_value=100,id='sme')
            add_slider_int(label='validation every ',min_value=100,max_value=1000,default_value=100,id='vi')
            add_slider_int(label='Show protein dynamics every ',min_value=100,max_value=1000,default_value=100,id='pd')
            add_slider_int(label='Number of frames, each axis',min_value=2,max_value=20,default_value=10,id='dstep')
            add_slider_float(label='Noise Contribution Factor',min_value=0.001,max_value=0.1,default_value=0.01,id='nf')
            add_slider_intx(label='Steps 1-4',min_value =1000,max_value=10000,default_value=(1000,1000,1000,1000),id='s1to4')
            add_slider_int(label='top off',min_value=1000,max_value=100000,default_value=2000,id='s5')
            add_slider_intx(label='Discriminator lr start/final',min_value=10,max_value=1,default_value=(6,5),id='dval',size=2)
            add_slider_intx(label='Generator lr start/final',min_value=10,max_value=1,default_value=(5,4),id='gval',size=2)


            add_checkbox(label="Classical Noise",id='noise_bg')
            add_same_line()
            add_checkbox(label="Segmentation",id='seg_mode')
            add_same_line()
            add_checkbox(label="Apply noise",id='noise')
            add_same_line()
            add_checkbox(label="Use a 3D voxel matrix",id='no_gen')
            add_checkbox(label="2D Classification ",id='2D_mode')
            add_same_line()
            add_checkbox(label="Only use VAE",id='Only_VAE')
            add_same_line()
            add_checkbox(label="We do not estimate the projection orientation",id='NO_Angels')

    # tool tips
    with tooltip('gpu_list'):
        add_text("You can specify which GPU devices you wish to use by GPU:X where X is the device")
  
    with tooltip('record'):
        add_text("To estimate how well the NN is at clustering with respect to the _rlnClass")
  
    with tooltip('oc'):
        add_text("If you are overestimating the number of true clusters, the clusters will merge by the sparse watersheed algorithm.")
    
    with tooltip('slurm'):
        add_text("If you want to run on slurm you can upload a slurm premade file which contains the overall slurm parameters.")
    with tooltip('nc'):
        add_text("The number of gaussian mixture models.")
    with tooltip('star'):
        add_text("The required input star file.")

    with tooltip('noise'):
        add_text("is their poisson noise in the image?")
    with tooltip('OD'):
        add_text("The output directory. As default is results")
    with tooltip('f16'):
        add_text("Run the model in half precision.")
    with tooltip('ctf'):
        add_text("The image contains microscope defects ")
    with tooltip('batch_size'):
        add_text("the batch size used for training the model. ")
    with tooltip('p_batch_size'):
        add_text("the batch size used for inference. ")
    with tooltip('num_gpus'):
        add_text("The number of graphic cards to use. ")
    with tooltip('num_cpus'):
        add_text("The number of cpus used to feed the images into the GPU. ")
    with tooltip('feat_size'):
        add_text('The input vector size into the generator to build the 3D density map')
    with tooltip('s1to4'):
        add_text('The number of steps for each image size 32 x 32, 64 x 64 , 128 x 128 and 256 x 256')
    with tooltip('s5'):
        add_text('The number of training steps for the final stage of training.')
    with tooltip('sme'):
        add_text('Save the deep learning model every x step. When the usuer restarts the training or does inference the model will only train the remaining steps.')
    with tooltip('vi'):
        add_text('Validation intervals. The number of steps before the GUI is updated and the results are streamed to Tensorboard')
    with tooltip('dstep'):
        add_text('Number of frames over each axis for the umap reduced dimensions ')
    with tooltip('pd'):
        add_text('Show a density map dynamic series for each x step')
    with tooltip('nf'):
        add_text('The noise scale parameter')

    with tooltip('dval'):
        add_text('The learning rate power of start of the training and the end for the discriminator')
    with tooltip('gval'):
        add_text('The learning rate power of start of the training and the end for the generator')
    with tooltip('seg_mode'):
        add_text('Run segmentation mode. This will run the segmentation algoritm which segments the 3D components')
    with tooltip('noise_bg'):
        add_text('Use classical methods to estimate background noise')
    with tooltip('no_gen'):
        add_text('Do not use the generator to generate the 3D model. Instead use a 3D grid of variables. This is for a single particle classification only.')
    with tooltip('2D_mode'):
        add_text('The algorithm convers to a 2D classification with variability.')
    with tooltip('Only_VAE'):
        add_text('If you only wish to use the variational part, saves time but generally the resolution is lower and the noise generator can not be used, instead we use the classical noise maker.')
    with tooltip('No_Angels'):
        add_text('The program is run without any projection angle estimation. It can only be done if the generator is present')
            
                    
            

def update_plot_values():
    
            reconstruction_loss = np.load(join(self.args['results'],'reconstruction_loss'))
            step = np.arange(reconstruction_loss.shape[0])
            angle_loss = np.load(join(self.args['results'],'angle_loss'))
            discriminator_loss = np.load(join(self.args['results'],'discriminator_loss'))
            gen_loss = np.load(join(self.args['results'],'gen_loss'))
            KL_loss = np.load(join(self.args['results'],'KL_loss'))
            trans_loss = np.load(join(self.args['results'],'trans_loss'))
            feature_loss = np.load(join(self.args['results'],'feature_loss'))
            noise_loss = np.load(join(self.args['results'],'noise_loss'))
            x = np.arange(step)
            a_1 = np.load(join(self.args['results'],'angle_1_step_%s' %step))
            a_2 =np.load(join(self.args['results'],'angle_2_step_%s'%step))
            a_3 =np.load(join(self.args['results'],'angle_3_step_%s'%step))
            t_1 =np.load(join(self.args['results'],'translations_1_step_%s'%step))
            t_2 =np.load(join(self.args['results'],'translations_2_step_%s'%step))
            set_value("Angle_2_1", [a_1[:,0], a_1[:,1]])
            set_value("Angle_3_2", [a_2[:,0], a_2[:,1]])
            set_value("Angle_3_1", [a_3[:,0], a_3[:,1]])
            set_value("trans'", [t_1, t_2])

            set_value("rec_loss", [step,reconstruction_loss])
            set_value("ang_loss", [step, angle_loss])
            set_value("disc_loss", [step,discriminator_loss])
            set_value("trans_loss", [step, trans_loss])
            set_value("KL_loss", [step, KL_loss])
            set_value("feature_loss", [step, feature_loss])
            set_value("noise_loss", [step, noise_loss])
            set_value("gen_loss", [step, gen_loss])

with window(label="Results",pos=(800,0),width=800,height=400) as window2:
      add_text("Outputs and the current step will be shown here when the algorithm is run")
        with plot(label="Angular Distribution", height=-1, width=-1):
            add_plot_axis(mvYAxis, label="Degrees", id="yaxis")
            set_axis_limits("yaxis", 0,360)
            add_plot_axis(mvXAxis, label="Degrees", id="xaxis")
            set_axis_limits("xaxis", 0,360)
            add_2d_histogram_series([],[],label='Angle 2-1',id='Angle_2_1', parent="yaxis")
            add_2d_histogram_series([],[],label='Angle 3-2',id='Angle_3_2', parent="yaxis")
            add_2d_histogram_series([],[],label='Angle 3-1',id='Angle_3_1', parent="yaxis")
       
        with plot(label="Translational Distribution", height=-1, width=-1):
            add_plot_axis(mvYAxis, label="Translastions", id="yaxis")
            set_axis_limits("yaxis", -1,1)
            add_plot_axis(mvXAxis, label="Translastions", id="xaxis")
            set_axis_limits("xaxis", -1,1)
            add_2d_histogram_series([],[],label='Translastions',id='trans')
            
        with plot(label="Reconstruction Loss", height=-1, width=-1):  
            add_plot_axis(mvYAxis, label="Loss", id="yaxis")     
            add_scatter_series([],[],id='rec_loss')

        with plot(label="Angular  Loss", height=-1, width=-1):  
            add_plot_axis(mvYAxis, label="Loss", id="yaxis")     
            add_scatter_series([],[],id='ang_loss')
        with plot(label="Discriminator  Loss", height=-1, width=-1):  
            add_plot_axis(mvYAxis, label="Loss", id="yaxis")     
            add_scatter_series([],[],id='disc_loss')
        with plot(label="Kullbach Liebler Loss", height=-1, width=-1):  
            add_plot_axis(mvYAxis, label="Loss", id="yaxis")     
            add_scatter_series([],[],id='KL_loss')
        with plot(label="Generator Loss", height=-1, width=-1):  
            add_plot_axis(mvYAxis, label="Loss", id="yaxis")     
            add_scatter_series([],[],id='gen_loss')
        with plot(label="Translational Loss", height=-1, width=-1):  
            add_plot_axis(mvYAxis, label="Loss", id="yaxis")     
            add_scatter_series([],[],id='gen_loss')
        with plot(label='Generator Loss
            add_scatter_series([],[],label='Generator Loss',id='gen_loss')

        add_scatter_series([],[],label='Kullbach Liebler Loss',id='KL_loss')
        add_scatter_series([],[],label='Translational Loss',id='trans_loss')
        add_scatter_series([],[],label='Feature Loss',id='feature_loss')
        add_scatter_series([],[],label='Noise Loss',id='noise_loss')
        with plot(label="Translational Loss", height=-1, width=-1):  
setup_viewport()
start_dearpygui()