-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexternal_job_cryolo.py
351 lines (308 loc) · 13.7 KB
/
external_job_cryolo.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
#!/usr/bin/env python3
# **************************************************************************
# *
# * Authors: Grigory Sharov ([email protected]) [1]
# *
# * [1] MRC Laboratory of Molecular Biology, MRC-LMB
# *
# * 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, write to the Free Software
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
# * 02111-1307 USA
# *
# * All comments concerning this program package may be sent to the
# * e-mail address '[email protected]'
# *
# **************************************************************************
""" Based on https://github.com/DiamondLightSource/python-relion-yolo-it by
Sjors H.W. Scheres, Takanori Nakane, Colin M. Palmer, Donovan Webb"""
import argparse
import json
import os
import time
import datetime
from glob import glob
import subprocess
import math
try:
from emtable import Table
except ModuleNotFoundError:
raise ModuleNotFoundError("Missing deps! Run 'pip3 install --user emtable' for system python")
CONDA_ENV = ". /lmb/home/gsharov/rc/conda.rc && conda activate cryolo-1.9.7"
CRYOLO_PREDICT = "cryolo_predict.py"
CRYOLO_GEN_MODEL = "/public/EM/Scipion/scipion-dev/software/em/cryolo_model-202005_N63_c17/gmodel_phosnet_202005_N63_c17.h5"
CRYOLO_GEN_JANNI_MODEL = "/public/EM/Scipion/scipion-dev/software/em/cryolo_model-202005_nn_N63_c17/gmodel_phosnet_202005_nn_N63_c17.h5"
CRYOLO_JANNI_MODEL = "/public/EM/Scipion/scipion-dev/software/em/janni_model-20190703/gmodel_janni_20190703.h5"
CRYOLO_NEGST_MODEL = "/public/EM/Scipion/scipion-dev/software/em/cryolo_negstain_model-20190226/gmodel_phosnet_negstain_20190226.h5"
SCRATCH_DIR = os.getenv("SLURM_SCRATCH_DIR") # SSD scratch space for filtered mics, can be None
DEBUG = 0
def run_job(args):
start = time.time()
in_mics = args.in_mics
job_dir = args.out_dir
thresh = args.threshold
box_size = args.box_size
distance = 0
model = args.model
filament = args.filament
if filament:
box_dist = args.box_distance
min_boxes = args.minimum_number_boxes
denoise = args.denoise
gpus = args.gpu
threads = args.threads
if SCRATCH_DIR is not None:
filtered_dir = os.path.join(SCRATCH_DIR, "filtered_tmp")
else:
filtered_dir = f"{job_dir}/filtered_tmp/"
if model == "None":
model = CRYOLO_GEN_MODEL if not denoise else CRYOLO_GEN_JANNI_MODEL
else:
model = os.path.abspath(model)
# Making a cryolo config file
json_dict = {
"model": {
"architecture": "PhosaurusNet",
"input_size": 1024,
"max_box_per_image": 600,
"norm": "STANDARD",
"filter": [
0.1,
filtered_dir
]
},
"other": {
"log_path": f"{job_dir}/logs/"
}
}
if box_size: # is not 0
json_dict["model"]["anchors"] = [int(box_size), int(box_size)]
if not filament:
distance = int(box_size / 2) # use half the box_size
if denoise:
json_dict["model"]["filter"] = [
CRYOLO_JANNI_MODEL,
24,
3,
filtered_dir
]
if DEBUG:
print("Using following config: ", json_dict)
with open(os.path.join(job_dir, "config_cryolo.json"), "w") as json_file:
json.dump(json_dict, json_file, indent=4)
# Reading the micrographs star file from Relion
mictable = Table(fileName=in_mics, tableName='micrographs')
mic_fns = mictable.getColumnValues("rlnMicrographName")
# Launching cryolo
args_dict = {
'--conf': os.path.join(job_dir, "config_cryolo.json"),
'--input': in_mics,
'--output': os.path.join(job_dir, 'output'),
'--weights': model,
'--gpu': gpus.replace(',', ' '),
'--threshold': thresh,
'--distance': distance,
'--cleanup': "",
'--skip': "",
'--write_empty': "",
'--num_cpu': -1 if threads == 1 else threads
}
if filament:
args_dict.update({
'--filament': "",
'--box_distance': box_dist,
'--minimum_number_boxes': min_boxes,
'--directional_method': 'PREDICTED'
})
args_dict.pop('--distance')
cmd = f"{CONDA_ENV} && {CRYOLO_PREDICT} "
cmd += " ".join([f"{k} {v}" for k, v in args_dict.items()])
print("Running command:\n{}".format(cmd))
proc = subprocess.Popen(cmd, shell=True)
proc.communicate()
if proc.returncode:
raise Exception(f"Command failed with return code {proc.returncode}")
# Moving output star files for Relion to use
table_coords = Table(columns=['rlnMicrographName', 'rlnMicrographCoordinates'])
star_dir = "EMAN_HELIX_SEGMENTED" if filament else "STAR"
ext = ".box" if filament else ".star"
with open(os.path.join(job_dir, "autopick.star"), "w") as mics_star:
for mic in mic_fns:
mic_base = os.path.basename(mic)
mic_dir = os.path.dirname(mic)
if len(mic_dir.split("/")) > 1 and "job" in mic_dir.split("/")[1]: # remove JobType/jobXXX
mic_dir = "/".join(mic_dir.split("/")[2:])
os.makedirs(os.path.join(job_dir, mic_dir), exist_ok=True)
coord_cryolo = os.path.splitext(mic_base)[0] + ext
coord_cryolo = os.path.join(job_dir, "output", star_dir, coord_cryolo)
coord_relion = os.path.splitext(mic_base)[0] + "_autopick" + ext
coord_relion = os.path.join(job_dir, mic_dir, coord_relion)
if os.path.exists(coord_cryolo):
os.rename(coord_cryolo, coord_relion)
table_coords.addRow(mic, coord_relion)
if DEBUG:
print(f"Moved {coord_cryolo} to {coord_relion}")
table_coords.writeStar(mics_star, tableName='coordinate_files')
# Required output to mini pipeline job_pipeline.star file
pipeline_fn = os.path.join(job_dir, "job_pipeline.star")
table_gen = Table(columns=['rlnPipeLineJobCounter'])
table_gen.addRow(2)
table_proc = Table(columns=['rlnPipeLineProcessName', 'rlnPipeLineProcessAlias',
'rlnPipeLineProcessTypeLabel', 'rlnPipeLineProcessStatusLabel'])
table_proc.addRow(job_dir, 'None', 'relion.external', 'Running')
table_nodes = Table(columns=['rlnPipeLineNodeName', 'rlnPipeLineNodeTypeLabel',
'rlnPipeLineNodeTypeLabelDepth'])
table_nodes.addRow(in_mics, "MicrographGroupMetadata.star.relion", 1)
table_nodes.addRow(os.path.join(job_dir, "autopick.star"),
"MicrographCoordsGroup.star.relion.autopick", 1)
table_input = Table(columns=['rlnPipeLineEdgeFromNode', 'rlnPipeLineEdgeProcess'])
table_input.addRow(in_mics, job_dir)
table_output = Table(columns=['rlnPipeLineEdgeProcess', 'rlnPipeLineEdgeToNode'])
table_output.addRow(job_dir, os.path.join(job_dir, "autopick.star"))
with open(pipeline_fn, "w") as f:
table_gen.writeStar(f, tableName="pipeline_general", singleRow=True)
table_proc.writeStar(f, tableName="pipeline_processes")
table_nodes.writeStar(f, tableName="pipeline_nodes")
table_input.writeStar(f, tableName="pipeline_input_edges")
table_output.writeStar(f, tableName="pipeline_output_edges")
# Register output nodes in .Nodes/
os.makedirs(os.path.join(".Nodes", "MicrographCoordsGroup", job_dir), exist_ok=True)
open(os.path.join(".Nodes", "MicrographCoordsGroup", job_dir, "autopick.star"), "w").close()
# get estimated box size
summaryfn = glob(os.path.join(job_dir, "output/DISTR", 'size_distribution_summary*.txt'))
if summaryfn:
with open(summaryfn[0]) as f:
for line in f:
if line.startswith("MEAN,"):
estim_sizepx = int(line.split(",")[-1])
break
print(f"\ncrYOLO estimated box size {estim_sizepx} px")
# calculate diameter, original (boxSize) and downsampled (boxSizeSmall) box
optics = Table(fileName=in_mics, tableName='optics')
angpix = float(optics[0].rlnMicrographPixelSize)
if filament:
# box size = 1.5x tube diam
diam = 0.66 * box_size
else:
# use + 20% for diameter
diam = math.ceil(estim_sizepx * angpix * 1.2)
# use +30% for box size, make it even
boxSize = 1.3 * estim_sizepx
boxSize = math.ceil(boxSize / 2.) * 2
# from relion_it.py script
# Authors: Sjors H.W. Scheres, Takanori Nakane & Colin M. Palmer
boxSizeSmall = None
for box 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 box > boxSize:
boxSizeSmall = boxSize
break
# If Nyquist freq. is better than 7.5 A, use this
# downscaled box, otherwise continue to next size up
small_box_angpix = angpix * boxSize / box
if small_box_angpix < 3.75:
boxSizeSmall = box
break
print("\nSuggested parameters:\n\t"
f"Diameter (A): {diam}\n\t"
f"Box size (px): {boxSize}\n\t"
f"Box size binned (px): {boxSizeSmall}")
# create .gui_manualpickjob.star for easy display
starString = """
# version 30001
data_job
_rlnJobTypeLabel relion.manualpick
_rlnJobIsContinue 0
_rlnJobIsTomo 0
# version 30001
data_joboptions_values
loop_
_rlnJobOptionVariable #1
_rlnJobOptionValue #2
angpix %0.6f
black_val 0
blue_value 0
color_label rlnParticleSelectZScore
diameter %d
do_color No
do_fom_threshold No
do_queue No
do_startend No
fn_color ""
fn_in ""
highpass -1
lowpass 20
micscale 0.2
min_dedicated 1
minimum_pick_fom 0
other_args ""
qsub qsub
qsubscript /public/EM/RELION/relion/bin/relion_qsub.csh
queuename openmpi
red_value 2
sigma_contrast 3
white_val 0
"""
with open(".gui_manualpickjob.star", "w") as f:
f.write(starString % (angpix, diam))
end = time.time()
diff = end - start
print(f"Job duration {str(datetime.timedelta(seconds=diff))}\n")
def main():
"""Change to the job working directory, then call run_job()"""
help = """
External job for calling crYOLO within Relion 5. Run it in the Relion project directory, e.g.:
external_job_cryolo.py --o External/cryolo_picking --in_mics CtfFind/job004/micrographs_ctf.star
"""
parser = argparse.ArgumentParser(usage=help)
parser.add_argument("--in_mics", help="Input micrographs STAR file")
parser.add_argument("--o", dest="out_dir", help="Output directory name")
parser.add_argument("--j", dest="threads", help="Number of CPU threads (default = 4)", type=int, default=4)
parser.add_argument("--box_size", help="Box size (default = 0 means it's estimated)", type=int, default=0)
parser.add_argument("--threshold", help="Threshold for picking (default = 0.3)", type=float, default=0.3)
parser.add_argument("--model", help="Cryolo training model (if not specified general model is used)", default="None")
parser.add_argument("--filament", help='Enable filament mode', default=False, action='store_true')
parser.add_argument("--bd", dest="box_distance", help='[FILAMENT MODE] Distance in pixel between two boxes', type=int, default=None)
parser.add_argument("--mn", dest="minimum_number_boxes", help='[FILAMENT MODE] Minimum number of boxes per filament', type=int, default=None)
parser.add_argument("--denoise", help="Denoise with JANNI instead of lowpass filtering", default=False, action='store_true')
parser.add_argument("--gpu", help='GPUs to use (e.g. "0,1,2,3", default = "0")', default="0")
parser.add_argument("--pipeline_control", help="Not used here. Required by Relion")
args = parser.parse_args()
if args.in_mics is None or args.out_dir is None:
print("Error: --in_mics and --o are required params!")
exit(1)
if not args.in_mics.endswith(".star"):
print("Error: --in_mics must point to a micrographs star file!")
exit(1)
if args.filament:
if None in [args.box_size, args.box_distance, args.minimum_number_boxes]:
print("Error: --box_size, --bd, --mn are required in filament mode!")
exit(1)
os.makedirs(args.out_dir, exist_ok=True)
RELION_JOB_FAILURE_FILENAME = os.path.join(args.out_dir, "RELION_JOB_EXIT_FAILURE")
RELION_JOB_SUCCESS_FILENAME = os.path.join(args.out_dir, "RELION_JOB_EXIT_SUCCESS")
if os.path.isfile(RELION_JOB_FAILURE_FILENAME):
os.remove(RELION_JOB_FAILURE_FILENAME)
if os.path.isfile(RELION_JOB_SUCCESS_FILENAME):
os.remove(RELION_JOB_SUCCESS_FILENAME)
try:
run_job(args)
except:
open(RELION_JOB_FAILURE_FILENAME, "w").close()
raise
else:
open(RELION_JOB_SUCCESS_FILENAME, "w").close()
if __name__ == "__main__":
main()