Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_plot.py
More file actions
1895 lines (1697 loc) · 75.1 KB
/
Copy path_plot.py
File metadata and controls
1895 lines (1697 loc) · 75.1 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
"""Build the tree-annotated chart by introspecting and extending a user's Altair chart."""
from __future__ import annotations
import copy
import json
import math
import re
import warnings
from collections.abc import Iterator
from html.parser import HTMLParser
from pathlib import Path
from typing import Any, Literal
import altair as alt
import pandas as pd
from . import _color, _config, _tree
from ._config import PlotConfig, TreeLocation
# Vega-Lite `orient` values that anchor the legend to the chart's left or
# right edge — these are the ones whose natural layout is one entry per row.
# (The Vega-Lite schema's other corner orients, `top-left`/`top-right`/
# `bottom-left`/`bottom-right`, all anchor to the top or bottom edge, so
# they're horizontal-direction by default and don't need the smart default.)
# If a chart's config-level `legend.columns` default is set (a common
# pattern in altair theme/config setups), Vega-Lite will pack entries into
# multiple columns even with a left/right orient. We force columns=1 in
# that case so the user's choice of `orient: "left"` or `"right"` produces
# vertical stacking without requiring them to know about the `columns`
# interaction.
_VERTICAL_ORIENTS = frozenset({"left", "right"})
# Accepted chart input forms for the public `plot` function.
ChartInput = alt.TopLevelMixin | str | Path | dict
# Type for an axis hit found by _find_strain_encoding: (path, encoding_dict, channel).
# `path` is a tuple of dict keys / list indices that locates `encoding_dict`
# inside the spec, ending with ("encoding", channel).
_AxisHit = tuple[tuple, dict, str]
def plot(
tree: str | Path | dict | _tree.TreeNode,
chart: ChartInput,
*,
chart_strain_field: str,
tree_strain_field: str,
branch_length: Literal["div", "num_date"],
tree_size: int = 100,
tree_location: TreeLocation | None = None,
tree_line_width: float = 2.0,
tree_node_size: float = 45,
leader_line_width: float = 1.0,
scale_bar: bool = False,
branch_length_units: str | None = None,
prune_tree_to_chart: bool = False,
prune_chart_to_tree: bool = False,
strict_version: bool = True,
connect_leader_to_label: bool = False,
strain_label_font_size: float = 10.0,
strain_label_font_weight: Literal["normal", "bold"] = "normal",
shift_tree_loc: int = 0,
color_tree_by: str | None = None,
tree_color_scale: dict[str, str] | None = None,
tree_color_legend_format: dict[str, Any] | None = None,
tree_color_legend_show: bool = True,
scale_bar_font_size: float = 10.0,
) -> alt.HConcatChart | alt.VConcatChart:
"""Return an Altair chart with a phylogenetic tree drawn alongside `chart`."""
return _build(
tree,
chart,
PlotConfig(
chart_strain_field=chart_strain_field,
tree_strain_field=tree_strain_field,
branch_length=branch_length,
tree_size=tree_size,
tree_location=tree_location,
tree_line_width=tree_line_width,
tree_node_size=tree_node_size,
leader_line_width=leader_line_width,
scale_bar=scale_bar,
branch_length_units=branch_length_units,
prune_tree_to_chart=prune_tree_to_chart,
prune_chart_to_tree=prune_chart_to_tree,
strict_version=strict_version,
connect_leader_to_label=connect_leader_to_label,
strain_label_font_size=strain_label_font_size,
strain_label_font_weight=strain_label_font_weight,
shift_tree_loc=shift_tree_loc,
color_tree_by=color_tree_by,
tree_color_scale=tree_color_scale,
tree_color_legend_format=tree_color_legend_format,
tree_color_legend_show=tree_color_legend_show,
scale_bar_font_size=scale_bar_font_size,
),
)
# `plot.__doc__` is assembled from canonical descriptions in `_config`:
# `PlotConfig`'s `Annotated[T, "<description>"]` metadata for every styling
# / behavior knob, and `_config.{TREE,CHART}_DESCRIPTION` for the two
# data-input parameters. The CLI's `--help` text reads from the same two
# sources, so per-parameter text lives in exactly one place.
_PLOT_DOC_HEADER = (
"Return an Altair chart with a phylogenetic tree drawn alongside `chart`.\n"
"\n"
"The chart's strain-axis sort is overridden to match the tree's tip order\n"
"(the headline behavior of this package).\n"
"\n"
"Parameters\n"
"----------\n"
+ _config._render_data_param("tree", _config.TREE_DESCRIPTION)
+ "\n"
+ _config._render_data_param("chart", _config.CHART_DESCRIPTION)
+ "\n"
)
_PLOT_DOC_FOOTER = """
Returns
-------
altair.HConcatChart | altair.VConcatChart
For vertical layout (chart strain on `y`), an `HConcatChart` with the
tree on the left and the user's chart on the right. For horizontal
layout (chart strain on `x`), a `VConcatChart` with the tree on top
and the chart below.
"""
plot.__doc__ = (
_PLOT_DOC_HEADER
+ _config._render_numpy_params(_config.PARAM_DOC_EXTRAS)
+ _PLOT_DOC_FOOTER
)
def _build(
tree: str | Path | dict | _tree.TreeNode,
chart: ChartInput,
config: PlotConfig,
) -> alt.HConcatChart | alt.VConcatChart:
"""Shared implementation used by both `plot()` and the CLI.
`tree` and `chart` are the data inputs (the things you can't usefully
set on a config object); `config` carries every styling / behavior
knob. Both surfaces converge here so they can never disagree.
"""
root, auspice_meta = _ensure_tree(
tree,
config.tree_strain_field,
branch_length=config.branch_length,
strict_version=config.strict_version,
)
tip_list = _tree.layout(root)
tip_names = [t.name for t in tip_list]
_check_no_duplicate_tip_strains(
tip_names, tree_strain_field=config.tree_strain_field
)
chart = _load_chart(chart, strict_version=config.strict_version)
spec = chart.to_dict()
axis_hits = _find_strain_encoding(spec, config.chart_strain_field)
axis = axis_hits[0][2]
location = _resolve_tree_location(config.tree_location, axis)
chart_strains = _extract_chart_strains(spec, axis_hits, config.chart_strain_field)
if config.prune_chart_to_tree and (set(chart_strains) - set(tip_names)):
_prune_chart_spec_to_strains(
spec,
chart_strain_field=config.chart_strain_field,
keep_strains=set(tip_names),
)
chart = alt.Chart.from_dict(spec)
chart_strains = _extract_chart_strains(
spec, axis_hits, config.chart_strain_field
)
if not chart_strains:
raise ValueError(
"prune_chart_to_tree=True dropped every chart row: no "
"chart strain matched any tree tip under "
f"chart_strain_field={config.chart_strain_field!r} / "
f"tree_strain_field={config.tree_strain_field!r}. Pruning "
"is meant for charts that bundle a superset of strains; "
"an empty intersection suggests a wrong field choice."
)
_reconcile_tips_and_strains(
tree_strains=tip_names,
chart_strains=chart_strains,
chart_strain_field=config.chart_strain_field,
tree_strain_field=config.tree_strain_field,
prune_tree_to_chart=config.prune_tree_to_chart,
prune_chart_to_tree=config.prune_chart_to_tree,
chart_spec=spec,
tree_source=tree,
)
if config.prune_tree_to_chart and (set(tip_names) - set(chart_strains)):
root = _tree._prune_tree_to(root, set(chart_strains))
tip_list = _tree.layout(root)
tip_names = [t.name for t in tip_list]
strain_dim = _coerce_dim(
_chart_strain_dim(spec, axis_hits, axis), n_tips=len(tip_names)
)
if config.color_tree_by is not None:
color_mapping = _color.compute_node_color_values(
root,
config.color_tree_by,
auspice_meta=auspice_meta,
tree_color_scale=config.tree_color_scale,
)
else:
if config.tree_color_scale is not None:
raise ValueError(
"tree_color_scale was supplied but color_tree_by is None; "
"the override only applies when the tree is being colored."
)
color_mapping = None
tree_chart = _build_tree_chart(
root,
n_tips=len(tip_names),
tree_size=config.tree_size,
strain_dim=strain_dim,
strain_axis=axis,
tree_location=location,
tree_line_width=config.tree_line_width,
tree_node_size=config.tree_node_size,
leader_line_width=config.leader_line_width,
scale_bar=config.scale_bar,
scale_bar_font_size=config.scale_bar_font_size,
branch_length=config.branch_length,
branch_length_units=config.branch_length_units,
connect_leader_to_label=config.connect_leader_to_label,
strain_label_font_size=config.strain_label_font_size,
strain_label_font_weight=config.strain_label_font_weight,
shift_tree_loc=config.shift_tree_loc,
tip_names=tip_names,
color_mapping=color_mapping,
legend_format=config.tree_color_legend_format,
legend_show=config.tree_color_legend_show,
)
new_chart = copy.deepcopy(chart)
suppress_axis_chrome = config.connect_leader_to_label
n_hits = 0
for ch in _iter_strain_axis_channels(new_chart, config.chart_strain_field):
ch.sort = list(tip_names)
if suppress_axis_chrome:
ch.axis = alt.Axis(labels=False, ticks=False, domain=False, title=None)
n_hits += 1
_check_walker_hits("strain-axis update", n_hits, len(axis_hits), axis)
# Pin line/trail/area connection order to tip order via Vega-Lite's
# `order` channel. Without this, an explicit categorical `color` scale
# `domain` (or other encoding choices) can shift Vega-Lite's
# connection-order heuristic away from the strain-axis sort, causing
# lines to crisscross. The order channel's `sort` only accepts
# ascending/descending, so we attach a `calculate` transform that
# computes a per-row tip rank and point `order` at that derived
# quantitative field. User-supplied `order` always wins.
rank_expr = (
f"indexof({json.dumps(list(tip_names))}, "
f"datum[{json.dumps(config.chart_strain_field)}])"
)
for node in _iter_connection_order_nodes(new_chart, config.chart_strain_field):
enc = _live_attr(node, "encoding")
if _live_attr(enc, "order") is not None:
continue
existing = _live_attr(node, "transform") or []
node.transform = list(existing) + [
{"calculate": rank_expr, "as": _TIP_ORDER_RANK_FIELD}
]
enc.order = alt.Order(f"{_TIP_ORDER_RANK_FIELD}:Q")
hoisted_config, hoisted_other = _pop_toplevel_only_attrs(new_chart)
combined = _concat_for_location(
tree_chart=tree_chart, user_chart=new_chart, location=location
)
_apply_combined_config(combined, hoisted_config)
for k, v in hoisted_other.items():
combined._kwds[k] = v
return combined
def _resolve_tree_location(
tree_location: TreeLocation | None, strain_axis: str
) -> TreeLocation:
"""Pick the default tree_location matching the strain axis, or validate
that an explicit value is compatible with the axis."""
valid_for_y = ("left", "right")
valid_for_x = ("top", "bottom")
if tree_location is None:
return "left" if strain_axis == "y" else "bottom"
if strain_axis == "y" and tree_location not in valid_for_y:
raise ValueError(
f"tree_location={tree_location!r} is incompatible with a "
"y-encoded strain (vertical layout). The chart's strain "
"axis is on `y`, so the tree must be alongside it on the "
f"left or right. Valid values: {valid_for_y!r}."
)
if strain_axis == "x" and tree_location not in valid_for_x:
raise ValueError(
f"tree_location={tree_location!r} is incompatible with an "
"x-encoded strain (horizontal layout). The chart's strain "
"axis is on `x`, so the tree must be above or below it. "
f"Valid values: {valid_for_x!r}."
)
return tree_location
def _concat_for_location(
*,
tree_chart: alt.TopLevelMixin,
user_chart: alt.TopLevelMixin,
location: TreeLocation,
) -> alt.HConcatChart | alt.VConcatChart:
"""Concat tree and chart in the order implied by the tree's location.
The strain axis is resolved independent so the tree and chart can use
different scales on that axis (the tree's branch length vs. the chart's
measurement value), while still sharing the orthogonal strain axis. The
`color` scale is also resolved independent: when ``color_tree_by`` is set
the tree panel emits a `color_value:N` color scale with a tree-specific
domain, and Vega-Lite's default of sharing color across concat views
would merge it with any color encoding on the user's chart, hiding
user-chart marks whose color values aren't in the tree's domain.
"""
if location == "left":
return alt.hconcat(tree_chart, user_chart, spacing=0).resolve_scale(
y="independent", color="independent"
)
if location == "right":
return alt.hconcat(user_chart, tree_chart, spacing=0).resolve_scale(
y="independent", color="independent"
)
if location == "top":
return alt.vconcat(tree_chart, user_chart, spacing=0).resolve_scale(
x="independent", color="independent"
)
if location == "bottom":
return alt.vconcat(user_chart, tree_chart, spacing=0).resolve_scale(
x="independent", color="independent"
)
raise ValueError(f"unreachable: tree_location={location!r}")
def _ensure_tree(
tree: str | Path | dict | _tree.TreeNode,
tree_strain_field: str,
*,
branch_length: str,
strict_version: bool,
) -> tuple[_tree.TreeNode, dict | None]:
"""Return ``(root, auspice_meta)``.
``auspice_meta`` is the loaded Auspice JSON's top-level ``meta`` dict, or
``None`` when the caller passed a pre-built ``TreeNode`` (in which case
we have no JSON to read ``meta.colorings`` from, and color resolution
falls back to the default palette).
"""
if isinstance(tree, _tree.TreeNode):
return tree, None
return _tree.load_auspice_with_meta(
tree,
tree_strain_field=tree_strain_field,
branch_length=branch_length,
strict_version=strict_version,
)
# ---------- chart loading (JSON / HTML / dict / live altair) ----------
def _load_chart(chart_input: ChartInput, *, strict_version: bool) -> alt.TopLevelMixin:
"""Convert any supported chart input into a live Altair chart.
A live `alt.TopLevelMixin` is returned as-is — its `$schema` is
irrelevant since the constructing altair version is necessarily the
running altair version. For dict / JSON path / HTML path inputs we run
the Vega-Lite version check (under `strict_version`), strip altair's
`params[].views` round-trip annotations, and then dispatch to the right
chart subclass via `alt.Chart.from_dict(...)`.
"""
if isinstance(chart_input, alt.TopLevelMixin):
return chart_input
if isinstance(chart_input, dict):
spec = chart_input
elif isinstance(chart_input, (str, Path)):
path = Path(chart_input)
suffix = path.suffix.lower()
if suffix == ".json":
with path.open() as f:
spec = json.load(f)
elif suffix == ".html":
spec = _extract_spec_from_html(path.read_text())
else:
raise ValueError(
f"unsupported chart file extension {suffix!r} for {path}; "
"expected .json or .html"
)
else:
raise TypeError(
"chart must be a live Altair chart, a path (str / pathlib.Path) "
"to a .json or .html file, or a parsed spec dict; got "
f"{type(chart_input).__name__}"
)
_check_chart_schema_version(spec, strict_version=strict_version)
spec = copy.deepcopy(spec)
_strip_params_views(spec)
# `from_dict` with validate=True dispatches to the right subclass
# (Chart / LayerChart / FacetChart / HConcatChart / VConcatChart /
# ConcatChart) based on the spec's shape.
return alt.Chart.from_dict(spec)
_TARGET_VEGA_LITE_MAJOR = 6
def _check_chart_schema_version(spec: dict, *, strict_version: bool) -> None:
"""Inspect spec['$schema'] and react to mismatched Vega-Lite versions.
Three regimes:
- Vega-Lite < 6 → known incompatible. Raises under strict_version
(the default); warns under strict_version=False.
- Vega-Lite = 6 → the version this package was built against.
Silent.
- Vega-Lite > 6 → newer than tested. We don't know whether it
works, but Vega-Lite tends to be backward-compatible so we
proceed and warn (regardless of strict_version). The user can
silence the warning via the `warnings` module if needed.
Missing or unrecognized $schema URLs always warn and proceed.
"""
schema = spec.get("$schema")
if not isinstance(schema, str) or not schema:
warnings.warn(
"chart spec has no $schema field; proceeding but the spec may "
"have been saved by an older altair version with a different "
"shape than this package expects.",
stacklevel=3,
)
return
m = re.search(r"vega-lite/v(\d+)", schema)
if m is None:
warnings.warn(
f"chart $schema={schema!r} does not look like a Vega-Lite "
"schema URL; proceeding but the spec may not be a Vega-Lite "
"chart.",
stacklevel=3,
)
return
major = int(m.group(1))
if major < _TARGET_VEGA_LITE_MAJOR:
msg = (
f"chart spec was saved with Vega-Lite {major} (likely altair "
f"{major - 1}); please re-save it from an altair "
f"{_TARGET_VEGA_LITE_MAJOR}+ environment with `chart.save(...)`."
)
if strict_version:
raise ValueError(msg)
warnings.warn(msg, stacklevel=3)
elif major > _TARGET_VEGA_LITE_MAJOR:
warnings.warn(
f"chart spec was saved with Vega-Lite {major}, newer than this "
f"package targets (Vega-Lite {_TARGET_VEGA_LITE_MAJOR}). Most "
"things should still work because Vega-Lite is largely "
"backward-compatible, but if rendering looks wrong please "
"file an issue.",
stacklevel=3,
)
def _strip_params_views(spec: Any) -> None:
"""Recursively delete `views` from every params[] entry.
altair's `to_dict()` annotates each selection-param with the views it's
bound to, but altair's own `from_dict()` validation rejects the field.
Stripping is safe: the renderer rebinds params to views on its own.
"""
if isinstance(spec, dict):
params = spec.get("params")
if isinstance(params, list):
for p in params:
if isinstance(p, dict):
p.pop("views", None)
for v in spec.values():
_strip_params_views(v)
elif isinstance(spec, list):
for item in spec:
_strip_params_views(item)
class _ScriptCollector(HTMLParser):
"""Collect the text content of every <script> tag in an HTML document."""
def __init__(self) -> None:
super().__init__()
self.scripts: list[str] = []
self._in_script = False
def handle_starttag(self, tag: str, attrs: list) -> None:
if tag == "script":
self._in_script = True
def handle_endtag(self, tag: str) -> None:
if tag == "script":
self._in_script = False
def handle_data(self, data: str) -> None:
if self._in_script:
self.scripts.append(data)
def _extract_spec_from_html(html: str) -> dict:
"""Pull the Vega-Lite spec dict out of an altair-saved HTML page.
altair's default `to_html()` template emits a `var spec = {...};` line
inside a `<script>` tag whose value is a json.dumps of the spec. We
locate that line via stdlib `html.parser` (no regex on the document)
and use `json.JSONDecoder.raw_decode` to do brace-balancing on the
JSON literal (no regex on the JSON either).
Limits: works on the default altair template. If the user passed
`chart.save(template=...)` with a custom template, this raises with a
remediation message pointing at JSON. A page with multiple `var spec`
blocks: we return the first one and document this as a known limit.
"""
parser = _ScriptCollector()
parser.feed(html)
decoder = json.JSONDecoder()
for script in parser.scripts:
i = script.find("var spec")
if i == -1:
continue
brace = script.index("{", i)
spec, _ = decoder.raw_decode(script, brace)
return spec
raise ValueError(
"no `var spec = {...}` block found in the HTML; this is likely a "
"non-default altair template. Re-save the chart as JSON: "
"chart.save('foo.json')."
)
# ---------- chart spec introspection ----------
def _walk_strain_encodings(spec: Any, chart_strain_field: str) -> list[_AxisHit]:
"""Return every encoding referencing `chart_strain_field` in the spec.
Walks vconcat/hconcat/concat/facet.spec/layer recursively. Each hit is
(path, encoding_dict, channel). Path is a tuple of dict keys and list
indices ending with ("encoding", channel) so the same path on the deepcopy
locates the same encoding for in-place modification.
"""
hits: list[_AxisHit] = []
def walk(node: Any, path: tuple) -> None:
if isinstance(node, dict):
enc = node.get("encoding")
if isinstance(enc, dict):
for channel, enc_def in enc.items():
if (
isinstance(enc_def, dict)
and enc_def.get("field") == chart_strain_field
):
hits.append((path + ("encoding", channel), enc_def, channel))
elif isinstance(enc_def, list):
# Some channels (notably `tooltip`) carry a list of
# field definitions. Walk each.
for i, item in enumerate(enc_def):
if (
isinstance(item, dict)
and item.get("field") == chart_strain_field
):
hits.append(
(path + ("encoding", channel, i), item, channel)
)
for k, v in node.items():
# `encoding` already inspected; `data`/`datasets`/`config`
# don't contain encodings.
if k in ("encoding", "data", "datasets", "config"):
continue
walk(v, path + (k,))
elif isinstance(node, list):
for i, item in enumerate(node):
walk(item, path + (i,))
walk(spec, ())
return hits
def _find_strain_encoding(spec: dict, chart_strain_field: str) -> list[_AxisHit]:
"""Walk the spec, validate, and return only the axis (x/y) hits.
Validates:
1. At least one axis hit exists.
2. All axis hits agree on the same channel ('x' or 'y').
3. Each axis hit's encoding type is 'nominal' or 'ordinal'.
Secondary hits (color, tooltip, detail, etc.) are allowed and ignored.
"""
all_hits = _walk_strain_encodings(spec, chart_strain_field)
axis_hits = [h for h in all_hits if h[2] in ("x", "y")]
secondary_hits = [h for h in all_hits if h[2] not in ("x", "y")]
if not axis_hits:
if secondary_hits:
channels = sorted({h[2] for h in secondary_hits})
raise ValueError(
f"chart_strain_field={chart_strain_field!r} is encoded on "
f"{channels} but not on 'x' or 'y'; tree alignment requires "
"the strain to be on an axis channel."
)
raise ValueError(
f"chart_strain_field={chart_strain_field!r} not found in any "
"encoding of the chart spec. Confirm the field name and that the "
"chart has an 'x' or 'y' encoding referencing it."
)
axes = {h[2] for h in axis_hits}
if len(axes) > 1:
raise ValueError(
f"chart_strain_field={chart_strain_field!r} is encoded on both "
f"{sorted(axes)} channels (across layers/panels). The alignment "
"axis is ambiguous; the chart must encode the strain on exactly "
"one of x or y."
)
for _, enc, channel in axis_hits:
t = enc.get("type")
if t not in ("nominal", "ordinal"):
raise ValueError(
f"chart_strain_field={chart_strain_field!r} on the {channel!r} "
f"channel has type={t!r}; expected 'nominal' or 'ordinal' so "
"each strain value collapses onto exactly one axis row."
)
return axis_hits
def _extract_chart_strains(
spec: dict, axis_hits: list[_AxisHit], chart_strain_field: str
) -> list[str]:
"""Return the chart's distinct strain values.
Prefers an explicit `sort` on the first axis hit. Falls back to walking
the spec's data (inline values or named datasets). Refuses URL data.
"""
for _, enc, _ in axis_hits:
sort = enc.get("sort")
if isinstance(sort, list) and sort:
return list(sort)
return _extract_field_values_from_spec_data(spec, chart_strain_field)
def _prune_chart_spec_to_strains(
spec: dict, *, chart_strain_field: str, keep_strains: set[str]
) -> None:
"""Filter a Vega-Lite spec in place to drop rows outside `keep_strains`.
Mutates three kinds of structure:
- top-level `datasets` entries (each a list of row-dicts).
- inline `data.values` lists anywhere in the spec tree.
- explicit `sort` lists on encoding channels bound to
`chart_strain_field` (any other `sort` is left alone).
Rows that don't carry `chart_strain_field` at all are preserved
(we have no signal to drop them). URL-backed data raises — we
can't fetch + filter at plot time, mirroring `_extract_chart_strains`.
"""
def row_kept(row: Any) -> bool:
if not isinstance(row, dict):
return True
if chart_strain_field not in row:
return True
return row[chart_strain_field] in keep_strains
datasets = spec.get("datasets") if isinstance(spec, dict) else None
if isinstance(datasets, dict):
for name, rows in list(datasets.items()):
if isinstance(rows, list):
datasets[name] = [row for row in rows if row_kept(row)]
def walk(node: Any) -> None:
if isinstance(node, dict):
data = node.get("data")
if isinstance(data, dict):
if "url" in data:
raise ValueError(
f"chart references data via URL ({data['url']!r}); "
"URL data is not supported, so prune_chart_to_tree "
"cannot filter it. Materialize the data inline "
"(via alt.Chart(df) with a pandas DataFrame) before "
"saving the chart."
)
if "values" in data and isinstance(data["values"], list):
data["values"] = [row for row in data["values"] if row_kept(row)]
encoding = node.get("encoding")
if isinstance(encoding, dict):
for channel in encoding.values():
if not isinstance(channel, dict):
continue
if channel.get("field") != chart_strain_field:
continue
sort = channel.get("sort")
if isinstance(sort, list):
channel["sort"] = [s for s in sort if s in keep_strains]
for k, v in node.items():
if k in ("data", "datasets"):
continue
walk(v)
elif isinstance(node, list):
for item in node:
walk(item)
walk(spec)
def _extract_field_values_from_spec_data(spec: dict, field: str) -> list[str]:
"""Walk spec for inline / named data and return distinct values of `field`.
Refuses URL data with a clear message: synchronous fetches at plot time
are out of scope.
"""
datasets = spec.get("datasets", {}) if isinstance(spec, dict) else {}
seen: list[Any] = []
def walk(node: Any) -> None:
if isinstance(node, dict):
data = node.get("data")
if isinstance(data, dict):
if "url" in data:
raise ValueError(
f"chart references data via URL ({data['url']!r}); "
"URL data is not supported. Materialize the data inline "
"(via alt.Chart(df) with a pandas DataFrame) before "
"saving the chart."
)
if "values" in data and isinstance(data["values"], list):
for row in data["values"]:
if isinstance(row, dict) and field in row:
seen.append(row[field])
elif "name" in data:
name = data["name"]
rows = datasets.get(name)
if isinstance(rows, list):
for row in rows:
if isinstance(row, dict) and field in row:
seen.append(row[field])
for k, v in node.items():
if k in ("data", "datasets"):
continue
walk(v)
elif isinstance(node, list):
for item in node:
walk(item)
walk(spec)
return list(dict.fromkeys(seen))
def _check_no_duplicate_tip_strains(
tip_names: list[str], *, tree_strain_field: str
) -> None:
"""Tip identifiers must be unique under the chosen `tree_strain_field`."""
if len(set(tip_names)) == len(tip_names):
return
from collections import Counter
dups = sorted(s for s, c in Counter(tip_names).items() if c > 1)
raise ValueError(
f"tree_strain_field={tree_strain_field!r} resolves to duplicate "
f"values across tips: {dups[:10]}. Each tip must have a unique "
"strain identifier; either pick a different tree_strain_field or "
"fix the underlying tree."
)
def _reconcile_tips_and_strains(
*,
tree_strains: list[str],
chart_strains: list[str],
chart_strain_field: str,
tree_strain_field: str,
prune_tree_to_chart: bool,
prune_chart_to_tree: bool,
chart_spec: dict,
tree_source: Any,
) -> None:
"""Verify tree strains and chart strains are reconcilable.
Three asymmetries:
- chart strains not in tree → fatal unless `prune_chart_to_tree=True`
(in which case the chart spec has already been pre-filtered upstream
and this set is expected to be empty by the time we get here).
- tree tips not in chart → fatal unless `prune_tree_to_chart=True`.
- (duplicate tree_strain_field values across tips → handled by the
separate `_check_no_duplicate_tip_strains`.)
On any fatal asymmetry, raises `ValueError` with a multi-line message
that includes sample values from both sides and any candidate-field
suggestions whose values overlap heavily with the other side.
"""
tree_set = set(tree_strains)
chart_set = set(chart_strains)
chart_minus_tree = chart_set - tree_set
tree_minus_chart = tree_set - chart_set
chart_ok = not chart_minus_tree
tree_ok = not tree_minus_chart or prune_tree_to_chart
if chart_ok and tree_ok:
return
hints = _candidate_field_hints(
chart_spec=chart_spec,
chart_strain_field=chart_strain_field,
tree_strains=tree_strains,
tree_source=tree_source,
tree_strain_field=tree_strain_field,
chart_strains=chart_strains,
)
raise ValueError(
_format_strain_mismatch(
chart_strain_field=chart_strain_field,
tree_strain_field=tree_strain_field,
chart_strains=chart_strains,
tree_strains=tree_strains,
chart_minus_tree=chart_minus_tree,
tree_minus_chart=tree_minus_chart,
prune_tree_to_chart=prune_tree_to_chart,
prune_chart_to_tree=prune_chart_to_tree,
hints=hints,
)
)
def _format_strain_mismatch(
*,
chart_strain_field: str,
tree_strain_field: str,
chart_strains: list[str],
tree_strains: list[str],
chart_minus_tree: set[str],
tree_minus_chart: set[str],
prune_tree_to_chart: bool,
prune_chart_to_tree: bool,
hints: list[str],
) -> str:
parts: list[str] = []
if chart_minus_tree and not prune_chart_to_tree:
parts.append(
f"{len(chart_minus_tree)} chart strain(s) are not present in the "
"tree. Pass `prune_chart_to_tree=True` to drop the offending "
"chart rows automatically (use with care — this discards plot "
"data)."
)
if tree_minus_chart and not prune_tree_to_chart:
parts.append(
f"{len(tree_minus_chart)} tree tip(s) are not present in the "
"chart. Pass `prune_tree_to_chart=True` to drop them automatically."
)
parts.append("")
parts.append(
f"Tried: chart_strain_field={chart_strain_field!r}, "
f"tree_strain_field={tree_strain_field!r}"
)
parts.append("Sample chart_strain_field values: " f"{sorted(chart_strains)[:5]}")
parts.append("Sample tree_strain_field values: " f"{sorted(tree_strains)[:5]}")
if chart_minus_tree and not prune_chart_to_tree:
parts.append(f"Sample chart-only values: {sorted(chart_minus_tree)[:5]}")
if tree_minus_chart and not prune_tree_to_chart:
parts.append(f"Sample tree-only values: {sorted(tree_minus_chart)[:5]}")
if hints:
parts.append("")
parts.append("Possible alternatives:")
for h in hints:
parts.append(f" - {h}")
return "\n".join(parts)
def _candidate_field_hints(
*,
chart_spec: dict,
chart_strain_field: str,
tree_strains: list[str],
tree_source: Any,
tree_strain_field: str,
chart_strains: list[str],
) -> list[str]:
"""Return human-readable hints suggesting alternative strain fields.
Scans:
- chart side: every column appearing in inline / named data of the
spec. For each, fraction of values that are in tree_strains.
- tree side: every node_attrs key on tips, plus the literal "name"
(top-level Auspice tip ID). For each, fraction of values that are
in chart_strains. Skipped if `tree_source` is a parsed TreeNode
rather than a path/dict (we'd have no original Auspice JSON to
introspect).
Threshold: 50% overlap. Tunable; lower threshold trades fewer
false-negatives for more false-positives in the hint.
"""
OVERLAP_THRESHOLD = 0.5
hints: list[str] = []
tree_set = set(tree_strains)
chart_set = set(chart_strains)
if tree_set:
for field_name, values in _enumerate_chart_data_columns(chart_spec):
if field_name == chart_strain_field:
continue
distinct = set(values)
if not distinct:
continue
overlap = len(distinct & tree_set)
if overlap / len(tree_set) >= OVERLAP_THRESHOLD:
hints.append(
f"the chart has a field {field_name!r} whose values "
f"match {overlap}/{len(tree_set)} tree strains — did "
f"you mean chart_strain_field={field_name!r}?"
)
tree_dict = _tree_source_as_dict(tree_source)
if chart_set and tree_dict is not None and "tree" in tree_dict:
for attr, values in _enumerate_tree_tip_attrs(tree_dict["tree"]):
if attr == tree_strain_field:
continue
distinct = set(values)
if not distinct:
continue
overlap = len(distinct & chart_set)
if overlap / len(chart_set) >= OVERLAP_THRESHOLD:
hint_lhs = (
"the tree has node `name` field"
if attr == "name"
else f"the tree has node_attrs[{attr!r}]"
)
hints.append(
f"{hint_lhs} whose values match {overlap}/"
f"{len(chart_set)} chart strains — did you mean "
f"tree_strain_field={attr!r}?"
)
return hints
def _enumerate_chart_data_columns(spec: Any) -> list[tuple[str, list]]:
"""Walk the spec for every column appearing in inline / named data.
Returns `[(field_name, values), ...]` where `values` is the list of
raw values seen for that field across all data rows visited (with
duplicates).
"""
datasets = spec.get("datasets", {}) if isinstance(spec, dict) else {}
by_field: dict[str, list] = {}
def walk(node: Any) -> None:
if isinstance(node, dict):
data = node.get("data")
if isinstance(data, dict):
rows: list | None = None
if "values" in data and isinstance(data["values"], list):
rows = data["values"]
elif "name" in data:
name = data["name"]
if isinstance(datasets.get(name), list):
rows = datasets[name]
if rows:
for row in rows:
if isinstance(row, dict):
for k, v in row.items():
by_field.setdefault(k, []).append(v)
for k, v in node.items():
if k in ("data", "datasets"):
continue
walk(v)
elif isinstance(node, list):
for item in node:
walk(item)
walk(spec)
return list(by_field.items())
def _tree_source_as_dict(tree_source: Any) -> dict | None:
"""Return the original Auspice JSON dict if available, else None.
You can’t perform that action at this time.
