@dsh-ft/dsh-fft-plot 0.1.0 → 0.2.0

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.
@@ -9,17 +9,64 @@
9
9
  中文字体由 `font-family` 回退链解析——SVG 在 `<img>` 里是独立文档,继承不到宿主字体。
10
10
  - **不依赖任何第三方包**:没有 matplotlib、没有 numpy。
11
11
  """
12
+ import datetime
12
13
  import math
13
14
  import os
15
+ import re
14
16
 
15
17
  from .theme import FONT_STACK
16
18
 
19
+ #: XML 1.0 不允许的控制字符。上游数据偶尔带进来,转义层必须清掉:
20
+ #: 它们不会报错,但写出的文件不是合法 XML,浏览器打开是空白。
21
+ _INVALID_XML = re.compile('[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]')
22
+ _HEX = re.compile(r'^#([0-9a-fA-F]{6})$')
23
+
17
24
 
18
25
  # ---------------------------------------------------------------- 基础工具
19
26
 
20
27
  def esc(s):
21
- """转义 XML 文本内容。"""
22
- return (str(s).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;'))
28
+ """转义 XML 文本内容,并剔除 XML 不允许的控制字符。"""
29
+ text = _INVALID_XML.sub('', str(s))
30
+ return text.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
31
+
32
+
33
+ def _rgb(color):
34
+ """`#RRGGBB` → (r, g, b);非法值退回中灰。"""
35
+ match = _HEX.match(str(color))
36
+ if not match:
37
+ return (128, 128, 128)
38
+ value = int(match.group(1), 16)
39
+ return ((value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff)
40
+
41
+
42
+ def mix_hex(start, end, ratio):
43
+ """在两个 `#RRGGBB` 之间线性插值,ratio=0 取 start、1 取 end。
44
+
45
+ 热力图/示意图需要按数值强度调色,而 SVG 的 `fill` 只能是具体颜色;
46
+ 在生成期算好插值,比给每个格子叠一层透明度更可控(叠透明度会露出底纹)。
47
+ """
48
+ ratio = min(max(float(ratio), 0.0), 1.0)
49
+ sr, sg, sb = _rgb(start)
50
+ er, eg, eb = _rgb(end)
51
+ return '#{:02X}{:02X}{:02X}'.format(
52
+ round(sr + (er - sr) * ratio),
53
+ round(sg + (eg - sg) * ratio),
54
+ round(sb + (eb - sb) * ratio),
55
+ )
56
+
57
+
58
+ def relative_luminance(color):
59
+ """WCAG 相对亮度,用来决定块上的文字用深色还是浅色。"""
60
+ channels = []
61
+ for value in _rgb(color):
62
+ channel = value / 255
63
+ channels.append(channel / 12.92 if channel <= 0.03928 else ((channel + 0.055) / 1.055) ** 2.4)
64
+ return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2]
65
+
66
+
67
+ def contrast_ink(background, dark, light):
68
+ """在给定底色上选可读的文字色:深底用浅字、浅底用深字。"""
69
+ return dark if relative_luminance(background) > 0.45 else light
23
70
 
24
71
 
25
72
  def nice_ticks(lo, hi, target=5):
@@ -41,33 +88,81 @@ def nice_ticks(lo, hi, target=5):
41
88
  return out
42
89
 
43
90
 
91
+ #: 上游日期一律按上海时区解释;不能用机器本地时区,否则跨时区会错一天。
92
+ _SHANGHAI = datetime.timezone(datetime.timedelta(hours=8))
93
+ _ISO_DATE = re.compile(r'^(\d{4})-(\d{1,2})-(\d{1,2})')
94
+ _CN_DATE = re.compile(r'^(\d{4})年(\d{1,2})月')
95
+
96
+
97
+ def date_parts(raw):
98
+ """把常见时间写法收敛成 `(year, month, day)`;无法识别返回 None。
99
+
100
+ 支持(SKILL.md「数据形状的坑」列的五种形态):
101
+ `20260810`、`2026-08-10`、`2026-09-30 00:00:00`、毫秒/秒/纳秒时间戳、
102
+ `2026年09月份`。只有年月时 day 为 None。
103
+ """
104
+ text = str(raw).strip()
105
+ digits = ''.join(ch for ch in text if ch.isdigit())
106
+ if not digits:
107
+ return None
108
+ # 时间戳:纯数字且量级像 1973–2286 年,按秒/毫秒/微秒/纳秒识别
109
+ if text.lstrip('-').isdigit():
110
+ stamp = int(digits)
111
+ length = len(digits)
112
+ if length == 10 and 10 ** 8 <= stamp < 10 ** 10:
113
+ moment = datetime.datetime.fromtimestamp(stamp, _SHANGHAI)
114
+ return (moment.year, moment.month, moment.day)
115
+ if length == 13 and 10 ** 11 <= stamp < 10 ** 13:
116
+ moment = datetime.datetime.fromtimestamp(stamp / 1e3, _SHANGHAI)
117
+ return (moment.year, moment.month, moment.day)
118
+ if length == 16 and 10 ** 14 <= stamp < 10 ** 16:
119
+ moment = datetime.datetime.fromtimestamp(stamp / 1e6, _SHANGHAI)
120
+ return (moment.year, moment.month, moment.day)
121
+ if length == 19 and 10 ** 17 <= stamp < 10 ** 19:
122
+ moment = datetime.datetime.fromtimestamp(stamp / 1e9, _SHANGHAI)
123
+ return (moment.year, moment.month, moment.day)
124
+ if len(digits) == 8 and text[:4].isdigit():
125
+ year, month, day = int(digits[:4]), int(digits[4:6]), int(digits[6:8])
126
+ if 1900 <= year <= 2200 and 1 <= month <= 12 and 1 <= day <= 31:
127
+ return (year, month, day)
128
+ iso = _ISO_DATE.match(text)
129
+ if iso:
130
+ return (int(iso.group(1)), int(iso.group(2)), int(iso.group(3)))
131
+ cn = _CN_DATE.match(text)
132
+ if cn:
133
+ return (int(cn.group(1)), int(cn.group(2)), None)
134
+ if len(digits) == 6 and len(text) <= 10: # 202609 -> 年月
135
+ year, month = int(digits[:4]), int(digits[4:6])
136
+ if 1900 <= year <= 2200 and 1 <= month <= 12:
137
+ return (year, month, None)
138
+ return None
139
+
140
+
44
141
  def fmt_date_label(raw, compact=True):
45
142
  """把返回里常见的日期写法收敛成短标签。
46
143
 
47
144
  上游日期有五种互不兼容形态(`20260810`、`2026-08-10`、`2026-09-30 00:00:00`、
48
145
  毫秒/纳秒时间戳、`2026年09月份`),8 位数字直接当轴标签既挤又难读。
49
- `compact=True` 时同一年内只留「月-日」,跨年时保留年份。
146
+ `compact=True` 时只留「月-日」,跨年时保留年份;认不出的值原样返回。
50
147
  """
51
- text = str(raw).strip()
52
- digits = ''.join(ch for ch in text if ch.isdigit())
53
- if len(digits) == 8 and text[:4].isdigit():
54
- year, month, day = digits[:4], digits[4:6], digits[6:8]
55
- return f'{month}-{day}' if compact else f'{year}-{month}-{day}'
56
- if len(digits) == 6 and len(text) <= 7: # 202609 -> 年月
57
- return f'{digits[:4]}-{digits[4:6]}'
58
- # `2026-09-30 00:00:00` 之类:去掉时间部分
59
- if ' ' in text and len(text.split(' ')[0]) == 10:
60
- return text.split(' ')[0] if not compact else text[5:10]
61
- return text
148
+ parts = date_parts(raw)
149
+ if parts is None:
150
+ return str(raw)
151
+ year, month, day = parts
152
+ if day is None:
153
+ return f'{year:04d}-{month:02d}'
154
+ if compact:
155
+ return f'{month:02d}-{day:02d}'
156
+ return f'{year:04d}-{month:02d}-{day:02d}'
62
157
 
63
158
 
64
159
  def has_multiple_years(values):
65
160
  """判断一组日期标签是否跨年——跨年就不能只写月-日。"""
66
161
  years = set()
67
162
  for raw in values:
68
- digits = ''.join(ch for ch in str(raw) if ch.isdigit())
69
- if len(digits) >= 6 and str(raw).strip()[:4].isdigit():
70
- years.add(digits[:4])
163
+ parts = date_parts(raw)
164
+ if parts is not None:
165
+ years.add(parts[0])
71
166
  return len(years) > 1
72
167
 
73
168
 
@@ -161,12 +256,16 @@ class Svg:
161
256
 
162
257
  # ---- 图元 ----
163
258
 
164
- def rect(self, x, y, w, h, fill, rx=0, opacity=None):
259
+ def rect(self, x, y, w, h, fill, rx=0, opacity=None, stroke=None, stroke_width=1, dash=None):
165
260
  attrs = f'x="{x:.2f}" y="{y:.2f}" width="{max(w, 0):.2f}" height="{max(h, 0):.2f}"'
166
261
  if rx:
167
262
  attrs += f' rx="{rx}"'
168
263
  if opacity is not None:
169
264
  attrs += f' opacity="{opacity}"'
265
+ if stroke:
266
+ attrs += f' stroke="{stroke}" stroke-width="{stroke_width}"'
267
+ if dash:
268
+ attrs += f' stroke-dasharray="{dash}"'
170
269
  self.ops.append(f'<rect {attrs} fill="{fill}"/>')
171
270
 
172
271
  def line(self, x1, y1, x2, y2, stroke, width=1, dash=None, opacity=None):
@@ -177,7 +276,8 @@ class Svg:
177
276
  attrs += f' opacity="{opacity}"'
178
277
  self.ops.append(f'<line {attrs} stroke="{stroke}" stroke-width="{width}"/>')
179
278
 
180
- def path(self, d, fill='none', stroke=None, width=2, opacity=None, dash=None):
279
+ def path(self, d, fill='none', stroke=None, width=2, opacity=None, dash=None,
280
+ marker_end=None):
181
281
  attrs = f'd="{d}" fill="{fill}"'
182
282
  if stroke:
183
283
  attrs += (f' stroke="{stroke}" stroke-width="{width}"'
@@ -186,6 +286,8 @@ class Svg:
186
286
  attrs += f' opacity="{opacity}"'
187
287
  if dash:
188
288
  attrs += f' stroke-dasharray="{dash}"'
289
+ if marker_end:
290
+ attrs += f' marker-end="url(#{marker_end})"'
189
291
  self.ops.append(f'<path {attrs}/>')
190
292
 
191
293
  def polyline(self, points, stroke, width=2.5, opacity=None, dash=None):
@@ -211,8 +313,10 @@ class Svg:
211
313
  def text(self, x, y, s, size=14, fill=None, weight='normal', anchor='start',
212
314
  baseline='auto', opacity=None):
213
315
  """一段文本。`anchor`: start/middle/end;`baseline`: auto/middle/hanging。"""
214
- attrs = (f'x="{x:.2f}" y="{y:.2f}" font-family="{FONT_STACK}" font-size="{size}"'
215
- f' text-anchor="{anchor}" dominant-baseline="{baseline}"')
316
+ font = self.t.get('body_font') or FONT_STACK
317
+ attrs = (f'x="{x:.2f}" y="{y:.2f}" font-family="{esc(font)}" font-size="{size}"'
318
+ f' text-anchor="{anchor}" dominant-baseline="{baseline}"'
319
+ f' style="font-variant-numeric:tabular-nums"')
216
320
  if weight != 'normal':
217
321
  attrs += f' font-weight="{weight}"'
218
322
  if opacity is not None:
@@ -227,13 +331,21 @@ class Svg:
227
331
  self.text(x, y + i * step, line, size=size, fill=fill, weight=weight, anchor=anchor)
228
332
  return y + len(lines) * step
229
333
 
230
- def save(self, path):
231
- """写出 SVG,返回字节数。目录不存在则创建。"""
334
+ def raw(self, xml):
335
+ """原样追加一段标记(`<defs>`/`<marker>` 这类无法用图元拼出的片段)。"""
336
+ self.ops.append(xml)
337
+
338
+ def document(self):
339
+ """拼出完整 SVG 文档字符串(不落盘)。"""
232
340
  head = (f'<svg xmlns="http://www.w3.org/2000/svg" width="{self.w}" height="{self.h}"'
233
341
  f' viewBox="0 0 {self.w} {self.h}" role="img">')
234
342
  background = (f'<rect x="0" y="0" width="{self.w}" height="{self.h}"'
235
343
  f' fill="{self.t["bg"]}"/>')
236
- doc = '\n'.join([head, background, *self.ops, '</svg>', ''])
344
+ return '\n'.join([head, background, *self.ops, '</svg>', ''])
345
+
346
+ def save(self, path):
347
+ """写出 SVG,返回字节数。目录不存在则创建。"""
348
+ doc = self.document()
237
349
  parent = os.path.dirname(os.path.abspath(path))
238
350
  os.makedirs(parent, exist_ok=True)
239
351
  with open(path, 'w', encoding='utf-8') as handle: