Repository navigation
Expand file tree
/
Copy pathprocess.py
More file actions
767 lines (627 loc) · 25.4 KB
/
Copy pathprocess.py
File metadata and controls
767 lines (627 loc) · 25.4 KB
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
"""Widgets to work with processes."""
from __future__ import annotations
import inspect
import os
import re
import sys
import threading
import time
import traceback
import uuid
import warnings
from collections.abc import Mapping
import ipywidgets as ipw
import traitlets as tl
# AiiDA imports
from aiida import common, orm
from aiida.cmdline.utils.ascii_vis import format_call_graph
from aiida.cmdline.utils.common import (
get_calcjob_report,
get_process_function_report,
get_workchain_report,
)
from aiida.common.links import LinkType
from aiida.tools.query.calculation import CalculationQueryBuilder
from IPython.display import HTML, Javascript, clear_output, display
from jinja2 import Template
from home.node_preview import render_node_preview
class CantRegisterCallbackError(Exception):
"""Exception raised when trying to register a callback after monitoring has started."""
def __init__(self, function):
super().__init__(
f"Cannot register callback function {function.__name__!r} after monitoring has started."
)
PROCESS_TABLE_TEMPLATE = Template(
"""
<style>
.df { border: none; }
.df tbody tr:nth-child(odd) { background-color: #e5e7e9; }
.df tbody tr:nth-child(odd):hover { background-color: #f5b7b1; }
.df tbody tr:nth-child(even):hover { background-color: #f5b7b1; }
.df tbody td { min-width: 150px; text-align: center; border: none; }
.df th { text-align: center; border: none; border-bottom: 1px solid black; }
</style>
<table class="df">
<thead>
<tr>
{% for header in headers %}
<th>{{ header }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in rows %}
<tr>
{% for header in headers %}
<td>{{ row[header] }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
"""
)
def _stringify_process_cell(value):
if value is None:
return ""
return str(value)
def _normalize_process_rows(projected):
if not projected:
return [], []
headers = list(projected[0])
rows = [
{
header: _stringify_process_cell(value)
for header, value in zip(headers, entry)
}
for entry in projected[1:]
]
return headers, rows
def _filter_process_rows(rows, description_contains):
if not description_contains:
return rows
pattern = re.compile(description_contains)
return [row for row in rows if pattern.search(row.get("Description", ""))]
def _add_process_links(rows, path_to_root):
linked_rows = []
for row in rows:
linked_row = dict(row)
pk = linked_row.get("PK", "")
linked_row["PK"] = (
f"""<a href={path_to_root}home/process.ipynb?id={pk} target="_blank">{pk}</a>"""
if pk
else ""
)
linked_rows.append(linked_row)
return linked_rows
def _render_process_table(headers, rows):
return PROCESS_TABLE_TEMPLATE.render(headers=headers, rows=rows)
def get_running_calcs(process):
"""Takes a process and yeilds running children calculations."""
# If a process is a running calculation - returning it
if issubclass(type(process), orm.CalcJobNode) and not process.is_sealed:
yield process
# If the process is a running work chain - returning its children
elif issubclass(type(process), orm.WorkChainNode) and not process.is_sealed:
for out_link in process.get_outgoing():
if (
isinstance(out_link.node, orm.ProcessNode)
and not out_link.node.is_sealed
):
yield from get_running_calcs(out_link.node)
class CalcJobOutputWidget(ipw.Textarea):
"""Output of a calculation."""
calculation = tl.Instance(orm.CalcJobNode, allow_none=True)
def __init__(self, **kwargs):
default_params = {
"value": "",
"placeholder": "Calculation output will appear here",
"description": "Calculation output:",
"layout": {"width": "900px", "height": "300px"},
"disabled": False,
"style": {"description_width": "initial"},
}
default_params.update(kwargs)
self.output = []
# Hack to make font monospace. As far as I am aware, currently there are no better ways.
display(HTML("<style>textarea, input { font-family: monospace; }</style>"))
super().__init__(**default_params)
@tl.observe("calculation")
def _change_calculation(self, _=None):
"""Reset things if the observed calculation has changed."""
self.output = []
self.value = ""
def update(self):
"""Update the displayed output and scroll to its end.
NOTE: when this widgets is called by ProcessFollowerWidget in non-blocking manner
the auto-scrolling won't work. There used to be a function for the Textarea widget,
but it didn't work properly and got removed. For more information please visit:
https://github.com/jupyter-widgets/ipywidgets/issues/1815"""
if self.calculation is None:
return
try:
output_file_path = os.path.join(
self.calculation.outputs.remote_folder.get_remote_path(),
self.calculation.base.attributes.get("output_filename"),
)
except KeyError:
self.placeholder = (
"The `output_filename` attribute is not set for "
f"{self.calculation.process_class}. Nothing to show."
)
except common.exceptions.NotExistentAttributeError:
self.placeholder = (
"The object `remote_folder` was not found among the process outputs. "
"Nothing to show."
)
else:
if os.path.exists(output_file_path):
with open(output_file_path) as fobj:
difference = fobj.readlines()[
len(self.output) : -1
] # Only adding the difference
self.output += difference
self.value += "".join(difference)
# Auto scroll down. Doesn't work in detached mode.
# Also a hack as it is applied to all the textareas
display(
Javascript(
"""
$('textarea').each(function(){
// get the id
var id_value = $(this).attr('id');
if (typeof id_value !== 'undefined') {
// the variable is defined
var textarea = document.getElementById(id_value);
textarea.scrollTop = textarea.scrollHeight;
}
});"""
)
)
class ProcessCallStackWidget(ipw.HTML):
"""Widget that shows process call stack."""
process = tl.Instance(orm.ProcessNode, allow_none=True)
def __init__(self, title="Process Call Stack", path_to_root="../", **kwargs):
self.title = title
self.path_to_root = path_to_root
super().__init__(**kwargs)
self.update()
def update(self):
"""Update the call stack that is shown."""
if self.process is None:
return
string = format_call_graph(self.process, info_fn=self.calc_info)
self.value = (
string.replace("\n", "<br/>").replace(" ", " ").replace("#space#", " ")
)
# The third parameter 'call_link_label', added in AiiDA 2.4, is not used here.
# https://github.com/aiidateam/aiida-core/pull/6056
def calc_info(self, node, _=False):
"""Return a string with the summary of the state of a CalculationNode."""
if not isinstance(node, orm.ProcessNode):
raise TypeError(f"Unknown type: {type(node)}")
process_state = node.process_state.value.capitalize()
pk = f"""<a#space#href={self.path_to_root}home/process.ipynb?id={node.pk}#space#target="_blank">{node.pk}</a>"""
if node.exit_status is not None:
string = f"{node.process_label}<{pk}> {process_state} [{node.exit_status}]"
else:
string = f"{node.process_label}<{pk}> {process_state}"
if isinstance(node, orm.WorkChainNode) and node.stepper_state_info:
string += f" [{node.stepper_state_info}]"
return string
class ProcessFollowerWidget(ipw.VBox):
"""A Widget that follows a process until finished."""
process = tl.Instance(orm.ProcessNode, allow_none=True)
def __init__(
self,
process=None,
followers=None,
update_interval=1.0,
path_to_root="../",
**kwargs,
):
"""Initiate all the followers."""
self._monitor = None
self.process = process
self._run_after_completed = []
self.update_interval = update_interval
self.followers = []
if followers is not None:
for follower in followers:
follower.process = self.process
follower.path_to_root = path_to_root
self.followers.append(
ipw.VBox(
[
ipw.HTML(f"<h2><b>{follower.title}</b></h2>"),
follower,
]
)
)
self.output = ipw.HTML()
super().__init__(children=[self.output, *self.followers], **kwargs)
self.update()
def update(self):
for follower in self.followers:
follower.children[1].update()
def follow(self, detach=False):
"""Initiate following the process with or without blocking."""
if self.process is None:
self.output.value = """<font color="red"> ProcessFollowerWidget: process
is set to 'None', nothing to follow. </font>"""
return
self.output.value = ""
if self._monitor is None:
self._monitor = ProcessMonitor(
callbacks=[self.update],
on_sealed=self._run_after_completed,
timeout=self.update_interval,
)
ipw.dlink(
(self, "process"), (self._monitor, "value"), transform=lambda x: x.uuid
)
if not detach:
self._monitor.join()
def on_completed(self, function):
"""Run functions after a process has been completed."""
if self._monitor is not None:
raise CantRegisterCallbackError(function)
self._run_after_completed.append(function)
class ProcessInputsWidget(ipw.VBox):
"""Widget to select and show process inputs."""
process = tl.Instance(orm.ProcessNode, allow_none=True)
def __init__(self, process=None, **kwargs):
self.process = process
self.output = ipw.Output()
self.info = ipw.HTML()
self.flat_mapping = self.generate_flat_mapping(process=process) or {}
inputs_list = list(self.flat_mapping.items())
self._inputs = ipw.Dropdown(
options=[("Select input", ""), *inputs_list],
description="Select input:",
style={"description_width": "initial"},
disabled=False,
)
self._inputs.observe(self.show_selected_input, names=["value"])
super().__init__(
children=[ipw.HBox([self._inputs, self.info]), self.output], **kwargs
)
def generate_flat_mapping(
self, process: orm.ProcessNode | None = None
) -> None | dict[str, str]:
"""Generate a dict of input to node uuid mapping.
If the input port is a namespace, it will further parse the namespace and attach the entity the
`<namespace>.<childnamespace>.<node_name>` format.
:param process: Process node.
:return: Dict of flatten embed key name to node UUID."""
if process is None:
return None
nested_dict = process.base.links.get_incoming(
link_type=(LinkType.INPUT_CALC, LinkType.INPUT_WORK)
).nested()
def flatten(d, parent_key="", sep="."):
items = []
for key, value in d.items():
new_key = parent_key + sep + key if parent_key else key
if isinstance(value, Mapping):
items.extend(flatten(value, new_key, sep=sep).items())
else:
items.append((new_key, value.uuid))
return dict(items)
options_map = flatten(nested_dict)
return options_map
def show_selected_input(self, change=None):
"""Function that displays process inputs selected in the `inputs` Dropdown widget."""
with self.output:
self.info.value = ""
clear_output()
if change["new"]:
selected_input = orm.load_node(change["new"])
self.info.value = f"PK: {selected_input.pk}"
display(render_node_preview(selected_input))
class ProcessMonitor(tl.HasTraits):
"""Monitor a process and execute callback functions at specified intervals."""
value = tl.Unicode(allow_none=True)
def __init__(self, callbacks=None, on_sealed=None, timeout=None, **kwargs):
self.callbacks = [] if callbacks is None else list(callbacks)
self.on_sealed = [] if on_sealed is None else list(on_sealed)
self.timeout = 1.0 if timeout is None else timeout
self._monitor_thread = None
self._monitor_thread_stop = threading.Event()
self._monitor_thread_lock = threading.Lock()
self.log_widget: ipw.Output | None = kwargs.pop("log_widget", None)
super().__init__(**kwargs)
@tl.observe("value")
def _observe_process(self, change):
"""When the value (process uuid) is changed, stop the previous
monitor if exist. Start a new one in thread."""
process_uuid = change["new"]
# stop thread (if running)
if self._monitor_thread is not None:
with self._monitor_thread_lock:
self._monitor_thread_stop.set()
self._monitor_thread.join()
if process_uuid is None:
return
with self._monitor_thread_lock:
self._monitor_thread_stop.clear()
self._monitor_thread = threading.Thread(
target=self._monitor_process, args=(process_uuid,)
)
self._monitor_thread.start()
def _monitor_process(self, process_uuid):
assert process_uuid is not None
process = orm.load_node(process_uuid)
disabled_funcs = set()
def _run(funcs):
for func in funcs:
# skip all functions that had previously raised an exception
if func in disabled_funcs:
continue
try:
if len(inspect.signature(func).parameters) > 0:
func(process_uuid)
else:
func()
except Exception:
if self.log_widget:
with self.log_widget:
traceback.print_exc(file=sys.stdout)
warnings.warn(
f"WARNING: The callback function {func.__name__!r} was disabled due to an error:\n{traceback.format_exc()}",
stacklevel=2,
)
disabled_funcs.add(func)
while not process.is_sealed:
_run(self.callbacks)
if self._monitor_thread_stop.wait(timeout=self.timeout):
break # thread was signaled to be stopped
# Final update:
_run(self.callbacks)
# Run special 'on_sealed' callback functions in case that process is sealed.
if process.is_sealed:
_run(self.on_sealed)
def join(self):
if self._monitor_thread is not None:
self._monitor_thread.join()
class ProcessOutputsWidget(ipw.VBox):
"""Widget to select and show process outputs."""
process = tl.Instance(orm.ProcessNode, allow_none=True)
def __init__(self, process=None, **kwargs):
self.process = process
self.output = ipw.Output()
self.info = ipw.HTML()
outputs_list = (
[(output.title(), output) for output in self.process.outputs]
if self.process
else []
)
outputs = ipw.Dropdown(
options=[("Select output", ""), *outputs_list],
label="Select output",
description="Select outputs:",
style={"description_width": "initial"},
disabled=False,
)
outputs.observe(self.show_selected_output, names=["value"])
super().__init__(
children=[ipw.HBox([outputs, self.info]), self.output], **kwargs
)
def show_selected_output(self, change=None):
"""Function that displays process output selected in the `outputs` Dropdown widget."""
with self.output:
self.info.value = ""
clear_output()
if change["new"]:
selected_output = self.process.outputs[change["new"]]
self.info.value = f"PK: {selected_output.pk}"
display(render_node_preview(selected_output))
class ProcessReportWidget(ipw.HTML):
"""Widget that shows process report."""
process = tl.Instance(orm.ProcessNode, allow_none=True)
value = tl.Unicode(allow_none=True)
def __init__(self, title="Process Report", **kwargs):
self.title = title
self.max_depth = None
self.indent_size = 2
self.levelname = "REPORT"
super().__init__(**kwargs)
self.update()
def update(self):
"""Update report that is shown."""
if self.process is None:
return
if isinstance(self.process, orm.CalcJobNode):
string = get_calcjob_report(self.process)
elif isinstance(self.process, orm.WorkChainNode):
string = get_workchain_report(
self.process, self.levelname, self.indent_size, self.max_depth
)
elif isinstance(self.process, (orm.CalcFunctionNode, orm.WorkFunctionNode)):
string = get_process_function_report(self.process)
else:
string = f"Nothing to show for node type {self.process.__class__}"
self.value = string.replace("\n", "<br/>")
class ProgressBarWidget(ipw.VBox):
"""A bar showing the proggress of a process."""
process = tl.Instance(orm.ProcessNode, allow_none=True)
def __init__(self, title="Progress Bar", **kwargs):
"""Initialize ProgressBarWidget."""
self.title = title
self.correspondance = {
"created": 0,
"running": 1,
"waiting": 1,
"killed": 2,
"excepted": 2,
"finished": 2,
}
self.progress_bar = ipw.IntProgress(
value=0,
min=0,
max=2,
description="Progress:",
bar_style="warning", # 'success', 'info', 'warning', 'danger' or ''
orientation="horizontal",
layout={"width": "800px"},
)
self.state = ipw.HTML(
description="Calculation state:",
value="Created",
style={"description_width": "initial"},
)
super().__init__(children=[self.progress_bar, self.state], **kwargs)
self.update()
def update(self):
"""Update the bar."""
if self.process is None:
return
self.progress_bar.value = self.correspondance[self.current_state]
if self.current_state == "finished":
self.progress_bar.bar_style = "success"
elif self.current_state in ["killed", "excepted"]:
self.progress_bar.bar_style = "danger"
else:
self.progress_bar.bar_style = "info"
self.state.value = self.current_state.capitalize()
@property
def current_state(self):
return self.process.process_state.value
class ProcessListWidget(ipw.VBox):
"""List of AiiDA processes.
past_days (int): Sumulations that were submitted in the last `past_days`.
incoming_node (str): Trait that takes node uuid that must
be among the input nodes of the process of interest.
outgoing_node (str): Trait that takes node uuid that must
be among the output nodes of the process of interest.
process_states (list): List of allowed process states.
process_label (str): Show process states of type `process_label`.
description_contains (str): string that should be present in the description of a process node.
"""
past_days = tl.Int(7)
incoming_node = tl.Unicode(allow_none=True)
outgoing_node = tl.Unicode(allow_none=True)
process_states = tl.List()
process_label = tl.Unicode(allow_none=True)
description_contains = tl.Unicode(allow_none=True)
def __init__(self, path_to_root="../", **kwargs):
self.path_to_root = path_to_root
self.table = ipw.HTML()
self.output = ipw.HTML()
update_button = ipw.Button(description="Update now")
update_button.on_click(self.update)
super().__init__(
children=[ipw.HBox([self.output, update_button]), self.table], **kwargs
)
self.update()
def update(self, _=None):
"""Perform the query."""
builder = CalculationQueryBuilder()
filters = builder.get_filters(
all_entries=False,
process_state=self.process_states,
process_label=self.process_label,
exit_status=None,
failed=None,
)
relationships = {}
if self.incoming_node:
relationships = {
**relationships,
**{"with_outgoing": orm.load_node(self.incoming_node)},
}
if self.outgoing_node:
relationships = {
**relationships,
**{"with_incoming": orm.load_node(self.outgoing_node)},
}
query_set = builder.get_query_set(
filters=filters,
past_days=None if self.past_days < 0 else self.past_days,
order_by={"ctime": "desc"},
relationships=relationships,
)
projected = builder.get_projected(
query_set,
projections=[
"pk",
"ctime",
"process_label",
"state",
"process_status",
"description",
],
)
headers, rows = _normalize_process_rows(projected)
# Keep only process that contain the requested string in the description.
rows = _filter_process_rows(rows, self.description_contains)
self.output.value = f"{len(rows)} processes shown"
# Add HTML links.
rows = _add_process_links(rows, self.path_to_root)
self.table.value = _render_process_table(headers, rows)
@tl.validate("incoming_node")
def _validate_incoming_node(self, provided):
"""Validate incoming node."""
node_uuid = provided["value"]
try:
_ = uuid.UUID(node_uuid, version=4)
except ValueError:
self.output.value = f"""'<span style="color:red">{node_uuid}</span>'
is not a valid UUID."""
else:
return node_uuid
@tl.validate("outgoing_node")
def _validate_outgoing_node(self, provided):
"""Validate outgoing node. The function orm.load_node takes care of managing ids and uuids."""
node_uuid = provided["value"]
try:
_ = uuid.UUID(node_uuid, version=4)
except ValueError:
self.output.value = f"""'<span style="color:red">{node_uuid}</span>'
is not a valid UUID."""
else:
return node_uuid
@tl.default("process_label")
def _default_process_label(self):
return None
@tl.validate("process_label")
def _validate_process_label(self, provided):
if provided["value"]:
return provided["value"]
return None
def _follow(self, update_interval):
while True:
self.update()
time.sleep(update_interval)
def start_autoupdate(self, update_interval=10):
update_state = threading.Thread(target=self._follow, args=(update_interval,))
update_state.start()
class RunningCalcJobOutputWidget(ipw.VBox):
"""Show an output of selected running child calculation."""
process = tl.Instance(orm.ProcessNode, allow_none=True)
def __init__(self, title="Running Job Output", **kwargs):
self.title = title
self.selection = ipw.Dropdown(
description="Select calculation:",
options=tuple((p.pk, p) for p in get_running_calcs(self.process)),
style={"description_width": "initial"},
)
self.output = CalcJobOutputWidget()
super().__init__(children=[self.selection, self.output], **kwargs)
self.update()
def update(self):
"""Update the displayed output."""
if self.process is None:
return
with self.hold_trait_notifications():
old_label = self.selection.label
self.selection.options = tuple(
(str(p.pk), p) for p in get_running_calcs(self.process)
)
# If the selection remains the same.
if old_label in self.selection.options:
self.label = old_label # After changing options trait, the label and value traits might change as well.
# If selection has changed
else:
self.output.calculation = self.selection.value
self.output.update()
You can’t perform that action at this time.