Repository navigation
Expand file tree
/
Copy pathplotkit.py
More file actions
1712 lines (1557 loc) · 80 KB
/
Copy pathplotkit.py
File metadata and controls
1712 lines (1557 loc) · 80 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
plotkit.py - spec-driven plots of lab data (TGA preset built in).
AGENT QUICK GUIDE (read AGENT.md for the full guide)
1. Look at the data first: python plotkit.py inspect FILE
2. Write a JSON spec with ONLY what the user asked for (everything else has defaults).
3. Plot: python plotkit.py plot SPEC.json
(or: python plotkit.py plot --json '{"file": "TGA.xlsx"}')
4. Read the JSON that is printed. If "ok" is false, fix the spec using "hint" and retry.
Engines: matplotlib (default) or ECharts: PLOTKIT_ENGINE=echarts python plotkit.py plot SPEC.json
(or add --engine echarts; ECharts needs Node, see echartkit/README.md)
Do NOT edit this file. Every change the user can ask for is a spec key:
python plotkit.py schema (all keys)
python plotkit.py example (a full example spec)
Smallest useful spec (TGA preset: Temperature on x, Weight % on the left axis,
Deriv. weight on the right axis, residue at 800 °C and DTG peak labelled):
{"file": "TGA.xlsx"}
Reads .xlsx/.xlsm/.xls and text files (.csv/.txt/.tsv/.dat/anything else) with
blank or metadata rows on top, units rows, extra columns, Korean headers,
tab/comma/semicolon/space separators and decimal commas.
Python use: from plotkit import plot, inspect_file; plot({"file": "TGA.xlsx"})
Requires: numpy, matplotlib, scipy, openpyxl (+ xlrd for old .xls files)
"""
import copy
import difflib
import json
import math
import re
import sys
from pathlib import Path
import numpy as np
__version__ = "2.0"
class PlotkitError(Exception):
def __init__(self, message, hint=""):
super().__init__(message)
self.message = message
self.hint = hint
# =================================================================== spec
TGA_PRESET = {
"x": {"label": "Temperature (°C)"},
"y1": {"label": "Weight (%)", "color": "#1f4e9c"},
"y2": {"label": "Deriv. weight (%/°C)", "color": "#c0392b", "flip": "peaks_up"},
"annotate": {
"residue": {"type": "value_at_x", "on": "y1", "x": 800, "method": "nearest",
"text": "Residue {y:.1f}%"},
"peak": {"type": "peak", "on": "y2", "count": 1, "x_min": 150,
"text": "{x:.0f} °C"},
},
}
DEFAULTS = {
"file": None,
"sheets": "all",
"preset": "tga",
"read": {"header_row": None, "data_start_row": None, "sep": None,
"decimal": None, "encoding": None},
"x": {"col": None, "label": None, "min": None, "max": None, "step": None, "log": False,
"label_size": None, "label_color": None, "tick_size": None, "tick_color": None},
"y1": {"col": None, "label": None, "min": None, "max": None, "step": None,
"color": "#1f4e9c", "width": 1.8, "linestyle": "solid", "style": "line",
"flip": "none", "log": False, "legend": None, "show": True,
"label_size": None, "label_color": None, "tick_size": None, "tick_color": None},
"y2": {"col": None, "label": None, "min": None, "max": None, "step": None,
"color": "#c0392b", "width": 1.4, "linestyle": "solid", "style": "line",
"flip": "none", "log": False, "legend": None, "show": True,
"label_size": None, "label_color": None, "tick_size": None, "tick_color": None},
"annotate": {},
"title": {"text": "{sheet}", "size": None, "color": None},
"legend": {"where": "center left", "show": True, "size": None},
"text_color": "black",
"tick_direction": "in",
"code": None,
"echarts": None,
"grid": False,
"size": [6.4, 4.6],
"dpi": 300,
"font": None,
"font_size": 11,
"combine": False,
"output": {"dir": None, "format": "png", "name": None},
}
ANNOT_KEYS = {"type", "on", "x", "y", "method", "text", "color", "size", "count", "kind",
"x_min", "x_max", "min_rel", "where", "marker", "linestyle", "alpha"}
ANNOT_TYPES = {"value_at_x", "peak", "vline", "hline", "text", "band"}
ENGINES = ("matplotlib", "echarts")
SCHEMA_DOC = {
"file": "data file path, or a list of paths (xlsx/xls/csv/txt/...)",
"sheets": '"all" (default), a sheet name, a 1-based sheet number, or a list of those',
"preset": '"tga" (default; TGA labels, residue + DTG peak) or "none" (plain plot, you must give x.col and y1.col)',
"read.header_row": "1-based row of the column names; normally automatic",
"read.data_start_row": "1-based first row of numbers; normally automatic",
"read.sep": 'text files only: "," ";" "\\t" "space"; normally automatic',
"read.decimal": 'text files only: "." or ","; normally automatic',
"read.encoding": 'text files only, e.g. "utf-8", "cp949", "utf-16"; normally automatic',
"x|y1|y2.col": 'column letter like "B" (as in Excel; for text files A = 1st field) or part of the column name like "Temperature"',
"x|y1|y2.label": "axis label text (default: the preset's label, or the column's name when its unit differs, e.g. Weight (mg))",
"x|y1|y2.min / max": "axis range; leave out for automatic",
"x|y1|y2.step": "distance between tick marks, e.g. 200 or 0.2",
"x|y1|y2.log": "true for a log axis",
"x|y1|y2.label_size / label_color": "font size / color of the axis label (y labels default to the line color)",
"x|y1|y2.tick_size / tick_color": "font size / color of the tick numbers (y ticks default to the line color)",
"y1|y2.color": 'line color: name ("red", "빨강"), or hex "#c0392b"',
"y1|y2.width": "line width (default 1.8 / 1.4)",
"y1|y2.linestyle": '"solid" | "dashed" | "dotted" | "dashdot"',
"y1|y2.style": '"line" | "scatter" | "line+marker"',
"y1|y2.flip": '"none" | "flip" (multiply by -1) | "peaks_up" | "peaks_down"',
"y1|y2.legend": "name in the legend (default: the axis label)",
"y2": "false to draw no second axis",
"annotate.<name>": 'dict of labels; set one to false to remove a preset label (e.g. "peak": false), '
'true to ask for a preset label as it is (e.g. "residue": true). A value_at_x label with '
'no data at its x shows "no data" only when the spec names it; otherwise it is left out',
"annotate.<name>.type": '"value_at_x" | "peak" | "vline" | "hline" | "text" | "band" (guessed from the name: residue*/value* -> value_at_x, peak*/max* -> peak, band*/shade* -> band)',
"annotate.<name>.on": '"y1" or "y2"',
"annotate.<name>.x": "value_at_x / vline: the x position, e.g. 800",
"annotate.<name>.y": "hline: the y position",
"annotate.<name>.method": 'value_at_x: "nearest" (closest measured point, default) or "interp"',
"annotate.<name>.count": "peak: how many peaks to label (default 1)",
"annotate.<name>.kind": 'peak: "max" (default) or "min"',
"annotate.<name>.x_min / x_max": "peak: only search in this x range; band: the shaded x range (both needed)",
"annotate.<name>.alpha": "band: opacity of the shading, 0..1 (default 0.15)",
"annotate.<name>.min_rel": "peak: extra peaks must be at least this fraction of the main one (default 0.1)",
"annotate.<name>.text": 'label template: {x} {y} or {} (e.g. "Residue {}%", "{x:.0f} °C", "Residue {y:.2f}%"); '
"the preset residue label uses the column's unit when it isn't %, e.g. \"Residue 0.82 mg\"",
"annotate.<name>.where": 'text: "upper left" | "upper right" | "lower left" | "lower right"',
"annotate.<name>.color": "label color (default: the line color)",
"annotate.<name>.size": "label font size",
"title": 'plot title text, or {"text": ..., "size": ..., "color": ...}; "{sheet}" (default) and "{file}" are replaced; "" for none',
"legend": 'legend position "center left" (default), "best", "upper right", "lower left", ..., "none"; or {"where": ..., "show": true/false, "size": ...}',
"text_color": "color of all text that has no color of its own (default black); when given, also the y-axis "
"labels, tick labels and residue/peak labels, which otherwise follow the line colors",
"tick_direction": '"in" (default), "out" or "inout"',
"code": "matplotlib engine only: extra Python run after drawing, before saving. Names: fig, ax1 (left y), ax2 (right y or None), x, y1, y2 (arrays), sheet, plt, np. Use only for things no key covers.",
"echarts": "ECharts engine only: a partial ECharts option merged over the drawn plot, checked against an allowlist "
"(title, legend, grid, xAxis, yAxis, series[i] styles and markArea/markLine/markPoint, graphic text/line/rect). "
"series 0 = y1, 1 = y2 (combine: one y1 series per sheet, then one y2 series per sheet). Use only for things no key covers.",
"grid": "true / false",
"size": "[width, height] in inches (default [6.4, 4.6])",
"dpi": "resolution of png/jpg (default 300)",
"font": 'font family; Korean fonts are picked automatically when text is Korean',
"font_size": "base font size (default 11)",
"combine": "true = all sheets in ONE figure (one color per sheet)",
"output.dir": "output folder (default: <data file name>_plots next to the data)",
"output.format": '"png" (default) | "pdf" | "svg" | "jpg" | "tif", or a list like ["png","pdf"]',
"output.name": 'file name template; default "{sheet}" ("{file}_{sheet}" for several files)',
}
EXAMPLE_SPEC = {
"file": "TGA.xlsx",
"sheets": ["1006R1-V normal"],
"preset": "tga",
"x": {"col": "B", "min": 0, "step": 200},
"y1": {"col": "C", "step": 20},
"y2": {"col": "D", "step": 0.2},
"annotate": {
"residue": {"x": 800, "method": "nearest", "text": "Residue {}%"},
"peak": {"count": 1},
},
"output": {"format": "png"},
}
TOP_ALIASES = {"sheet": "sheets", "sheet_name": "sheets", "sheet_names": "sheets",
"files": "file", "path": "file", "input": "file",
"y": "y1", "y_left": "y1", "left": "y1", "yleft": "y1", "y_1": "y1",
"y_right": "y2", "right": "y2", "yright": "y2", "y_2": "y2",
"annotations": "annotate", "annotation": "annotate", "labels": "annotate",
"fontsize": "font_size", "figsize": "size", "figure_size": "size",
"overlay": "combine", "format": "output.format", "outdir": "output.dir",
"output_dir": "output.dir", "out": "output.dir", "font_color": "text_color",
"fontcolor": "text_color", "ticks": "tick_direction", "extra_code": "code",
"python": "code", "tweak": "code", "echarts_patch": "echarts", "echarts_option": "echarts",
"x_axis": "x", "xaxis": "x", "x축": "x", "y_axis": "y1", "y1_axis": "y1", "yaxis": "y1",
"y1axis": "y1", "y축": "y1", "y1축": "y1", "y2_axis": "y2", "y2axis": "y2", "y2축": "y2",
"secondary_y": "y2", "제목": "title", "그림 제목": "title", "범례": "legend",
"격자": "grid", "gridlines": "grid", "plot_title": "title", "figure_title": "title",
"주석": "annotate", "dpi_value": "dpi", "resolution": "dpi", "해상도": "dpi",
"text_colour": "text_color", "글자 색깔": "text_color", "글자 크기": "font_size",
"tick_dir": "tick_direction", "틱 방향": "tick_direction", "그림 크기": "size",
"파일 형식": "output.format", "시트": "sheets", "file_name": "file", "filename": "file"}
AXIS_ALIASES = {"column": "col", "source": "col", "data": "col", "name": "label",
"title": "label", "tick": "step", "ticks": "step", "tick_step": "step",
"interval": "step", "unit": "step", "major": "step", "spacing": "step",
"tick_spacing": "step", "tick_interval": "step", "tickstep": "step", "major_tick": "step",
"major_ticks": "step", "major_step": "step", "step_size": "step", "tick_gap": "step",
"틱 간격": "step", "간격": "step", "범위 시작": "min", "범위 끝": "max", "라벨": "label",
"선 색깔": "color", "색깔": "color", "색": "color", "선 굵기": "width", "굵기": "width",
"선 종류": "linestyle", "열": "col", "label_text": "label", "axis_label": "label",
"minimum": "min", "maximum": "max", "lower": "min", "upper": "max",
"start": "min", "from": "min", "lo": "min", "low": "min", "ymin": "min", "xmin": "min",
"end": "max", "to": "max", "hi": "max", "high": "max", "ymax": "max", "xmax": "max",
"colour": "color", "line_width": "width", "linewidth": "width", "lw": "width",
"ls": "linestyle", "line_style": "linestyle", "dash": "linestyle",
"legend_label": "legend", "invert": "flip", "sign": "flip", "visible": "show",
"labelsize": "label_size", "label_font_size": "label_size", "fontsize": "label_size",
"font_size": "label_size", "labelcolor": "label_color", "label_colour": "label_color",
"ticksize": "tick_size", "tick_label_size": "tick_size", "tick_font_size": "tick_size",
"tickcolor": "tick_color", "tick_label_color": "tick_color", "tick_colour": "tick_color"}
ANNOT_ALIASES = {"opacity": "alpha", "x_from": "x_min", "x_to": "x_max", "x_start": "x_min", "x_end": "x_max",
"label": "text", "format": "text", "template": "text", "series": "on",
"axis": "on", "at": "x", "temperature": "x", "at_x": "x", "n": "count",
"mode": "kind", "min_x": "x_min", "max_x": "x_max", "position": "where",
"colour": "color", "fontsize": "size", "font_size": "size"}
KOREAN_COLORS = {"빨강": "red", "빨간색": "red", "빨간": "red", "적색": "red",
"파랑": "blue", "파란색": "blue", "파란": "blue", "청색": "blue",
"남색": "navy", "초록": "green", "초록색": "green", "녹색": "green",
"검정": "black", "검정색": "black", "검은색": "black", "흑색": "black",
"회색": "gray", "주황": "orange", "주황색": "orange", "노랑": "gold",
"노란색": "gold", "보라": "purple", "보라색": "purple", "분홍": "hotpink",
"분홍색": "hotpink", "갈색": "saddlebrown", "하늘색": "deepskyblue"}
LINESTYLES = {"solid": "-", "실선": "-", "-": "-", "dashed": "--", "파선": "--", "--": "--",
"dotted": ":", "점선": ":", ":": ":", "dashdot": "-.", "일점쇄선": "-.", "-.": "-."}
LEGEND_PLACES = ["best", "upper right", "upper left", "lower left", "lower right", "right",
"center left", "center right", "lower center", "upper center", "center", "none"]
KOREAN_PLACES = {"오른쪽 위": "upper right", "우상단": "upper right", "왼쪽 위": "upper left",
"좌상단": "upper left", "왼쪽 아래": "lower left", "좌하단": "lower left",
"오른쪽 아래": "lower right", "우하단": "lower right", "가운데": "center",
"왼쪽 가운데": "center left", "오른쪽 가운데": "center right",
"위 가운데": "upper center", "아래 가운데": "lower center", "자동": "best",
"없음": "none", "숨김": "none"}
COMBINE_COLORS = ["#1f4e9c", "#c0392b", "#2e8b57", "#d4881c", "#7b3fa0", "#17a2b8",
"#8c564b", "#e377c2", "#555555", "#9aa31b"]
def _suggest(key, allowed):
m = difflib.get_close_matches(key, list(allowed), n=1, cutoff=0.5)
return f' Did you mean "{m[0]}"?' if m else ""
def _deep_merge(base, over):
out = copy.deepcopy(base)
for k, v in over.items():
if isinstance(v, dict) and isinstance(out.get(k), dict):
out[k] = _deep_merge(out[k], v)
else:
out[k] = copy.deepcopy(v)
return out
def _num(v, where):
if v is None or isinstance(v, bool):
return v
if isinstance(v, (int, float)):
return float(v)
try:
return float(str(v).strip().replace(",", "."))
except ValueError:
raise PlotkitError(f"{where} must be a number, got {v!r}", "write a plain number, e.g. 200")
def _normalize_axis(name, d):
if d is False or d is None:
if name == "y2":
return {"show": False}
raise PlotkitError(f"{name} cannot be switched off", "only y2 can be false")
if isinstance(d, str): # "x": "B" -> {"col": "B"}
d = {"col": d}
if not isinstance(d, dict):
raise PlotkitError(f'"{name}" must be an object like {{"col": "B"}}, got {d!r}')
allowed = set(DEFAULTS[name])
out = {}
for k, v in d.items():
k2 = AXIS_ALIASES.get(k.lower(), k.lower())
if k2 in ("range", "lim", "limits", "ylim", "xlim"):
if not (isinstance(v, (list, tuple)) and len(v) == 2):
raise PlotkitError(f"{name}.{k} must be [min, max]")
out["min"], out["max"] = v
continue
if k2 not in allowed:
raise PlotkitError(f'unknown key "{name}.{k}".{_suggest(k2, allowed)}',
f"allowed keys for {name}: {', '.join(sorted(allowed))}")
out[k2] = v
for k in ("min", "max", "step", "width", "label_size", "tick_size"):
if k in out:
out[k] = _num(out[k], f"{name}.{k}")
for k in ("label_color", "tick_color"):
if out.get(k) is not None:
out[k] = _color(out[k], f"{name}.{k}")
if out.get("step") is not None and out["step"] <= 0:
raise PlotkitError(f"{name}.step must be > 0")
if "color" in out and out["color"] is not None:
out["color"] = _color(out["color"], f"{name}.color")
if "linestyle" in out:
ls = str(out["linestyle"]).lower()
if ls not in LINESTYLES:
raise PlotkitError(f"{name}.linestyle {out['linestyle']!r} unknown",
"use solid, dashed, dotted or dashdot")
out["linestyle"] = ls
if "style" in out and out["style"] not in ("line", "scatter", "line+marker"):
raise PlotkitError(f"{name}.style {out['style']!r} unknown", "use line, scatter or line+marker")
if "flip" in out:
f = out["flip"]
f = {True: "flip", False: "none", None: "none", "up": "peaks_up",
"down": "peaks_down"}.get(f, f)
if f not in ("none", "flip", "peaks_up", "peaks_down"):
raise PlotkitError(f"{name}.flip {out['flip']!r} unknown",
"use none, flip, peaks_up or peaks_down")
out["flip"] = f
return out
def _color(c, where):
from matplotlib.colors import is_color_like
c2 = KOREAN_COLORS.get(str(c).strip(), str(c).strip())
if re.fullmatch(r"[0-9a-fA-F]{6}", c2):
c2 = "#" + c2
if not is_color_like(c2):
raise PlotkitError(f"{where}: {c!r} is not a color",
'use a name like "red", "navy", "black" or a hex code like "#c0392b"')
return c2
def _guess_annot_type(name):
n = name.lower()
if n.startswith(("residue", "value", "res", "잔류", "잔량")):
return "value_at_x"
if n.startswith(("peak", "max", "dtg", "피크", "최대")):
return "peak"
if n.startswith(("band", "span", "shade", "region", "구간", "음영")):
return "band"
for t in ("vline", "hline", "text"):
if n.startswith(t):
return t
return None
def _normalize_annotations(a):
if a is None or a is False:
return {}, True
replace = False
if isinstance(a, list): # a list replaces the preset labels completely
replace = True
a = {f"{(i.get('type') or 'label') if isinstance(i, dict) else 'label'}_{n}": i
for n, i in enumerate(a, 1)}
if not isinstance(a, dict):
raise PlotkitError('"annotate" must be an object like {"residue": {"x": 800}}')
out = {}
for name, d in a.items():
if d is False or d is None:
out[name] = None
continue
if d is True: # "residue": true = asked for, with the preset settings
out[name] = {}
continue
if not isinstance(d, dict):
raise PlotkitError(f'annotate.{name} must be an object, true or false, got {d!r}')
dd = {}
for k, v in d.items():
k2 = ANNOT_ALIASES.get(k.lower(), k.lower())
if k2 not in ANNOT_KEYS:
raise PlotkitError(f'unknown key "annotate.{name}.{k}".{_suggest(k2, ANNOT_KEYS)}',
f"allowed: {', '.join(sorted(ANNOT_KEYS))}")
dd[k2] = v
for k in ("x", "y", "x_min", "x_max", "min_rel", "size", "alpha"):
if k in dd:
dd[k] = _num(dd[k], f"annotate.{name}.{k}")
if "count" in dd:
dd["count"] = int(_num(dd["count"], f"annotate.{name}.count"))
if "on" in dd:
on = str(dd["on"]).lower()
on = {"left": "y1", "right": "y2", "y": "y1", "1": "y1", "2": "y2"}.get(on, on)
if on not in ("y1", "y2"):
raise PlotkitError(f"annotate.{name}.on must be y1 or y2, got {dd['on']!r}")
dd["on"] = on
if "color" in dd and dd["color"] is not None:
dd["color"] = _color(dd["color"], f"annotate.{name}.color")
if "type" in dd and dd["type"] not in ANNOT_TYPES:
raise PlotkitError(f"annotate.{name}.type {dd['type']!r} unknown.{_suggest(str(dd['type']), ANNOT_TYPES)}",
f"types: {', '.join(sorted(ANNOT_TYPES))}")
out[name] = dd
return out, replace
def normalize_spec(user):
"""Validate a user spec and merge it over defaults (and the preset)."""
if isinstance(user, str):
user = {"file": user}
if not isinstance(user, dict):
raise PlotkitError("the spec must be a JSON object")
# map aliases / dotted keys at the top level
u = {}
for k, v in user.items():
k2 = TOP_ALIASES.get(k.lower(), k.lower())
if "." in k2:
a, b = k2.split(".", 1)
u.setdefault(a, {})[b] = v
elif k2 in u and isinstance(u[k2], dict) and isinstance(v, dict):
u[k2].update(v)
else:
u[k2] = v
unknown = [k for k in u if k not in DEFAULTS]
if unknown:
k = unknown[0]
k_ax = AXIS_ALIASES.get(k, k)
if k_ax in DEFAULTS["y1"] or k_ax in ("range", "lim"):
raise PlotkitError(f'"{k}" belongs to an axis, not the top level',
f'put it inside "x", "y1" or "y2", e.g. "x": {{"{k_ax}": ...}}')
k_an = ANNOT_ALIASES.get(k, k)
if k_an in ANNOT_KEYS or re.match(r"(residue|peak|vline|hline|note)", k):
raise PlotkitError(f'"{k}" belongs inside "annotate"',
'e.g. "annotate": {"residue": {"x": 700}} or "annotate": {"vline1": {"type": "vline", "x": 450}}')
raise PlotkitError(f'unknown key "{k}".{_suggest(k, DEFAULTS)}',
"top-level keys: " + ", ".join(DEFAULTS))
if not u.get("file"):
raise PlotkitError('"file" is missing', 'add "file": "your_data.xlsx"')
preset = str(u.get("preset", DEFAULTS["preset"]) or "none").lower()
if preset not in ("tga", "none"):
raise PlotkitError(f'preset {preset!r} unknown', 'use "tga" or "none"')
spec = copy.deepcopy(DEFAULTS)
if preset == "tga":
p = copy.deepcopy(TGA_PRESET)
for ax in ("x", "y1", "y2"):
spec[ax].update(p[ax], _preset_label=True)
spec["annotate"] = p["annotate"]
for d in spec["annotate"].values():
d["_preset_text"] = True
spec["preset"] = preset
for ax in ("x", "y1", "y2"):
if ax in u:
n = _normalize_axis(ax, u[ax])
spec[ax].update(n)
if "label" in n:
spec[ax].pop("_preset_label", None)
if "annotate" in u:
ann, replace = _normalize_annotations(u["annotate"])
base = {} if replace else spec["annotate"]
for name, d in ann.items():
if d is None:
base.pop(name, None)
else: # named in the user's spec: say "no data" instead of hiding it
base[name] = {**base.get(name, {}), **d, "_requested": True}
if "text" in d:
base[name].pop("_preset_text", None)
spec["annotate"] = base
for name, d in spec["annotate"].items():
d.setdefault("type", _guess_annot_type(name))
if d["type"] is None:
raise PlotkitError(f'annotate.{name} needs a "type"',
f"types: {', '.join(sorted(ANNOT_TYPES))}")
need = {"value_at_x": "x", "vline": "x", "hline": "y"}.get(d["type"])
if need and d.get(need) is None:
raise PlotkitError(f'annotate.{name} needs "{need}"',
f'e.g. "annotate": {{"{name}": {{"{need}": 800}}}}')
if d["type"] == "band":
if d.get("x_min") is None or d.get("x_max") is None:
raise PlotkitError(f'annotate.{name} (band) needs "x_min" and "x_max"',
f'e.g. "annotate": {{"{name}": {{"type": "band", "x_min": 300, "x_max": 450}}}}')
if d["x_max"] <= d["x_min"]:
raise PlotkitError(f"annotate.{name}: x_max must be larger than x_min")
if d.get("alpha") is not None and not 0 <= d["alpha"] <= 1:
raise PlotkitError(f"annotate.{name}.alpha must be between 0 and 1", "e.g. 0.15")
for k in ("read", "output"):
if k in u:
if not isinstance(u[k], dict):
raise PlotkitError(f'"{k}" must be an object')
for kk in u[k]:
if kk not in DEFAULTS[k]:
raise PlotkitError(f'unknown key "{k}.{kk}".{_suggest(kk, DEFAULTS[k])}',
f"allowed: {', '.join(DEFAULTS[k])}")
spec[k].update(u[k])
for k in ("file", "sheets", "grid", "size", "dpi", "font", "font_size", "combine",
"text_color", "tick_direction", "code"):
if k in u:
spec[k] = u[k]
if u.get("echarts") not in (None, {}, False):
from plotkit_echarts import validate_patch # the allowlist lives with the engine
spec["echarts"] = validate_patch(u["echarts"])
if "title" in u:
t = u["title"]
if t is None or t is False:
t = {"text": ""}
if isinstance(t, str):
t = {"text": t}
if not isinstance(t, dict):
raise PlotkitError('"title" must be text or {"text": ..., "size": ..., "color": ...}')
t = {{"label": "text", "fontsize": "size", "font_size": "size", "colour": "color"}.get(k, k): v
for k, v in t.items()}
for k in t:
if k not in ("text", "size", "color"):
raise PlotkitError(f'unknown key "title.{k}"', "title keys: text, size, color")
spec["title"].update(t)
if "legend" in u:
lg = u["legend"]
if lg is False or lg is None or lg == "none":
lg = {"show": False}
elif lg is True:
lg = {"show": True}
elif isinstance(lg, str):
lg = {"where": lg}
if not isinstance(lg, dict):
raise PlotkitError('"legend" must be a position text, false, or {"where": ..., "show": ..., "size": ...}')
lg = {{"position": "where", "loc": "where", "location": "where", "fontsize": "size",
"font_size": "size", "visible": "show"}.get(k, k): v for k, v in lg.items()}
for k in lg:
if k not in ("where", "show", "size"):
raise PlotkitError(f'unknown key "legend.{k}"', "legend keys: where, show, size")
spec["legend"].update(lg)
spec["legend"]["where"] = KOREAN_PLACES.get(spec["legend"]["where"], spec["legend"]["where"])
if spec["legend"]["where"] == "none":
spec["legend"]["show"] = False
if spec["legend"]["where"] not in LEGEND_PLACES:
raise PlotkitError(f'legend position {spec["legend"]["where"]!r} unknown',
"use one of: " + ", ".join(LEGEND_PLACES))
if spec["title"].get("color"):
spec["title"]["color"] = _color(spec["title"]["color"], "title.color")
spec["text_color"] = _color(spec["text_color"] or "black", "text_color")
spec["_text_color_set"] = bool(u.get("text_color")) # then it also beats the line colours
td = {"안쪽": "in", "바깥쪽": "out", "밖": "out", "안": "in", "양쪽": "inout"}.get(
str(spec["tick_direction"]), str(spec["tick_direction"]).lower())
if td not in ("in", "out", "inout"):
raise PlotkitError(f"tick_direction {spec['tick_direction']!r} unknown", "use in, out or inout")
spec["tick_direction"] = td
if isinstance(spec["code"], list):
spec["code"] = "\n".join(spec["code"])
if isinstance(spec["file"], str):
spec["file"] = [spec["file"]]
fmts = spec["output"]["format"]
fmts = [fmts] if isinstance(fmts, str) else list(fmts)
fmts = [f.lower().lstrip(".").replace("jpeg", "jpg").replace("tiff", "tif") for f in fmts]
for f in fmts:
if f not in ("png", "pdf", "svg", "jpg", "tif"):
raise PlotkitError(f"output.format {f!r} not supported", "use png, pdf, svg, jpg or tif")
spec["output"]["format"] = fmts
return spec
# =================================================================== reading
_NUM_RE = re.compile(r"^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$")
def _to_num(v, decimal="."):
if v is None or isinstance(v, bool):
return None
if isinstance(v, (int, float)):
return float(v) if math.isfinite(v) else None
if not isinstance(v, str):
return None # dates, times, ...
s = v.strip().replace("−", "-").replace(" ", "")
if not s:
return None
if decimal == ",":
s = s.replace(".", "").replace(",", ".")
if not _NUM_RE.match(s):
return None
return float(s)
def col_letter(i):
s = ""
i += 1
while i:
i, r = divmod(i - 1, 26)
s = chr(65 + r) + s
return s
def col_index(letter):
n = 0
for ch in letter.upper():
n = n * 26 + (ord(ch) - 64)
return n - 1
def _decode(raw, encoding=None):
if encoding:
return raw.decode(encoding)
if raw[:2] in (b"\xff\xfe", b"\xfe\xff"):
return raw.decode("utf-16")
if raw[:3] == b"\xef\xbb\xbf":
return raw[3:].decode("utf-8")
head = raw[:2000]
if head.count(b"\x00") > len(head) // 4: # utf-16 without BOM
return raw.decode("utf-16-le" if head[1:2] == b"\x00" else "utf-16-be")
for enc in ("utf-8", "cp949", "latin-1"):
try:
return raw.decode(enc)
except UnicodeDecodeError:
pass
return raw.decode("latin-1", errors="replace")
def _read_text(path, ro):
text = _decode(Path(path).read_bytes(), ro.get("encoding"))
lines = text.splitlines()
nonblank = [ln for ln in lines if ln.strip()]
tail = nonblank[-60:] if len(nonblank) > 60 else nonblank
sep = ro.get("sep")
sep = {"tab": "\t", "\\t": "\t", "space": "space", "whitespace": "space", " ": "space"}.get(sep, sep)
if sep is None:
for cand in ("\t", ";", ",", "|"):
counts = [ln.count(cand) for ln in tail]
if counts and min(counts) >= 1:
mode = max(set(counts), key=counts.count)
if counts.count(mode) >= 0.8 * len(counts):
sep = cand
break
sep = sep or "space"
decimal = ro.get("decimal")
if decimal is None:
sample = " ".join(tail)
decimal = "," if (sep != "," and re.search(r"(?<![\d.])-?\d+,\d+(?![\d.])", sample)
and not re.search(r"\d\.\d", sample)) else "."
rows = []
for ln in lines:
if not ln.strip():
rows.append([])
continue
if sep == "space":
parts = ln.strip().split()
nums = sum(_to_num(p, decimal) is not None for p in parts)
if nums < len(parts): # header line: split on 2+ spaces
parts = re.split(r"\s{2,}|\t", ln.strip())
else:
parts = [p.strip().strip('"') for p in ln.split(sep)]
rows.append(parts)
return {Path(path).stem: rows}, decimal
def _read_xlsx(path):
import openpyxl
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
out = {}
for ws in wb.worksheets:
out[ws.title] = [list(r) for r in ws.iter_rows(values_only=True)]
wb.close()
return out
def _read_xls(path):
try:
import xlrd
except ImportError:
raise PlotkitError("reading old .xls files needs the xlrd package",
"run: pip install xlrd (or save the file as .xlsx)")
book = xlrd.open_workbook(path)
out = {}
for sh in book.sheets():
out[sh.name] = [[None if c == "" else c for c in sh.row_values(i)]
for i in range(sh.nrows)]
return out
def read_tables(path, ro=None):
"""Return {sheet_name: raw rows}, decimal mark."""
ro = ro or {}
p = Path(path)
if not p.exists():
near = [f.name for f in p.parent.glob("*") if f.is_file()][:20] if p.parent.exists() else []
raise PlotkitError(f"file not found: {path}",
f"files in {p.parent}: {', '.join(near)}" if near else "check the path")
ext = p.suffix.lower()
if ext in (".xlsx", ".xlsm"):
return _read_xlsx(p), "."
if ext == ".xls":
try:
return _read_xls(p), "."
except PlotkitError:
raise
except Exception: # some ".xls" are really text/html
return _read_text(p, ro)
return _read_text(p, ro)
def analyze_table(rows, decimal=".", header_row=None, data_start_row=None):
"""Find header and numeric block. Returns dict with columns + data."""
width = max((len(r) for r in rows), default=0)
rows = [list(r) + [None] * (width - len(r)) for r in rows]
nums = [[_to_num(c, decimal) for c in r] for r in rows]
ncount = [sum(n is not None for n in r) for r in nums]
if not rows or max(ncount, default=0) == 0:
raise PlotkitError("no numbers found in this sheet")
if data_start_row:
ds = int(data_start_row) - 1
elif header_row:
ds = int(header_row)
while ds < len(rows) and ncount[ds] < 2:
ds += 1
else:
wide = [c for c in ncount if c >= 2] or [c for c in ncount if c >= 1]
w = max(set(wide), key=wide.count)
ds = None
for i, c in enumerate(ncount):
if c >= w:
nxt = [ncount[j] for j in range(i + 1, min(len(rows), i + 40)) if ncount[j] or any(rows[j])][:5]
if all(n >= max(1, w - 1) for n in nxt):
ds = i
break
if ds is None:
ds = next(i for i, c in enumerate(ncount) if c == w)
if ds >= len(rows):
raise PlotkitError("data start row is after the end of the sheet")
body = nums[ds:]
body_rows = [r for r in body if any(v is not None for v in r)]
data_cols = [j for j in range(width)
if sum(r[j] is not None for r in body_rows) >= 0.5 * max(1, len(body_rows))]
if not data_cols:
raise PlotkitError("no numeric columns found")
def is_textual(r):
cells = [rows[r][j] for j in data_cols]
txt = sum(1 for c in cells if c is not None and str(c).strip() != "" and _to_num(c, decimal) is None)
return txt >= max(1, math.ceil(len(data_cols) / 2))
hdr_rows = []
if header_row:
hdr_rows = [int(header_row) - 1]
else:
i = ds - 1
while i >= 0 and len(hdr_rows) < 2:
if not any(c is not None and str(c).strip() for c in rows[i]):
if hdr_rows:
break
i -= 1
continue
if is_textual(i):
hdr_rows.insert(0, i)
i -= 1
else:
break
if len(hdr_rows) == 2 and not _looks_like_units(rows[hdr_rows[1]], data_cols):
hdr_rows = hdr_rows[1:] # upper row is a title, not names
columns = []
for j in data_cols:
parts = []
for r in hdr_rows:
c = rows[r][j]
if c is not None and str(c).strip():
parts.append(str(c).strip())
name = " ".join(parts)
vals = np.array([r[j] if r[j] is not None else np.nan for r in body], dtype=float)
columns.append({"letter": col_letter(j), "index": j, "name": name, "values": vals})
return {"columns": columns, "header_rows": [r + 1 for r in hdr_rows],
"data_start_row": ds + 1, "n_rows": len(body_rows)}
def _looks_like_units(row, cols):
cells = [str(row[j]).strip() for j in cols if row[j] is not None and str(row[j]).strip()]
if not cells:
return False
unit = re.compile(r"^[\(\[]?\s*(%|°c|℃|c|k|min|s|sec|h|mg|g|µg|ug|mw|w/g|mw/mg|%/°c|%/c|%/min|mg/min|°c/min|%/℃|deg\.?c|1/°c)\s*[\)\]]?$", re.I)
return sum(bool(unit.match(c)) for c in cells) >= 0.5 * len(cells)
# ---------------------------------------------------------- column matching
def _norm(s):
return re.sub(r"[\s._\-:·,]+", "", str(s).lower())
def _base(s):
return _norm(re.sub(r"[\(\[\{].*?[\)\]\}]", "", str(s)))
def find_column(table, query, where):
cols = table["columns"]
q = str(query).strip()
q = re.sub(r"^(col(umn)?\s*)|(\s*(열|행|column|col|컬럼|칸))$", "", q, flags=re.I).strip()
if re.fullmatch(r"[A-Za-z]{1,2}", q):
idx = col_index(q)
max_idx = max(c["index"] for c in cols)
if idx <= max_idx:
for c in cols:
if c["index"] == idx:
return c
raise PlotkitError(f"{where}: column {q.upper()} has no numbers",
"columns with numbers: " + _col_list(cols))
qn, qb = _norm(q), _base(q)
if not qn:
raise PlotkitError(f"{where}: empty column name")
scored = []
for c in cols:
n, b = _norm(c["name"]), _base(c["name"])
if not n:
continue
s = 0
if b == qb or n == qn:
s = 3
elif n.startswith(qn) or (qb and b.startswith(qb)):
s = 2
elif qn in n or (qb and qb in n):
s = 1
if s:
scored.append((s, c))
if not scored:
raise PlotkitError(f'{where}: no column matches "{query}"',
"use a letter or part of one of these names: " + _col_list(cols))
top = max(s for s, _ in scored)
best = [c for s, c in scored if s == top]
if len(best) > 1:
raise PlotkitError(f'{where}: "{query}" matches several columns: ' + _col_list(best),
"use the column letter instead")
return best[0]
def _col_list(cols):
return ", ".join(f'{c["letter"]} "{c["name"] or "(no name)"}"' for c in cols)
ROLE_PATTERNS = [
("y2", [r"deriv", r"dtg", r"\bd\.?\s*w\b", r"dw/?dt", r"미분", r"%\s*/\s*(°|℃|c\b|min|deg)", r"/\s*(°c|℃)"]),
("time", [r"time", r"시간", r"^\s*t\s*\(\s*(min|s)\s*\)", r"\(\s*(min|s|sec)\s*\)\s*$"]),
("x", [r"temp", r"온도", r"^\s*t\s*(\(|$)", r"(°c|℃)"]),
("y1", [r"weight", r"\bwt", r"mass", r"무게", r"중량", r"질량", r"^\s*tg\b", r"\(\s*%\s*\)", r"^\s*%\s*$"]),
]
def guess_tga_columns(table):
"""Guess x (temperature), y1 (weight), y2 (DTG) by names, then by values."""
cols = table["columns"]
roles = {"x": [], "y1": [], "y2": [], "time": []}
for c in cols:
name = c["name"].lower()
if not name:
continue
for role, pats in ROLE_PATTERNS:
if any(re.search(p, name) for p in pats):
roles[role].append(c)
break
pick = {}
if roles["x"]:
pick["x"] = next((c for c in roles["x"] if "sample" in c["name"].lower()), roles["x"][0])
if roles["y1"]:
pick["y1"] = next((c for c in roles["y1"] if "%" in c["name"]), roles["y1"][0])
if roles["y2"]:
pick["y2"] = next((c for c in roles["y2"] if re.search(r"°c|℃|/c\b", c["name"].lower())),
roles["y2"][0])
how = "by name"
if len(pick) < 3: # fill gaps from the values
how = "by name and values" if pick else "by values"
used = {id(c) for c in pick.values()}
free = [c for c in cols if id(c) not in used]
if "x" not in pick:
cand = []
for c in free:
v = c["values"][np.isfinite(c["values"])]
if len(v) > 10:
inc = np.mean(np.diff(v) > 0)
if inc > 0.7 and 150 <= v.max() <= 2000 and v.min() < 200:
cand.append((inc, c))
if cand:
pick["x"] = max(cand, key=lambda t: t[0])[1]
free = [c for c in free if c is not pick.get("x")]
if "y1" not in pick:
cand = []
for c in free:
v = c["values"][np.isfinite(c["values"])]
if len(v) > 10 and 50 <= v[:5].mean() <= 110 and v[-5:].mean() < v[:5].mean():
cand.append(c)
if cand:
pick["y1"] = cand[0]
free = [c for c in free if c is not pick.get("y1")]
if "y2" not in pick and "x" in pick and "y1" in pick:
best, bestr = None, 0.6
T, W = pick["x"]["values"], pick["y1"]["values"]
ok = np.isfinite(T) & np.isfinite(W)
if ok.sum() > 10:
with np.errstate(all="ignore"):
g = np.gradient(W[ok], T[ok])
for c in free:
v = c["values"][ok]
m = np.isfinite(v) & np.isfinite(g)
if m.sum() > 10 and np.std(v[m]) > 0:
r = abs(np.corrcoef(v[m], g[m])[0, 1])
if r > bestr:
best, bestr = c, r
if best is not None:
pick["y2"] = best
return pick, how
# =================================================================== loading
def load_sheets(spec_or_file, ro=None):
"""Yield (file, sheet_name, table) for every selected sheet."""
files = spec_or_file["file"] if isinstance(spec_or_file, dict) else [spec_or_file]
ro = (spec_or_file.get("read") if isinstance(spec_or_file, dict) else ro) or {}
sel = spec_or_file.get("sheets", "all") if isinstance(spec_or_file, dict) else "all"
out = []
for f in files:
tables, decimal = read_tables(f, ro)
names = list(tables)
chosen = _select_sheets(names, sel, f)
for n in chosen:
try:
t = analyze_table(tables[n], decimal, ro.get("header_row"), ro.get("data_start_row"))
except PlotkitError as e:
if sel in ("all", None) and len(chosen) > 1:
out.append((f, n, PlotkitError(e.message, e.hint)))
continue
raise PlotkitError(f'{Path(f).name} / sheet "{n}": {e.message}', e.hint)
out.append((f, n, t))
return out
def _select_sheets(names, sel, f):
if sel in ("all", None, "", "*"):
return names
sel = sel if isinstance(sel, list) else [sel]
chosen = []
for s in sel:
if isinstance(s, str) and s.strip().isdigit() and s not in names:
s = int(s)
if isinstance(s, (int, float)) and not isinstance(s, bool):
i = int(s)
if not 1 <= i <= len(names):
raise PlotkitError(f"sheet number {i} does not exist in {Path(f).name}",
f"it has {len(names)} sheet(s): {names}")
chosen.append(names[i - 1])
continue
hit = [n for n in names if n == s] or \
[n for n in names if _norm(n) == _norm(s)] or \
[n for n in names if _norm(s) in _norm(n)]
if len(hit) != 1:
m = difflib.get_close_matches(str(s), names, n=3, cutoff=0.3)
raise PlotkitError(
f'sheet "{s}" {"is ambiguous" if hit else "not found"} in {Path(f).name}',
f"sheet names: {names}" + (f"; closest: {m}" if m else ""))
chosen.append(hit[0])
return chosen
# =================================================================== analysis
def _flip(v, mode):
if mode == "flip":
return -v
if mode in ("peaks_up", "peaks_down"):
f = v[np.isfinite(v)]
if not len(f):
return v
up = abs(f.max()) >= abs(f.min())
v = v if up else -v
return v if mode == "peaks_up" else -v
return v
def value_at_x(X, Y, x0, method):
ok = np.isfinite(X) & np.isfinite(Y)
X, Y = X[ok], Y[ok]
if not len(X) or x0 < X.min() - 1e-9 or x0 > X.max() + 1e-9:
return None, None
if method == "interp":
keep = np.r_[True, np.diff(np.maximum.accumulate(X)) > 0]
return float(x0), float(np.interp(x0, X[keep], Y[keep]))
i = int(np.argmin(np.abs(X - x0)))
return float(X[i]), float(Y[i])
def find_peaks_xy(X, Y, count=1, kind="max", x_min=None, x_max=None, min_rel=0.1):
from scipy.signal import find_peaks, savgol_filter
ok = np.isfinite(X) & np.isfinite(Y)
X, Y = X[ok], Y[ok]
y = Y if kind == "max" else -Y
n = len(y)
ys = y.copy()
win = max(5, (n // 100) | 1)
if win < n:
ys = savgol_filter(y, win, 2)
valid = np.ones(n, bool)
if x_min is not None:
valid &= X >= x_min
if x_max is not None:
valid &= X <= x_max
if not valid.any():
return []
base = np.nanmedian(ys[valid])
top = ys[valid].max()
span = top - base
if span <= 0:
return []
idx, _ = find_peaks(ys, height=base + min_rel * span, prominence=0.5 * min_rel * span)
idx = [i for i in idx if valid[i]]
if not idx:
idx = [int(np.argmax(np.where(valid, ys, -np.inf)))]
idx = sorted(idx, key=lambda i: ys[i], reverse=True)[:max(1, count)]
return sorted([(float(X[i]), float(Y[i])) for i in idx])
def _fmt(text, x, y, primary):
"""Fill a label template. {} gets the main value, {x} and {y} are numbers."""
if text is None:
return ""
t = text
if "{}" in t: