diff --git a/OpenBench/pipeline_layout.py b/OpenBench/pipeline_layout.py new file mode 100644 index 0000000..8dd2eed --- /dev/null +++ b/OpenBench/pipeline_layout.py @@ -0,0 +1,426 @@ +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# # +# OpenBench is a chess engine testing framework authored by Andrew Grant. # +# # +# # +# OpenBench is free software: you can redistribute it and/or modify # +# it under the terms of the GNU General Public License as published by # +# the Free Software Foundation, either version 3 of the License, or # +# (at your option) any later version. # +# # +# OpenBench is distributed in the hope that it will be useful, # +# but WITHOUT ANY WARRANTY; without even the implied warranty of # +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # +# GNU General Public License for more details. # +# # +# You should have received a copy of the GNU General Public License # +# along with this program. If not, see . # +# # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + + + +# Draws a Pipeline graph ( see pipeline_graph.py ) as an inline SVG. Like the +# graph module, this is pure Python: no Django, no database. It never reads the +# page it ends up on, so it can be tested on its own. +# +# The layout is layered, left to right. A step sits one column to the right of +# the furthest step that leads into it. Edges that loop back to an earlier step +# are drawn underneath the nodes, so that the main flow stays readable. +# +# Every piece of text in the output may come from a person ( step names, setting +# values ), so all of it is escaped here, and only here. The result is a finished +# string that a template may mark as safe. + +import html + +NODE_W = 196 +NODE_H = 84 +GAP_X = 112 # The least that is left between two columns +GAP_Y = 34 +PAD = 36 +RADIUS = 2 # The corner radius of the theme ( --radius ). Sharp, and never more +LOOP_DEPTH = 34 # How far below the nodes the first looping edge dips +LOOP_STEP = 16 # How much further every other looping edge runs +STUB = 34 # How far the stub of an edge that leads nowhere reaches past its label +NAME_LIMIT = 24 # Characters of a step name that fit on the first line of a step + +STATUSES = ('queued', 'launching', 'running', 'passed', 'failed', 'stopped', 'error') +CONDITIONS = ('passed', 'failed', 'stopped', 'any') + +def edge_label(condition, changes): + + """ What is written on an edge: when it is followed, and what it changes """ + + condition = condition if condition in CONDITIONS else 'any' + label = condition + + if changes: + label += ' (%d change%s)' % (len(changes), '' if len(changes) == 1 else 's') + + return label + +def label_width(label): + return len(label) * 6.6 + 18 + +def esc(text): + return html.escape(str(text), quote=True) + +def clip(text, limit): + text = str(text) + return text if len(text) <= limit else text[:limit - 1] + '\u2026' + + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# LAYOUT # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +def _walk(graph): + + """ Splits the edges into forward and back edges, using a depth first walk + from the start. Returns ( order the steps were met in, back edge indices ) """ + + steps, edges = graph['steps'], graph.get('edges', []) + outgoing = { step_id : [] for step_id in steps } + + for index, edge in enumerate(edges): + if edge.get('from') in outgoing and edge.get('to') in steps: + outgoing[edge['from']].append((index, edge['to'])) + + state, order, back = {}, [], set() + + def visit(step_id): + state[step_id] = 1 + order.append(step_id) + for index, target in outgoing[step_id]: + if state.get(target) == 1: + back.add(index) # Leads to a step that is still being walked: a loop + elif target not in state: + visit(target) + state[step_id] = 2 + + if graph.get('start') in steps: + visit(graph['start']) + + return order, back + +def layout(graph): + + """ Positions of every step and edge, in SVG units """ + + steps, edges = graph['steps'], graph.get('edges', []) + order, back = _walk(graph) + reachable = set(order) + + # A step is one column right of the furthest step leading into it. Steps are + # taken in reverse finishing order, which is a valid order for the forward edges + forward = [(e['from'], e['to']) for i, e in enumerate(edges) + if i not in back and e.get('to') in steps and e.get('from') in reachable] + + layer = { step_id : 0 for step_id in order } + for _ in range(len(order)): + changed = False + for source, target in forward: + if layer[target] < layer[source] + 1: + layer[target] = layer[source] + 1 + changed = True + if not changed: + break + + # Steps that can never start get a column of their own, at the end + orphans = [step_id for step_id in steps if step_id not in reachable] + if orphans: + last = max(layer.values(), default=-1) + 1 + for step_id in orphans: + layer[step_id] = last + + columns = {} + for step_id in list(order) + orphans: + columns.setdefault(layer[step_id], []).append(step_id) + + # Order inside a column: by the average row of whatever leads in + row = {} + for number in sorted(columns): + members = columns[number] + if number > 0: + def average(step_id): + rows = [row[s] for s, t in forward if t == step_id and s in row] + return sum(rows) / len(rows) if rows else float('inf') + + met = { step_id : position for position, step_id in enumerate(members) } + members.sort(key=lambda step_id: (average(step_id), met[step_id])) + for position, step_id in enumerate(members): + row[step_id] = position + + tallest = max((len(members) for members in columns.values()), default=1) + back_count = len(back) + + # Edges that skip over a column run in a lane above the steps in between, so + # that they never cut through one. Those lanes need room above everything + skipping = [i for i, e in enumerate(edges) + if i not in back and e.get('to') in steps and e.get('from') in reachable + and layer[e['to']] - layer[e['from']] > 1] + headroom = (20 + 14 * len(skipping)) if skipping else 0 + + # The gap after a column is wide enough for the widest label that sits in it + gap_after = { number : GAP_X for number in columns } + for index, edge in enumerate(edges): + if index not in back and edge.get('to') in steps and edge.get('from') in reachable \ + and layer[edge['to']] - layer[edge['from']] == 1: + width = label_width(edge_label(edge.get('on'), edge.get('set') or {})) + 28 + gap_after[layer[edge['from']]] = max(gap_after[layer[edge['from']]], width) + + left = {} + for number in sorted(columns): + left[number] = PAD if number == min(columns) else left[number - 1] + NODE_W + gap_after[number - 1] + + nodes = {} + for number, members in columns.items(): + shift = (tallest - len(members)) * (NODE_H + GAP_Y) / 2 + for position, step_id in enumerate(members): + nodes[step_id] = { + 'id' : step_id, + 'layer' : number, + 'row' : position, + 'x' : left[number], + 'y' : PAD + headroom + shift + position * (NODE_H + GAP_Y), + 'w' : NODE_W, + 'h' : NODE_H, + 'reachable' : step_id in reachable, + } + + # Ports: edges leaving or entering the same side of a step are spread out + leaving, entering = {}, {} + for index, edge in enumerate(edges): + if index in back or edge.get('from') not in nodes: + continue + leaving.setdefault(edge['from'], []).append(index) + if edge.get('to') in nodes: + entering.setdefault(edge['to'], []).append(index) + + def port(table, step_id, index): + indices = table[step_id] + return nodes[step_id]['y'] + NODE_H * (indices.index(index) + 1) / (len(indices) + 1) + + drawn, loops_seen = [], 0 + lowest = max((n['y'] + NODE_H for n in nodes.values()), default=0) + + for index, edge in enumerate(edges): + + source, target = edge.get('from'), edge.get('to') + if source not in nodes or (target is not None and target not in nodes): + continue + + item = { + 'index' : index, 'source' : source, 'target' : target, + 'on' : edge.get('on'), 'back' : index in back, + 'end' : target is None, 'changes' : dict(edge.get('set') or {}), + } + + s = nodes[source] + + if index in back: + + # Under every step, so that a loop never runs through one + t = nodes[target] + lane = lowest + LOOP_DEPTH + LOOP_STEP * loops_seen + loops_seen += 1 + + if source == target: + x1, x2 = s['x'] + NODE_W * 0.35, s['x'] + NODE_W * 0.65 + else: + x1, x2 = s['x'] + NODE_W * 0.5, t['x'] + NODE_W * 0.5 + + y1, y2 = s['y'] + NODE_H, t['y'] + NODE_H + pull = (8 * lane - y1 - y2) / 6 # Puts the middle of the curve on the lane + item['path'] = 'M%.1f %.1f C%.1f %.1f %.1f %.1f %.1f %.1f' % (x1, y1, x1, pull, x2, pull, x2, y2) + item['lx'], item['ly'] = (x1 + x2) / 2, lane + + elif target is None: + + width = label_width(edge_label(edge.get('on'), item['changes'])) + length = width + STUB + x1, y1 = s['x'] + NODE_W, port(leaving, source, index) + x2 = x1 + length + item['path'] = 'M%.1f %.1f L%.1f %.1f' % (x1, y1, x2, y1) + item['lx'], item['ly'] = x1 + width / 2 + 8, y1 + item['ex'], item['ey'] = x2, y1 + item['length'] = length + + elif index in skipping: + + # Out into the gap, up to a lane above the steps in between, along it, and down again + t = nodes[target] + x1, y1 = s['x'] + NODE_W, port(leaving, source, index) + x2, y2 = t['x'], port(entering, target, index) + between = [n['y'] for n in nodes.values() if s['layer'] < n['layer'] < t['layer']] + lane = min(between) - 18 - 14 * skipping.index(index) + out_of = gap_after[s['layer']] # The gap that it leaves through + into = gap_after[t['layer'] - 1] # And the one that it arrives through + + item['path'] = 'M%.1f %.1f C%.1f %.1f %.1f %.1f %.1f %.1f L%.1f %.1f C%.1f %.1f %.1f %.1f %.1f %.1f' % ( + x1, y1, x1 + out_of * 0.6, y1, x1 + out_of * 0.6, lane, x1 + out_of, lane, + x2 - into, lane, + x2 - into * 0.6, lane, x2 - into * 0.6, y2, x2, y2) + item['lx'], item['ly'] = (x1 + x2) / 2, lane + + else: + + t = nodes[target] + x1, y1 = s['x'] + NODE_W, port(leaving, source, index) + x2, y2 = t['x'], port(entering, target, index) + reach = max(36.0, (x2 - x1) / 2) + item['path'] = 'M%.1f %.1f C%.1f %.1f %.1f %.1f %.1f %.1f' % ( + x1, y1, x1 + reach, y1, x2 - reach, y2, x2, y2) + item['lx'], item['ly'] = (x1 + x2) / 2, (y1 + y2) / 2 + + drawn.append(item) + + right = max((n['x'] + NODE_W for n in nodes.values()), default=0) + right += max((item['length'] for item in drawn if item['end']), default=0) + + dip = (LOOP_DEPTH + LOOP_STEP * max(back_count - 1, 0) + 28) if back_count else 0 + + return { + 'width' : right + PAD, + 'height' : PAD * 2 + headroom + tallest * NODE_H + (tallest - 1) * GAP_Y + dip, + 'nodes' : nodes, + 'edges' : drawn, + } + + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# DRAWING # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +def step_summary(step): + + """ Two short facts about what a step runs: what it does, and how fast """ + + payload, kind = step.get('payload') or {}, step.get('kind') + + if kind == 'TEST': + if str(payload.get('test_mode')) == 'GAMES': + what = '%s games' % (payload.get('test_max_games', '?')) + else: + what = 'SPRT %s' % (payload.get('test_bounds', '')) + return what.strip(), str(payload.get('dev_time_control', '')) + + if kind == 'TUNE': + return 'SPSA, %s iterations' % (payload.get('spsa_iterations', '?')), str(payload.get('dev_time_control', '')) + + if kind == 'DATAGEN': + return '%s games' % (payload.get('datagen_max_games', '?')), str(payload.get('dev_time_control', '')) + + return '', '' + +def _safe_link(url): + + # Links come from our own views, and are always paths on this site + url = str(url or '') + return url if url.startswith('/') and not url.startswith('//') else '' + +def render_svg(graph, geometry=None, states=None, taken=None): + + """ states : { step_id : { 'status' : 'running', 'runs' : 2, 'url' : '/test/9/' } } + taken : set of edge indices that a run actually followed. When given, + every edge that was not followed is drawn quietly. """ + + geometry = geometry or layout(graph) + states = states or {} + steps = graph['steps'] + + out = [] + out.append( + '' % ( + geometry['width'], geometry['height'], geometry['width'], geometry['height'])) + + out.append('') + for condition in CONDITIONS: + out.append( + '' % ( + condition, condition)) + out.append('') + + for item in geometry['edges']: + + condition = item['on'] if item['on'] in CONDITIONS else 'any' + classes = ['pl-edge', 'pl-c-' + condition] + + if taken is not None: + classes.append('pl-taken' if item['index'] in taken else 'pl-idle') + if item['back']: + classes.append('pl-back') + + label = edge_label(condition, item['changes']) + width = label_width(label) + notes = [] + if item['changes']: + notes = ['Settings changed when this is followed:'] + [ + '%s = %s' % (k, v) for k, v in sorted(item['changes'].items())] + + out.append('' % (' '.join(classes), item['index'])) + out.append('' % (item['path'], condition)) + + if item['end']: + out.append('' % (item['ex'], item['ey'])) + + out.append('') + if notes: + out.append('%s' % (esc('\n'.join(notes)))) + out.append('' % ( + item['lx'] - width / 2, item['ly'] - 10, width, RADIUS)) + out.append('%s' % ( + item['lx'], item['ly'] + 4, esc(label))) + out.append('') + + for step_id, node in geometry['nodes'].items(): + + step = steps[step_id] + state = states.get(step_id) or {} + status = state.get('status') + status = status.lower() if isinstance(status, str) and status.lower() in STATUSES else 'idle' + what, speed = step_summary(step) + + classes = ['pl-node', 'pl-s-' + status] + if step_id == graph.get('start'): + classes.append('pl-start') + if not node['reachable']: + classes.append('pl-unreachable') + + x, y = node['x'], node['y'] + name = step.get('name') or step_id + runs = state.get('runs') or 0 + spoken = '%s: %s' % (name, status if status != 'idle' else ('never starts' if not node['reachable'] else 'not run')) + if runs > 1: + spoken += ', %d runs' % (runs) + + link = _safe_link(state.get('url')) + if link: + out.append('' % (esc(link))) + + out.append('' % (' '.join(classes), esc(step_id))) + out.append('%s' % (esc(spoken))) + out.append('' % (x, y, NODE_W, NODE_H, RADIUS)) + + if step_id == graph.get('start'): + out.append('' % ( + x - 20, y + NODE_H / 2 - 7, x - 8, y + NODE_H / 2, x - 20, y + NODE_H / 2 + 7)) + + out.append('%s' % (x + 14, y + 27, esc(clip(name, NAME_LIMIT)))) + out.append('%s' % (x + 14, y + 49, esc(clip(what, 24)))) + out.append('%s' % (x + 14, y + 70, esc(clip(speed, 12)))) + + if status != 'idle': + tag = status + (' x%d' % (runs) if runs > 1 else '') + out.append('%s' % ( + x + NODE_W - 14, y + 70, esc(tag))) + + out.append('') + if link: + out.append('') + + out.append('') + return ''.join(out)