Coverage for src/python/ensembl/vep/render/chart.py: 100%

96 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-18 14:41 +0000

1# See the NOTICE file distributed with this work for additional information 

2# regarding copyright ownership. 

3# 

4# Licensed under the Apache License, Version 2.0 (the "License"); 

5# you may not use this file except in compliance with the License. 

6# You may obtain a copy of the License at 

7# http://www.apache.org/licenses/LICENSE-2.0 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, 

11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

12# See the License for the specific language governing permissions and 

13# limitations under the License. 

14"""Charts as inline SVG. 

15 

16Replaces the Google Charts the old VEP summary loaded from a CDN, so a report opens offline. The 

17legend matches ``ensembl-client``'s legend component: a 10px square marker, 12px from its label. 

18""" 

19 

20from __future__ import annotations 

21 

22import math 

23from collections.abc import Sequence 

24from xml.sax.saxutils import escape 

25 

26from attrs import define, field 

27 

28from ensembl.vep.render.theme import Colour, Font 

29 

30__all__ = ["Slice", "render_bars", "render_legend", "render_pie", "render_series"] 

31 

32MARKER_SIZE = 10 

33"""Legend marker edge length, in pixels, matching the site's legend component.""" 

34MARKER_GAP = 12 

35LEGEND_ROW_HEIGHT = 20 

36LABEL_SIZE = 11 

37 

38PIE_DIAMETER = 200 

39BAR_HEIGHT = 18 

40BAR_GAP = 8 

41BAR_LABEL_WIDTH = 220 

42BAR_TRACK_WIDTH = 320 

43SERIES_HEIGHT = 120 

44MARGIN = 12 

45 

46DEFAULT_COLOURS = ( 

47 Colour.BLUE, 

48 Colour.DARK_PINK, 

49 Colour.DARK_YELLOW, 

50 Colour.LIME, 

51 Colour.TEAL, 

52 Colour.DUCKEGG_BLUE, 

53 Colour.PURPLE, 

54 Colour.ORANGE, 

55 Colour.GREY, 

56) 

57"""Fallback categorical palette, for a chart whose slices name no colour of their own.""" 

58 

59 

60@define(frozen=True, kw_only=True, auto_attribs=True) 

61class Slice: 

62 """One labelled quantity in a chart. 

63 

64 Attributes: 

65 label (str): What the quantity counts. 

66 value (float): How much. 

67 colour (Colour | None): The colour to draw it in, or None to take one from the default 

68 palette by position. 

69 """ 

70 

71 label: str 

72 value: float 

73 colour: Colour | None = field(default=None) 

74 

75 

76def _colour_at(slices: Sequence[Slice], index: int) -> Colour: 

77 """Return the colour a slice is drawn in, falling back to the palette by position.""" 

78 declared = slices[index].colour 

79 if declared is not None: 

80 return declared 

81 return DEFAULT_COLOURS[index % len(DEFAULT_COLOURS)] 

82 

83 

84def _svg(width: int, height: int, body: str, title: str = "") -> str: 

85 """Wrap chart body markup in a sized ``<svg>`` element.""" 

86 heading = f"<title>{escape(title)}</title>" if title else "" 

87 return ( 

88 f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {height}" ' 

89 f'width="{width}" height="{height}" font-family="{Font.BODY.value}">{heading}\n ' 

90 f"{body}\n</svg>" 

91 ) 

92 

93 

94def render_legend(slices: Sequence[Slice]) -> str: 

95 """Return a legend listing each slice with its marker.""" 

96 rows = [] 

97 for index, item in enumerate(slices): 

98 y = MARGIN + index * LEGEND_ROW_HEIGHT 

99 colour = _colour_at(slices, index) 

100 rows.append( 

101 f'<rect x="{MARGIN}" y="{y}" width="{MARKER_SIZE}" height="{MARKER_SIZE}" ' 

102 f'fill="{colour.value}"/>' 

103 ) 

104 rows.append( 

105 f'<text x="{MARGIN + MARKER_SIZE + MARKER_GAP}" y="{y + MARKER_SIZE}" ' 

106 f'font-size="{LABEL_SIZE}" fill="{Colour.BLACK.value}">' 

107 f"{escape(item.label)} ({item.value:g})</text>" 

108 ) 

109 height = MARGIN * 2 + max(len(slices), 1) * LEGEND_ROW_HEIGHT 

110 return _svg(320, height, "\n ".join(rows)) 

111 

112 

113def _arc_path(centre: float, radius: float, start: float, end: float) -> str: 

114 """Return the path of a pie wedge between two angles, in radians.""" 

115 start_x = centre + radius * math.cos(start) 

116 start_y = centre + radius * math.sin(start) 

117 end_x = centre + radius * math.cos(end) 

118 end_y = centre + radius * math.sin(end) 

119 large_arc = 1 if end - start > math.pi else 0 

120 return ( 

121 f"M {centre:.2f} {centre:.2f} L {start_x:.2f} {start_y:.2f} " 

122 f"A {radius:.2f} {radius:.2f} 0 {large_arc} 1 {end_x:.2f} {end_y:.2f} Z" 

123 ) 

124 

125 

126def render_pie(slices: Sequence[Slice], title: str = "") -> str: 

127 """Return a pie chart. 

128 

129 A single slice is drawn as a whole circle, because a wedge spanning the full turn has 

130 coincident start and end points and would render as nothing. 

131 """ 

132 total = sum(item.value for item in slices) 

133 radius = PIE_DIAMETER / 2 

134 centre = radius + MARGIN 

135 size = PIE_DIAMETER + MARGIN * 2 

136 

137 if total <= 0: 

138 body = f'<circle cx="{centre}" cy="{centre}" r="{radius}" fill="{Colour.LIGHT_GREY.value}"/>' 

139 return _svg(size, size, body, title) 

140 

141 drawn = [] 

142 if len(slices) == 1: 

143 drawn.append( 

144 f'<circle cx="{centre}" cy="{centre}" r="{radius}" fill="{_colour_at(slices, 0).value}"/>' 

145 ) 

146 else: 

147 angle = -math.pi / 2 

148 for index, item in enumerate(slices): 

149 sweep = 2 * math.pi * (item.value / total) 

150 path = _arc_path(centre, radius, angle, angle + sweep) 

151 drawn.append(f'<path d="{path}" fill="{_colour_at(slices, index).value}"/>') 

152 angle += sweep 

153 return _svg(size, size, "\n ".join(drawn), title) 

154 

155 

156def render_bars(slices: Sequence[Slice], title: str = "") -> str: 

157 """Return a horizontal bar chart, one labelled bar per slice.""" 

158 largest = max((item.value for item in slices), default=0) 

159 rows = [] 

160 for index, item in enumerate(slices): 

161 y = MARGIN + index * (BAR_HEIGHT + BAR_GAP) 

162 length = 0 if largest <= 0 else int(BAR_TRACK_WIDTH * item.value / largest) 

163 rows.append( 

164 f'<text x="{MARGIN}" y="{y + BAR_HEIGHT - 5}" font-size="{LABEL_SIZE}" ' 

165 f'fill="{Colour.BLACK.value}">{escape(item.label)}</text>' 

166 ) 

167 rows.append( 

168 f'<rect x="{MARGIN + BAR_LABEL_WIDTH}" y="{y}" width="{length}" height="{BAR_HEIGHT}" ' 

169 f'fill="{_colour_at(slices, index).value}"/>' 

170 ) 

171 rows.append( 

172 f'<text x="{MARGIN + BAR_LABEL_WIDTH + length + 6}" y="{y + BAR_HEIGHT - 5}" ' 

173 f'font-size="{LABEL_SIZE}" fill="{Colour.DARK_GREY.value}">{item.value:g}</text>' 

174 ) 

175 width = MARGIN * 2 + BAR_LABEL_WIDTH + BAR_TRACK_WIDTH + 60 

176 height = MARGIN * 2 + max(len(slices), 1) * (BAR_HEIGHT + BAR_GAP) 

177 return _svg(width, height, "\n ".join(rows), title) 

178 

179 

180def render_series(values: Sequence[float], title: str = "", colour: Colour = Colour.BLUE) -> str: 

181 """Return a filled area chart of one series, for a positional distribution.""" 

182 width = max(len(values), 1) * 3 + MARGIN * 2 

183 height = SERIES_HEIGHT + MARGIN * 2 

184 largest = max(values, default=0) 

185 

186 if not values or largest <= 0: 

187 baseline = f'<line x1="{MARGIN}" y1="{height - MARGIN}" x2="{width - MARGIN}" ' 

188 baseline += f'y2="{height - MARGIN}" stroke="{Colour.GREY.value}" stroke-width="1"/>' 

189 return _svg(width, height, baseline, title) 

190 

191 points = [f"{MARGIN},{height - MARGIN}"] 

192 for index, value in enumerate(values): 

193 x = MARGIN + index * 3 

194 y = height - MARGIN - int(SERIES_HEIGHT * value / largest) 

195 points.append(f"{x},{y}") 

196 points.append(f"{MARGIN + (len(values) - 1) * 3},{height - MARGIN}") 

197 body = f'<polygon points="{" ".join(points)}" fill="{colour.value}" fill-opacity="0.75"/>' 

198 return _svg(width, height, body, title)