cockpit 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. #!/usr/bin/env python
  2. import os
  3. import re
  4. import json
  5. import glob
  6. import shlex
  7. import collections
  8. import datetime
  9. import logging
  10. import random
  11. import argparse
  12. import subprocess
  13. import curses
  14. def read_info_file(path):
  15. result = {}
  16. with open(path) as f:
  17. for line in f:
  18. key, value = line.split('=')
  19. result[key] = value.strip()
  20. return result
  21. def read_edf_id19_header(filename):
  22. result = {}
  23. with open(filename) as f:
  24. data = f.read(1024)
  25. pattern = re.compile(r'(.*) = (.*) ;')
  26. for line in data.split('\n'):
  27. m = pattern.match(line)
  28. if m:
  29. result[m.group(1).strip()] = m.group(2).strip()
  30. return result
  31. def extract_motor_positions(id19_header):
  32. names = id19_header['motor_mne'].split(' ')
  33. values = id19_header['motor_pos'].split(' ')
  34. return {k: float(v) for (k, v) in zip(names, values)}
  35. def have_data(path):
  36. return os.path.exists(path) and glob.glob(os.path.join(path, '*.tif'))
  37. class Configuration(object):
  38. def __init__(self, source, destination):
  39. self.source = os.path.abspath(source)
  40. self.destination = os.path.abspath(destination)
  41. class LineList(object):
  42. def __init__(self, window):
  43. self.window = window
  44. self.height, self.width = window.getmaxyx()
  45. self.current = 0
  46. self.lines = []
  47. def redraw(self):
  48. for y in range(len(self.lines)):
  49. line, attr = self.lines[y]
  50. self.window.addnstr(y, 0, line, self.width, attr)
  51. self.window.clrtoeol()
  52. self.window.refresh()
  53. def add_line(self, s, attr=0):
  54. self.lines.append((s, attr))
  55. if len(self.lines) > self.height - 1:
  56. self.lines = self.lines[1:]
  57. self.redraw()
  58. def update_last(self, line=None, attr=None):
  59. if not self.lines:
  60. return
  61. old_line, old_attr = self.lines[-1]
  62. self.lines[-1] = (line or old_line, attr or old_attr)
  63. self.redraw()
  64. class Colors(object):
  65. NORMAL = 1
  66. SUCCESS = 2
  67. WARN = 3
  68. ERROR = 4
  69. STATUS_BAR = 5
  70. HIGHLIGHT = 6
  71. def __init__(self):
  72. curses.init_pair(Colors.NORMAL, curses.COLOR_WHITE, curses.COLOR_BLACK)
  73. curses.init_pair(Colors.SUCCESS, curses.COLOR_GREEN, curses.COLOR_BLACK)
  74. curses.init_pair(Colors.WARN, curses.COLOR_YELLOW, curses.COLOR_BLACK)
  75. curses.init_pair(Colors.ERROR, curses.COLOR_RED, curses.COLOR_BLACK)
  76. curses.init_pair(Colors.STATUS_BAR, curses.COLOR_BLACK, curses.COLOR_YELLOW)
  77. curses.init_pair(Colors.HIGHLIGHT, curses.COLOR_WHITE, curses.COLOR_BLACK)
  78. self.attrs = {
  79. Colors.NORMAL: curses.A_NORMAL,
  80. Colors.SUCCESS: curses.A_NORMAL,
  81. Colors.WARN: curses.A_BOLD,
  82. Colors.ERROR: curses.A_BOLD,
  83. Colors.STATUS_BAR: curses.A_NORMAL,
  84. Colors.HIGHLIGHT: curses.A_BOLD,
  85. }
  86. def get(self, code):
  87. return curses.color_pair(code) | self.attrs[code]
  88. class StatusBar(object):
  89. def __init__(self, window, colors):
  90. self.window = window
  91. self.c = colors
  92. def update(self, s):
  93. self.window.clear()
  94. self.window.bkgd(' ', self.c.get(Colors.STATUS_BAR))
  95. self.window.addstr(s, self.c.get(Colors.STATUS_BAR))
  96. class LogList(LineList):
  97. def __init__(self, window, colors):
  98. self.line_list = LineList(window)
  99. self.c = colors
  100. self.log_file = open('cockpit.log', 'a')
  101. def _log_time(self, s, attr):
  102. timestamp = datetime.datetime.now().strftime('%H:%M:%S')
  103. log = '[{}] {}'.format(timestamp, s)
  104. self.line_list.add_line(log, attr)
  105. self.log_file.write(log)
  106. if not log.endswith('\n'):
  107. self.log_file.write('\n')
  108. self.log_file.flush()
  109. os.fsync(self.log_file.fileno())
  110. def info(self, s):
  111. self._log_time(s, self.c.get(Colors.NORMAL))
  112. def highlight(self, s):
  113. self._log_time(s, self.c.get(Colors.HIGHLIGHT))
  114. def success(self, s):
  115. self._log_time(s, self.c.get(Colors.SUCCESS))
  116. def warn(self, s):
  117. self._log_time(s, self.c.get(Colors.WARN))
  118. def error(self, s):
  119. self._log_time(s, self.c.get(Colors.ERROR))
  120. class CommandList(LineList):
  121. def __init__(self, window, colors):
  122. self.line_list = LineList(window)
  123. self.normal = colors.get(Colors.NORMAL)
  124. self.highlight = colors.get(Colors.HIGHLIGHT)
  125. self.current = ''
  126. def add_character(self, c):
  127. self.current += c
  128. self.line_list.update_last(line='> {}'.format(self.current))
  129. def backspace(self):
  130. if self.current:
  131. self.current = self.current[:len(self.current) - 1]
  132. self.add_character('')
  133. def set_actions(self, actions):
  134. self.current = ''
  135. for a in actions.values():
  136. self.line_list.add_line('[{}] {}'.format(a.key, a.note), self.highlight)
  137. class Action(object):
  138. def __init__(self, key, note, func, next_state):
  139. self.key = key
  140. self.note = note
  141. self.run = func
  142. self.next_state = next_state
  143. def __repr__(self):
  144. return '<Action:key={}>'.format(self.key)
  145. class StateMachine(object):
  146. START = 0
  147. QUIT = 1
  148. SYNC = 2
  149. CLEAN = 3
  150. OPTIMIZE = 5
  151. QUICK_OPTIMIZE = 6
  152. RECONSTRUCT = 7
  153. def __init__(self):
  154. self.current = StateMachine.START
  155. self.transitions = {
  156. StateMachine.START: collections.OrderedDict(),
  157. StateMachine.CLEAN: collections.OrderedDict(),
  158. StateMachine.QUIT: collections.OrderedDict(),
  159. StateMachine.SYNC: collections.OrderedDict(),
  160. StateMachine.OPTIMIZE: collections.OrderedDict(),
  161. StateMachine.QUICK_OPTIMIZE: collections.OrderedDict(),
  162. StateMachine.RECONSTRUCT: collections.OrderedDict(),
  163. }
  164. def add_action(self, from_state, action):
  165. self.transitions[from_state][action.key] = action
  166. def transition(self, action):
  167. self.current = self.transitions[self.current][action.key].next_state
  168. @property
  169. def actions(self):
  170. return self.transitions[self.current]
  171. def is_valid_key(self, key):
  172. return key in (k for k in self.transitions[self.current].keys())
  173. class Parameters(object):
  174. def __init__(self, axis, angle):
  175. self.axis = axis
  176. self.angle = angle
  177. class Dataset(object):
  178. def __init__(self, path):
  179. self.path = path
  180. self.prefix = os.path.basename(path)
  181. def __repr__(self):
  182. return '<Dataset(prefix={})>'.format(self.prefix)
  183. def join_path(self, child_path):
  184. return os.path.join(self.path, child_path)
  185. class Application(object):
  186. def __init__(self, config):
  187. self.config = config
  188. self.running = True
  189. self.datasets = []
  190. self.known = set()
  191. self.current = None
  192. self.index = -1
  193. def scan(self):
  194. new = []
  195. for p in os.listdir(self.config.destination):
  196. path = os.path.join(self.config.destination, p)
  197. if os.path.isdir(path) and p not in self.known:
  198. new.append(Dataset(path))
  199. self.known.add(p)
  200. if new:
  201. for d in new:
  202. self.log.highlight("Found new dataset {}".format(d.prefix))
  203. self.datasets.append(d)
  204. def run_command(self, cmd):
  205. try:
  206. self.log.info("Executing `{}`".format(cmd))
  207. p = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  208. for line in iter(p.stdout.readline, ''):
  209. self.log.info(line)
  210. for line in iter(p.stderr.readline, ''):
  211. self.log.error(line)
  212. while p.poll() is None:
  213. pass
  214. if p.returncode == 0:
  215. self.log.success("done")
  216. return True
  217. self.log.error("Command returned {}".format(p.returncode))
  218. return False
  219. except Exception as e:
  220. self.log.error("{}".format(e))
  221. return False
  222. @property
  223. def params_name(self):
  224. return '{}params.json'.format(self.current.prefix)
  225. def read_info(self):
  226. info_file = os.path.join(self.current.path, '{}.info'.format(self.current.prefix))
  227. return read_info_file(info_file)
  228. def read_optimal_params(self, scale=1.0):
  229. with open(self.params_name) as f:
  230. opt = json.load(f)
  231. return Parameters(opt['x-center']['value'], opt['lamino-angle']['value'] * scale)
  232. def optimize(self, resize):
  233. slices_per_device = 100
  234. half_range = 1.0
  235. info = self.read_info()
  236. axis = (float(info['Col_end']) + 1) / 2.0
  237. axis_step = 0.25
  238. fname = os.path.join(self.current.path, '{}0000.edf'.format(self.current.prefix))
  239. header = read_edf_id19_header(fname)
  240. motor_pos = extract_motor_positions(header)
  241. inclination_angle = motor_pos['rytot']
  242. theta = 90.0 - inclination_angle
  243. angle_step = 0.025
  244. angle_start = theta - half_range
  245. angle_stop = theta + half_range
  246. x_region = 960
  247. y_region = 960
  248. fc_path = '{path}/fc'.format(path=self.current.path)
  249. if resize:
  250. x_region /= 2
  251. y_region /= 2
  252. axis /= 2
  253. axis_step /= 2
  254. fc_path = '{path}/fc-small'.format(path=self.current.path)
  255. axis_start = axis - slices_per_device * axis_step
  256. axis_stop = axis + slices_per_device * axis_step
  257. self.log.info(" Using theta = {}, inclination angle = {}".format(theta, inclination_angle))
  258. self.log.info(" Scanning lamino angle within [{}:{}:{}]".format(angle_start, angle_stop, angle_step))
  259. self.log.info(" Scanning x axis within [{}:{}:{}]".format(axis_start, axis_stop, axis_step))
  260. opt_params = ('--num-iterations 2'
  261. ' --axis-range={ax_start},{ax_stop},{ax_step}'
  262. ' --lamino-angle-range={an_start},{an_stop},{an_step}'
  263. ' --metric kurtosis --z-metric kurtosis'
  264. ' --tmp-output {path}/tmp'
  265. .format(ax_start=axis_start, ax_stop=axis_stop, ax_step=axis_step,
  266. an_start=angle_start, an_stop=angle_stop, an_step=angle_step,
  267. path=self.current.path))
  268. params = ('--x-region="-{x_region},{x_region},1"'
  269. ' --y-region="-{y_region},{y_region},1"'
  270. ' --overall-angle -360'
  271. ' --pixel-size {pixel_size}e-6'
  272. ' --roll-angle 0'
  273. ' --slices-per-device 100'
  274. .format(pixel_size=info['PixelSize'], x_region=x_region, y_region=y_region))
  275. cmd = ('optimize-parameters --verbose'
  276. ' {fc_path}'
  277. ' {opt_params}'
  278. ' --reco-params "{params}"'
  279. ' --params-filename {params_name}'
  280. .format(opt_params=opt_params, params=params, params_name=self.params_name, fc_path=fc_path))
  281. return self.run_command(cmd)
  282. def update_statusbar(self):
  283. self.log.info("Current dataset: {}".format(self.current.prefix))
  284. if self.current:
  285. self.status_bar.update("Current: {} [{}/{}]".format(self.current.prefix, self.index + 1, len(self.datasets)))
  286. def on_reconstruct(self):
  287. self.log.highlight("Reconstructing ...")
  288. path = self.current.join_path('fc')
  289. if not have_data(path):
  290. if not self.flat_correct(path):
  291. return False
  292. params = self.read_optimal_params()
  293. info = self.read_info()
  294. x_region = 960
  295. y_region = 960
  296. cmd = ('tofu lamino --verbose'
  297. ' --projections {prefix}/fc'
  298. ' --x-region="-{x_region},{x_region},1"'
  299. ' --y-region="-{y_region},{y_region},1"'
  300. ' --lamino-angle {lamino_angle}'
  301. ' --axis {x_axis},{y_axis}'
  302. ' --overall-angle -360'
  303. ' --pixel-size {pixel_size}e-6'
  304. ' --roll-angle 0'
  305. ' --slices-per-device 300'
  306. ' --output {prefix}/slices/slice'
  307. .format(pixel_size=info['PixelSize'],
  308. x_region=x_region, y_region=y_region,
  309. lamino_angle=params.angle,
  310. x_axis=params.axis, y_axis=float(info['Dim_2']) / 2,
  311. prefix=self.current.prefix))
  312. return self.run_command(cmd)
  313. def on_quit(self):
  314. self.running = False
  315. return True
  316. def on_sync(self):
  317. self.log.highlight("Syncing data ...")
  318. cmd = 'bash sync.sh {} {}'.format(self.config.source, self.config.destination)
  319. return self.run_command(cmd)
  320. def on_clean(self):
  321. self.log.highlight("Cleaning {}".format(self.config.destination))
  322. return True
  323. def flat_correct(self, output_path, append=''):
  324. self.log.highlight("Generate flat field corrected projections ...")
  325. try:
  326. info = self.read_info()
  327. path = self.current.path
  328. data = dict(path=path, prefix=self.current.prefix,
  329. num=info['TOMO_N'], step=1, output=output_path)
  330. cmd = ('tofu flatcorrect --verbose'
  331. ' --reduction-mode median'
  332. ' --projections "{path}/{prefix}*.edf"'
  333. ' --darks {path}/darkend0000.edf'
  334. ' --flats {path}/ref*_0000.edf'
  335. ' --flats2 {path}/ref*_{num}.edf'
  336. ' --output {output}/fc-%04i.tif'
  337. ' --number {num}'
  338. ' --step {step}'
  339. ' --absorptivity'
  340. ' --fix-nan-and-inf '.format(**data))
  341. cmd += append
  342. return self.run_command(cmd)
  343. except Exception as e:
  344. self.log.error("Error: {}".format(e))
  345. return False
  346. def on_quick_optimize(self):
  347. self.log.highlight("Quick optimization ...")
  348. path = self.current.join_path('fc-small')
  349. if not have_data(path):
  350. if not self.flat_correct(path, append='--resize 2'):
  351. return False
  352. try:
  353. if self.optimize(True):
  354. with open(self.params_name) as f:
  355. opt = json.load(f)
  356. opt['x-center']['value'] *= 2.0
  357. with open(self.params_name, 'w') as f:
  358. json.dump(opt, f)
  359. params = self.read_optimal_params()
  360. self.log.highlight(" Optimal axis: {}".format(params.angle))
  361. self.log.highlight(" Optimal center: {}".format(params.axis))
  362. return True
  363. except Exception as e:
  364. self.log.error("Error: {}".format(e))
  365. return False
  366. def on_optimize(self):
  367. self.log.highlight("Optimizing ...")
  368. path = self.current.join_path('fc')
  369. if not have_data(path):
  370. if not self.flat_correct(path):
  371. return False
  372. try:
  373. if self.optimize(False):
  374. params = self.read_optimal_params()
  375. self.log.highlight(" Optimal axis: {}".format(params.angle))
  376. self.log.highlight(" Optimal center: {}".format(params.axis))
  377. return True
  378. except Exception as e:
  379. self.log.error("Could not optimize: {}".format(e))
  380. return False
  381. def on_next_dataset(self):
  382. self.index = (self.index + 1) % len(self.datasets)
  383. self.current = self.datasets[self.index]
  384. self.update_statusbar()
  385. def on_previous_dataset(self):
  386. self.index = (self.index - 1) % len(self.datasets)
  387. self.current = self.datasets[self.index]
  388. self.update_statusbar()
  389. def do_nothing(self):
  390. return True
  391. def _run(self, screen):
  392. curses.curs_set(False)
  393. height, width = screen.getmaxyx()
  394. colors = Colors()
  395. top_pane = screen.subwin(1, width, 0, 0)
  396. bottom_pane = screen.subwin(height - 1, width, 1, 0)
  397. left_pane = bottom_pane.subwin(height - 1, width / 4, 1, 0)
  398. right_pane = bottom_pane.subwin(height - 1, 3 * width / 4, 1, width / 4)
  399. self.status_bar = StatusBar(top_pane, colors)
  400. self.status_bar.update('Cockpit')
  401. cmd_window = CommandList(left_pane, colors)
  402. machine = StateMachine()
  403. quit = Action('e', 'Exit', self.on_quit, machine.QUIT)
  404. sync = Action('s', 'Sync', self.on_sync, machine.SYNC)
  405. clean = Action('c', 'Clean', self.on_clean, machine.CLEAN)
  406. quick_optimize = Action('q', 'Quick optimization', self.on_quick_optimize, machine.QUICK_OPTIMIZE)
  407. optimize = Action('o', 'Optimization', self.on_optimize, machine.OPTIMIZE)
  408. reconstruct = Action('r', 'Reconstruct', self.on_reconstruct, machine.RECONSTRUCT)
  409. next_dataset = Action('n', 'Next dataset', self.on_next_dataset, machine.START)
  410. previous_dataset = Action('p', 'Previous dataset', self.on_previous_dataset, machine.START)
  411. machine.add_action(machine.START, sync)
  412. machine.add_action(machine.START, quick_optimize)
  413. machine.add_action(machine.START, optimize)
  414. machine.add_action(machine.START, next_dataset)
  415. machine.add_action(machine.START, previous_dataset)
  416. machine.add_action(machine.START, quit)
  417. machine.add_action(machine.SYNC, quit)
  418. machine.add_action(machine.QUICK_OPTIMIZE, reconstruct)
  419. machine.add_action(machine.QUICK_OPTIMIZE, optimize)
  420. machine.add_action(machine.QUICK_OPTIMIZE, next_dataset)
  421. machine.add_action(machine.QUICK_OPTIMIZE, previous_dataset)
  422. machine.add_action(machine.QUICK_OPTIMIZE, quit)
  423. machine.add_action(machine.OPTIMIZE, quick_optimize)
  424. machine.add_action(machine.OPTIMIZE, reconstruct)
  425. machine.add_action(machine.OPTIMIZE, next_dataset)
  426. machine.add_action(machine.OPTIMIZE, previous_dataset)
  427. machine.add_action(machine.OPTIMIZE, quit)
  428. machine.add_action(machine.CLEAN, sync)
  429. machine.add_action(machine.CLEAN, quit)
  430. self.log = LogList(right_pane, colors)
  431. self.log.info('Source dir set to {}'.format(self.config.source))
  432. self.log.info('Destination dir set to {}'.format(self.config.destination))
  433. self.scan()
  434. if self.datasets:
  435. self.index = 0
  436. self.current = self.datasets[0]
  437. if os.path.exists(self.params_name):
  438. machine.add_action(machine.START, reconstruct)
  439. self.update_statusbar()
  440. cmd_window.set_actions(machine.actions)
  441. while self.running:
  442. ci = screen.getch()
  443. cc = chr(ci) if ci < 256 else ''
  444. if machine.is_valid_key(cc):
  445. cmd_window.add_character(cc)
  446. action = machine.actions[cc]
  447. if action.run():
  448. machine.transition(action)
  449. cmd_window.set_actions(machine.actions)
  450. elif ci == curses.KEY_BACKSPACE:
  451. cmd_window.backspace()
  452. self.scan()
  453. screen.refresh()
  454. def run(self):
  455. curses.wrapper(self._run)
  456. if __name__ == '__main__':
  457. parser = argparse.ArgumentParser()
  458. parser.add_argument('--source', help='Source directory', default='.', metavar='DIR')
  459. parser.add_argument('--destination', help='Destination directory', default='.', metavar='DIR')
  460. args = parser.parse_args()
  461. config = Configuration(args.source, args.destination)
  462. app = Application(config)
  463. app.run()