speechplotlib 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.
- speechplotlib/__init__.py +40 -0
- speechplotlib/accessor.py +102 -0
- speechplotlib/analyzers/__init__.py +12 -0
- speechplotlib/analyzers/_input.py +97 -0
- speechplotlib/analyzers/_stats.py +165 -0
- speechplotlib/analyzers/_text.py +192 -0
- speechplotlib/analyzers/categorical.py +211 -0
- speechplotlib/analyzers/distribution.py +409 -0
- speechplotlib/analyzers/model.py +456 -0
- speechplotlib/analyzers/overview.py +157 -0
- speechplotlib/analyzers/relationship.py +413 -0
- speechplotlib/analyzers/trend.py +281 -0
- speechplotlib/config.py +124 -0
- speechplotlib/errors.py +8 -0
- speechplotlib/plotting.py +102 -0
- speechplotlib/result.py +207 -0
- speechplotlib/rules.py +139 -0
- speechplotlib/session.py +73 -0
- speechplotlib/speech.py +117 -0
- speechplotlib/var.py +303 -0
- speechplotlib-0.1.0.dist-info/METADATA +166 -0
- speechplotlib-0.1.0.dist-info/RECORD +25 -0
- speechplotlib-0.1.0.dist-info/WHEEL +5 -0
- speechplotlib-0.1.0.dist-info/licenses/LICENSE +21 -0
- speechplotlib-0.1.0.dist-info/top_level.txt +1 -0
speechplotlib/result.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""The object every speechplotlib call returns.
|
|
2
|
+
|
|
3
|
+
A ``Result`` holds three things:
|
|
4
|
+
|
|
5
|
+
* ``facts``: every computed number, also reachable as attributes (``h.skewness``).
|
|
6
|
+
* ``lines``: the description, as sentences tagged with the level they belong to.
|
|
7
|
+
* extras such as ``outliers`` or ``bins`` for follow-up questions.
|
|
8
|
+
|
|
9
|
+
Displaying a result reads its description. In Jupyter it is printed once when
|
|
10
|
+
the call runs; typing the variable again later reads it again.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import sys
|
|
16
|
+
from typing import Any, Callable
|
|
17
|
+
|
|
18
|
+
from .config import LEVELS, config
|
|
19
|
+
|
|
20
|
+
_LEVEL_RANK = {name: i for i, name in enumerate(LEVELS)}
|
|
21
|
+
|
|
22
|
+
_seen_kinds: set[str] = set()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _in_ipython() -> bool:
|
|
26
|
+
try:
|
|
27
|
+
from IPython import get_ipython # type: ignore
|
|
28
|
+
except Exception:
|
|
29
|
+
return False
|
|
30
|
+
return get_ipython() is not None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _execution_count():
|
|
34
|
+
try:
|
|
35
|
+
from IPython import get_ipython # type: ignore
|
|
36
|
+
|
|
37
|
+
ip = get_ipython()
|
|
38
|
+
return getattr(ip, "execution_count", None) if ip is not None else None
|
|
39
|
+
except Exception:
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _plain_prompt() -> bool:
|
|
44
|
+
return hasattr(sys, "ps1") and not _in_ipython()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Result:
|
|
48
|
+
"""A described chart. See ``detail()``, ``explain()``, ``advice()`` and ``values()``."""
|
|
49
|
+
|
|
50
|
+
def __init__(
|
|
51
|
+
self,
|
|
52
|
+
kind: str,
|
|
53
|
+
name: str,
|
|
54
|
+
facts: dict[str, Any],
|
|
55
|
+
lines: list[tuple[str, str]],
|
|
56
|
+
*,
|
|
57
|
+
title: str | None = None,
|
|
58
|
+
glossary: dict[str, str] | None = None,
|
|
59
|
+
advice: list[str] | None = None,
|
|
60
|
+
extras: dict[str, Any] | None = None,
|
|
61
|
+
level: str | None = None,
|
|
62
|
+
) -> None:
|
|
63
|
+
self.kind = kind
|
|
64
|
+
self.name = name
|
|
65
|
+
self.title = title or f"{kind} of {name}"
|
|
66
|
+
self.facts = dict(facts)
|
|
67
|
+
self.lines = list(lines)
|
|
68
|
+
self._glossary = glossary or {}
|
|
69
|
+
self._advice = advice or []
|
|
70
|
+
self._extras = extras or {}
|
|
71
|
+
self.level = config.check_level(level)
|
|
72
|
+
self.figure = None
|
|
73
|
+
self._announced_at = None
|
|
74
|
+
self._hint = None
|
|
75
|
+
# The tip is given once per session, on the first result.
|
|
76
|
+
if config.hints and not _seen_kinds:
|
|
77
|
+
_seen_kinds.add(kind)
|
|
78
|
+
self._hint = (
|
|
79
|
+
"Tip: .detail() for more, .explain() for terms, .advice() for next steps, "
|
|
80
|
+
".values() for every number."
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
# ----- text -----------------------------------------------------------
|
|
84
|
+
def text(self, level: str | None = None) -> str:
|
|
85
|
+
"""The description at ``level`` ("brief", "standard" or "full")."""
|
|
86
|
+
level = config.check_level(level or self.level)
|
|
87
|
+
rank = _LEVEL_RANK[level]
|
|
88
|
+
body = " ".join(s for lv, s in self.lines if _LEVEL_RANK[lv] <= rank)
|
|
89
|
+
return body
|
|
90
|
+
|
|
91
|
+
def detail(self) -> "Spoken":
|
|
92
|
+
"""The standard-level description."""
|
|
93
|
+
return Spoken(self.text("standard"))
|
|
94
|
+
|
|
95
|
+
def full(self) -> "Spoken":
|
|
96
|
+
"""Everything computed, in words."""
|
|
97
|
+
return Spoken(self.text("full"))
|
|
98
|
+
|
|
99
|
+
def explain(self, term: str | None = None) -> "Spoken":
|
|
100
|
+
"""What a term means and which bands were used. Call with no term to list the terms."""
|
|
101
|
+
if not self._glossary:
|
|
102
|
+
return Spoken("No terms to explain for this result.")
|
|
103
|
+
if term is None:
|
|
104
|
+
terms = ", ".join(sorted(self._glossary))
|
|
105
|
+
return Spoken(f"Terms for this result: {terms}. Call explain with one of them.")
|
|
106
|
+
key = term.lower().strip()
|
|
107
|
+
if key not in self._glossary:
|
|
108
|
+
terms = ", ".join(sorted(self._glossary))
|
|
109
|
+
return Spoken(f"No entry for {term}. Terms for this result: {terms}.")
|
|
110
|
+
return Spoken(self._glossary[key])
|
|
111
|
+
|
|
112
|
+
def advice(self) -> "Spoken":
|
|
113
|
+
"""Suggested next steps, kept apart from the facts."""
|
|
114
|
+
if not self._advice:
|
|
115
|
+
return Spoken("No suggestions for this result.")
|
|
116
|
+
return Spoken(" ".join(self._advice))
|
|
117
|
+
|
|
118
|
+
def values(self) -> dict[str, Any]:
|
|
119
|
+
"""Every computed number, as a plain dict."""
|
|
120
|
+
return dict(self.facts)
|
|
121
|
+
|
|
122
|
+
# ----- attribute access ---------------------------------------------
|
|
123
|
+
def __getattr__(self, item: str):
|
|
124
|
+
if item.startswith("_"):
|
|
125
|
+
raise AttributeError(item)
|
|
126
|
+
facts = self.__dict__.get("facts", {})
|
|
127
|
+
if item in facts:
|
|
128
|
+
return facts[item]
|
|
129
|
+
extras = self.__dict__.get("_extras", {})
|
|
130
|
+
if item in extras:
|
|
131
|
+
return extras[item]
|
|
132
|
+
raise AttributeError(
|
|
133
|
+
f"{item!r} is not part of this result. Available: "
|
|
134
|
+
+ ", ".join(sorted(list(facts) + list(extras)))
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
def __dir__(self):
|
|
138
|
+
return sorted(set(super().__dir__()) | set(self.facts) | set(self._extras))
|
|
139
|
+
|
|
140
|
+
# ----- display ------------------------------------------------------
|
|
141
|
+
def _spoken(self) -> str:
|
|
142
|
+
out = self.text()
|
|
143
|
+
if self._hint:
|
|
144
|
+
out += "\n" + self._hint
|
|
145
|
+
return out
|
|
146
|
+
|
|
147
|
+
def __str__(self) -> str:
|
|
148
|
+
return self.text()
|
|
149
|
+
|
|
150
|
+
def __repr__(self) -> str:
|
|
151
|
+
return self._spoken()
|
|
152
|
+
|
|
153
|
+
def _announce(self) -> None:
|
|
154
|
+
mode = config.autoprint
|
|
155
|
+
if mode is False:
|
|
156
|
+
return
|
|
157
|
+
if mode == "auto" and _plain_prompt():
|
|
158
|
+
return # the prompt shows the repr itself
|
|
159
|
+
print(self._spoken())
|
|
160
|
+
self._hint = None
|
|
161
|
+
self._announced_at = _execution_count()
|
|
162
|
+
|
|
163
|
+
def _ipython_display_(self):
|
|
164
|
+
# Skip the automatic display in the same cell that already printed the result.
|
|
165
|
+
if self._announced_at is not None and self._announced_at == _execution_count():
|
|
166
|
+
return
|
|
167
|
+
print(self._spoken())
|
|
168
|
+
self._hint = None
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class Spoken(str):
|
|
172
|
+
"""A string that displays as plain text without quotes."""
|
|
173
|
+
|
|
174
|
+
def __repr__(self) -> str:
|
|
175
|
+
return str(self)
|
|
176
|
+
|
|
177
|
+
def _ipython_display_(self):
|
|
178
|
+
print(str(self))
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def build(
|
|
182
|
+
kind: str,
|
|
183
|
+
name: str,
|
|
184
|
+
facts: dict,
|
|
185
|
+
lines: list[tuple[str, str]],
|
|
186
|
+
*,
|
|
187
|
+
register: bool = True,
|
|
188
|
+
announce: bool = True,
|
|
189
|
+
**kwargs,
|
|
190
|
+
) -> Result:
|
|
191
|
+
"""Create a result, store it in the session and print it."""
|
|
192
|
+
from .session import session
|
|
193
|
+
|
|
194
|
+
res = Result(kind, name, facts, lines, **kwargs)
|
|
195
|
+
if register:
|
|
196
|
+
session.add(res)
|
|
197
|
+
if announce:
|
|
198
|
+
res._announce()
|
|
199
|
+
return res
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def reset_hints() -> None:
|
|
203
|
+
_seen_kinds.clear()
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
Line = tuple[str, str]
|
|
207
|
+
Renderer = Callable[..., list[Line]]
|
speechplotlib/rules.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Turn statistics into labels using the bands in ``config.thresholds``.
|
|
2
|
+
|
|
3
|
+
Every function returns a short label that templates turn into words. No
|
|
4
|
+
function here builds sentences, so the bands can be tested on their own.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
|
|
11
|
+
from .config import config
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _t():
|
|
15
|
+
return config.thresholds
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def skew_band(skew: float) -> str:
|
|
19
|
+
"""``"symmetric"``, ``"moderate"`` or ``"high"``; ``"undefined"`` when not computable."""
|
|
20
|
+
if skew is None or math.isnan(skew):
|
|
21
|
+
return "undefined"
|
|
22
|
+
a = abs(skew)
|
|
23
|
+
t = _t()["skewness"]
|
|
24
|
+
if a >= t["high"]:
|
|
25
|
+
return "high"
|
|
26
|
+
if a >= t["moderate"]:
|
|
27
|
+
return "moderate"
|
|
28
|
+
return "symmetric"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def skew_words(skew: float) -> str:
|
|
32
|
+
"""``"highly right-skewed"``, ``"moderately left-skewed"`` or ``"roughly symmetric"``."""
|
|
33
|
+
band = skew_band(skew)
|
|
34
|
+
if band == "undefined":
|
|
35
|
+
return "shape undefined"
|
|
36
|
+
if band == "symmetric":
|
|
37
|
+
return "roughly symmetric"
|
|
38
|
+
side = "right" if skew > 0 else "left"
|
|
39
|
+
lead = "highly" if band == "high" else "moderately"
|
|
40
|
+
return f"{lead} {side}-skewed"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def kurtosis_band(kurt: float) -> str:
|
|
44
|
+
"""``"light"``, ``"normal"``, ``"heavy"`` or ``"very heavy"`` tails."""
|
|
45
|
+
if kurt is None or math.isnan(kurt):
|
|
46
|
+
return "undefined"
|
|
47
|
+
t = _t()["kurtosis"]
|
|
48
|
+
if kurt > t["very_heavy"]:
|
|
49
|
+
return "very heavy"
|
|
50
|
+
if kurt > t["heavy"]:
|
|
51
|
+
return "heavy"
|
|
52
|
+
if kurt < t["light"]:
|
|
53
|
+
return "light"
|
|
54
|
+
return "normal"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def kurtosis_words(kurt: float) -> str:
|
|
58
|
+
band = kurtosis_band(kurt)
|
|
59
|
+
return {
|
|
60
|
+
"very heavy": "very heavy tails",
|
|
61
|
+
"heavy": "heavy tails",
|
|
62
|
+
"light": "light tails",
|
|
63
|
+
"normal": "tails close to normal",
|
|
64
|
+
"undefined": "tails undefined",
|
|
65
|
+
}[band]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def correlation_band(r: float) -> str:
|
|
69
|
+
if r is None or math.isnan(r):
|
|
70
|
+
return "undefined"
|
|
71
|
+
a = abs(r)
|
|
72
|
+
for lower, label in _t()["correlation"]:
|
|
73
|
+
if a >= lower:
|
|
74
|
+
return label
|
|
75
|
+
return _t()["correlation"][-1][1]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def missing_band(share: float) -> str:
|
|
79
|
+
"""``"none"``, ``"low"``, ``"moderate"`` or ``"high"`` share of missing values."""
|
|
80
|
+
t = _t()["missing"]
|
|
81
|
+
if share <= 0:
|
|
82
|
+
return "none"
|
|
83
|
+
if share < t["low"]:
|
|
84
|
+
return "low"
|
|
85
|
+
if share <= t["high"]:
|
|
86
|
+
return "moderate"
|
|
87
|
+
return "high"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def modality(n_peaks: int) -> str:
|
|
91
|
+
if n_peaks <= 0:
|
|
92
|
+
return "no clear peak"
|
|
93
|
+
if n_peaks == 1:
|
|
94
|
+
return "unimodal"
|
|
95
|
+
if n_peaks == 2:
|
|
96
|
+
return "bimodal"
|
|
97
|
+
return "multimodal"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def normal_verdict(p: float) -> str:
|
|
101
|
+
if p is None or math.isnan(p):
|
|
102
|
+
return "undefined"
|
|
103
|
+
return "departs from normal" if p < _t()["normality_alpha"] else "consistent with normal"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def r2_band(r2: float) -> str:
|
|
107
|
+
"""``"weak"``, ``"moderate"`` or ``"strong"`` fit."""
|
|
108
|
+
if r2 is None or math.isnan(r2):
|
|
109
|
+
return "undefined"
|
|
110
|
+
t = _t()["r2"]
|
|
111
|
+
if r2 >= t["strong"]:
|
|
112
|
+
return "strong"
|
|
113
|
+
if r2 >= t["moderate"]:
|
|
114
|
+
return "moderate"
|
|
115
|
+
return "weak"
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def auc_band(auc: float) -> str:
|
|
119
|
+
if auc is None or math.isnan(auc):
|
|
120
|
+
return "undefined"
|
|
121
|
+
for lower, label in _t()["auc"]:
|
|
122
|
+
if auc >= lower:
|
|
123
|
+
return label
|
|
124
|
+
return _t()["auc"][-1][1]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def direction(r: float) -> str:
|
|
128
|
+
if r is None or math.isnan(r) or r == 0:
|
|
129
|
+
return "no"
|
|
130
|
+
return "positive" if r > 0 else "negative"
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def balance_band(min_share: float) -> str:
|
|
134
|
+
t = _t()
|
|
135
|
+
if min_share < t["severe_imbalance"]:
|
|
136
|
+
return "severely imbalanced"
|
|
137
|
+
if min_share < t["imbalance"]:
|
|
138
|
+
return "imbalanced"
|
|
139
|
+
return "balanced"
|
speechplotlib/session.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""The session store: every result made in this Python session, by name."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import OrderedDict
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from .errors import SpeechKeyError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Session:
|
|
13
|
+
"""Keeps results in the order they were made. The newest result with a name wins."""
|
|
14
|
+
|
|
15
|
+
def __init__(self) -> None:
|
|
16
|
+
self._results: "OrderedDict[str, object]" = OrderedDict()
|
|
17
|
+
self._history: list = []
|
|
18
|
+
|
|
19
|
+
@staticmethod
|
|
20
|
+
def key(result) -> str:
|
|
21
|
+
return f"{result.kind}:{result.name}"
|
|
22
|
+
|
|
23
|
+
def add(self, result) -> None:
|
|
24
|
+
k = self.key(result)
|
|
25
|
+
self._results.pop(k, None)
|
|
26
|
+
self._results[k] = result
|
|
27
|
+
self._history.append(result)
|
|
28
|
+
|
|
29
|
+
def list(self) -> list[str]:
|
|
30
|
+
"""Names of saved results, oldest first, for example ``"hist:price"``."""
|
|
31
|
+
return list(self._results)
|
|
32
|
+
|
|
33
|
+
def get(self, name: str):
|
|
34
|
+
"""Bring back a saved result by name, for example ``spl.get("hist:price")``."""
|
|
35
|
+
if name in self._results:
|
|
36
|
+
return self._results[name]
|
|
37
|
+
matches = [k for k in self._results if k.split(":", 1)[-1] == name]
|
|
38
|
+
if len(matches) == 1:
|
|
39
|
+
return self._results[matches[0]]
|
|
40
|
+
if matches:
|
|
41
|
+
raise SpeechKeyError(f"{name!r} matches several results: {', '.join(matches)}")
|
|
42
|
+
raise SpeechKeyError(f"No result named {name!r}. Saved: {', '.join(self._results) or 'none'}")
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def last(self):
|
|
46
|
+
"""The most recent result, or None."""
|
|
47
|
+
return self._history[-1] if self._history else None
|
|
48
|
+
|
|
49
|
+
def clear(self) -> None:
|
|
50
|
+
self._results.clear()
|
|
51
|
+
self._history.clear()
|
|
52
|
+
|
|
53
|
+
def save(self, path: str | Path, level: str = "standard") -> Path:
|
|
54
|
+
"""Write every saved description to one plain-text Markdown file."""
|
|
55
|
+
path = Path(path)
|
|
56
|
+
stamp = datetime.now().strftime("%Y-%m-%d %H:%M")
|
|
57
|
+
parts = [f"# speechplotlib session notes\n\nSaved {stamp}.\n"]
|
|
58
|
+
for k, res in self._results.items():
|
|
59
|
+
parts.append(f"## {res.title}\n\n{res.text(level)}\n")
|
|
60
|
+
path.write_text("\n".join(parts), encoding="utf-8")
|
|
61
|
+
return path
|
|
62
|
+
|
|
63
|
+
def __len__(self) -> int:
|
|
64
|
+
return len(self._results)
|
|
65
|
+
|
|
66
|
+
def __repr__(self) -> str:
|
|
67
|
+
names = self.list()
|
|
68
|
+
if not names:
|
|
69
|
+
return "Session: no results yet."
|
|
70
|
+
return f"Session: {len(names)} results. " + ", ".join(names) + "."
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
session = Session()
|
speechplotlib/speech.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Turn numbers and lists into text a screen reader speaks cleanly.
|
|
2
|
+
|
|
3
|
+
Rules: a fixed number of significant figures, thousands separators, the word
|
|
4
|
+
"minus" instead of a hyphen, no symbols such as plus-minus or approximately
|
|
5
|
+
equal, and lists cut to a few items with "and N more".
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import math
|
|
11
|
+
from typing import Iterable, Sequence
|
|
12
|
+
|
|
13
|
+
from .config import config
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def is_missing(x) -> bool:
|
|
17
|
+
try:
|
|
18
|
+
return x is None or (isinstance(x, float) and math.isnan(x))
|
|
19
|
+
except TypeError:
|
|
20
|
+
return False
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def num(x, sig: int | None = None) -> str:
|
|
24
|
+
"""A number for speech: ``1234567.8`` -> ``"1,230,000"``, ``-0.391`` -> ``"minus 0.391"``."""
|
|
25
|
+
if is_missing(x):
|
|
26
|
+
return "not available"
|
|
27
|
+
x = float(x)
|
|
28
|
+
if math.isinf(x):
|
|
29
|
+
return "infinity" if x > 0 else "minus infinity"
|
|
30
|
+
sig = sig or config.sig_figs
|
|
31
|
+
sign = "minus " if x < 0 else ""
|
|
32
|
+
a = abs(x)
|
|
33
|
+
if a == 0:
|
|
34
|
+
return "0"
|
|
35
|
+
mag = math.floor(math.log10(a))
|
|
36
|
+
decimals = max(0, sig - 1 - mag)
|
|
37
|
+
rounded = round(a, decimals)
|
|
38
|
+
# Rounding can carry into a new magnitude, for example 999.6 -> 1000.
|
|
39
|
+
if decimals == 0:
|
|
40
|
+
rounded = round(a, sig - 1 - mag)
|
|
41
|
+
text = f"{int(round(rounded)):,}"
|
|
42
|
+
else:
|
|
43
|
+
text = f"{rounded:,.{decimals}f}".rstrip("0").rstrip(".")
|
|
44
|
+
return sign + text
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def integer(x) -> str:
|
|
48
|
+
"""An exact count with thousands separators."""
|
|
49
|
+
if is_missing(x):
|
|
50
|
+
return "not available"
|
|
51
|
+
return f"{int(x):,}"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def pct(fraction, decimals: int = 1) -> str:
|
|
55
|
+
"""A share as a percentage: ``0.7723`` -> ``"77.2%"``, ``0.5`` -> ``"50%"``."""
|
|
56
|
+
if is_missing(fraction):
|
|
57
|
+
return "not available"
|
|
58
|
+
value = float(fraction) * 100
|
|
59
|
+
if value != 0 and abs(value) < 0.1:
|
|
60
|
+
return "under 0.1%"
|
|
61
|
+
if abs(value) >= 100: # three significant figures: 285.7% reads as 286%
|
|
62
|
+
decimals = 0
|
|
63
|
+
text = f"{value:.{decimals}f}".rstrip("0").rstrip(".") if decimals else f"{value:.0f}"
|
|
64
|
+
return f"{text}%"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def pvalue(p) -> str:
|
|
68
|
+
"""A p-value: ``"p below 0.001"`` or ``"p 0.034"``."""
|
|
69
|
+
if is_missing(p):
|
|
70
|
+
return "p not available"
|
|
71
|
+
if p < 0.001:
|
|
72
|
+
return "p below 0.001"
|
|
73
|
+
return f"p {num(p, 2)}"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def plural(n: int, word: str, plural_word: str | None = None) -> str:
|
|
77
|
+
"""``plural(1, "value")`` -> ``"1 value"``; ``plural(3, "value")`` -> ``"3 values"``."""
|
|
78
|
+
form = word if n == 1 else (plural_word or word + "s")
|
|
79
|
+
return f"{integer(n)} {form}"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def join(items: Sequence[str], conj: str = "and") -> str:
|
|
83
|
+
"""``["a", "b", "c"]`` -> ``"a, b and c"``."""
|
|
84
|
+
items = [str(i) for i in items]
|
|
85
|
+
if not items:
|
|
86
|
+
return ""
|
|
87
|
+
if len(items) == 1:
|
|
88
|
+
return items[0]
|
|
89
|
+
return f"{', '.join(items[:-1])} {conj} {items[-1]}"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def capped(items: Iterable[str], where: str | None = None, limit: int | None = None) -> str:
|
|
93
|
+
"""Name at most ``limit`` items, then ``"and N more"`` with where to find the rest."""
|
|
94
|
+
items = list(items)
|
|
95
|
+
limit = limit or config.max_items
|
|
96
|
+
if len(items) <= limit:
|
|
97
|
+
return join(items)
|
|
98
|
+
rest = len(items) - limit
|
|
99
|
+
tail = f"and {integer(rest)} more"
|
|
100
|
+
if where:
|
|
101
|
+
tail += f", see {where}"
|
|
102
|
+
return ", ".join(items[:limit]) + ", " + tail
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def sentence(text: str) -> str:
|
|
106
|
+
"""Capitalise the first letter and end with a full stop."""
|
|
107
|
+
text = text.strip()
|
|
108
|
+
if not text:
|
|
109
|
+
return ""
|
|
110
|
+
text = text[0].upper() + text[1:]
|
|
111
|
+
if text[-1] not in ".!?":
|
|
112
|
+
text += "."
|
|
113
|
+
return text
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def range_text(lo, hi) -> str:
|
|
117
|
+
return f"{num(lo)} to {num(hi)}"
|