shinymap 0.1.0a1__py3-none-any.whl

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.
shinymap/__init__.py ADDED
@@ -0,0 +1,36 @@
1
+ __version__ = "0.0.1"
2
+
3
+ """Core Shiny for Python bindings for the shinymap renderer."""
4
+
5
+ from ._colors import (
6
+ NEUTRALS,
7
+ QUALITATIVE,
8
+ SEQUENTIAL_BLUE,
9
+ SEQUENTIAL_GREEN,
10
+ SEQUENTIAL_ORANGE,
11
+ lerp_hex,
12
+ scale_diverging,
13
+ scale_qualitative,
14
+ scale_sequential,
15
+ )
16
+ from ._ui import Map, MapBuilder, MapPayload, input_map, output_map, render_map
17
+
18
+ __all__ = [
19
+ "__version__",
20
+ "Map",
21
+ "MapBuilder",
22
+ "MapPayload",
23
+ "input_map",
24
+ "output_map",
25
+ "render_map",
26
+ # Color utilities
27
+ "NEUTRALS",
28
+ "QUALITATIVE",
29
+ "SEQUENTIAL_BLUE",
30
+ "SEQUENTIAL_GREEN",
31
+ "SEQUENTIAL_ORANGE",
32
+ "lerp_hex",
33
+ "scale_sequential",
34
+ "scale_diverging",
35
+ "scale_qualitative",
36
+ ]
shinymap/_colors.py ADDED
@@ -0,0 +1,181 @@
1
+ """Color scale utilities for shinymap."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Mapping
6
+
7
+ # Tailwind-inspired color palettes
8
+ NEUTRALS = {
9
+ "stroke": "#1f2937", # slate-800
10
+ "stroke_active": "#0f172a", # slate-900
11
+ "fill": "#e2e8f0", # slate-200
12
+ }
13
+
14
+ QUALITATIVE = [
15
+ "#2563eb", # blue-600
16
+ "#16a34a", # green-600
17
+ "#f59e0b", # amber-500
18
+ "#ef4444", # red-500
19
+ "#a855f7", # purple-500
20
+ "#06b6d4", # cyan-500
21
+ ]
22
+
23
+ SEQUENTIAL_BLUE = ["#eff6ff", "#bfdbfe", "#93c5fd", "#60a5fa", "#3b82f6", "#2563eb", "#1d4ed8"]
24
+ SEQUENTIAL_GREEN = ["#ecfdf3", "#bbf7d0", "#86efac", "#4ade80", "#22c55e", "#16a34a", "#15803d"]
25
+ SEQUENTIAL_ORANGE = ["#fff7ed", "#ffedd5", "#fed7aa", "#fdba74", "#fb923c", "#f97316", "#c2410c"]
26
+
27
+
28
+ def lerp_hex(start: str, end: str, t: float) -> str:
29
+ """Interpolate between two hex colors.
30
+
31
+ Args:
32
+ start: Starting hex color (e.g., "#ff0000")
33
+ end: Ending hex color (e.g., "#00ff00")
34
+ t: Interpolation factor, clamped to [0, 1]
35
+
36
+ Returns:
37
+ Interpolated hex color
38
+ """
39
+ t = max(0.0, min(1.0, t))
40
+ s_rgb = tuple(int(start[i : i + 2], 16) for i in (1, 3, 5))
41
+ e_rgb = tuple(int(end[i : i + 2], 16) for i in (1, 3, 5))
42
+ mix = tuple(int(s + (e - s) * t) for s, e in zip(s_rgb, e_rgb))
43
+ return f"#{mix[0]:02x}{mix[1]:02x}{mix[2]:02x}"
44
+
45
+
46
+ def scale_sequential(
47
+ counts: Mapping[str, int],
48
+ region_ids: list[str],
49
+ palette: list[str] = SEQUENTIAL_BLUE,
50
+ neutral_color: str = NEUTRALS["fill"],
51
+ max_count: int | None = None,
52
+ ) -> dict[str, str]:
53
+ """Create a sequential color scale based on counts.
54
+
55
+ Regions with count=0 get the neutral color.
56
+ Regions with counts are colored from palette[0] (low) to palette[-1] (high).
57
+
58
+ Args:
59
+ counts: Mapping of region_id to count
60
+ region_ids: All region IDs to include
61
+ palette: Color palette to use (default: SEQUENTIAL_BLUE)
62
+ neutral_color: Color for regions with count=0
63
+ max_count: Fixed maximum for scaling. If None, uses dynamic max from counts.
64
+ For interactive visualizations, use a fixed value to prevent
65
+ other regions from changing color when one region is clicked.
66
+
67
+ Returns:
68
+ Mapping of region_id to hex color
69
+ """
70
+ # Determine the maximum count for scaling
71
+ if max_count is None:
72
+ # Dynamic: use the actual maximum from current counts
73
+ max_count = max(counts.values(), default=0)
74
+
75
+ if max_count <= 0:
76
+ return {region_id: neutral_color for region_id in region_ids}
77
+
78
+ fills = {}
79
+ for region_id in region_ids:
80
+ count = counts.get(region_id, 0)
81
+ # Use continuous color interpolation for smooth visual feedback
82
+ # Interpolate between palette colors based on count
83
+ if count == 0:
84
+ fills[region_id] = palette[0]
85
+ elif count >= max_count:
86
+ fills[region_id] = palette[-1]
87
+ else:
88
+ # Map count to continuous position in palette
89
+ t = count / max_count # Normalize to [0, 1]
90
+ palette_pos = t * (len(palette) - 1) # Map to [0, palette_size-1]
91
+
92
+ # Interpolate between adjacent palette colors
93
+ lower_idx = int(palette_pos)
94
+ upper_idx = min(lower_idx + 1, len(palette) - 1)
95
+ blend_factor = palette_pos - lower_idx # Fraction between colors
96
+
97
+ fills[region_id] = lerp_hex(palette[lower_idx], palette[upper_idx], blend_factor)
98
+
99
+ return fills
100
+
101
+
102
+ def scale_diverging(
103
+ values: Mapping[str, float],
104
+ region_ids: list[str],
105
+ low_color: str = "#ef4444", # red
106
+ mid_color: str = "#f3f4f6", # gray
107
+ high_color: str = "#3b82f6", # blue
108
+ midpoint: float = 0.0,
109
+ ) -> dict[str, str]:
110
+ """Create a diverging color scale (red-white-blue style).
111
+
112
+ Args:
113
+ values: Mapping of region_id to numeric value
114
+ region_ids: All region IDs to include
115
+ low_color: Color for low values
116
+ mid_color: Color for midpoint value
117
+ high_color: Color for high values
118
+ midpoint: Value that maps to mid_color
119
+
120
+ Returns:
121
+ Mapping of region_id to hex color
122
+ """
123
+ fills = {}
124
+ val_list = [v for v in values.values() if v is not None]
125
+ if not val_list:
126
+ return {region_id: mid_color for region_id in region_ids}
127
+
128
+ min_val, max_val = min(val_list), max(val_list)
129
+
130
+ for region_id in region_ids:
131
+ value = values.get(region_id)
132
+ if value is None:
133
+ fills[region_id] = mid_color
134
+ elif value <= midpoint:
135
+ # Interpolate from low_color to mid_color
136
+ if min_val < midpoint:
137
+ t = (value - min_val) / (midpoint - min_val)
138
+ else:
139
+ t = 0.0
140
+ fills[region_id] = lerp_hex(low_color, mid_color, t)
141
+ else:
142
+ # Interpolate from mid_color to high_color
143
+ if max_val > midpoint:
144
+ t = (value - midpoint) / (max_val - midpoint)
145
+ else:
146
+ t = 0.0
147
+ fills[region_id] = lerp_hex(mid_color, high_color, t)
148
+
149
+ return fills
150
+
151
+
152
+ def scale_qualitative(
153
+ categories: Mapping[str, str | None],
154
+ region_ids: list[str],
155
+ palette: list[str] = QUALITATIVE,
156
+ neutral_color: str = NEUTRALS["fill"],
157
+ ) -> dict[str, str]:
158
+ """Create a qualitative color scale for categorical data.
159
+
160
+ Args:
161
+ categories: Mapping of region_id to category name (or None)
162
+ region_ids: All region IDs to include
163
+ palette: Color palette to use (cycles if more categories than colors)
164
+ neutral_color: Color for regions with no category
165
+
166
+ Returns:
167
+ Mapping of region_id to hex color
168
+ """
169
+ # Build category -> color mapping
170
+ unique_cats = sorted({cat for cat in categories.values() if cat is not None})
171
+ cat_colors = {cat: palette[i % len(palette)] for i, cat in enumerate(unique_cats)}
172
+
173
+ fills = {}
174
+ for region_id in region_ids:
175
+ cat = categories.get(region_id)
176
+ if cat is None:
177
+ fills[region_id] = neutral_color
178
+ else:
179
+ fills[region_id] = cat_colors[cat]
180
+
181
+ return fills
shinymap/_ui.py ADDED
@@ -0,0 +1,306 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from dataclasses import asdict, dataclass
5
+ from functools import wraps
6
+ from typing import Any, Mapping, MutableMapping
7
+
8
+ from htmltools import HTMLDependency, Tag, TagList, css
9
+ from shiny import render, ui
10
+
11
+ from . import __version__
12
+
13
+ GeometryMap = Mapping[str, str]
14
+ TooltipMap = Mapping[str, str] | None
15
+ FillMap = Mapping[str, str] | None
16
+ CountMap = Mapping[str, int] | None
17
+ Selection = str | list[str] | None
18
+
19
+
20
+ def _dependency() -> HTMLDependency:
21
+ return HTMLDependency(
22
+ name="shinymap",
23
+ version=__version__,
24
+ source={"package": "shinymap", "subdir": "www"},
25
+ script=[{"src": "shinymap.global.js"}, {"src": "shinymap-shiny.js"}],
26
+ )
27
+
28
+
29
+ def _merge_styles(
30
+ width: str | None, height: str | None, style: MutableMapping[str, str] | None
31
+ ) -> MutableMapping[str, str]:
32
+ merged: MutableMapping[str, str] = {} if style is None else dict(style)
33
+ if width is not None:
34
+ merged.setdefault("width", width)
35
+ if height is not None:
36
+ merged.setdefault("height", height)
37
+ return merged
38
+
39
+
40
+ def _class_names(base: str, extra: str | None) -> str:
41
+ return f"{base} {extra}" if extra else base
42
+
43
+
44
+ def _drop_nones(data: MutableMapping[str, Any]) -> MutableMapping[str, Any]:
45
+ return {k: v for k, v in data.items() if v is not None}
46
+
47
+
48
+ def _camel_props(data: MutableMapping[str, Any]) -> MutableMapping[str, Any]:
49
+ """Convert select snake_case keys to camelCase for the JS component API."""
50
+ mapping = {
51
+ "max_selection": "maxSelection",
52
+ "view_box": "viewBox",
53
+ "default_aesthetic": "defaultAesthetic",
54
+ "active_ids": "activeIds",
55
+ "hover_highlight": "hoverHighlight",
56
+ }
57
+ out: MutableMapping[str, Any] = {}
58
+ for key, value in data.items():
59
+ if value is None:
60
+ continue
61
+ out[mapping.get(key, key)] = value
62
+ return out
63
+
64
+
65
+ def input_map(
66
+ id: str,
67
+ geometry: GeometryMap,
68
+ *,
69
+ tooltips: TooltipMap = None,
70
+ fills: FillMap = None,
71
+ mode: str | None = "multiple",
72
+ value: CountMap = None,
73
+ cycle: int | None = None,
74
+ max_selection: int | None = None,
75
+ view_box: str | None = None,
76
+ default_aesthetic: Mapping[str, Any] | None = None,
77
+ hover_highlight: Mapping[str, Any] | None = None,
78
+ width: str | None = "100%",
79
+ height: str | None = "320px",
80
+ class_: str | None = None,
81
+ style: MutableMapping[str, str] | None = None,
82
+ ) -> TagList:
83
+ """Shiny input that emits region selections.
84
+
85
+ For mode="single": returns a string (single selected region ID) or None
86
+ For mode="multiple": returns a list of selected region IDs
87
+ For mode="count": returns a dict mapping region IDs to counts
88
+
89
+ The underlying value is always a count map (dict[str, int]), but Shiny
90
+ automatically transforms it based on the mode using a value function.
91
+ """
92
+ if mode not in {None, "single", "multiple", "count"}:
93
+ raise ValueError('mode must be one of "single", "multiple", "count", or None')
94
+
95
+ # Mode presets mirror the React InputMap defaults.
96
+ effective_cycle = cycle
97
+ effective_max_selection = max_selection
98
+ if mode == "single":
99
+ effective_cycle = 2 if cycle is None else cycle
100
+ effective_max_selection = 1 if max_selection is None else max_selection
101
+ elif mode == "multiple":
102
+ effective_cycle = 2 if cycle is None else cycle
103
+ effective_max_selection = max_selection
104
+ elif mode == "count":
105
+ effective_cycle = cycle
106
+ effective_max_selection = max_selection
107
+
108
+ props = _camel_props(
109
+ {
110
+ "geometry": geometry,
111
+ "tooltips": tooltips,
112
+ "fills": fills,
113
+ "mode": mode,
114
+ "value": value,
115
+ "cycle": effective_cycle,
116
+ "max_selection": effective_max_selection,
117
+ "view_box": view_box,
118
+ "default_aesthetic": default_aesthetic,
119
+ "hover_highlight": hover_highlight,
120
+ }
121
+ )
122
+
123
+ # Store mode in data attribute for value transformation
124
+ div = ui.div(
125
+ id=id,
126
+ class_=_class_names("shinymap-input", class_),
127
+ style=css(**_merge_styles(width, height, style)),
128
+ data_shinymap_input="1",
129
+ data_shinymap_input_id=id,
130
+ data_shinymap_input_mode=mode, # Store mode for JS value transformation
131
+ data_shinymap_props=json.dumps(props),
132
+ )
133
+
134
+ return TagList(_dependency(), div)
135
+
136
+
137
+ @dataclass
138
+ class MapPayload:
139
+ geometry: GeometryMap
140
+ tooltips: TooltipMap = None
141
+ fills: FillMap = None
142
+ counts: CountMap = None
143
+ active_ids: Selection = None
144
+ view_box: str | None = None
145
+ default_aesthetic: Mapping[str, Any] | None = None
146
+
147
+ def as_json(self) -> Mapping[str, Any]:
148
+ return _camel_props(_drop_nones(asdict(self)))
149
+
150
+
151
+ class MapBuilder:
152
+ """Fluent builder for constructing map payloads with method chaining.
153
+
154
+ Example:
155
+ @render_map
156
+ def my_map():
157
+ return (
158
+ Map(geometry, tooltips=tooltips)
159
+ .with_fills(my_fills)
160
+ .with_counts(my_counts)
161
+ .with_active(selected_ids)
162
+ )
163
+ """
164
+
165
+ def __init__(
166
+ self,
167
+ geometry: GeometryMap,
168
+ *,
169
+ tooltips: TooltipMap = None,
170
+ view_box: str | None = None,
171
+ ):
172
+ self._geometry = geometry
173
+ self._tooltips = tooltips
174
+ self._fills: FillMap = None
175
+ self._counts: CountMap = None
176
+ self._active_ids: Selection = None
177
+ self._view_box = view_box
178
+ self._default_aesthetic: Mapping[str, Any] | None = None
179
+
180
+ def with_tooltips(self, tooltips: TooltipMap) -> "MapBuilder":
181
+ """Set region tooltips."""
182
+ self._tooltips = tooltips
183
+ return self
184
+
185
+ def with_fills(self, fills: FillMap) -> "MapBuilder":
186
+ """Set region fill colors."""
187
+ self._fills = fills
188
+ return self
189
+
190
+ def with_counts(self, counts: CountMap) -> "MapBuilder":
191
+ """Set region count badges."""
192
+ self._counts = counts
193
+ return self
194
+
195
+ def with_active(self, active_ids: Selection) -> "MapBuilder":
196
+ """Set active/highlighted region IDs."""
197
+ self._active_ids = active_ids
198
+ return self
199
+
200
+ def with_view_box(self, view_box: str) -> "MapBuilder":
201
+ """Set the SVG viewBox."""
202
+ self._view_box = view_box
203
+ return self
204
+
205
+ def with_stroke_width(self, width: float) -> "MapBuilder":
206
+ """Set stroke width for all regions."""
207
+ if self._default_aesthetic is None:
208
+ self._default_aesthetic = {}
209
+ self._default_aesthetic = {**self._default_aesthetic, "strokeWidth": width}
210
+ return self
211
+
212
+ def with_aesthetic(self, **kwargs: Any) -> "MapBuilder":
213
+ """Set default aesthetic properties (strokeWidth, fillOpacity, etc.)."""
214
+ if self._default_aesthetic is None:
215
+ self._default_aesthetic = {}
216
+ self._default_aesthetic = {**self._default_aesthetic, **kwargs}
217
+ return self
218
+
219
+ def build(self) -> MapPayload:
220
+ """Build and return the MapPayload."""
221
+ return MapPayload(
222
+ geometry=self._geometry,
223
+ tooltips=self._tooltips,
224
+ fills=self._fills,
225
+ counts=self._counts,
226
+ active_ids=self._active_ids,
227
+ view_box=self._view_box,
228
+ default_aesthetic=self._default_aesthetic,
229
+ )
230
+
231
+ def as_json(self) -> Mapping[str, Any]:
232
+ """Convert to JSON dict (for use with render_map)."""
233
+ return self.build().as_json()
234
+
235
+
236
+ # Alias for more concise usage
237
+ Map = MapBuilder
238
+
239
+
240
+ def _render_map_ui(
241
+ payload: MapPayload | MapBuilder,
242
+ *,
243
+ width: str | None = "100%",
244
+ height: str | None = "320px",
245
+ class_: str | None = None,
246
+ style: MutableMapping[str, str] | None = None,
247
+ click_input_id: str | None = None,
248
+ _include_dependency: bool = True,
249
+ ) -> Tag | TagList:
250
+ """Internal: Render a map payload to HTML. Used by @render_map decorator."""
251
+ if isinstance(payload, (Tag, TagList)):
252
+ if _include_dependency:
253
+ return TagList(_dependency(), payload)
254
+ return payload
255
+
256
+ payload_dict = payload.as_json()
257
+ div = ui.div(
258
+ class_=_class_names("shinymap-output", class_),
259
+ style=css(**_merge_styles(width, height, style)),
260
+ data_shinymap_output="1",
261
+ data_shinymap_payload=json.dumps(payload_dict),
262
+ data_shinymap_click_input_id=click_input_id if click_input_id else None,
263
+ )
264
+
265
+ if _include_dependency:
266
+ return TagList(_dependency(), div)
267
+ return div
268
+
269
+
270
+ def output_map(
271
+ id: str,
272
+ *,
273
+ width: str | None = "100%",
274
+ height: str | None = "320px",
275
+ class_: str | None = None,
276
+ style: MutableMapping[str, str] | None = None,
277
+ ) -> TagList:
278
+ """UI placeholder for a ``@render_map`` output."""
279
+ return TagList(
280
+ _dependency(),
281
+ ui.div(
282
+ ui.output_ui(id),
283
+ class_=_class_names("shinymap-output-container", class_),
284
+ style=css(**_merge_styles(width, height, style)),
285
+ ),
286
+ )
287
+
288
+
289
+ def render_map(fn=None):
290
+ """Shiny render decorator that emits a :class:`MapBuilder` or :class:`MapPayload`."""
291
+
292
+ def decorator(func):
293
+ @render.ui
294
+ @wraps(func)
295
+ def wrapper():
296
+ val = func()
297
+ result = _render_map_ui(val, _include_dependency=False)
298
+ print(f"[shinymap] render_map {func.__name__} type={type(val)} result={type(result)}")
299
+ return result
300
+
301
+ return wrapper
302
+
303
+ if fn is None:
304
+ return decorator
305
+
306
+ return decorator(fn)