File size: 4,384 Bytes
9c6594c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

from dataclasses import dataclass
from typing import Any

import wandb


@dataclass
class CustomChartSpec:
    spec_name: str
    fields: dict[str, Any]
    string_fields: dict[str, Any]
    key: str = ""
    panel_type: str = "Vega2"
    split_table: bool = False

    @property
    def table_key(self) -> str:
        if not self.key:
            raise wandb.Error("Key for the custom chart spec is not set.")
        if self.split_table:
            return f"Custom Chart Tables/{self.key}_table"
        return f"{self.key}_table"

    @property
    def config_value(self) -> dict[str, Any]:
        return {
            "panel_type": self.panel_type,
            "panel_config": {
                "panelDefId": self.spec_name,
                "fieldSettings": self.fields,
                "stringSettings": self.string_fields,
                "transform": {"name": "tableWithLeafColNames"},
                "userQuery": {
                    "queryFields": [
                        {
                            "name": "runSets",
                            "args": [{"name": "runSets", "value": "${runSets}"}],
                            "fields": [
                                {"name": "id", "fields": []},
                                {"name": "name", "fields": []},
                                {"name": "_defaultColorIndex", "fields": []},
                                {
                                    "name": "summaryTable",
                                    "args": [
                                        {
                                            "name": "tableKey",
                                            "value": self.table_key,
                                        }
                                    ],
                                    "fields": [],
                                },
                            ],
                        }
                    ],
                },
            },
        }

    @property
    def config_key(self) -> tuple[str, str, str]:
        return ("_wandb", "visualize", self.key)


@dataclass
class CustomChart:
    table: wandb.Table
    spec: CustomChartSpec

    def set_key(self, key: str):
        """Sets the key for the spec and updates dependent configurations."""
        self.spec.key = key


def plot_table(
    vega_spec_name: str,
    data_table: wandb.Table,
    fields: dict[str, Any],
    string_fields: dict[str, Any] | None = None,
    split_table: bool = False,
) -> CustomChart:
    """Creates a custom charts using a Vega-Lite specification and a `wandb.Table`.

    This function creates a custom chart based on a Vega-Lite specification and
    a data table represented by a `wandb.Table` object. The specification needs
    to be predefined and stored in the W&B backend. The function returns a custom
    chart object that can be logged to W&B using `wandb.log()`.

    Args:
        vega_spec_name (str): The name or identifier of the Vega-Lite spec
            that defines the visualization structure.
        data_table (wandb.Table): A `wandb.Table` object containing the data to be
            visualized.
        fields (dict[str, Any]): A mapping between the fields in the Vega-Lite spec and the
            corresponding columns in the data table to be visualized.
        string_fields (dict[str, Any] | None): A dictionary for providing values for any string constants
            required by the custom visualization.
        split_table (bool): Whether the table should be split into a separate section
            in the W&B UI. If `True`, the table will be displayed in a section named
            "Custom Chart Tables". Default is `False`.

    Returns:
        CustomChart: A custom chart object that can be logged to W&B. To log the
            chart, pass it to `wandb.log()`.

    Raises:
        wandb.Error: If `data_table` is not a `wandb.Table` object.
    """

    if not isinstance(data_table, wandb.Table):
        raise wandb.Error(
            f"Expected `data_table` to be `wandb.Table` type, instead got {type(data_table).__name__}"
        )

    return CustomChart(
        table=data_table,
        spec=CustomChartSpec(
            spec_name=vega_spec_name,
            fields=fields,
            string_fields=string_fields or {},
            split_table=split_table,
        ),
    )