cockpit 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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 - 1:
  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. self.log_file = open('cockpit.log', 'a')
  96. def _log_time(self, s, attr):
  97. timestamp = datetime.datetime.now().strftime('%H:%M:%S')
  98. log = '[{}] {}'.format(timestamp, s)
  99. self.line_list.add_line(log, attr)
  100. self.log_file.write(log)
  101. if not log.endswith('\n'):
  102. self.log_file.write('\n')
  103. self.log_file.flush()
  104. os.fsync(self.log_file.fileno())
  105. def info(self, s):
  106. self._log_time(s, self.c.get(Colors.NORMAL))
  107. def highlight(self, s):
  108. self._log_time(s, self.c.get(Colors.HIGHLIGHT))
  109. def success(self, s):
  110. self._log_time(s, self.c.get(Colors.SUCCESS))
  111. def warn(self, s):
  112. self._log_time(s, self.c.get(Colors.WARN))
  113. def error(self, s):
  114. self._log_time(s, self.c.get(Colors.ERROR))
  115. class CommandList(LineList):
  116. def __init__(self, window, colors):
  117. self.line_list = LineList(window)
  118. self.normal = colors.get(Colors.NORMAL)
  119. self.highlight = colors.get(Colors.HIGHLIGHT)
  120. self.current = ''
  121. def add_character(self, c):
  122. self.current += c
  123. self.line_list.update_last(line='> {}'.format(self.current))
  124. def backspace(self):
  125. if self.current:
  126. self.current = self.current[:len(self.current) - 1]
  127. self.add_character('')
  128. def set_actions(self, actions):
  129. self.line_list.update_last(attr=self.normal)
  130. self.current = ''
  131. message = ' | '.join(('[{}] {}'.format(a.key, a.note) for a in actions.values()))
  132. self.line_list.add_line(message, self.highlight)
  133. class Action(object):
  134. def __init__(self, key, note, func, next_state):
  135. self.key = key
  136. self.note = note
  137. self.run = func
  138. self.next_state = next_state
  139. def __repr__(self):
  140. return '<Action:key={}>'.format(self.key)
  141. class StateMachine(object):
  142. START = 0
  143. QUIT = 1
  144. SYNC = 2
  145. CLEAN = 3
  146. FLATCORRECT = 4
  147. OPTIMIZE = 5
  148. def __init__(self):
  149. self.current = StateMachine.START
  150. self.transitions = {
  151. StateMachine.START: collections.OrderedDict(),
  152. StateMachine.CLEAN: collections.OrderedDict(),
  153. StateMachine.FLATCORRECT: collections.OrderedDict(),
  154. StateMachine.QUIT: collections.OrderedDict(),
  155. StateMachine.SYNC: collections.OrderedDict(),
  156. StateMachine.OPTIMIZE: collections.OrderedDict(),
  157. }
  158. def add_action(self, from_state, action):
  159. self.transitions[from_state][action.key] = action
  160. def transition(self, action):
  161. self.current = self.transitions[self.current][action.key].next_state
  162. @property
  163. def actions(self):
  164. return self.transitions[self.current]
  165. def is_valid_key(self, key):
  166. return key in (k for k in self.transitions[self.current].keys())
  167. class Application(object):
  168. def __init__(self, config):
  169. self.config = config
  170. self.running = True
  171. def run_command(self, cmd):
  172. try:
  173. p = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  174. for line in iter(p.stdout.readline, ''):
  175. self.log.info(line)
  176. for line in iter(p.stderr.readline, ''):
  177. self.log.error(line)
  178. while p.poll() is None:
  179. pass
  180. if p.returncode == 0:
  181. self.log.success("done")
  182. return True
  183. self.log.error("Command returned {}".format(p.returncode))
  184. return False
  185. except Exception as e:
  186. self.log.error("{}".format(e))
  187. return False
  188. @property
  189. def prefix(self):
  190. return os.path.basename(self.config.destination)
  191. def read_info(self):
  192. info_file = os.path.join(self.config.destination, '{}.info'.format(self.prefix))
  193. return read_info_file(info_file)
  194. def on_quit(self):
  195. self.running = False
  196. return True
  197. def on_sync(self):
  198. self.log.highlight("Syncing data ...")
  199. cmd = 'bash sync.sh {} {}'.format(self.config.source, self.config.destination)
  200. return self.run_command(cmd)
  201. def on_clean(self):
  202. self.log.highlight("Cleaning {}".format(self.config.destination))
  203. return True
  204. def on_flat_correct(self):
  205. self.log.highlight("Flat field correction ...")
  206. info = self.read_info()
  207. data = dict(path=self.config.destination, prefix=self.prefix, num=info['TOMO_N'], step=1)
  208. cmd = ('tofu flatcorrect --verbose'
  209. ' --reduction-mode median'
  210. ' --projections "{path}/{prefix}*.edf"'
  211. ' --darks {path}/darkend0000.edf'
  212. ' --flats {path}/ref*_0000.edf'
  213. ' --flats2 {path}/ref*_{num}.edf'
  214. ' --output {path}/fc/fc-%04i.tif'
  215. ' --number {num}'
  216. ' --step {step}'
  217. ' --absorptivity'
  218. ' --fix-nan-and-inf'.format(**data))
  219. return self.run_command(cmd)
  220. def on_optimize(self):
  221. self.log.highlight("Optimizing ...")
  222. slices_per_device = 100
  223. half_range = 1.0
  224. info = self.read_info()
  225. axis = (float(info['Col_end']) + 1) / 2.0
  226. axis_step = 0.25
  227. axis_start = axis - slices_per_device * axis_step
  228. axis_stop = axis + slices_per_device * axis_step
  229. fname = os.path.join(self.config.destination, '{}0000.edf'.format(self.prefix))
  230. header = read_edf_id19_header(fname)
  231. motor_pos = extract_motor_positions(header)
  232. inclination_angle = motor_pos['rytot']
  233. theta = 90.0 - inclination_angle
  234. angle_step = 0.025
  235. angle_start = theta - half_range
  236. angle_stop = theta + half_range
  237. self.log.info(" Using theta = {}, inclination angle = {}".format(theta, inclination_angle))
  238. self.log.info(" Scanning angle within [{}:{}:{}]".format(angle_start, angle_stop, angle_step))
  239. self.log.info(" Scanning axis within [{}:{}:{}]".format(axis_start, axis_stop, axis_step))
  240. opt_params = ('--num-iterations 2'
  241. ' --axis-range={ax_start},{ax_stop},{ax_step}'
  242. ' --lamino-angle-range={an_start},{an_stop},{an_step}'
  243. ' --metric kurtosis --z-metric kurtosis'
  244. .format(ax_start=axis_start, ax_stop=axis_stop, ax_step=axis_step,
  245. an_start=angle_start, an_stop=angle_stop, an_step=angle_step))
  246. params = ('--x-region=-960,960,1'
  247. ' --y-region=-960,960,1'
  248. ' --overall-angle -360'
  249. ' --pixel-size {pixel_size}e-6'
  250. ' --roll-angle 0'
  251. ' --slices-per-device 100'
  252. .format(pixel_size=info['PixelSize']))
  253. cmd = ('optimize-parameters --verbose'
  254. ' {prefix}/fc'
  255. ' {opt_params}'
  256. ' --reco-params "{params}"'
  257. ' --params-filename params.json'
  258. .format(opt_params=opt_params, params=params, prefix=self.prefix))
  259. with open('log.txt', 'w') as f:
  260. f.write(cmd)
  261. return self.run_command(cmd)
  262. def do_nothing(self):
  263. return True
  264. def _run(self, screen):
  265. curses.curs_set(False)
  266. height, width = screen.getmaxyx()
  267. colors = Colors()
  268. top_pane = screen.subwin(1, width, 0, 0)
  269. bottom_pane = screen.subwin(height - 1, width, 1, 0)
  270. left_pane = bottom_pane.subwin(height - 1, width / 3, 1, 0)
  271. right_pane = bottom_pane.subwin(height - 1, 2 * width / 3, 1, width / 3)
  272. status_bar = StatusBar(top_pane, colors)
  273. status_bar.update('Cockpit')
  274. cmd_window = CommandList(left_pane, colors)
  275. machine = StateMachine()
  276. quit = Action('q', 'Quit', self.on_quit, machine.QUIT)
  277. sync = Action('s', 'Sync', self.on_sync, machine.SYNC)
  278. flatcorrect = Action('f', 'Flat correct', self.on_flat_correct, machine.FLATCORRECT)
  279. clean = Action('c', 'Clean', self.on_clean, machine.CLEAN)
  280. optimize = Action('o', 'Optimize', self.on_optimize, machine.OPTIMIZE)
  281. machine.add_action(machine.START, sync)
  282. machine.add_action(machine.START, flatcorrect)
  283. machine.add_action(machine.START, optimize)
  284. machine.add_action(machine.START, clean)
  285. machine.add_action(machine.START, quit)
  286. machine.add_action(machine.SYNC, flatcorrect)
  287. machine.add_action(machine.SYNC, clean)
  288. machine.add_action(machine.SYNC, quit)
  289. machine.add_action(machine.FLATCORRECT, optimize)
  290. machine.add_action(machine.FLATCORRECT, quit)
  291. machine.add_action(machine.OPTIMIZE, sync)
  292. machine.add_action(machine.OPTIMIZE, clean)
  293. machine.add_action(machine.OPTIMIZE, quit)
  294. machine.add_action(machine.CLEAN, sync)
  295. machine.add_action(machine.CLEAN, quit)
  296. cmd_window.set_actions(machine.actions)
  297. self.log = LogList(right_pane, colors)
  298. self.log.info('Source dir set to {}'.format(self.config.source))
  299. self.log.info('Destination dir set to {}'.format(self.config.destination))
  300. while self.running:
  301. ci = screen.getch()
  302. cc = chr(ci) if ci < 256 else ''
  303. if machine.is_valid_key(cc):
  304. cmd_window.add_character(cc)
  305. action = machine.actions[cc]
  306. if action.run():
  307. machine.transition(action)
  308. cmd_window.set_actions(machine.actions)
  309. elif ci == curses.KEY_BACKSPACE:
  310. cmd_window.backspace()
  311. screen.refresh()
  312. def run(self):
  313. curses.wrapper(self._run)
  314. if __name__ == '__main__':
  315. parser = argparse.ArgumentParser()
  316. parser.add_argument('--source', help='Source directory', default='.', metavar='DIR')
  317. parser.add_argument('--destination', help='Destination directory', default='.', metavar='DIR')
  318. args = parser.parse_args()
  319. config = Configuration(args.source, args.destination)
  320. app = Application(config)
  321. app.run()