cockpit 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. #!/usr/bin/env python
  2. import os
  3. import re
  4. import shlex
  5. import collections
  6. import datetime
  7. import logging
  8. import random
  9. import argparse
  10. import subprocess
  11. import curses
  12. def read_info_file(path):
  13. result = {}
  14. with open(path) as f:
  15. for line in f:
  16. key, value = line.split('=')
  17. result[key] = value.strip()
  18. return result
  19. def read_edf_id19_header(filename):
  20. result = {}
  21. with open(filename) as f:
  22. data = f.read(1024)
  23. pattern = re.compile(r'(.*) = (.*) ;')
  24. for line in data.split('\n'):
  25. m = pattern.match(line)
  26. if m:
  27. result[m.group(1).strip()] = m.group(2).strip()
  28. return result
  29. def extract_motor_positions(id19_header):
  30. names = id19_header['motor_mne'].split(' ')
  31. values = id19_header['motor_pos'].split(' ')
  32. return {k: float(v) for (k, v) in zip(names, values)}
  33. class Configuration(object):
  34. def __init__(self, source, destination):
  35. self.source = os.path.abspath(source)
  36. self.destination = os.path.abspath(destination)
  37. class LineList(object):
  38. def __init__(self, window):
  39. self.window = window
  40. self.height, self.width = window.getmaxyx()
  41. self.current = 0
  42. self.lines = []
  43. def redraw(self):
  44. for y in range(len(self.lines)):
  45. line, attr = self.lines[y]
  46. self.window.addnstr(y, 0, line, self.width, attr)
  47. self.window.clrtoeol()
  48. self.window.refresh()
  49. def add_line(self, s, attr=0):
  50. self.lines.append((s, attr))
  51. if len(self.lines) > self.height:
  52. self.lines = self.lines[1:]
  53. self.redraw()
  54. def update_last(self, line=None, attr=None):
  55. if not self.lines:
  56. return
  57. old_line, old_attr = self.lines[-1]
  58. self.lines[-1] = (line or old_line, attr or old_attr)
  59. self.redraw()
  60. class Colors(object):
  61. NORMAL = 1
  62. SUCCESS = 2
  63. WARN = 3
  64. ERROR = 4
  65. STATUS_BAR = 5
  66. HIGHLIGHT = 6
  67. def __init__(self):
  68. curses.init_pair(Colors.NORMAL, curses.COLOR_WHITE, curses.COLOR_BLACK)
  69. curses.init_pair(Colors.SUCCESS, curses.COLOR_GREEN, curses.COLOR_BLACK)
  70. curses.init_pair(Colors.WARN, curses.COLOR_YELLOW, curses.COLOR_BLACK)
  71. curses.init_pair(Colors.ERROR, curses.COLOR_RED, curses.COLOR_BLACK)
  72. curses.init_pair(Colors.STATUS_BAR, curses.COLOR_BLACK, curses.COLOR_YELLOW)
  73. curses.init_pair(Colors.HIGHLIGHT, curses.COLOR_WHITE, curses.COLOR_BLACK)
  74. self.attrs = {
  75. Colors.NORMAL: curses.A_NORMAL,
  76. Colors.SUCCESS: curses.A_NORMAL,
  77. Colors.WARN: curses.A_BOLD,
  78. Colors.ERROR: curses.A_BOLD,
  79. Colors.STATUS_BAR: curses.A_NORMAL,
  80. Colors.HIGHLIGHT: curses.A_BOLD,
  81. }
  82. def get(self, code):
  83. return curses.color_pair(code) | self.attrs[code]
  84. class StatusBar(object):
  85. def __init__(self, window, colors):
  86. self.window = window
  87. self.c = colors
  88. def update(self, s):
  89. self.window.bkgd(' ', self.c.get(Colors.STATUS_BAR))
  90. self.window.addstr(s, self.c.get(Colors.STATUS_BAR))
  91. class LogList(LineList):
  92. def __init__(self, window, colors):
  93. self.line_list = LineList(window)
  94. self.c = colors
  95. def _log_time(self, s, attr):
  96. timestamp = datetime.datetime.now().strftime('%H:%M:%S')
  97. self.line_list.add_line('[{}] {}'.format(timestamp, s), attr)
  98. def info(self, s):
  99. self._log_time(s, self.c.get(Colors.NORMAL))
  100. def highlight(self, s):
  101. self._log_time(s, self.c.get(Colors.HIGHLIGHT))
  102. def success(self, s):
  103. self._log_time(s, self.c.get(Colors.SUCCESS))
  104. def warn(self, s):
  105. self._log_time(s, self.c.get(Colors.WARN))
  106. def error(self, s):
  107. self._log_time(s, self.c.get(Colors.ERROR))
  108. class CommandList(LineList):
  109. def __init__(self, window, colors):
  110. self.line_list = LineList(window)
  111. self.normal = colors.get(Colors.NORMAL)
  112. self.highlight = colors.get(Colors.HIGHLIGHT)
  113. self.current = ''
  114. def add_character(self, c):
  115. self.current += c
  116. self.line_list.update_last(line='> {}'.format(self.current))
  117. def backspace(self):
  118. if self.current:
  119. self.current = self.current[:len(self.current) - 1]
  120. self.add_character('')
  121. def set_actions(self, actions):
  122. self.line_list.update_last(attr=self.normal)
  123. self.current = ''
  124. message = ' | '.join(('[{}] {}'.format(a.key, a.note) for a in actions.values()))
  125. self.line_list.add_line(message, self.highlight)
  126. class Action(object):
  127. def __init__(self, key, note, func, next_state):
  128. self.key = key
  129. self.note = note
  130. self.run = func
  131. self.next_state = next_state
  132. def __repr__(self):
  133. return '<Action:key={}>'.format(self.key)
  134. class StateMachine(object):
  135. START = 0
  136. QUIT = 1
  137. SYNC = 2
  138. CLEAN = 3
  139. FLATCORRECT = 4
  140. OPTIMIZE = 5
  141. def __init__(self):
  142. self.current = StateMachine.START
  143. self.transitions = {
  144. StateMachine.START: collections.OrderedDict(),
  145. StateMachine.CLEAN: collections.OrderedDict(),
  146. StateMachine.FLATCORRECT: collections.OrderedDict(),
  147. StateMachine.QUIT: collections.OrderedDict(),
  148. StateMachine.SYNC: collections.OrderedDict(),
  149. StateMachine.OPTIMIZE: collections.OrderedDict(),
  150. }
  151. def add_action(self, from_state, action):
  152. self.transitions[from_state][action.key] = action
  153. def transition(self, action):
  154. self.current = self.transitions[self.current][action.key].next_state
  155. @property
  156. def actions(self):
  157. return self.transitions[self.current]
  158. def is_valid_key(self, key):
  159. return key in (k for k in self.transitions[self.current].keys())
  160. class Application(object):
  161. def __init__(self, config):
  162. self.config = config
  163. self.running = True
  164. def run_command(self, cmd):
  165. try:
  166. p = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  167. for line in iter(p.stdout.readline, ''):
  168. self.log.info(line)
  169. for line in iter(p.stderr.readline, ''):
  170. self.log.error(line)
  171. while p.poll() is None:
  172. pass
  173. if p.returncode == 0:
  174. self.log.success("done")
  175. return True
  176. self.log.error("Command returned {}".format(p.returncode))
  177. return False
  178. except Exception as e:
  179. self.log.error("{}".format(e))
  180. return False
  181. @property
  182. def prefix(self):
  183. return os.path.basename(self.config.destination)
  184. def read_info(self):
  185. info_file = os.path.join(self.config.destination, '{}.info'.format(self.prefix))
  186. return read_info_file(info_file)
  187. def on_quit(self):
  188. self.running = False
  189. return True
  190. def on_sync(self):
  191. self.log.highlight("Syncing data ...")
  192. cmd = 'bash sync.sh {} {}'.format(self.config.source, self.config.destination)
  193. return self.run_command(cmd)
  194. def on_clean(self):
  195. self.log.highlight("Cleaning {}".format(self.config.destination))
  196. return True
  197. def on_flat_correct(self):
  198. self.log.highlight("Flat field correction ...")
  199. info = self.read_info()
  200. data = dict(path=self.config.destination, prefix=self.prefix, num=info['TOMO_N'], step=1)
  201. cmd = ('tofu flatcorrect --verbose'
  202. ' --reduction-mode median'
  203. ' --projections "{path}/{prefix}*.edf"'
  204. ' --darks {path}/darkend0000.edf'
  205. ' --flats {path}/ref*_0000.edf'
  206. ' --flats2 {path}/ref*_{num}.edf'
  207. ' --output {path}/fc/fc-%04i.tif'
  208. ' --number {num}'
  209. ' --step {step}'
  210. ' --absorptivity'
  211. ' --fix-nan-and-inf'.format(**data))
  212. return self.run_command(cmd)
  213. def on_optimize(self):
  214. self.log.highlight("Optimizing ...")
  215. slices_per_device = 100
  216. half_range = 1.0
  217. info = self.read_info()
  218. axis = (float(info['Col_end']) + 1) / 2.0
  219. axis_step = 0.25
  220. axis_start = axis - slices_per_device * axis_step
  221. axis_stop = axis + slices_per_device * axis_step
  222. fname = os.path.join(self.config.destination, '{}0000.edf'.format(self.prefix))
  223. header = read_edf_id19_header(fname)
  224. motor_pos = extract_motor_positions(header)
  225. inclination_angle = motor_pos['rytot']
  226. theta = 90.0 - inclination_angle
  227. angle_step = 0.025
  228. angle_start = theta - half_range
  229. angle_stop = theta + half_range
  230. self.log.info(" Using theta = {}, inclination angle = {}".format(theta, inclination_angle))
  231. self.log.info(" Scanning angle within [{}:{}:{}]".format(angle_start, angle_stop, angle_step))
  232. self.log.info(" Scanning axis within [{}:{}:{}]".format(axis_start, axis_stop, axis_step))
  233. opt_params = ('--num-iterations 2'
  234. ' --axis-range={ax_start},{ax_stop},{ax_step}'
  235. ' --lamino-angle-range={an_start},{an_stop},{an_step}'
  236. ' --metric kurtosis --z-metric kurtosis'
  237. .format(ax_start=axis_start, ax_stop=axis_stop, ax_step=axis_step,
  238. an_start=angle_start, an_stop=angle_stop, an_step=angle_step))
  239. params = ('--x-region=-960,960,1'
  240. ' --y-region=-960,960,1'
  241. ' --overall-angle -360'
  242. ' --pixel-size {pixel_size}e-6'
  243. ' --roll-angle 0'
  244. ' --slices-per-device 100'
  245. .format(pixel_size=info['PixelSize']))
  246. cmd = ('optimize-parameters --verbose'
  247. ' {prefix}/fc'
  248. ' {opt_params}'
  249. ' --reco-params "{params}"'
  250. ' --final-reco-params "{params}"'
  251. .format(opt_params=opt_params, params=params, prefix=self.prefix))
  252. with open('log.txt', 'w') as f:
  253. f.write(cmd)
  254. return self.run_command(cmd)
  255. def do_nothing(self):
  256. return True
  257. def _run(self, screen):
  258. curses.curs_set(False)
  259. height, width = screen.getmaxyx()
  260. colors = Colors()
  261. top_pane = screen.subwin(1, width, 0, 0)
  262. bottom_pane = screen.subwin(height - 1, width, 1, 0)
  263. left_pane = bottom_pane.subwin(height - 1, width / 3, 1, 0)
  264. right_pane = bottom_pane.subwin(height - 1, 2 * width / 3, 1, width / 3)
  265. status_bar = StatusBar(top_pane, colors)
  266. status_bar.update('Cockpit')
  267. cmd_window = CommandList(left_pane, colors)
  268. machine = StateMachine()
  269. quit = Action('q', 'Quit', self.on_quit, machine.QUIT)
  270. sync = Action('s', 'Sync data', self.on_sync, machine.SYNC)
  271. flatcorrect = Action('f', 'Flat correct', self.on_flat_correct, machine.FLATCORRECT)
  272. clean = Action('c', 'Clean', self.on_clean, machine.CLEAN)
  273. optimize = Action('o', 'Optimize', self.on_optimize, machine.OPTIMIZE)
  274. machine.add_action(machine.START, sync)
  275. machine.add_action(machine.START, flatcorrect)
  276. machine.add_action(machine.START, optimize)
  277. machine.add_action(machine.START, clean)
  278. machine.add_action(machine.START, quit)
  279. machine.add_action(machine.SYNC, flatcorrect)
  280. machine.add_action(machine.SYNC, clean)
  281. machine.add_action(machine.SYNC, quit)
  282. machine.add_action(machine.FLATCORRECT, optimize)
  283. machine.add_action(machine.FLATCORRECT, quit)
  284. machine.add_action(machine.OPTIMIZE, sync)
  285. machine.add_action(machine.OPTIMIZE, clean)
  286. machine.add_action(machine.OPTIMIZE, quit)
  287. machine.add_action(machine.CLEAN, sync)
  288. machine.add_action(machine.CLEAN, quit)
  289. cmd_window.set_actions(machine.actions)
  290. self.log = LogList(right_pane, colors)
  291. self.log.info('Source dir set to {}'.format(self.config.source))
  292. self.log.info('Destination dir set to {}'.format(self.config.destination))
  293. while self.running:
  294. ci = screen.getch()
  295. cc = chr(ci) if ci < 256 else ''
  296. if machine.is_valid_key(cc):
  297. cmd_window.add_character(cc)
  298. action = machine.actions[cc]
  299. if action.run():
  300. machine.transition(action)
  301. cmd_window.set_actions(machine.actions)
  302. elif ci == curses.KEY_BACKSPACE:
  303. cmd_window.backspace()
  304. screen.refresh()
  305. def run(self):
  306. curses.wrapper(self._run)
  307. if __name__ == '__main__':
  308. parser = argparse.ArgumentParser()
  309. parser.add_argument('--source', help='Source directory', default='.', metavar='DIR')
  310. parser.add_argument('--destination', help='Destination directory', default='.', metavar='DIR')
  311. args = parser.parse_args()
  312. config = Configuration(args.source, args.destination)
  313. app = Application(config)
  314. app.run()