-
Notifications
You must be signed in to change notification settings - Fork 2
/
relion_fixed_it.py
2164 lines (1769 loc) · 108 KB
/
relion_fixed_it.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
#!/usr/bin/env python2.7
"""
relion_it.py
============
Script for automated, on-the-fly single-particle analysis in RELION 3
Authors: Sjors H.W. Scheres, Takanori Nakane & Colin M. Palmer
Usage:
relion_it.py [extra_options.py [extra_options2.py ....] ] [--gui] [--continue]
To get started, go to the intended location of your RELION project directory and make sure your micrographs are
accessible from within it (e.g. in a subdirectory called `Movies/' - use a symlink if necessary). Then run this
script, providing the names of files containing options if needed. (To call the script, you'll need to enter the full
path to it, put the directory containing it on your PATH environment variable, or put a copy of the script in the
current directory.)
Run with the `--gui' option to launch a simple GUI which will set up a run from a few basic options. (The GUI can
also be used to save a complete options file that you can then edit as required.)
Once the script is running, open a normal RELION GUI to see what's happening and visualise the results.
See below for full instructions including how to handle errors. If you have any problems, please edit the script as
needed, call on your local Python expert or email the CCP-EM mailing list (https://www.jiscmail.ac.uk/ccpem).
Overview
--------
relion_it.py creates a number of RELION jobs and then runs one or more `relion_pipeliner' processes to schedule them
(exactly like using the "Schedule" button in the RELION GUI). Instructions and information are printed to the terminal
by relion_it.py as it runs.
relion_it.py uses a large number of options to control how the jobs are run. It's designed to be very flexible and so
these options can be changed in a number of ways:
- The easiest way is to use the simple GUI (enabled by passing the `--gui' argument), which allows you to set a few
simple options. These are then used to calculate appropriate values for the complete set of options. (See "Using the
GUI" below for more information on this.)
- For more control, options can be put into one or more Python files (with a simple "option_name = value" format or
with more complicated calculations - see "Options files" below for more information). The names of these options
files can passed as command line arguments to relion_it.py.
- For maximum control, you can make your own copy of this script and change the option values and the code itself
however you want.
Before running relion_it.py, you need to make sure you're in your intended RELION project directory, and that your
movie files are accessible by relative paths within that directory (as usual for a RELION project). You could do this
by moving the files from the microscope straight into the project directory, using a symlink from your project
directory to the real location of the data, or running a script to create a new symlink to each micrograph as it is
collected.
Options files
-------------
relion_it.py uses a large number of options for controlling both the flow of the script and the parameters for
individual jobs. These options can be read from Python script files when relion_it.py is started.
The options are all listed the body of the script below, with a comment to explain each option. One way to use this
script is to copy it in its entirety into your project directory, edit the options directly in the script and then
run it (with no command line arguments). However, it's often better to keep the script in the RELION source directory
(where it can be updated easily) and use options files to configure it.
An example of a simple options file is:
angpix = 1.06
This would override the default pixel size value, but leave all other options at their defaults.
The options files are read and interpreted as Python scripts. A simple list of "option_name = value" lines is all
that is needed, though you can also use any Python commands you like to do more complex calculations. To generate
an example file containing all of the options, run "relion_it.py --gui" and then click the "Save options" button,
which will save all the current options to a file called `relion_it_options.py' in the working directory.
The options are named descriptively so you can probably understand what most of them do quite easily. For more help on
any particular option, look at the comment above its definition in this script, or search the script's code to see
how it is used.
Options files can be useful as templates. As an example, at Diamond Light Source's eBIC facility, we have a template
file called `dls_cluster_options.py' that contains the necessary settings to make relion_it.py submit most of its jobs
to run on the DLS GPU cluster. You could also set up standard templates for a particular microscope (say, voltage and
Cs settings) or for a particular project or computer configuration.
When relion_it.py starts, it reads all options files in the order they are given on the command line. Subsequent files
will override earlier ones, so the last value given for any particular option will be the value that is used.
If you start relion_it.py with the `--continue' argument, it will automatically add `relion_it_options.py' to the end
of the list of options files. This means that if you are in a project directory where the relion_it.py GUI has
previously been used, all options will be defined in the relion_it_options.py file and they will override any other
options files given on the command line. (This is very useful for restarting the script after a problem, but it would
be pointless to combine `--continue' with any options template files.)
Note that if relion_it.py finds option names that it doesn't recognise while it's reading an options file, it will
print a warning (but continue anyway). If you've been editing options files by hand, you should check the output from
relion_it.py when it starts to make sure there are no typos in the options you wanted to set. (If you're using local
variables for intermediate Python calculations in an options file, it's a good idea to use names starting with a
leading underscore so you can immediately tell them apart from warnings about genuine spelling mistakes.)
Using the GUI
-------------
The GUI provides a simple way to start new projects with relion_it.py. If you want to use it, prepare your project
directory as described above, then start the GUI with "relion_it.py --gui". (If you're using any template options
files, you can give those too, for example "relion_it.py /path/to/site/options.py --gui".)
The window that appears should be self-explanatory. Fill in the options as needed for your project, and use the check
boxes on the right to control what processing steps will be done. When you're ready, click either "Save options" or
"Save & run". The program will check the values you've entered and then use them to calculate a few extra options for
relion_it.py. The options will then be saved to a file called `relion_it_options.py', and if you clicked "Save & run"
the processing run will start immediately.
If any of the entered values are invalid (for example, if there are letters in a field which should be a number), the
GUI will display a message box with an error when you click one of the buttons. It will also display a warning if any
values appear to be incorrect (but you can choose to ignore the warning by clicking "OK").
The GUI will try to calculate some extra options from the values you enter using the following rules:
1. If a 3D reference is given, use a single pass with reference-based autopicking, minimum distance between particles
of 0.7 times the particle size, and a batch size of 100,000 particles.
2. If no 3D reference is given, run a first pass with reference-free LoG autopicking and a batch size of 10,000, and
then a second pass with reference-based autopicking and a batch size of 100,000.
These options should be sensible in many cases, but if you'd like to change them, save the options from the GUI using
the "Save options" button, close the GUI, and edit the `relion_it_options.py' file to change the option values as
needed. You can then start the processing run with "relion_it.py --continue".
Running the pipelines
---------------------
relion_it.py uses several different scheduling pipelines to run its jobs. While each one is running, a file is
created in the project directory called `RUNNING_PIPELINER_<name>'. A log of the jobs run by that pipeline is stored
in `pipeline_<name>.log'.
If you want to stop one of the pipelines for any reason, delete its `RUNNING_' file and within a minute or two the
pipeliner will notice that the file has been removed and stop.
relion_it.py itself uses a similar file called `RUNNING_RELION_IT', and you can delete this to stop the script (which
will not affect any pipelines that are already running). It keeps a list of all of the jobs it has submitted in a
file called `RELION_IT_SUBMITTED_JOBS'. This file can be edited manually if necessary (but not while the script is
running!) Most of the jobs are run by the `preprocessing' pipeline. This will do the following:
1. Import movies
2. Motion correction
3. CTF estimation
4. Particle auto-picking
5. Particle extraction
6. Batch selection
After a number of particles have been extracted (1,000 by default), a 2D classification job will be run to provide
feedback on the quality of the data collection and particle picking.
Particles are split into batches of a fixed size (default 10,000 for the first pass with no reference, or 100,000
otherwise). The first batch is special: as it grows, the 2D classification job is re-run repeatedly to provide early
feedback on the quality of the data. For subsequent batches, the script waits for each batch to be complete before
running 2D classification on it.
You can provide reference structures for auto-picking and 3D classification. (If you provide a 3D reference in the
GUI it will automatically be used for both tasks.)
If you do not provide a reference for auto-picking, reference-free LoG picking will be used. If you do not provide a
reference for classification, relion_it.py will run the preprocessing pipeline twice. In the first pass, an initial
model will be generated, and then a second pass of preprocessing will be done using the initial model as a reference
for auto-picking and classification.
relion_it.py makes an effort to try to identify a suitable reference to use from the classes produced by the
InitialModel job, but if it selects an inappropriate reference, you can change it by stopping the pipelines and
script ("rm RUNNING_*"), updating the reference filename stored in the file named `RELION_IT_2NDPASS_3DREF', deleting
the relevant jobs (`autopick2_job' and those following) from the `RELION_IT_SUBMITTED_JOBS' file, then restarting the
pipeline with "relion_it.py --continue".
Fixing problems
---------------
One-off job failure
```````````````````
Occasionally, a single job can fail with an isolated error, for example if there are temporary network problems while
working on a remote filesystem. If this happens, RELION will wait forever for the files to appear that would indicate
the job has finished. In the meantime, no new jobs will be run, which can cause a backlog of micrographs to build up.
To fix this (for a preprocessing job), you can just try to re-run the job from the RELION GUI. Select the job in the
"Running jobs" list, then click "Job actions" -> "Mark as finished". Select the job again in the "Finished jobs"
list, then click "Continue!" to re-start the job.
That approach should work for preprocessing jobs, but probably won't work for classification or inital model
generation jobs, since those cannot be continued and must instead be restarted from the beginning. The best way to do
that is to restart the job manually, outside the RELION GUI, and then when the job finishes RELION should continue as
if the job had never failed.
For example, with a failed local job:
ps -e | grep relion # to check if the job is still active
kill <process_id> # to stop the job
# now re-run the commands from the job's `note.txt' file
or with a job that was submitted to an SGE cluster queue:
qstat # to check if the job is still active in the queue
qdel <job_id> # to remove the job from the queue
qsub job_type/job_directory/run_submit.script # to re-submit the job
The other option is to just run a new job from the RELION GUI in the normal way (select the job you want to "copy" in
the jobs list, make a "new" job by clicking on the job type in the list in the top-left of the GUI, then click
"Run!"). However, if you do this, relion_it.py will not know about the new job and will not run any further
downstream processing based on it. In this situation, you can either continue to process your data manually in RELION,
or you could edit the `RELION_IT_SUBMITTED_JOBS' file to replace the failed job with the manual one, and delete the
jobs that followed the original one. After that, if you re-run the script it should continue as normal from that
job onwards.
Repeated job failure
````````````````````
If a job fails repeatedly, it usually indicates that there is some problem with the job parameters or the files that
the job needs to access.
In favourable cases, it's possible you could fix the problem by selecting the job in the RELION GUI, changing one of
the parameters that is not greyed out, then clicking "Continue!". Often, though, the problem will be with one of the
parameters that can't be changed for a job that already exists, so the job will need to be deleted and recreated with
a different set of parameters.
To handle this situation, stop all of the pipelines and the relion_it.py script ("rm RUNNING_*"), then identify and
fix the problem. Often, the problem will be an error in one of the job parameters, which can usually be fixed by
changing one of the script options (for example by changing the settings in `relion_it_options.py', if you originally
used the GUI to start the run).
If the problem is caused by missing files from an upstream job, you might need to check the output of previous jobs
and look in the job directories to figure out what the problem is. Again, if it's an error in the parameters for a
job, you can probably fix it by editing `relion_it_options.py'.
After changing any script options, you'll need to use the RELION GUI to delete the affected job and all jobs
downstream of it, and also remove them from the list in the `RELION_IT_SUBMITTED_JOBS' file. Then you should be able
to restart the pipelines by running "relion_it.py --continue".
If you still can't get a particular job to run without errors, you can at least continue to run the upstream jobs
that are working properly. You can do this either by changing the options for relion_it.py (there are options to
switch off 2D or 3D classification, or to stop after CTF estimation), or by manually scheduling the jobs you want
using the RELION GUI. Remember that after running relion_it.py, you have a normal RELION project, so if the script
can't do what you want, you can simply stop it and then use all of RELION's normal job management and scheduling
abilities.
Advanced usage
--------------
It's possible to customise many aspects of the way relion_it.py works, but the details go beyond the scope of this
introduction. Simple customisation can be done by setting appropriate option values (see "Option files" above). For
more substantial changes, you might need to edit the script's Python code to get the behaviour you want. Most of the
important logic is in the `run_pipeline()' function so that's a good place to start. Good luck!
"""
from __future__ import division # always use float division
import argparse
import glob
import inspect
import math
import os
import runpy
import time
import traceback
try:
import Tkinter as tk
import tkMessageBox
import tkFileDialog
except ImportError:
# The GUI is optional. If the user requests it, it will fail when it tries
# to open so we can ignore the error for now.
pass
# Constants
PIPELINE_STAR = 'default_pipeline.star'
RUNNING_FILE = 'RUNNING_RELION_IT'
SECONDPASS_REF3D_FILE = 'RELION_IT_2NDPASS_3DREF'
SETUP_CHECK_FILE = 'RELION_IT_SUBMITTED_JOBS'
PREPROCESS_SCHEDULE_PASS1 = 'PREPROCESS'
PREPROCESS_SCHEDULE_PASS2 = 'PREPROCESS_PASS2'
OPTIONS_FILE = 'relion_it_options.py'
class RelionItOptions(object):
"""
Options for the relion_it pipeline setup script.
When initialised, this contains default values for all options. Call
``update_from()`` to override the defaults with a dictionary of new values.
"""
#############################################################################
# Change the parameters below to reflect your experiment #
# Current defaults reflect cryo-ARM betagal data set of RELION-3.0 tutorial #
#############################################################################
### General parameters
# Pixel size in Angstroms in the input movies
angpix = 0.885
# Acceleration voltage (in kV)
voltage = 200
# Polara = 2.0; Talos/Krios = 2.7; some Cryo-ARM = 1.4
Cs = 1.4
### Import images (Linux wild card; movies as *.mrc, *.mrcs, *.tiff or *.tif; single-frame micrographs as *.mrc)
import_images = 'Movies/*.tiff'
# Are these multi-frame movies? Set to False for single-frame micrographs (and motion-correction will be skipped)
images_are_movies = True
### MotionCorrection parameters
# Dose in electrons per squared Angstrom per frame
motioncor_doseperframe = 1.277
# Gain-reference image in MRC format (only necessary if input movies are not yet gain-corrected, e.g. compressed TIFFs from K2)
motioncor_gainreference = 'Movies/gain.mrc'
### CTF estimation parameters
# Most cases won't need changes here...
### Autopick parameters
# Use reference-free Laplacian-of-Gaussian picking (otherwise use reference-based template matching instead)
autopick_do_LoG = True
# Minimum and maximum diameter in Angstrom for the LoG filter
autopick_LoG_diam_min = 150
autopick_LoG_diam_max = 180
# Use positive values (0-1) to pick fewer particles; use negative values (-1-0) to pick more particles
autopick_LoG_adjust_threshold = 0.0
#
# OR:
#
# References for reference-based picking (when autopick_do_LoG = False)
autopick_2dreferences = ''
# OR: provide a 3D references for reference-based picking (when autopick_do_LoG = False)
autopick_3dreference = ''
# Threshold for reference-based autopicking (threshold 0 will pick too many particles. Default of 0.4 is hopefully better. Ultimately, just hope classification will sort it all out...)
autopick_refs_threshold = 0.4
# Minimum inter-particle distance for reference-based picking (~70% of particle diameter often works well)
autopick_refs_min_distance = 120
#
# For both LoG and refs:
#
# Use this to remove false positives from carbon edges (useful range: 1.0-1.2, -1 to switch off)
autopick_stddev_noise = -1
# Use this to remove false positives from carbon edges (useful range: -0.5-0.0; -999 to switch off)
autopick_avg_noise = -999
### Extract parameters
# Box size of particles in the averaged micrographs (in pixels)
extract_boxsize = 256
# Down-scale the particles upon extraction?
extract_downscale = False
# Box size of the down-scaled particles (in pixels)
extract_small_boxsize = 64
# In second pass, down-scale the particles upon extraction?
extract2_downscale = False
# In second pass, box size of the down-scaled particles (in pixels)
extract2_small_boxsize = 128
### Now perform 2D and/or 3D classification with the extracted particles?
do_class2d = True
# And/or perform 3D classification?
do_class3d = True
# Repeat 2D and/or 3D-classification for batches of this many particles
batch_size = 10000
# Number of 2D classes to use
class2d_nr_classes = 50
# Diameter of the mask used for 2D/3D classification (in Angstrom)
mask_diameter = 190
# Symmetry group (when using SGD for initial model generation, C1 may work best)
symmetry = 'C1'
#
### 3D-classification parameters
# Number of 3D classes to use
class3d_nr_classes = 4
# Have initial 3D model? If not, calculate one using SGD initial model generation
have_3d_reference = False
# Initial reference model
class3d_reference = ''
# Is reference on correct greyscale?
class3d_ref_is_correct_greyscale = False
# Has the initial reference been CTF-corrected?
class3d_ref_is_ctf_corrected = True
# Initial lowpass filter on reference
class3d_ini_lowpass = 40
### Use the largest 3D class from the first batch as a 3D reference for a second pass of autopicking? (only when do_class3d is True)
do_second_pass = True
# Only move on to template-based autopicking if the 3D references achieves this resolution (in A)
minimum_resolution_3dref_2ndpass = 20
# In the second pass, perform 2D classification?
do_class2d_pass2 = True
# In the second pass, perform 3D classification?
do_class3d_pass2 = False
# Batch size in the second pass
batch_size_pass2 = 100000
###################################################################################
############ Often the parameters below can be kept the same for a given set-up
###################################################################################
### Repeat settings for entire pipeline
# Repeat the pre-processing runs this many times (or until RUNNING_PIPELINER_default_PREPROCESS file is deleted)
preprocess_repeat_times = 999
# Wait at least this many minutes between each repeat cycle
preprocess_repeat_wait = 1
### Stop after CTF estimation? I.e., skip autopicking, extraction, 2D/3D classification, etc?
stop_after_ctf_estimation = False
# Check every this many minutes if enough particles have been extracted for a new batch of 2D-classification
batch_repeat_time = 1
### MotionCorrection parameters
# Use RELION's own implementation of motion-correction (CPU-only) instead of the UCSF implementation?
motioncor_do_own = False
# The number of threads (only for RELION's own implementation) is optimal when nr_movie_frames/nr_threads = integer
motioncor_threads = 12
# Exectutable of UCSF MotionCor2
motioncor_exe = '/public/EM/MOTIONCOR2/MotionCor2'
# On which GPU(s) to execute UCSF MotionCor2
motioncor_gpu = '0'
# How many MPI processes to use for running motion correction?
motioncor_mpi = 1
# Local motion-estimation patches for MotionCor2
motioncor_patches_x = 5
motioncor_patches_y = 5
# B-factor in A^2 for downweighting of high-spatial frequencies
motioncor_bfactor = 150
# Use binning=2 for super-resolution K2 movies
motioncor_binning = 1
# Provide a defect file for your camera if you have one
motioncor_defectfile = ''
# orientation of the gain-reference w.r.t your movies (if input movies are not yet gain-corrected, e.g. TIFFs)
motioncor_gainflip = 'No flipping (0)'
motioncor_gainrot = 'No rotation (0)'
# Other arguments for MotionCor2
motioncor_other_args = ''
# Submit motion correction job to the cluster?
motioncor_submit_to_queue = False
### CTF estimation parameters
# Amplitude contrast (Q0)
ampl_contrast = 0.1
# CTFFIND-defined parameters
ctffind_boxsize = 512
ctffind_astigmatism = 100
ctffind_maxres = 5
ctffind_minres = 30
ctffind_defocus_max = 50000
ctffind_defocus_min = 5000
ctffind_defocus_step = 500
# For Gctf: ignore parameters on the 'Searches' tab?
ctffind_do_ignore_search_params = True
# For Gctf: perform equi-phase averaging?
ctffind_do_EPA = True
# Also estimate phase shifts (for VPP data)
ctffind_do_phaseshift = False
# Executable to Kai Zhang's Gctf
gctf_exe = '/public/EM/Gctf/bin/Gctf'
# On which GPU(s) to execute Gctf
gctf_gpu = '0'
# Use Alexis Rohou's CTFFIND4 (CPU-only) instead?
use_ctffind_instead = False
# Executable for Alexis Rohou's CTFFIND4
ctffind4_exe = '/public/EM/ctffind/ctffind.exe'
# How many MPI processes to use for running CTF estimation?
ctffind_mpi = 1
# Submit CTF estimation job to the cluster?
ctffind_submit_to_queue = False
### Autopick parameters
# Use GPU-acceleration for autopicking?
autopick_do_gpu = True
# Which GPU(s) to use for autopicking
autopick_gpu = '0'
# Low-pass filter for auto-picking the micrographs
autopick_lowpass = 20
# Shrink factor for faster picking (0 = fastest; 1 = slowest)
autopick_shrink_factor = 0
# How many MPI processes to use for running auto-picking?
autopick_mpi = 1
# Additional arguments for autopicking
autopick_other_args = ''
# Submit Autopick job to the cluster?
autopick_submit_to_queue = False
# Are the references CTF-corrected?
autopick_refs_are_ctf_corrected = True
# Do the references have inverted contrast wrt the micrographs?
autopick_refs_have_inverted_contrast = True
# Ignore CTFs until the first peak
autopick_refs_ignore_ctf1stpeak = False
# Diameter of mask for the references (in A; negative value for automated detection of mask diameter)
autopick_refs_mask_diam = -1
# In-plane angular sampling interval
autopick_inplane_sampling = 10
# Symmetry of the 3D reference for autopicking
autopick_3dref_symmetry = 'C1'
# 3D angular sampling for generating projections of the 3D reference for autopicking (30 degrees is usually enough)
autopick_3dref_sampling = '30 degrees'
# Pixel size in the provided 2D/3D references (negative for same as in motion-corrected movies)
autopick_ref_angpix = -1
### Extract parameters
# Diameter for background normalisation (in pixels; negative value: default is 75% box size)
extract_bg_diameter = -1
# How many MPI processes to use for running particle extraction?
extract_mpi = 1
# Submit Extract job to the cluster?
extract_submit_to_queue = False
## Discard particles based on average/stddev values? (this may be important for SGD initial model generation)
do_discard_on_image_statistics = False
# Discard images that have average/stddev values that are more than this many sigma away from the ensemble average
discard_sigma = 4
# Submit discard job to the cluster?
discard_submit_to_queue = False
#### Common relion_refine paremeters used for 2D/3D classification and initial model generation
# Read all particles in one batch into memory?
refine_preread_images = False
# Or copy particles to scratch disk?
refine_scratch_disk = ''
# Number of pooled particles?
refine_nr_pool = 10
# Use GPU-acceleration?
refine_do_gpu = True
# Which GPU to use (different from GPU used for pre-processing?)
refine_gpu = '1'
# How many MPI processes to use
refine_mpi = 1
# How many threads to use
refine_threads = 6
# Skip padding?
refine_skip_padding = False
# Submit jobs to the cluster?
refine_submit_to_queue = False
# Use fast subsets in 2D/3D classification when batch_size is bigger than this
refine_batchsize_for_fast_subsets = 100000
### 2D classification parameters
# Wait with the first 2D classification batch until at least this many particles are extracted
minimum_batch_size = 1000
# Number of iterations to perform in 2D classification
class2d_nr_iter = 20
# Rotational search step (in degrees)
class2d_angle_step = 6
# Offset search range (in pixels)
class2d_offset_range = 5
# Offset search step (in pixels)
class2d_offset_step = 1
# Option to ignore the CTFs until their first peak (try this if all particles go into very few classes)
class2d_ctf_ign1stpeak = False
# Additional arguments to pass to relion-refine
class2d_other_args = ''
### 3D classification parameters
# Number of iterations to perform in 3D classification
class3d_nr_iter = 20
# Reference mask
class3d_reference_mask = ''
# Option to ignore the CTFs until their first peak (try this if all particles go into very few classes)
class3d_ctf_ign1stpeak = False
# Regularisation parameter (T)
class3d_T_value = 4
# Angular sampling step
class3d_angle_step = '7.5 degrees'
# Offset search range (in pixels)
class3d_offset_range = 5
# Offset search step (in pixels)
class3d_offset_step = 1
# Additional arguments to pass to relion-refine
class3d_other_args = ''
## SGD initial model generation
# Number of models to generate simulatenously (K>1 may be useful for getting rid of outliers in the particle images)
inimodel_nr_classes = 4
# Ignore CTFs until first peak?
inimodel_ctf_ign1stpeak = False
# Enforce non-negative solvent?
inimodel_solvent_flatten = True
# Initial angular sampling
inimodel_angle_step = '15 degrees'
# Initial search range (in pixels)
inimodel_offset_range = 6
# Initial offset search step (in pixels)
inimodel_offset_step = 2
# Number of initial iterations
inimodel_nr_iter_initial = 50
# Number of in-between iterations
inimodel_nr_iter_inbetween = 200
# Number of final iterations
inimodel_nr_iter_final = 50
# Frequency to write out information
inimodel_freq_writeout = 10
# Initial resolution (in A)
inimodel_resol_ini = 35
# Final resolution (in A)
inimodel_resol_final = 15
# Initial mini-batch size
inimodel_batchsize_ini = 100
# Final mini-batch size
inimodel_batchsize_final = 500
# Increased noise variance half-life (off, i.e. -1, by default; values of ~1000 have been observed to be useful in difficult cases)
inimodel_sigmafudge_halflife = -1
# Additional arguments to pass to relion_refine (skip annealing to get rid of outlier particles)
inimodel_other_args = ' --sgd_skip_anneal '
### Cluster submission settings
# Name of the queue to which to submit the job
queue_name = 'openmpi'
# Name of the command used to submit scripts to the queue
queue_submit_command = 'qsub'
# The template for your standard queue job submission script
queue_submission_template = '/public/EM/RELION/relion/bin/qsub.csh'
# Minimum number of dedicated cores that need to be requested on each node
queue_minimum_dedicated = 1
### End of options
#######################################################################
############ typically no need to change anything below this line
#######################################################################
def update_from(self, other):
"""
Update this RelionItOptions object from a dictionary.
Special values (with names like '__xxx__') are removed, allowing this
method to be given a dictionary containing the namespace from a script
run with ``runpy``.
"""
while len(other) > 0:
key, value = other.popitem()
if not (key.startswith('__') and key.endswith('__')): # exclude __name__, __builtins__ etc.
if hasattr(self, key):
setattr(self, key, value)
else:
print("RELION_IT: Unrecognised option '{}'".format(key))
def print_options(self, out_file=None):
"""
Print the current options.
This method prints the options in the same format as they are read,
allowing options to be written to a file and re-used.
Args:
out_file: A file object (optional). If supplied, options will be
written to this file, otherwise they will be printed to
sys.stdout.
Raises:
ValueError: If there is a problem printing the options.
"""
print >>out_file, "# Options file for relion_it.py"
print >>out_file
seen_start = False
option_names = [key for key in dir(self) if (not (key.startswith('__') and key.endswith('__'))
and not callable(getattr(self, key)))]
# Parse the source code for this class, and write out all comments along with option lines containing new values
for line in inspect.getsourcelines(RelionItOptions)[0]:
line = line.strip()
if not seen_start:
if line != "### General parameters":
# Ignore lines until this one
continue
seen_start = True
if line == "### End of options":
# Stop here
break
if line.startswith('#') or len(line) == 0:
# Print comments or blank lines as-is
print >>out_file, line
else:
# Assume all other lines define an option name and value. Replace with new value.
equals_index = line.find('=')
if equals_index > 0:
option_name = line[:equals_index].strip()
if option_name in option_names:
print >>out_file, '{} = {}'.format(option_name, repr(getattr(self, option_name)))
option_names.remove(option_name)
else:
# This error should not occur. If it does, there is probably a programming error.
raise ValueError("Unrecognised option name '{}'".format(option_name))
if len(option_names) > 0:
# This error should not occur. If it does, there is probably a programming error.
raise ValueError("Some options were not written to the output file: {}".format(option_names))
class RelionItGui(object):
def __init__(self, main_window, options):
self.main_window = main_window
self.options = options
# Convenience function for making file browser buttons
def new_browse_button(master, var_to_set, filetypes=(('MRC file', '*.mrc'), ('All files', '*'))):
def browse_command():
chosen_file = tkFileDialog.askopenfilename(filetypes=filetypes)
if chosen_file is not None:
# Make path relative if it's in the current directory
if chosen_file.startswith(os.getcwd()):
chosen_file = os.path.relpath(chosen_file)
var_to_set.set(chosen_file)
return tk.Button(master, text="Browse...", command=browse_command)
### Create GUI
main_frame = tk.Frame(main_window)
main_frame.pack(fill=tk.BOTH, expand=1)
left_frame = tk.Frame(main_frame)
left_frame.pack(side=tk.LEFT, anchor=tk.N, fill=tk.X, expand=1)
right_frame = tk.Frame(main_frame)
right_frame.pack(side=tk.LEFT, anchor=tk.N, fill=tk.X, expand=1)
###
expt_frame = tk.LabelFrame(left_frame, text="Experimental details", padx=5, pady=5)
expt_frame.pack(padx=5, pady=5, fill=tk.X, expand=1)
tk.Grid.columnconfigure(expt_frame, 1, weight=1)
row = 0
tk.Label(expt_frame, text="Voltage (kV):").grid(row=row, sticky=tk.W)
self.voltage_entry = tk.Entry(expt_frame)
self.voltage_entry.grid(row=row, column=1, sticky=tk.W+tk.E)
self.voltage_entry.insert(0, str(options.voltage))
row += 1
tk.Label(expt_frame, text="Cs (mm):").grid(row=row, sticky=tk.W)
self.cs_entry = tk.Entry(expt_frame)
self.cs_entry.grid(row=row, column=1, sticky=tk.W+tk.E)
self.cs_entry.insert(0, str(options.Cs))
row += 1
tk.Label(expt_frame, text="Phase plate?").grid(row=row, sticky=tk.W)
self.phaseplate_var = tk.IntVar()
phaseplate_button = tk.Checkbutton(expt_frame, var=self.phaseplate_var)
phaseplate_button.grid(row=row, column=1, sticky=tk.W)
if options.ctffind_do_phaseshift:
phaseplate_button.select()
row += 1
tk.Label(expt_frame, text=u"Pixel size (\u212B):").grid(row=row, sticky=tk.W)
self.angpix_var = tk.StringVar() # for data binding
self.angpix_entry = tk.Entry(expt_frame, textvariable=self.angpix_var)
self.angpix_entry.grid(row=row, column=1, sticky=tk.W+tk.E)
self.angpix_entry.insert(0, str(options.angpix))
row += 1
tk.Label(expt_frame, text=u"Exposure rate (e\u207B / \u212B\u00B2 / frame):").grid(row=row, sticky=tk.W)
self.exposure_entry = tk.Entry(expt_frame)
self.exposure_entry.grid(row=row, column=1, sticky=tk.W + tk.E)
self.exposure_entry.insert(0, str(options.motioncor_doseperframe))
###
particle_frame = tk.LabelFrame(left_frame, text="Particle details", padx=5, pady=5)
particle_frame.pack(padx=5, pady=5, fill=tk.X, expand=1)
tk.Grid.columnconfigure(particle_frame, 1, weight=1)
row = 0
tk.Label(particle_frame, text=u"Longest diameter (\u212B):").grid(row=row, sticky=tk.W)
self.particle_max_diam_var = tk.StringVar() # for data binding
self.particle_max_diam_entry = tk.Entry(particle_frame, textvariable=self.particle_max_diam_var)
self.particle_max_diam_entry.grid(row=row, column=1, sticky=tk.W+tk.E, columnspan=2)
self.particle_max_diam_entry.insert(0, str(options.autopick_LoG_diam_max))
row += 1
tk.Label(particle_frame, text=u"Shortest diameter (\u212B):").grid(row=row, sticky=tk.W)
self.particle_min_diam_entry = tk.Entry(particle_frame)
self.particle_min_diam_entry.grid(row=row, column=1, sticky=tk.W+tk.E, columnspan=2)
self.particle_min_diam_entry.insert(0, str(options.autopick_LoG_diam_min))
row += 1
tk.Label(particle_frame, text="3D reference (optional):").grid(row=row, sticky=tk.W)
self.ref_3d_var = tk.StringVar() # for data binding
self.ref_3d_entry = tk.Entry(particle_frame, textvariable=self.ref_3d_var)
self.ref_3d_entry.grid(row=row, column=1, sticky=tk.W+tk.E)
self.ref_3d_entry.insert(0, str(options.autopick_3dreference))
new_browse_button(particle_frame, self.ref_3d_var).grid(row=row, column=2)
row += 1
tk.Label(particle_frame, text=u"Mask diameter (\u212B):").grid(row=row, sticky=tk.W)
self.mask_diameter_var = tk.StringVar() # for data binding
self.mask_diameter_entry = tk.Entry(particle_frame, textvariable=self.mask_diameter_var)
self.mask_diameter_entry.grid(row=row, column=1, sticky=tk.W+tk.E)
self.mask_diameter_entry.insert(0, str(options.mask_diameter))
self.mask_diameter_px = tk.Label(particle_frame, text="= NNN px")
self.mask_diameter_px.grid(row=row, column=2,sticky=tk.W)
row += 1
tk.Label(particle_frame, text="Box size (px):").grid(row=row, sticky=tk.W)
self.box_size_var = tk.StringVar() # for data binding
self.box_size_entry = tk.Entry(particle_frame, textvariable=self.box_size_var)
self.box_size_entry.grid(row=row, column=1, sticky=tk.W+tk.E)
self.box_size_entry.insert(0, str(options.extract_boxsize))
self.box_size_in_angstrom = tk.Label(particle_frame, text=u"= NNN \u212B")
self.box_size_in_angstrom.grid(row=row, column=2,sticky=tk.W)
row += 1
tk.Label(particle_frame, text="Down-sample to (px):").grid(row=row, sticky=tk.W)
self.extract_small_boxsize_var = tk.StringVar() # for data binding
self.extract_small_boxsize_entry = tk.Entry(particle_frame, textvariable=self.extract_small_boxsize_var)
self.extract_small_boxsize_entry.grid(row=row, column=1, sticky=tk.W+tk.E)
self.extract_small_boxsize_entry.insert(0, str(options.extract_small_boxsize))
self.extract_angpix = tk.Label(particle_frame, text=u"= NNN \u212B/px")
self.extract_angpix.grid(row=row, column=2,sticky=tk.W)
row += 1
tk.Label(particle_frame, text="Calculate for me:").grid(row=row, sticky=tk.W)
self.auto_boxsize_var = tk.IntVar()
auto_boxsize_button = tk.Checkbutton(particle_frame, var=self.auto_boxsize_var)
auto_boxsize_button.grid(row=row, column=1, sticky=tk.W)
auto_boxsize_button.select()
###
project_frame = tk.LabelFrame(right_frame, text="Project details", padx=5, pady=5)
project_frame.pack(padx=5, pady=5, fill=tk.X, expand=1)
tk.Grid.columnconfigure(project_frame, 1, weight=1)
row = 0
tk.Label(project_frame, text="Project directory:").grid(row=row, sticky=tk.W)
tk.Label(project_frame, text=os.getcwd(), anchor=tk.W).grid(row=row, column=1, sticky=tk.W, columnspan=2)
row += 1
tk.Label(project_frame, text="Pattern for movies:").grid(row=row, sticky=tk.W)
self.import_images_var = tk.StringVar() # for data binding
self.import_images_entry = tk.Entry(project_frame, textvariable=self.import_images_var)
self.import_images_entry.grid(row=row, column=1, sticky=tk.W+tk.E)
self.import_images_entry.insert(0, self.options.import_images)
import_button = new_browse_button(project_frame, self.import_images_var,
filetypes=(('Image file', '{*.mrc, *.mrcs, *.tif, *.tiff}'), ('All files', '*')))
import_button.grid(row=row, column=2)
row += 1
tk.Label(project_frame, text="Gain reference (optional):").grid(row=row, sticky=tk.W)
self.gainref_var = tk.StringVar() # for data binding
self.gainref_entry = tk.Entry(project_frame, textvariable=self.gainref_var)
self.gainref_entry.grid(row=row, column=1, sticky=tk.W+tk.E)
self.gainref_entry.insert(0, self.options.motioncor_gainreference)
new_browse_button(project_frame, self.gainref_var).grid(row=row, column=2)
###
pipeline_frame = tk.LabelFrame(right_frame, text="Pipeline control", padx=5, pady=5)
pipeline_frame.pack(padx=5, pady=5, fill=tk.X, expand=1)
tk.Grid.columnconfigure(expt_frame, 1, weight=1)
row = 0
tk.Label(pipeline_frame, text="Stop after CTF estimation?").grid(row=row, sticky=tk.W)
self.stop_after_ctf_var = tk.IntVar()
stop_after_ctf_button = tk.Checkbutton(pipeline_frame, var=self.stop_after_ctf_var)
stop_after_ctf_button.grid(row=row, column=1, sticky=tk.W)
if options.stop_after_ctf_estimation:
stop_after_ctf_button.select()
row += 1
tk.Label(pipeline_frame, text="Do 2D classification?").grid(row=row, sticky=tk.W)
self.class2d_var = tk.IntVar()
class2d_button = tk.Checkbutton(pipeline_frame, var=self.class2d_var)
class2d_button.grid(row=row, column=1, sticky=tk.W)
if options.do_class2d:
class2d_button.select()
row += 1
tk.Label(pipeline_frame, text="Do 3D classification?").grid(row=row, sticky=tk.W)
self.class3d_var = tk.IntVar()
class3d_button = tk.Checkbutton(pipeline_frame, var=self.class3d_var)
class3d_button.grid(row=row, column=1, sticky=tk.W)
if options.do_class3d:
class3d_button.select()
row += 1
tk.Label(pipeline_frame, text="Do second pass? (only if no 3D ref)").grid(row=row, sticky=tk.W)
self.second_pass_var = tk.IntVar()
second_pass_button = tk.Checkbutton(pipeline_frame, var=self.second_pass_var)
second_pass_button.grid(row=row, column=1, sticky=tk.W)
if options.do_second_pass:
second_pass_button.select()
row += 1
tk.Label(pipeline_frame, text="Do 2D classification (2nd pass)?").grid(row=row, sticky=tk.W)
self.class2d_pass2_var = tk.IntVar()
class2d_pass2_button = tk.Checkbutton(pipeline_frame, var=self.class2d_pass2_var)
class2d_pass2_button.grid(row=row, column=1, sticky=tk.W)
class2d_pass2_button.select()
if options.do_class2d_pass2:
class2d_pass2_button.select()
row += 1
tk.Label(pipeline_frame, text="Do 3D classification (2nd pass)?").grid(row=row, sticky=tk.W)
self.class3d_pass2_var = tk.IntVar()
class3d_pass2_button = tk.Checkbutton(pipeline_frame, var=self.class3d_pass2_var)
class3d_pass2_button.grid(row=row, column=1, sticky=tk.W)
if options.do_class3d_pass2:
class3d_pass2_button.select()
### Add logic to the box size boxes
def calculate_box_size(particle_size_pixels):
# Use box 20% larger than particle and ensure size is even
box_size_exact = 1.2 * particle_size_pixels
box_size_int = int(math.ceil(box_size_exact))
return box_size_int + box_size_int % 2
def calculate_downscaled_box_size(box_size_pix, angpix):
for small_box_pix in (48, 64, 96, 128, 160, 192, 256, 288, 300, 320, 360,
384, 400, 420, 450, 480, 512, 640, 768, 896, 1024):
# Don't go larger than the original box
if small_box_pix > box_size_pix:
return box_size_pix
# If Nyquist freq. is better than 8.5 A, use this downscaled box, otherwise continue to next size up
small_box_angpix = angpix * box_size_pix / small_box_pix
if small_box_angpix < 4.25:
return small_box_pix
# Fall back to a warning message
return "Box size is too large!"
def update_box_size_labels(*args_ignored, **kwargs_ignored):
try:
angpix = float(self.angpix_entry.get())
except ValueError:
# Can't update any of the labels without angpix
self.mask_diameter_px.config(text="= NNN px")
self.box_size_in_angstrom.config(text=u"= NNN \u212B")
self.extract_angpix.config(text=u"= NNN \u212B/px")
return
try:
mask_diameter = float(self.mask_diameter_entry.get())
mask_diameter_px = mask_diameter / angpix
self.mask_diameter_px.config(text="= {:.1f} px".format(mask_diameter_px))
except (ValueError, ZeroDivisionError):
self.mask_diameter_px.config(text="= NNN px")
# Don't return - an error here doesn't stop us calculating the other labels
try:
box_size = float(self.box_size_entry.get())
box_angpix = angpix * box_size
self.box_size_in_angstrom.config(text=u"= {:.1f} \u212B".format(box_angpix))
except ValueError:
# Can't update these without the box size
self.box_size_in_angstrom.config(text=u"= NNN \u212B")
self.extract_angpix.config(text=u"= NNN \u212B/px")
return
try:
extract_small_boxsize = float(self.extract_small_boxsize_entry.get())
small_box_angpix = box_angpix / extract_small_boxsize
self.extract_angpix.config(text=u"= {:.3f} \u212B/px".format(small_box_angpix))
except (ValueError, ZeroDivisionError):
# Can't update the downscaled pixel size unless the downscaled box size is valid
self.extract_angpix.config(text=u"= NNN \u212B/px")
def update_box_sizes(*args_ignored, **kwargs_ignored):
# Always activate entry boxes - either we're activating them anyway, or we need to edit the text.
# For text editing we need to activate the box first then deactivate again afterwards.
self.mask_diameter_entry.config(state=tk.NORMAL)