-
Notifications
You must be signed in to change notification settings - Fork 0
/
the_monitor.py
331 lines (213 loc) · 10.9 KB
/
the_monitor.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
# type: ignore
### Standard imports. ###
import os
import curses
import pickle
### Local imports. ###
from src_scripts.utilities import (reader,
unpickler)
if __name__ == '__main__':
import argparse
import textwrap
#####################################################################################
parser = argparse.ArgumentParser(
formatter_class = argparse.RawDescriptionHelpFormatter,
usage = argparse.SUPPRESS,
description = textwrap.dedent('''
######################################
GHRSS Survey FFA Pipeline: The Monitor
######################################
Just like the cosmic being in the DC universe it is
named after, the Monitor updates the user about both
per-file and per-date progress of the pipeline. The
only input is the particular date for which the user
wishes to get an update or summary.
To be run from the "GHRSS_FFA_Pipeline" directory only.
usage: python the_monitor.py [date]
'''))
parser.add_argument('date',
type = str,
help = textwrap.dedent(
""" The date for which updates are required. """))
try:
args = parser.parse_args()
except:
parser.print_help()
parser.exit(1)
date = args.date
#####################################################################################
def build_record(config, summary):
""" Build the summary of all processing done till now by the pipeline. """
record = []
# Record the configuration.
descp_cfg = ('Current Pipeline Configuration\n'
'------------------------------\n'
'Node(s): {nodes}\n'
'Machine configuration: {mach_config}\n'
'Dates to be analysed: {dates}\n'
'Number of cores per node: {cores}\n\n'
'DM range: {DM_lowest} to {DM_highest} pc cm^-3\n'
'Number of DM trials: {numDMs}\n'
'Period ranges searched by the FFA:\n'
' (0.2 to 0.5 s), (0.5 to 2s) and (2 to 100s)\n\n'
'').format(nodes=config._config['pipeline_variables']['nodes'],
mach_config=config.mach_config,
dates=config._config['pipeline_variables']['dates'][config.backend],
cores=config.cores,
DM_lowest=config.ddplan['DM_lowest'],
DM_highest=config.ddplan['DM_highest'],
numDMs=config.ddplan['numDMs'])
record.append(descp_cfg)
# Then the summary.
header = ['Filename',
'DM trials',
'Candidates',
'Folding Status',
'Archiving Status']
fmt_hdr = ('{:<50} {:<11} {:<11} {:<15} {}\n\n').format(*header)
# Record table header.
record.append(fmt_hdr)
for meta in summary:
# Check if folding has been carried out properly.
if meta['num_fold_prfs']:
if (meta['num_candidates'] == meta['num_fold_prfs']):
fold_flag = 'Done.'
else:
fold_flag = 'Incomplete.'
else:
fold_flag = 'Not Done.'
# Check if archiving has been carried out properly.
if meta['num_arv_prfs']:
if (meta['num_fold_prfs'] == meta['num_arv_prfs']):
archive_flag = 'Done.'
else:
archive_flag = 'Incomplete.'
else:
archive_flag = 'Not Done.'
# Construct each row of the table.
row = ('{fname:<53}'
'{proc_dm_trials:<13}'
'{num_candidates:<13}'
'{fd_flag:<16}'
'{arv_flag}\n').format(fname=meta['fname'],
proc_dm_trials=str(meta['proc_dm_trials']),
num_candidates=str(meta['num_candidates']),
fd_flag=fold_flag,
arv_flag=archive_flag)
# Record each row.
record.append(row)
return record
def cli_updater(stdscr, date):
""" Create a CLI where all summaries and updates are displayed.
The CLI was built using the "curses" module in Python.
"""
if curses.has_colors():
curses.start_color()
curses.use_default_colors()
stdscr.keypad(1)
curses.curs_set(0)
# Initialise the color combinations we're going to use.
curses.init_pair(1, curses.COLOR_RED, -1)
curses.init_pair(2, curses.COLOR_GREEN, -1)
# Begin the program.
stdscr.addstr('GHRSS FFA Pipeline', curses.A_REVERSE)
stdscr.chgat(-1, curses.A_REVERSE)
stdscr.addstr(curses.LINES-1, 0, ('Press "U" to request a new update, '
'Press "S" to request a summary, '
'"Q" to quit.'))
# Change the U and the S to green and the Q to red.
stdscr.chgat(curses.LINES-1, 7, 1, curses.A_BOLD | curses.color_pair(2))
stdscr.chgat(curses.LINES-1, 42, 1, curses.A_BOLD | curses.color_pair(2))
stdscr.chgat(curses.LINES-1, 68, 1, curses.A_BOLD | curses.color_pair(1))
# Set up the window to hold the updates.
update_window = curses.newwin(curses.LINES-2, curses.COLS, 1, 0)
# Create a sub-window so as to cleanly display the update without worrying
# about over-writing the update window's borders.
update_text_window = update_window.subwin(curses.LINES-6, curses.COLS-4, 3, 2)
update_text_window.addstr('Press "U" to get an update. Press "S" to get a summary.')
# Draw a border around the main update window.
update_window.box()
# Update the internal window data structures.
stdscr.noutrefresh()
update_window.noutrefresh()
# Redraw the screen.
curses.doupdate()
# Start the event loop.
while True:
c = update_window.getch()
#####################################################################################
# If user needs an update...
if c == ord('u') or c == ord('U'):
update_text_window.clear()
update_text_window.addstr('Getting update...')
update_text_window.refresh()
update_text_window.clear()
# Get updates from the hidden process log file.
updates = reader('./{}.PIDS.log'.format(date))
# Print updates to screen.
try:
for line in updates:
update_text_window.addstr(line)
update_text_window.refresh()
# If there are no updates to print, inform the user that there is a problem.
except StopIteration:
update_text_window.addstr('Houston, we may have a problem.')
update_text_window.refresh()
#####################################################################################
# If user needs a summary...
elif c == ord('s') or c == ord('S'):
update_text_window.clear()
update_text_window.addstr('Getting summary...')
update_text_window.refresh()
update_text_window.clear()
# Restore information about the state of the pipeline.
# Read first line to get configuration.
summ_log = unpickler('./{}.history.log'.format(date))
try:
# Get the configuration.
config = next(summ_log)
# Get the summary.
summary = summ_log
# Build the record.
record = build_record(config, summary)
# Print the summary on the screen.
for line in record:
update_text_window.addstr(line)
update_text_window.refresh()
# Path where summary must be saved.
_rec_ = os.path.join(config.state_path,
date,
'{}.rec'.format(date))
# Save the recorded summary.
try:
with open(_rec_, 'w+') as _save_:
for line in record:
_save_.write(line)
except IOError:
update_text_window.addstr('\n')
update_text_window.addstr('Cannot write summary to file.')
# Inform the user that the summary has been saved
# and where it has been saved.
update_text_window.addstr('\n')
update_text_window.addstr('Summary saved at {}'.format(_rec_))
# Refresh window.
update_text_window.refresh()
except StopIteration:
# Hold your horses, user!
update_text_window.addstr('No files processed yet. Work ongoing.')
update_text_window.refresh()
#####################################################################################
elif c == ord('q') or c == ord('Q'):
# Quit and exit event loop.
break
# Refresh the windows from the bottom up.
stdscr.noutrefresh()
update_window.noutrefresh()
update_text_window.noutrefresh()
curses.doupdate()
#########################################################################
# Wrap the "cli_updater" in the curses "wrapper" function so that all
# initialisations are handled appropriately and the terminal is restored
# to its former glory without a hitch, even if there is an exception.
curses.wrapper(cli_updater, date)
#########################################################################