biocentral-vis 2.0.0__tar.gz
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.
- biocentral_vis-2.0.0/PKG-INFO +19 -0
- biocentral_vis-2.0.0/README.md +8 -0
- biocentral_vis-2.0.0/biocentral_vis/__init__.py +4 -0
- biocentral_vis-2.0.0/biocentral_vis/base/__init__.py +5 -0
- biocentral_vis-2.0.0/biocentral_vis/base/biocentral_visualization.py +48 -0
- biocentral_vis-2.0.0/biocentral_vis/base/constants.py +1 -0
- biocentral_vis-2.0.0/biocentral_vis/base/exporter.py +275 -0
- biocentral_vis-2.0.0/biocentral_vis/base/sequence_data_utils.py +63 -0
- biocentral_vis-2.0.0/biocentral_vis/biocentral_chart.py +122 -0
- biocentral_vis-2.0.0/biocentral_vis/biocentral_highlight.py +44 -0
- biocentral_vis-2.0.0/biocentral_vis/datasets/__init__.py +15 -0
- biocentral_vis-2.0.0/biocentral_vis/datasets/label_distribution.py +254 -0
- biocentral_vis-2.0.0/biocentral_vis/datasets/labels_by_split_distribution.py +260 -0
- biocentral_vis-2.0.0/biocentral_vis/datasets/mutation_depth_distribution.py +57 -0
- biocentral_vis-2.0.0/biocentral_vis/datasets/sequence_length_distribution.py +93 -0
- biocentral_vis-2.0.0/biocentral_vis/datasets/split_distribution.py +63 -0
- biocentral_vis-2.0.0/biocentral_vis/datasets/variant_score_distribution.py +18 -0
- biocentral_vis-2.0.0/biocentral_vis/models/__init__.py +3 -0
- biocentral_vis-2.0.0/biocentral_vis/models/model_plotting.py +114 -0
- biocentral_vis-2.0.0/biocentral_vis/predictions/__init__.py +3 -0
- biocentral_vis-2.0.0/biocentral_vis/predictions/highlight_prediction.py +179 -0
- biocentral_vis-2.0.0/biocentral_vis/projections/__init__.py +3 -0
- biocentral_vis-2.0.0/biocentral_vis/projections/projection_plotting.py +149 -0
- biocentral_vis-2.0.0/biocentral_vis.egg-info/PKG-INFO +19 -0
- biocentral_vis-2.0.0/biocentral_vis.egg-info/SOURCES.txt +28 -0
- biocentral_vis-2.0.0/biocentral_vis.egg-info/dependency_links.txt +1 -0
- biocentral_vis-2.0.0/biocentral_vis.egg-info/requires.txt +4 -0
- biocentral_vis-2.0.0/biocentral_vis.egg-info/top_level.txt +1 -0
- biocentral_vis-2.0.0/pyproject.toml +19 -0
- biocentral_vis-2.0.0/setup.cfg +4 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: biocentral-vis
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: Cross-Platform Visualizations for the Biocentral Ecosystem
|
|
5
|
+
Requires-Python: <3.14,>=3.12
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: altair>=6.0.0
|
|
8
|
+
Requires-Dist: vl-convert-python>=1.9.0.post1
|
|
9
|
+
Requires-Dist: biocentral-api<3.0.0,>=2.0.0
|
|
10
|
+
Requires-Dist: biotrainer-core<3.0.0,>=2.0.0
|
|
11
|
+
|
|
12
|
+
# Biotrainer-Vis: Standardized visualization library for biological datasets based on biotrainer-core dataclasses
|
|
13
|
+
|
|
14
|
+
Part of [biocentral](https://github.com/biotrainer/biocentral) and the
|
|
15
|
+
[biocentral pypi package](https://pypi.org/project/biocentral/).
|
|
16
|
+
|
|
17
|
+
## License
|
|
18
|
+
|
|
19
|
+
*biocentral-vis* is licensed under the MIT License.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Biotrainer-Vis: Standardized visualization library for biological datasets based on biotrainer-core dataclasses
|
|
2
|
+
|
|
3
|
+
Part of [biocentral](https://github.com/biotrainer/biocentral) and the
|
|
4
|
+
[biocentral pypi package](https://pypi.org/project/biocentral/).
|
|
5
|
+
|
|
6
|
+
## License
|
|
7
|
+
|
|
8
|
+
*biocentral-vis* is licensed under the MIT License.
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import altair as alt
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from typing import Dict, Any, Union, Optional
|
|
7
|
+
|
|
8
|
+
from .exporter import CrossPlatformMetadataExporter
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class BiocentralVisualization(ABC):
|
|
12
|
+
"""Base class for all biocentral visualizations"""
|
|
13
|
+
|
|
14
|
+
metadata: Dict[str, Any]
|
|
15
|
+
|
|
16
|
+
@abstractmethod
|
|
17
|
+
def to_svg(self) -> str:
|
|
18
|
+
"""Convert visualization to SVG string"""
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
@abstractmethod
|
|
22
|
+
def save(self, output_path: Union[str, Path]):
|
|
23
|
+
"""Save data to file"""
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
def save_export(self, output_path: Union[str, Path]):
|
|
27
|
+
"""Save export schema JSON File"""
|
|
28
|
+
if Path(output_path).suffix != ".json":
|
|
29
|
+
raise ValueError("Output path must have .json extension")
|
|
30
|
+
|
|
31
|
+
export_data = self.export()
|
|
32
|
+
with open(output_path, "w") as f:
|
|
33
|
+
json.dump(export_data, f)
|
|
34
|
+
|
|
35
|
+
def get_metadata(self) -> Dict[str, Any]:
|
|
36
|
+
"""Get metadata about the visualization"""
|
|
37
|
+
return self.metadata
|
|
38
|
+
|
|
39
|
+
def get_chart(self) -> Optional[alt.Chart]:
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
def export(self) -> Dict[str, Any]:
|
|
43
|
+
"""Create export schema dict"""
|
|
44
|
+
svg = self.to_svg()
|
|
45
|
+
metadata = self.get_metadata()
|
|
46
|
+
chart = self.get_chart()
|
|
47
|
+
exporter = CrossPlatformMetadataExporter(svg, metadata, chart)
|
|
48
|
+
return exporter.export()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
DISCRETE_THRESHOLD = 20
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import re
|
|
2
|
+
import altair as alt
|
|
3
|
+
import xml.etree.ElementTree as ET
|
|
4
|
+
|
|
5
|
+
from typing import List, Union, Dict, Any, Optional, Tuple
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class CrossPlatformMetadataExporter:
|
|
9
|
+
"""Export Biocentral visualizations (Altair/Custom) to SVG + metadata JSON for Flutter."""
|
|
10
|
+
|
|
11
|
+
def __init__(
|
|
12
|
+
self,
|
|
13
|
+
svg_string: str,
|
|
14
|
+
metadata: Dict[str, Any],
|
|
15
|
+
chart: Optional[alt.Chart] = None,
|
|
16
|
+
):
|
|
17
|
+
self.svg_string = svg_string
|
|
18
|
+
self.metadata = metadata
|
|
19
|
+
if chart is not None:
|
|
20
|
+
chart_metadata = self._extract_metadata_from_altair(chart)
|
|
21
|
+
self.metadata.update(chart_metadata)
|
|
22
|
+
|
|
23
|
+
def export(self) -> Dict[str, Any]:
|
|
24
|
+
"""
|
|
25
|
+
Export visualization to a single JSON file containing SVG and metadata.
|
|
26
|
+
|
|
27
|
+
Returns:
|
|
28
|
+
Dictionary containing both SVG string and metadata
|
|
29
|
+
"""
|
|
30
|
+
# Parse SVG to extract interactive elements if not already present or to complement
|
|
31
|
+
interactive_elements = self._parse_svg_elements(self.svg_string)
|
|
32
|
+
|
|
33
|
+
# Merge or set points
|
|
34
|
+
if "points" not in self.metadata or not self.metadata["points"]:
|
|
35
|
+
self.metadata["points"] = interactive_elements
|
|
36
|
+
else:
|
|
37
|
+
# If we already have points (e.g. from custom metadata), we might want to keep them
|
|
38
|
+
# but for now let's prefer parsed ones if they exist to ensure sync with SVG
|
|
39
|
+
if interactive_elements:
|
|
40
|
+
self.metadata["points"] = interactive_elements
|
|
41
|
+
|
|
42
|
+
output = {"svg": self.svg_string, "metadata": self.metadata}
|
|
43
|
+
|
|
44
|
+
return output
|
|
45
|
+
|
|
46
|
+
@staticmethod
|
|
47
|
+
def _extract_metadata_from_altair(chart: alt.Chart) -> Dict[str, Any]:
|
|
48
|
+
"""Extract metadata from Altair chart specification."""
|
|
49
|
+
spec = chart.to_dict()
|
|
50
|
+
|
|
51
|
+
# Extract basic chart info
|
|
52
|
+
title = spec.get("title", "Chart")
|
|
53
|
+
if isinstance(title, dict):
|
|
54
|
+
title = title.get("text", "Chart")
|
|
55
|
+
|
|
56
|
+
# Extract dimensions
|
|
57
|
+
width = spec.get("width", 400)
|
|
58
|
+
height = spec.get("height", 300)
|
|
59
|
+
|
|
60
|
+
# Extract axis labels
|
|
61
|
+
encoding = spec.get("encoding", {})
|
|
62
|
+
x_label = CrossPlatformMetadataExporter._extract_axis_label(
|
|
63
|
+
encoding.get("x", {})
|
|
64
|
+
)
|
|
65
|
+
y_label = CrossPlatformMetadataExporter._extract_axis_label(
|
|
66
|
+
encoding.get("y", {})
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
# Detect chart type
|
|
70
|
+
mark = spec.get("mark", {})
|
|
71
|
+
if isinstance(mark, str):
|
|
72
|
+
chart_type = mark
|
|
73
|
+
else:
|
|
74
|
+
chart_type = mark.get("type", "unknown")
|
|
75
|
+
|
|
76
|
+
metadata = {
|
|
77
|
+
"title": title,
|
|
78
|
+
"x_label": x_label,
|
|
79
|
+
"y_label": y_label,
|
|
80
|
+
"chart_type": chart_type,
|
|
81
|
+
"dimensions": {
|
|
82
|
+
"width": float(width) if isinstance(width, (int, float)) else 400.0,
|
|
83
|
+
"height": float(height) if isinstance(height, (int, float)) else 300.0,
|
|
84
|
+
"margin_left": 60.0,
|
|
85
|
+
"margin_top": 40.0,
|
|
86
|
+
},
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return metadata
|
|
90
|
+
|
|
91
|
+
@staticmethod
|
|
92
|
+
def _extract_axis_label(axis_spec: Dict) -> str:
|
|
93
|
+
"""Extract axis label from encoding specification."""
|
|
94
|
+
if "title" in axis_spec:
|
|
95
|
+
title = axis_spec["title"]
|
|
96
|
+
return title if isinstance(title, str) else str(title)
|
|
97
|
+
if "field" in axis_spec:
|
|
98
|
+
return str(axis_spec["field"])
|
|
99
|
+
return ""
|
|
100
|
+
|
|
101
|
+
@staticmethod
|
|
102
|
+
def _parse_svg_elements(svg_string: str) -> List[Dict[str, Any]]:
|
|
103
|
+
"""Parse SVG to extract interactive elements (bars, points, residues)."""
|
|
104
|
+
try:
|
|
105
|
+
# Handle potential namespaces in SVG
|
|
106
|
+
root = ET.fromstring(svg_string)
|
|
107
|
+
|
|
108
|
+
elements = []
|
|
109
|
+
|
|
110
|
+
for element in root.iter():
|
|
111
|
+
# Check for custom data attributes (used in our highlight prediction)
|
|
112
|
+
# Note: ElementTree might represent data-residue as '{namespace}data-residue' or just 'data-residue'
|
|
113
|
+
data_attrs = {
|
|
114
|
+
k: v
|
|
115
|
+
for k, v in element.attrib.items()
|
|
116
|
+
if "data-" in k or k == "aria-label"
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if not data_attrs:
|
|
120
|
+
continue
|
|
121
|
+
|
|
122
|
+
parsed = None
|
|
123
|
+
tag = element.tag.split("}")[-1] # Remove namespace
|
|
124
|
+
|
|
125
|
+
if tag == "path":
|
|
126
|
+
aria_desc = element.get("aria-roledescription", "")
|
|
127
|
+
if "bar" in aria_desc.lower():
|
|
128
|
+
parsed = CrossPlatformMetadataExporter._parse_bar_path(element)
|
|
129
|
+
else:
|
|
130
|
+
parsed = CrossPlatformMetadataExporter._parse_generic_path(
|
|
131
|
+
element
|
|
132
|
+
)
|
|
133
|
+
elif tag == "circle":
|
|
134
|
+
parsed = CrossPlatformMetadataExporter._parse_circle(element)
|
|
135
|
+
elif tag == "rect":
|
|
136
|
+
parsed = CrossPlatformMetadataExporter._parse_rect(element)
|
|
137
|
+
elif tag == "symbol":
|
|
138
|
+
# Sometimes Altair uses <symbol> for points
|
|
139
|
+
parsed = CrossPlatformMetadataExporter._parse_symbol(element)
|
|
140
|
+
|
|
141
|
+
if parsed:
|
|
142
|
+
# Collect all data-* attributes and aria-label
|
|
143
|
+
data = {}
|
|
144
|
+
for k, v in element.attrib.items():
|
|
145
|
+
if k.startswith("data-"):
|
|
146
|
+
key = k[5:] # remove 'data-'
|
|
147
|
+
data[key] = CrossPlatformMetadataExporter._try_parse_number(
|
|
148
|
+
v
|
|
149
|
+
)
|
|
150
|
+
elif k == "aria-label":
|
|
151
|
+
data.update(
|
|
152
|
+
CrossPlatformMetadataExporter._parse_aria_label(v)
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
if data:
|
|
156
|
+
parsed["data"] = data
|
|
157
|
+
elements.append(parsed)
|
|
158
|
+
|
|
159
|
+
return elements
|
|
160
|
+
|
|
161
|
+
except Exception as e:
|
|
162
|
+
print(f"⚠️ Warning: Could not parse SVG elements: {e}")
|
|
163
|
+
return []
|
|
164
|
+
|
|
165
|
+
@staticmethod
|
|
166
|
+
def _parse_bar_path(path: ET.Element) -> Optional[Dict[str, Any]]:
|
|
167
|
+
"""Parse a path element that represents a bar."""
|
|
168
|
+
d = path.get("d", "")
|
|
169
|
+
coords = CrossPlatformMetadataExporter._parse_bar_path_coords(d)
|
|
170
|
+
if coords:
|
|
171
|
+
x, y, width, height = coords
|
|
172
|
+
return {
|
|
173
|
+
"x": float(x + width / 2),
|
|
174
|
+
"y": float(y + height / 2),
|
|
175
|
+
"radius": 5.0,
|
|
176
|
+
}
|
|
177
|
+
return None
|
|
178
|
+
|
|
179
|
+
@staticmethod
|
|
180
|
+
def _parse_bar_path_coords(d: str) -> Optional[Tuple[float, float, float, float]]:
|
|
181
|
+
"""Parse bar path coordinates: 'M x,y h width v height h -width Z'"""
|
|
182
|
+
# Improved regex to handle various spacing and signs
|
|
183
|
+
m_match = re.search(r"M\s*([\d.-]+)[,\s]+([\d.-]+)", d)
|
|
184
|
+
h_match = re.search(r"h\s*([\d.-]+)", d)
|
|
185
|
+
v_match = re.search(r"v\s*([\d.-]+)", d)
|
|
186
|
+
if m_match and h_match and v_match:
|
|
187
|
+
return (
|
|
188
|
+
float(m_match.group(1)),
|
|
189
|
+
float(m_match.group(2)),
|
|
190
|
+
float(h_match.group(1)),
|
|
191
|
+
float(v_match.group(1)),
|
|
192
|
+
)
|
|
193
|
+
return None
|
|
194
|
+
|
|
195
|
+
@staticmethod
|
|
196
|
+
def _parse_circle(circle: ET.Element) -> Optional[Dict[str, Any]]:
|
|
197
|
+
"""Parse a circle element."""
|
|
198
|
+
try:
|
|
199
|
+
return {
|
|
200
|
+
"x": float(circle.get("cx", 0)),
|
|
201
|
+
"y": float(circle.get("cy", 0)),
|
|
202
|
+
"radius": float(circle.get("r", 5)),
|
|
203
|
+
}
|
|
204
|
+
except (ValueError, TypeError):
|
|
205
|
+
return None
|
|
206
|
+
|
|
207
|
+
@staticmethod
|
|
208
|
+
def _parse_rect(rect: ET.Element) -> Optional[Dict[str, Any]]:
|
|
209
|
+
"""Parse a rectangle element."""
|
|
210
|
+
try:
|
|
211
|
+
x = float(rect.get("x", 0))
|
|
212
|
+
y = float(rect.get("y", 0))
|
|
213
|
+
w = float(rect.get("width", 0))
|
|
214
|
+
h = float(rect.get("height", 0))
|
|
215
|
+
return {
|
|
216
|
+
"x": x + w / 2,
|
|
217
|
+
"y": y + h / 2,
|
|
218
|
+
"width": w,
|
|
219
|
+
"height": h,
|
|
220
|
+
"radius": 5.0,
|
|
221
|
+
}
|
|
222
|
+
except (ValueError, TypeError):
|
|
223
|
+
return None
|
|
224
|
+
|
|
225
|
+
@staticmethod
|
|
226
|
+
def _parse_generic_path(path: ET.Element) -> Optional[Dict[str, Any]]:
|
|
227
|
+
"""Extract first coordinate from path data."""
|
|
228
|
+
d = path.get("d", "")
|
|
229
|
+
# Try to find the first move command
|
|
230
|
+
match = re.search(r"M\s*([\d.-]+)[,\s]+([\d.-]+)", d)
|
|
231
|
+
if match:
|
|
232
|
+
return {
|
|
233
|
+
"x": float(match.group(1)),
|
|
234
|
+
"y": float(match.group(2)),
|
|
235
|
+
"radius": 5.0,
|
|
236
|
+
}
|
|
237
|
+
return None
|
|
238
|
+
|
|
239
|
+
@staticmethod
|
|
240
|
+
def _parse_symbol(symbol: ET.Element) -> Optional[Dict[str, Any]]:
|
|
241
|
+
"""Parse a symbol element (used for some points)."""
|
|
242
|
+
# Symbols often use transform="translate(x,y)"
|
|
243
|
+
transform = symbol.get("transform", "")
|
|
244
|
+
match = re.search(r"translate\(([\d.-]+)[,\s]+([\d.-]+)\)", transform)
|
|
245
|
+
if match:
|
|
246
|
+
return {
|
|
247
|
+
"x": float(match.group(1)),
|
|
248
|
+
"y": float(match.group(2)),
|
|
249
|
+
"radius": 5.0,
|
|
250
|
+
}
|
|
251
|
+
return None
|
|
252
|
+
|
|
253
|
+
@staticmethod
|
|
254
|
+
def _parse_aria_label(aria_label: str) -> Dict[str, Any]:
|
|
255
|
+
"""Parse aria-label to extract data values."""
|
|
256
|
+
data = {}
|
|
257
|
+
if not aria_label:
|
|
258
|
+
return data
|
|
259
|
+
parts = aria_label.split(";")
|
|
260
|
+
for part in parts:
|
|
261
|
+
if ":" in part:
|
|
262
|
+
key, value = part.split(":", 1)
|
|
263
|
+
data[key.strip()] = CrossPlatformMetadataExporter._try_parse_number(
|
|
264
|
+
value.strip()
|
|
265
|
+
)
|
|
266
|
+
return data
|
|
267
|
+
|
|
268
|
+
@staticmethod
|
|
269
|
+
def _try_parse_number(value: str) -> Union[float, int, str]:
|
|
270
|
+
try:
|
|
271
|
+
if "." in value:
|
|
272
|
+
return float(value)
|
|
273
|
+
return int(value)
|
|
274
|
+
except ValueError:
|
|
275
|
+
return value
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
from typing import List, Optional
|
|
2
|
+
from biotrainer_core.data_classes import SequenceData
|
|
3
|
+
|
|
4
|
+
from .constants import DISCRETE_THRESHOLD
|
|
5
|
+
|
|
6
|
+
# Helper for SequenceData, move to biotrainer_core later
|
|
7
|
+
class SequenceDataUtils:
|
|
8
|
+
DELIMITERS = [";", ","]
|
|
9
|
+
|
|
10
|
+
def __init__(self, sequence_data: List[SequenceData]):
|
|
11
|
+
self._sequence_data = sequence_data
|
|
12
|
+
self._is_per_residue = None
|
|
13
|
+
self._is_discrete = None
|
|
14
|
+
self._maybe_delimiter = None
|
|
15
|
+
|
|
16
|
+
def _maybe_label_delimiter(self) -> Optional[str]:
|
|
17
|
+
if self._maybe_delimiter:
|
|
18
|
+
return self._maybe_delimiter
|
|
19
|
+
|
|
20
|
+
for seq_record in self._sequence_data:
|
|
21
|
+
label = seq_record.label
|
|
22
|
+
if label is not None:
|
|
23
|
+
for delimiter in self.DELIMITERS:
|
|
24
|
+
if delimiter in label:
|
|
25
|
+
self._maybe_delimiter = delimiter
|
|
26
|
+
return delimiter
|
|
27
|
+
return None
|
|
28
|
+
|
|
29
|
+
def is_per_residue(self) -> bool:
|
|
30
|
+
if self._is_per_residue is not None:
|
|
31
|
+
return self._is_per_residue
|
|
32
|
+
maybe_delimiter = self._maybe_label_delimiter()
|
|
33
|
+
is_per_residue = all(
|
|
34
|
+
[
|
|
35
|
+
len(seq.label or "") == len(seq.seq or "") or (maybe_delimiter in (seq.label or "") if maybe_delimiter else False)
|
|
36
|
+
for seq in self._sequence_data
|
|
37
|
+
]
|
|
38
|
+
)
|
|
39
|
+
self._is_per_residue = is_per_residue
|
|
40
|
+
return is_per_residue
|
|
41
|
+
|
|
42
|
+
def is_discrete(self) -> bool:
|
|
43
|
+
if self._is_discrete is not None:
|
|
44
|
+
return self._is_discrete
|
|
45
|
+
|
|
46
|
+
is_per_residue = self.is_per_residue()
|
|
47
|
+
labels_set = set()
|
|
48
|
+
if is_per_residue:
|
|
49
|
+
delimiter = self._maybe_label_delimiter()
|
|
50
|
+
for seq_record in self._sequence_data:
|
|
51
|
+
label = seq_record.label
|
|
52
|
+
if label is None:
|
|
53
|
+
continue
|
|
54
|
+
labels = label.split(delimiter)
|
|
55
|
+
if len(labels) == 1: # No delimiter
|
|
56
|
+
labels = list(labels[0])
|
|
57
|
+
labels_set.update(labels)
|
|
58
|
+
else:
|
|
59
|
+
labels_set = {seq_record.label for seq_record in self._sequence_data if seq_record.label is not None}
|
|
60
|
+
is_discrete = len(labels_set) < DISCRETE_THRESHOLD
|
|
61
|
+
self._is_discrete = is_discrete
|
|
62
|
+
return is_discrete
|
|
63
|
+
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import tempfile
|
|
2
|
+
import altair as alt
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from biocentral_api import ProjectionResult
|
|
6
|
+
from typing import List, Union, Dict, Any, Optional, Set, Callable
|
|
7
|
+
from biotrainer_core.data_classes import SequenceData, BiotrainerModelResult, Variant, VariantScore
|
|
8
|
+
|
|
9
|
+
from .base import BiocentralVisualization
|
|
10
|
+
from .datasets import (
|
|
11
|
+
plot_label_distribution,
|
|
12
|
+
plot_split_distribution,
|
|
13
|
+
plot_labels_by_split_distribution,
|
|
14
|
+
plot_sequence_length_distribution,
|
|
15
|
+
plot_mutation_depth_distribution,
|
|
16
|
+
plot_variant_score_distribution,
|
|
17
|
+
)
|
|
18
|
+
from .projections import plot_projection_result
|
|
19
|
+
from .models import plot_test_set_performance, plot_loss_curves
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class BiocentralChart(BiocentralVisualization):
|
|
23
|
+
def __init__(self, default_chart_name: str, chart: alt.Chart, metadata: Dict[str, Any]):
|
|
24
|
+
self._default_chart_name = default_chart_name
|
|
25
|
+
self.chart = chart
|
|
26
|
+
self.metadata = metadata
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def sequence_length_distribution(cls, dataset: List[SequenceData]):
|
|
30
|
+
chart, metadata = plot_sequence_length_distribution(dataset)
|
|
31
|
+
return cls("sequence_length_distribution", chart, metadata)
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def label_distribution(cls, dataset: List[SequenceData],
|
|
35
|
+
labels_filter: Optional[Callable[[str], bool]] = None):
|
|
36
|
+
""" Plot the distribution of labels in the dataset.
|
|
37
|
+
Filter function must return True if the label should be considered for plotting. """
|
|
38
|
+
chart, metadata = plot_label_distribution(dataset, labels_filter)
|
|
39
|
+
return cls("label_distribution", chart, metadata)
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
def split_distribution(cls, dataset: List[SequenceData]):
|
|
43
|
+
chart, metadata = plot_split_distribution(dataset)
|
|
44
|
+
return cls("split_distribution", chart, metadata)
|
|
45
|
+
|
|
46
|
+
@classmethod
|
|
47
|
+
def labels_by_split_distribution(cls, dataset: List[SequenceData],
|
|
48
|
+
labels_filter: Optional[Callable[[str], bool]] = None):
|
|
49
|
+
""" Plot the distribution of labels in the dataset by training/val/test split.
|
|
50
|
+
Filter function must return True if the label should be considered for plotting. """
|
|
51
|
+
chart, metadata = plot_labels_by_split_distribution(dataset, labels_filter)
|
|
52
|
+
return cls("labels_by_split_distribution", chart, metadata)
|
|
53
|
+
|
|
54
|
+
@classmethod
|
|
55
|
+
def mutation_depth_distribution(cls, dataset: List[Variant]):
|
|
56
|
+
chart, metadata = plot_mutation_depth_distribution(dataset)
|
|
57
|
+
return cls("mutation_depth_distribution", chart, metadata)
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def variant_score_distribution(cls, dataset: List[VariantScore]):
|
|
61
|
+
chart, metadata = plot_variant_score_distribution(dataset)
|
|
62
|
+
return cls("variant_score_distribution", chart, metadata)
|
|
63
|
+
|
|
64
|
+
@classmethod
|
|
65
|
+
def model_loss_curve(
|
|
66
|
+
cls, model_result: BiotrainerModelResult, cv_split: str = "hold_out"
|
|
67
|
+
):
|
|
68
|
+
chart, metadata = plot_loss_curves(model_result, cv_split)
|
|
69
|
+
return cls("model_loss_curve", chart, metadata)
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def model_test_set_performance(
|
|
73
|
+
cls, model_result: BiotrainerModelResult, metric_name: str
|
|
74
|
+
):
|
|
75
|
+
chart, metadata = plot_test_set_performance(model_result, metric_name)
|
|
76
|
+
return cls("model_test_set_performance", chart, metadata)
|
|
77
|
+
|
|
78
|
+
@classmethod
|
|
79
|
+
def projection_result(
|
|
80
|
+
cls,
|
|
81
|
+
projection_result: ProjectionResult,
|
|
82
|
+
dataset: List[SequenceData],
|
|
83
|
+
color_attribute: str = "TARGET",
|
|
84
|
+
highlight_ids: Optional[Set[str]] = None,
|
|
85
|
+
highlight_name: Optional[str] = "highlight",
|
|
86
|
+
):
|
|
87
|
+
chart, metadata = plot_projection_result(
|
|
88
|
+
projection_result,
|
|
89
|
+
dataset,
|
|
90
|
+
color_attribute=color_attribute,
|
|
91
|
+
highlight_ids=highlight_ids,
|
|
92
|
+
highlight_name=highlight_name,
|
|
93
|
+
)
|
|
94
|
+
return cls("projection_result", chart, metadata)
|
|
95
|
+
|
|
96
|
+
def to_svg(self) -> str:
|
|
97
|
+
with tempfile.NamedTemporaryFile(suffix=".svg", delete=False) as tmp:
|
|
98
|
+
self.chart.save(tmp.name)
|
|
99
|
+
tmp_path = Path(tmp.name)
|
|
100
|
+
svg_content = tmp_path.read_text()
|
|
101
|
+
tmp_path.unlink()
|
|
102
|
+
return svg_content
|
|
103
|
+
|
|
104
|
+
def to_png(self) -> bytes:
|
|
105
|
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
|
|
106
|
+
self.chart.save(tmp.name)
|
|
107
|
+
tmp_path = Path(tmp.name)
|
|
108
|
+
png_bytes = tmp_path.read_bytes()
|
|
109
|
+
tmp_path.unlink()
|
|
110
|
+
return png_bytes
|
|
111
|
+
|
|
112
|
+
def get_chart(self) -> Optional[alt.Chart]:
|
|
113
|
+
return self.chart
|
|
114
|
+
|
|
115
|
+
def save(self, output_path: Union[str, Path]):
|
|
116
|
+
output_path = Path(output_path)
|
|
117
|
+
if output_path.is_dir():
|
|
118
|
+
output_path = output_path / f"{self._default_chart_name}.svg"
|
|
119
|
+
format = "svg"
|
|
120
|
+
else:
|
|
121
|
+
format = output_path.suffix.strip(".")
|
|
122
|
+
self.chart.save(output_path, format=format)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Dict, Optional, Any, Union
|
|
3
|
+
from biocentral_api import Prediction
|
|
4
|
+
|
|
5
|
+
from .base import BiocentralVisualization
|
|
6
|
+
from .predictions import highlight_prediction
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class BiocentralHighlight(BiocentralVisualization):
|
|
10
|
+
"""Visualize sequence with per-residue predictions as colored highlights"""
|
|
11
|
+
|
|
12
|
+
def __init__(
|
|
13
|
+
self,
|
|
14
|
+
svg: str,
|
|
15
|
+
metadata: Dict[str, Any],
|
|
16
|
+
):
|
|
17
|
+
self.svg = svg
|
|
18
|
+
self.metadata = metadata
|
|
19
|
+
|
|
20
|
+
# Color schemes for common prediction types
|
|
21
|
+
@classmethod
|
|
22
|
+
def from_prediction(
|
|
23
|
+
cls,
|
|
24
|
+
sequence: str,
|
|
25
|
+
prediction: Prediction,
|
|
26
|
+
title: Optional[str] = None,
|
|
27
|
+
residues_per_line: int = 100,
|
|
28
|
+
):
|
|
29
|
+
"""Factory method to create highlight from prediction"""
|
|
30
|
+
svg, metadata = highlight_prediction(
|
|
31
|
+
sequence=sequence,
|
|
32
|
+
prediction=prediction,
|
|
33
|
+
title=title,
|
|
34
|
+
residues_per_line=residues_per_line,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
return cls(svg, metadata)
|
|
38
|
+
|
|
39
|
+
def to_svg(self) -> str:
|
|
40
|
+
return self.svg
|
|
41
|
+
|
|
42
|
+
def save(self, output_path: Union[str, Path]):
|
|
43
|
+
with open(output_path, "w") as f:
|
|
44
|
+
f.write(self.svg)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from .label_distribution import plot_label_distribution
|
|
2
|
+
from .labels_by_split_distribution import plot_labels_by_split_distribution
|
|
3
|
+
from .split_distribution import plot_split_distribution
|
|
4
|
+
from .sequence_length_distribution import plot_sequence_length_distribution
|
|
5
|
+
from .mutation_depth_distribution import plot_mutation_depth_distribution
|
|
6
|
+
from .variant_score_distribution import plot_variant_score_distribution
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"plot_label_distribution",
|
|
10
|
+
"plot_labels_by_split_distribution",
|
|
11
|
+
"plot_split_distribution",
|
|
12
|
+
"plot_sequence_length_distribution",
|
|
13
|
+
"plot_mutation_depth_distribution",
|
|
14
|
+
"plot_variant_score_distribution",
|
|
15
|
+
]
|