From 343d655e97b70150137adef402923eacf600167d Mon Sep 17 00:00:00 2001
From: Zheng Ruan <zruan1991@gmail.com>
Date: Sun, 21 Feb 2021 12:45:26 -0500
Subject: [PATCH] Detect relion-style folder organization and store
 *_topazpicks.star files into the right place

---
 relion_run_topaz/run_topaz_pick.py | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)

diff --git a/relion_run_topaz/run_topaz_pick.py b/relion_run_topaz/run_topaz_pick.py
index 198133e..c31ef56 100644
--- a/relion_run_topaz/run_topaz_pick.py
+++ b/relion_run_topaz/run_topaz_pick.py
@@ -14,6 +14,8 @@
 """Import >>>"""
 import argparse
 import os
+import subprocess
+import re
 """<<< Import"""
 
 """USAGE >>>"""
@@ -25,7 +27,7 @@
 """VARIABLES >>>"""
 print('running ...')
 parser = argparse.ArgumentParser()
-parser.add_argument("-t", "-tpath", "--topaz_path" , type=str, default='/usr/local/bin/topaz', help = "Topaz path. Input either a direct path to a topaz executable or a directory path where topaz exists.")
+parser.add_argument("-t", "-tpath", "--topaz_path" , type=str, default='/secondary/projects/lu/Zheng/software/conda/anaconda3/envs/topaz/bin/topaz', help = "Topaz path. Input either a direct path to a topaz executable or a directory path where topaz exists.")
 parser.add_argument("-i", "--input", "--in_mics", help = "Input micrographs")
 parser.add_argument("-o", "--output", type=str, help = "Output folder (full path)")
 parser.add_argument("-d", "--device", type=int, default=0, help = "GPU/CPU devide. Non-negative numbers correspond to GPU IDs. Negative numbers correspond to CPU processing.")
@@ -93,10 +95,15 @@
 """make star files >>>"""
 #make star files in the right folder
 print('Making star files...')
-os.system(str('''relion_star_printtable ''')+inargsMics+str(''' data_micrographs _rlnMicrographName | awk -F"/" 'NR==1{print $(NF-1)}' > ''')+tmpfile)
-tmpdf=open(tmpfile).readline().rstrip('\n')
+file_path = subprocess.check_output(' '.join(['relion_star_printtable', inargsMics, 'data_micrographs _rlnMicrographName | head -n 1']), shell=True, encoding='utf-8').strip()
+job_pattern = re.compile('/job[0-9]{3}/(?P<suffix>.*$)')
+match = job_pattern.search(file_path)
+if match:
+    tmpdf = os.path.dirname(match['suffix'])
+else:
+    tmpdf = os.path.basename(os.path.dirname(file_path))
 outopaz_path=outargsPath+tmpdf+'/'
-os.system(str('mkdir ')+outopaz_path+str(';rm ')+tmpfile)
+os.system(str('mkdir -p ')+outopaz_path)
 mic_filenames=list(set([x.split('\t')[0] for x in open(outargsResults2).readlines()[1:]]))
 topaz_picks=[x.split('\t') for x in open(outargsResults2).readlines()[1:]]
 for name in mic_filenames: