bindview 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. bindview/__init__.py +88 -0
  2. bindview/__main__.py +6 -0
  3. bindview/align.py +493 -0
  4. bindview/arrange.js +347 -0
  5. bindview/arrange.py +248 -0
  6. bindview/backends.py +290 -0
  7. bindview/basepairs.py +1711 -0
  8. bindview/chains.py +264 -0
  9. bindview/chem.py +57 -0
  10. bindview/clearance.py +123 -0
  11. bindview/cli.py +990 -0
  12. bindview/compare.py +1854 -0
  13. bindview/confidence.py +531 -0
  14. bindview/consensus.py +303 -0
  15. bindview/covalent.py +220 -0
  16. bindview/depict.py +790 -0
  17. bindview/detect.py +378 -0
  18. bindview/diagram.py +1891 -0
  19. bindview/distance_table.py +589 -0
  20. bindview/ensemble.py +787 -0
  21. bindview/errors.py +47 -0
  22. bindview/exposure.py +207 -0
  23. bindview/features.py +179 -0
  24. bindview/fingerprint.py +469 -0
  25. bindview/fragments.py +304 -0
  26. bindview/geometry.py +482 -0
  27. bindview/graph.py +611 -0
  28. bindview/graphbuild.py +431 -0
  29. bindview/interactions.py +418 -0
  30. bindview/interactive.py +334 -0
  31. bindview/interface.py +1329 -0
  32. bindview/ions.py +155 -0
  33. bindview/layout/__init__.py +15 -0
  34. bindview/layout/body.py +421 -0
  35. bindview/layout/engine.py +1084 -0
  36. bindview/layout/field.py +261 -0
  37. bindview/ligand.py +583 -0
  38. bindview/near.py +67 -0
  39. bindview/options.py +92 -0
  40. bindview/pae.py +991 -0
  41. bindview/peptide.py +610 -0
  42. bindview/plane.py +320 -0
  43. bindview/polymer.py +678 -0
  44. bindview/py.typed +0 -0
  45. bindview/report.py +1407 -0
  46. bindview/residues.py +296 -0
  47. bindview/resolve.py +493 -0
  48. bindview/scene.py +239 -0
  49. bindview/solvent.py +254 -0
  50. bindview/structure.py +1145 -0
  51. bindview/styles/__init__.py +2 -0
  52. bindview/styles/absence.py +180 -0
  53. bindview/styles/base.py +2128 -0
  54. bindview/styles/closeup.py +146 -0
  55. bindview/styles/detailed.py +690 -0
  56. bindview/styles/ligand_draw.py +289 -0
  57. bindview/styles/mixed.py +70 -0
  58. bindview/styles/polymer_draw.py +354 -0
  59. bindview/styles/rings.py +75 -0
  60. bindview/styles/schematic.py +311 -0
  61. bindview/styles/summary.py +147 -0
  62. bindview/svg.py +310 -0
  63. bindview/textmetrics.py +64 -0
  64. bindview/theme.py +317 -0
  65. bindview-0.1.0.dist-info/METADATA +270 -0
  66. bindview-0.1.0.dist-info/RECORD +70 -0
  67. bindview-0.1.0.dist-info/WHEEL +4 -0
  68. bindview-0.1.0.dist-info/entry_points.txt +2 -0
  69. bindview-0.1.0.dist-info/licenses/LICENSE +21 -0
  70. bindview-0.1.0.dist-info/licenses/NOTICE +48 -0
bindview/svg.py ADDED
@@ -0,0 +1,310 @@
1
+ """Serialising a :class:`~bindview.scene.Scene` to SVG text.
2
+
3
+ The writer is deliberately boring: fixed attribute order, numbers rounded and
4
+ formatted one way, no timestamps, no generated ids, no dependence on dict
5
+ ordering of anything that is not already ordered. The same scene always gives
6
+ the same bytes. Text is escaped, and a character that no XML file can hold (a
7
+ control character in a title, half a surrogate pair) is left out.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import re
14
+ from typing import Any, Iterable, Sequence
15
+ from xml.sax.saxutils import escape, quoteattr
16
+
17
+ from .interactive import NUMBER, OVER, ROOT_CLASS, UNDER, Hooks, hooks
18
+ from .scene import Circle, Group, Item, Line, Paint, Path, Polygon, Polyline, Rect, Scene, Span, Text
19
+ from .textmetrics import FONT_FAMILY
20
+ from .theme import EXTRAS, Palette, fixed_tokens
21
+
22
+ __all__ = ["to_svg", "svg_and_css", "stylesheet", "fmt"]
23
+
24
+
25
+ #: What XML 1.0 cannot hold, as text or in an attribute, escaped or not: the control characters other than tab
26
+ #: and the two that end a line, half a surrogate pair, and the last two code points of the first plane.
27
+ _NOT_XML = re.compile("[^\t\n\r\x20-\ud7ff\ue000-\ufffd\U00010000-\U0010ffff]")
28
+
29
+
30
+ def _plain(text: str) -> str:
31
+ """``text`` without the characters that no XML file can hold."""
32
+ return _NOT_XML.sub("", text)
33
+
34
+
35
+ def fmt(value: float) -> str:
36
+ """Format a coordinate: two decimals, no trailing zeros, no negative zero."""
37
+ s = f"{value:.2f}"
38
+ if "." in s:
39
+ s = s.rstrip("0").rstrip(".")
40
+ return "0" if s in ("-0", "") else s
41
+
42
+
43
+ #: What no colour has in it, and what would end the attribute or the declaration that a colour is written into.
44
+ _NOT_IN_A_COLOUR = re.compile(r"""["'<>&;{}\\]|/\*|[\x00-\x1f\x7f]""")
45
+ _TOKEN = re.compile(r"[A-Za-z0-9_-]+")
46
+
47
+
48
+ def _colour(token: str, value: str, palette: str = "") -> str:
49
+ """``value`` as it is, where it can be written for a colour: a palette is the caller's, and its colours go into
50
+ attributes and into a style sheet as they are given."""
51
+ whose = f"the colour {token!r}" + (f" of the palette {palette!r}" if palette else "")
52
+ if not _TOKEN.fullmatch(token):
53
+ raise ValueError(f"{whose} has a name that cannot be written into a style sheet: letters, digits, _ and - can")
54
+ if not isinstance(value, str) or not value.strip() or _NOT_IN_A_COLOUR.search(value):
55
+ raise ValueError(f"{whose} is {value!r}: a colour is a name, #rrggbb or a function such as rgb(...), without "
56
+ "quotes, angle brackets, braces, semicolons, backslashes or line breaks")
57
+ return value
58
+
59
+
60
+ class _Resolver:
61
+ """Turns palette tokens into SVG paint values."""
62
+
63
+ def __init__(self, palette: Palette, css_vars: bool) -> None:
64
+ self.name = palette.name
65
+ self.paints: dict[str, str] = {}
66
+ # (The tokens that are the same in every palette come first: a palette that names one wins.)
67
+ self.tokens = {**fixed_tokens(), **palette.tokens()}
68
+ self.css_vars = css_vars
69
+ # What a palette has beside its tokens (``Palette.extra``), and which of it this figure asked for:
70
+ # only those are declared in its style sheet, so a figure that asks for none declares none.
71
+ self.extra = {**EXTRAS, **palette.extra}
72
+ self.used: set[str] = set()
73
+
74
+ def colour(self, token: str | None) -> str:
75
+ if token is None:
76
+ return "none"
77
+ paint = self.paints.get(token)
78
+ if paint is None:
79
+ paint = self.paints[token] = self._paint(token)
80
+ return paint
81
+
82
+ def _paint(self, token: str) -> str:
83
+ if token.startswith("#") or token == "none":
84
+ return _colour("a literal", token)
85
+ try:
86
+ value = self.tokens[token]
87
+ except KeyError:
88
+ if token not in self.extra:
89
+ raise KeyError(f"unknown colour token {token!r}") from None
90
+ value = self.extra[token]
91
+ self.used.add(token)
92
+ value = _colour(token, value, self.name)
93
+ if self.css_vars:
94
+ return f"var(--lf-{token.replace('_', '-')},{value})"
95
+ return value
96
+
97
+
98
+ def _paint_attrs(p: Paint, res: _Resolver) -> str:
99
+ if res.css_vars:
100
+ style = [f"fill:{res.colour(p.fill)}"]
101
+ if p.stroke is not None:
102
+ style.append(f"stroke:{res.colour(p.stroke)}")
103
+ out = [f'style="{";".join(style)}"']
104
+ else:
105
+ out = [f'fill="{res.colour(p.fill)}"']
106
+ if p.stroke is not None:
107
+ out.append(f'stroke="{res.colour(p.stroke)}"')
108
+ if p.stroke is not None:
109
+ out.append(f'stroke-width="{fmt(p.width)}"')
110
+ if p.cap != "butt":
111
+ out.append(f'stroke-linecap="{p.cap}"')
112
+ if p.join != "miter":
113
+ out.append(f'stroke-linejoin="{p.join}"')
114
+ if p.dash:
115
+ out.append(f'stroke-dasharray="{" ".join(fmt(d) for d in p.dash)}"')
116
+ if p.opacity < 1.0:
117
+ out.append(f'opacity="{fmt(p.opacity)}"')
118
+ return " ".join(out)
119
+
120
+
121
+ def _text_fill(token: str, res: _Resolver) -> str:
122
+ if res.css_vars:
123
+ return f'style="fill:{res.colour(token)}"'
124
+ return f'fill="{res.colour(token)}"'
125
+
126
+
127
+ def _span(s: Span, res: _Resolver) -> str:
128
+ attrs = []
129
+ if s.dy:
130
+ attrs.append(f'dy="{fmt(s.dy)}"')
131
+ if s.size is not None:
132
+ attrs.append(f'font-size="{fmt(s.size)}"')
133
+ if s.fill is not None:
134
+ attrs.append(_text_fill(s.fill, res))
135
+ if s.bold is not None:
136
+ attrs.append(f'font-weight="{"bold" if s.bold else "normal"}"')
137
+ if s.italic:
138
+ attrs.append('font-style="italic"')
139
+ body = escape(_plain(s.text))
140
+ if not attrs:
141
+ return body
142
+ return f"<tspan {' '.join(attrs)}>{body}</tspan>"
143
+
144
+
145
+ def _item(it: Item, res: _Resolver, out: list[str], indent: str, live: "Hooks | None" = None) -> None:
146
+ if isinstance(it, Group):
147
+ cls = it.cls
148
+ if live is not None and id(it) in live.classes: # a figure that answers the pointer
149
+ cls = f"{cls} {live.classes[id(it)]}".strip()
150
+ attrs = [f'class="{cls}"'] if cls else []
151
+ for k in sorted(it.data):
152
+ if k != NUMBER or live is not None: # (the number is there for a page that has the hooks)
153
+ attrs.append(f"data-{k}={quoteattr(_plain(str(it.data[k])))}")
154
+ if it.translate is not None:
155
+ attrs.append(f'transform="translate({fmt(it.translate[0])} {fmt(it.translate[1])})"')
156
+ if it.opacity < 1.0:
157
+ attrs.append(f'opacity="{fmt(it.opacity)}"')
158
+ if live is not None and id(it) in live.focus:
159
+ attrs.append(f'tabindex="{live.focus[id(it)]}"')
160
+ if live is not None and id(it) in live.hidden:
161
+ attrs.append('display="none"')
162
+ out.append(f"{indent}<g{' ' if attrs else ''}{' '.join(attrs)}>")
163
+ if it.title:
164
+ out.append(f"{indent} <title>{escape(_plain(it.title))}</title>")
165
+ for child in it.items:
166
+ _item(child, res, out, indent + " ", live)
167
+ out.append(f"{indent}</g>")
168
+ elif isinstance(it, Line):
169
+ under = f'class="{UNDER}" ' if live is not None and id(it) in live.under else ""
170
+ out.append(f'{indent}<line {under}x1="{fmt(it.x1)}" y1="{fmt(it.y1)}" x2="{fmt(it.x2)}" y2="{fmt(it.y2)}" '
171
+ f"{_paint_attrs(it.paint, res)}/>")
172
+ elif isinstance(it, Polyline):
173
+ pts = " ".join(f"{fmt(x)},{fmt(y)}" for x, y in it.points)
174
+ tag = "polygon" if it.closed else "polyline"
175
+ out.append(f'{indent}<{tag} points="{pts}" {_paint_attrs(it.paint, res)}/>')
176
+ elif isinstance(it, Polygon):
177
+ pts = " ".join(f"{fmt(x)},{fmt(y)}" for x, y in it.points)
178
+ out.append(f'{indent}<polygon points="{pts}" {_paint_attrs(it.paint, res)}/>')
179
+ elif isinstance(it, Circle):
180
+ out.append(f'{indent}<circle cx="{fmt(it.cx)}" cy="{fmt(it.cy)}" r="{fmt(it.r)}" '
181
+ f"{_paint_attrs(it.paint, res)}/>")
182
+ elif isinstance(it, Rect):
183
+ rx = f' rx="{fmt(it.rx)}"' if it.rx else ""
184
+ out.append(f'{indent}<rect x="{fmt(it.x)}" y="{fmt(it.y)}" width="{fmt(it.w)}" height="{fmt(it.h)}"{rx} '
185
+ f"{_paint_attrs(it.paint, res)}/>")
186
+ elif isinstance(it, Path):
187
+ d = " ".join(c[0] + " ".join(fmt(v) if isinstance(v, float) else str(int(v)) for v in c[1:])
188
+ for c in it.commands)
189
+ out.append(f'{indent}<path d="{d}" {_paint_attrs(it.paint, res)}/>')
190
+ elif isinstance(it, Text):
191
+ attrs = [f'x="{fmt(it.x)}"', f'y="{fmt(it.y)}"', f'font-size="{fmt(it.size)}"']
192
+ if it.anchor != "start":
193
+ attrs.append(f'text-anchor="{it.anchor}"')
194
+ if it.bold:
195
+ attrs.append('font-weight="bold"')
196
+ if it.italic:
197
+ attrs.append('font-style="italic"')
198
+ attrs.append(_text_fill(it.fill, res))
199
+ if it.opacity < 1.0:
200
+ attrs.append(f'opacity="{fmt(it.opacity)}"')
201
+ body = "".join(_span(s, res) for s in it.spans)
202
+ out.append(f"{indent}<text {' '.join(attrs)}>{body}</text>")
203
+ else: # pragma: no cover - exhaustive over Item
204
+ raise TypeError(f"cannot serialise {type(it).__name__}")
205
+
206
+
207
+ def _css_rules(light: Palette, dark: Palette | None, used: "Iterable[str]" = (), scope: str = "") -> list[str]:
208
+ """The palette as custom properties. ``used`` names what the figure asked for of ``Palette.extra``; ``scope`` is a
209
+ class that the figure has for itself."""
210
+ def decl(p: Palette) -> str:
211
+ tokens = dict(p.tokens())
212
+ tokens.update({k: p.extra[k] for k in used if k in p.extra})
213
+ return "".join(f"--lf-{k.replace('_', '-')}:{_colour(k, v, p.name)};" for k, v in sorted(tokens.items()))
214
+
215
+ root = "svg.bindview" + (f".{scope}" if scope else "")
216
+ rules = [f"{root}{{{decl(light)}}}"]
217
+ if dark is not None:
218
+ rules.append(f"@media (prefers-color-scheme:dark){{{root}:not([data-theme=light]){{{decl(dark)}}}}}")
219
+ rules.append(f"{root}[data-theme=dark]{{{decl(dark)}}}")
220
+ return rules
221
+
222
+
223
+ def _scope(rules: Sequence[str]) -> str:
224
+ """The class of the figures that go with these rules: named by what the rules are, so that two figures in the same
225
+ colours share it, and two in different ones do not."""
226
+ return "lf-c" + hashlib.sha256("".join(rules).encode()).hexdigest()[:8]
227
+
228
+
229
+ def to_svg(scene: Scene, palette: Palette, *, background: bool = True, css_vars: bool = False,
230
+ dark_palette: Palette | None = None, scale: float = 1.0, interactive: "bool | Hooks" = False,
231
+ over: "Sequence[Group]" = (), stylesheet: str = "inline") -> str:
232
+ """Serialise ``scene``: :func:`svg_and_css` without the sheet beside it."""
233
+ return svg_and_css(scene, palette, background=background, css_vars=css_vars, dark_palette=dark_palette, scale=scale,
234
+ interactive=interactive, over=over, stylesheet=stylesheet)[0]
235
+
236
+
237
+ def svg_and_css(scene: Scene, palette: Palette, *, background: bool = True, css_vars: bool = False,
238
+ dark_palette: Palette | None = None, scale: float = 1.0, interactive: "bool | Hooks" = False,
239
+ over: "Sequence[Group]" = (), stylesheet: str = "inline") -> "tuple[str, str | None]":
240
+ """``scene`` as SVG, and the style sheet that goes with it where that is kept apart.
241
+
242
+ With ``css_vars`` every colour is emitted as a CSS custom property with the
243
+ palette colour as fallback, and (given ``dark_palette``) the embedded style
244
+ sheet switches palettes on ``prefers-color-scheme`` or a ``data-theme``
245
+ attribute -- one cached file serves both themes.
246
+
247
+ With ``interactive`` the figure answers the pointer (:mod:`bindview.interactive`):
248
+ its residues and contacts get classes and can take the focus, and a second
249
+ style sheet says what steps back when one of them is pointed at. A scene
250
+ with nothing to point at is written as it is without it. A figure that
251
+ knows its own parts better passes its :class:`~bindview.interactive.Hooks`.
252
+ ``over`` is what such a figure has beside (:mod:`bindview.styles.closeup`); it is written with the
253
+ hooks or not at all.
254
+
255
+ ``stylesheet``: a ``<style>`` in an SVG that is part of a page speaks to the whole page. ``"inline"`` declares the
256
+ palette for every figure there, so that of two in different colours the later one colours both; ``"scoped"``
257
+ declares it for figures in these colours alone; ``"external"`` leaves both sheets out and hands them back, one
258
+ rule on a line, each of which says the same in every figure that has it.
259
+ """
260
+ res = _Resolver(palette, css_vars)
261
+ live = interactive if isinstance(interactive, Hooks) else hooks(scene, over) if interactive else None
262
+ w, h = scene.width, scene.height
263
+ apart = stylesheet == "external"
264
+ # (The drawing is written first and set after the style sheet: the sheet declares what the drawing
265
+ # asked for of the palette's extras, which is known once it is written.)
266
+ body: list[str] = []
267
+ if background:
268
+ body.append(f' <rect class="background" width="{fmt(w)}" height="{fmt(h)}" '
269
+ f"{_paint_attrs(Paint(fill='background'), res)}/>")
270
+ for it in scene.items:
271
+ _item(it, res, body, " ", live)
272
+ if live is not None and over:
273
+ _item(Group(OVER, list(over)), res, body, " ", live)
274
+ classes, rules = "bindview" + (f" {ROOT_CLASS}" if live is not None else ""), []
275
+ if css_vars:
276
+ # (A sheet that is shared declares all of a palette: which of it one figure uses does not matter there.)
277
+ used = sorted(palette.extra) if apart else sorted(res.used)
278
+ rules = _css_rules(palette, dark_palette, used)
279
+ if stylesheet != "inline":
280
+ scope = _scope(rules)
281
+ classes, rules = f"{classes} {scope}", _css_rules(palette, dark_palette, used, scope)
282
+ out = [
283
+ f'<svg xmlns="http://www.w3.org/2000/svg" class="{classes}" '
284
+ f'width="{fmt(w * scale)}" height="{fmt(h * scale)}" '
285
+ f'viewBox="0 0 {fmt(w)} {fmt(h)}" font-family="{FONT_FAMILY}" role="img">'
286
+ ]
287
+ if scene.title:
288
+ out.append(f" <title>{escape(_plain(scene.title))}</title>")
289
+ if scene.description:
290
+ out.append(f" <desc>{escape(_plain(scene.description))}</desc>")
291
+ if css_vars and not apart:
292
+ out.append(f" <style>{''.join(rules)}</style>")
293
+ if live is not None and not apart:
294
+ out.append(f" <style>{live.css}</style>")
295
+ out += body
296
+ out.append("</svg>")
297
+ css = None
298
+ if apart and (rules or live is not None):
299
+ css = "\n".join(rules + (live.shared or [live.css] if live is not None else [])) + "\n"
300
+ return "\n".join(out) + "\n", css
301
+
302
+
303
+ def stylesheet(figures: "Iterable[Any]") -> str:
304
+ """One style sheet for a page with several figures (``render(stylesheet="external")``): what each of them goes
305
+ with, every rule once. ``figures``: their results, or their sheets (``result.css``)."""
306
+ rules: dict[str, None] = {}
307
+ for figure in figures:
308
+ css = figure if isinstance(figure, str) else figure.css
309
+ rules.update(dict.fromkeys((css or "").splitlines()))
310
+ return "".join(f"{rule}\n" for rule in rules)
@@ -0,0 +1,64 @@
1
+ """Text extents without a font engine.
2
+
3
+ Layout has to know how wide a label is before anything is drawn, and it has to
4
+ give the same answer on every machine (hard requirement: deterministic output).
5
+ So widths come from a fixed table -- the advance widths of Helvetica, with which
6
+ Arial and Liberation Sans are metric-compatible -- rather than from whatever
7
+ font happens to be installed. The SVG asks for exactly that font family.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ __all__ = ["text_width", "CAP_HEIGHT", "DESCENT", "FONT_FAMILY"]
13
+
14
+ FONT_FAMILY = "Helvetica, Arial, 'Liberation Sans', sans-serif"
15
+
16
+ #: Vertical metrics as a fraction of the font size.
17
+ CAP_HEIGHT = 0.718
18
+ DESCENT = 0.207
19
+
20
+ _REGULAR = {
21
+ " ": 278, "!": 278, '"': 355, "#": 556, "$": 556, "%": 889, "&": 667, "'": 191, "(": 333, ")": 333,
22
+ "*": 389, "+": 584, ",": 278, "-": 333, ".": 278, "/": 278, ":": 278, ";": 278, "<": 584, "=": 584,
23
+ ">": 584, "?": 556, "@": 1015, "[": 278, "\\": 278, "]": 278, "^": 469, "_": 556, "`": 333,
24
+ "{": 334, "|": 260, "}": 334, "~": 584,
25
+ "A": 667, "B": 667, "C": 722, "D": 722, "E": 667, "F": 611, "G": 778, "H": 722, "I": 278, "J": 500,
26
+ "K": 667, "L": 556, "M": 833, "N": 722, "O": 778, "P": 667, "Q": 778, "R": 722, "S": 667, "T": 611,
27
+ "U": 722, "V": 667, "W": 944, "X": 667, "Y": 667, "Z": 611,
28
+ "a": 556, "b": 556, "c": 500, "d": 556, "e": 556, "f": 278, "g": 556, "h": 556, "i": 222, "j": 222,
29
+ "k": 500, "l": 222, "m": 833, "n": 556, "o": 556, "p": 556, "q": 556, "r": 333, "s": 500, "t": 278,
30
+ "u": 556, "v": 500, "w": 722, "x": 500, "y": 500, "z": 500,
31
+ "Å": 667, "°": 400, "·": 278, "–": 556, "—": 1000, "−": 584,
32
+ "π": 549, "×": 584, "′": 247, "→": 1000, "†": 556, "≥": 549, "≤": 549,
33
+ "…": 1000, "±": 584,
34
+ }
35
+
36
+ _BOLD = {
37
+ " ": 278, "!": 333, '"': 474, "#": 556, "$": 556, "%": 889, "&": 722, "'": 238, "(": 333, ")": 333,
38
+ "*": 389, "+": 584, ",": 278, "-": 333, ".": 278, "/": 278, ":": 333, ";": 333, "<": 584, "=": 584,
39
+ ">": 584, "?": 611, "@": 975, "[": 333, "\\": 278, "]": 333, "^": 584, "_": 556, "`": 333,
40
+ "{": 389, "|": 280, "}": 389, "~": 584,
41
+ "A": 722, "B": 722, "C": 722, "D": 722, "E": 667, "F": 611, "G": 778, "H": 722, "I": 278, "J": 556,
42
+ "K": 722, "L": 611, "M": 833, "N": 722, "O": 778, "P": 667, "Q": 778, "R": 722, "S": 667, "T": 611,
43
+ "U": 722, "V": 667, "W": 944, "X": 667, "Y": 667, "Z": 611,
44
+ "a": 556, "b": 611, "c": 556, "d": 611, "e": 556, "f": 333, "g": 611, "h": 611, "i": 278, "j": 278,
45
+ "k": 556, "l": 278, "m": 889, "n": 611, "o": 611, "p": 611, "q": 611, "r": 389, "s": 556, "t": 333,
46
+ "u": 611, "v": 556, "w": 778, "x": 556, "y": 556, "z": 500,
47
+ "Å": 722, "°": 400, "·": 278, "–": 556, "—": 1000, "−": 584,
48
+ "π": 549, "×": 584, "′": 247, "→": 1000, "†": 556, "≥": 549, "≤": 549,
49
+ "…": 1000, "±": 584,
50
+ }
51
+ for _d in "0123456789":
52
+ _REGULAR[_d] = 556
53
+ _BOLD[_d] = 556
54
+ for _sub in "\u2080\u2081\u2082\u2083\u2084": # subscript digits
55
+ _REGULAR[_sub] = 370
56
+ _BOLD[_sub] = 370
57
+
58
+ _DEFAULT = 600
59
+
60
+
61
+ def text_width(text: str, size: float, bold: bool = False) -> float:
62
+ """Advance width of ``text`` at ``size`` (same units as ``size``)."""
63
+ table = _BOLD if bold else _REGULAR
64
+ return sum(table.get(ch, _DEFAULT) for ch in text) * size / 1000.0