"""Filled differences between piecewise-linear embedding curves."""
from html import escape
import numpy as np
import plotly.graph_objects as go
def shaded_regions(first, second):
"""Return separate polygons where the first or second curve is higher.
Split at interpolated crossings so a fill never changes colour on the
wrong side of an intersection. None separates disconnected polygons.
"""
first, second = np.asarray(first, dtype=float), np.asarray(second, dtype=float)
if first.ndim != 1 or first.shape != second.shape or not np.isfinite([first, second]).all():
raise ValueError('Shading needs two finite vectors with matching dimensions.')
regions = {1: {'x': [], 'y': []}, -1: {'x': [], 'y': []}}
current_sign, current = 0, []
def finish():
if not current:
return
region = regions[current_sign]
region['x'].extend([p[0] for p in current] + [p[0] for p in reversed(current)] + [None])
region['y'].extend([p[1] for p in current] + [p[2] for p in reversed(current)] + [None])
for index in range(len(first) - 1):
start = (float(index), first[index], second[index])
end = (float(index + 1), first[index + 1], second[index + 1])
d0, d1 = start[1] - start[2], end[1] - end[2]
points = [start]
if (d0 < 0 < d1) or (d1 < 0 < d0):
fraction = float(d0 / (d0 - d1))
value = start[1] + fraction * (end[1] - start[1])
points.append((index + fraction, value, value))
points.append(end)
for left, right in zip(points, points[1:]):
change = (left[1] - left[2]) + (right[1] - right[2])
sign = 1 if change > 0 else -1 if change < 0 else 0
if sign != current_sign or sign == 0:
finish()
current_sign, current = sign, []
if sign:
if not current:
current.append(left)
current.append(right)
finish()
return regions
def translucent(color, alpha=.28):
if color.startswith('#'):
channels = tuple(int(color[i:i + 2], 16) for i in (1, 3, 5))
else:
channels = tuple(int(value.strip()) for value in color.removeprefix('rgb(').removesuffix(')').split(','))
return f'rgba({channels[0]},{channels[1]},{channels[2]},{alpha})'
def token_pair_ribbon_traces(first, second, first_name, second_name, color, show_average=True):
"""One ribbon bounded by the actual curves, with their mean as its centre."""
regions = shaded_regions(first, second)
first, second = np.asarray(first, dtype=float), np.asarray(second, dtype=float)
x = np.arange(len(first))
fill_x = regions[1]['x'] + regions[-1]['x']
fill_y = regions[1]['y'] + regions[-1]['y']
group = f'ribbon:{first_name}:{second_name}'
traces = []
if fill_x:
traces.append(go.Scatter(x=fill_x, y=fill_y, mode='lines', fill='toself',
fillcolor=translucent(color, .22), line={'width': 0},
name='Gap between tokens', legendgroup=group, hoverinfo='skip', showlegend=False, connectgaps=False))
customdata = np.column_stack([first, second, first - second, np.abs(first - second)])
pair_hover = (f'{escape(first_name)}: %{{customdata[0]:.7f}}
'
f'{escape(second_name)}: %{{customdata[1]:.7f}}
')
gap_hover = 'Gap: %{customdata[3]:.7f}
First − Second: %{customdata[2]:.7f}'
for index, (name, values) in enumerate(((first_name, first), (second_name, second))):
handle_hover = not show_average and index == 0
traces.append(go.Scatter(x=x, y=values, mode='lines', name=name,
line={'color': translucent(color, .45), 'width': .8},
legendgroup=group, hoverinfo='all' if handle_hover else 'skip', showlegend=False,
customdata=customdata if handle_hover else None,
hovertemplate=pair_hover + gap_hover if handle_hover else None))
if show_average:
traces.append(go.Scatter(x=x, y=(first + second) / 2, mode='lines',
name=f'{first_name} ↔ {second_name}', legendgroup=group, line={'color': color, 'width': 2.5},
customdata=customdata,
hovertemplate=pair_hover + 'Average: %{y:.7f}
' + gap_hover))
return traces
def moved_range_traces(new_start, endpoint, start_name, show_average=True):
"""A translated ribbon with a solid anchor and a dashed calculated edge."""
traces = token_pair_ribbon_traces(new_start, endpoint, start_name, 'Predicted endpoint (calculated)',
'#ee8a20', show_average=show_average)
edges = [trace for trace in traces if trace.fill != 'toself']
edges[0].line.update(color='#16866b', width=1.8)
edges[1].line.update(color='#ee8a20', width=2.2, dash='dash')
for edge in edges[:2]:
edge.showlegend = True
edge.legendgroup = edge.name
if show_average:
edges[2].name = 'Average of moved range'
edges[2].line.width = 1.2
return traces