syd 0.1.4__py3-none-any.whl → 0.1.6__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.
@@ -0,0 +1 @@
1
+ from .deployer import NotebookDeployment
@@ -0,0 +1,254 @@
1
+ from typing import Dict, Any, Optional, cast
2
+ from dataclasses import dataclass
3
+ from contextlib import contextmanager
4
+ import ipywidgets as widgets
5
+ from IPython.display import display
6
+ import matplotlib.pyplot as plt
7
+ import warnings
8
+ from ..parameters import ParameterUpdateWarning
9
+
10
+ from ..interactive_viewer import InteractiveViewer
11
+ from .widgets import BaseWidget, create_widget
12
+
13
+
14
+ @contextmanager
15
+ def _plot_context():
16
+ plt.ioff()
17
+ try:
18
+ yield
19
+ finally:
20
+ plt.ion()
21
+
22
+
23
+ @dataclass
24
+ class LayoutConfig:
25
+ """Configuration for the viewer layout."""
26
+
27
+ controls_position: str = "left" # Options are: 'left', 'top'
28
+ figure_width: float = 8.0
29
+ figure_height: float = 6.0
30
+ controls_width_percent: int = 30
31
+
32
+ def __post_init__(self):
33
+ valid_positions = ["left", "top"]
34
+ if self.controls_position not in valid_positions:
35
+ raise ValueError(
36
+ f"Invalid controls position: {self.controls_position}. Must be one of {valid_positions}"
37
+ )
38
+
39
+ @property
40
+ def is_horizontal(self) -> bool:
41
+ return self.controls_position == "left"
42
+
43
+
44
+ class NotebookDeployment:
45
+ """
46
+ A deployment system for InteractiveViewer in Jupyter notebooks using ipywidgets.
47
+ Built around the parameter widget system for clean separation of concerns.
48
+ """
49
+
50
+ def __init__(
51
+ self,
52
+ viewer: InteractiveViewer,
53
+ layout_config: Optional[LayoutConfig] = None,
54
+ continuous: bool = False,
55
+ suppress_warnings: bool = False,
56
+ ):
57
+ if not isinstance(viewer, InteractiveViewer): # type: ignore
58
+ raise TypeError(
59
+ f"viewer must be an InteractiveViewer, got {type(viewer).__name__}"
60
+ )
61
+
62
+ self.viewer = viewer
63
+ self.config = layout_config or LayoutConfig()
64
+ self.continuous = continuous
65
+ self.suppress_warnings = suppress_warnings
66
+
67
+ # Initialize containers
68
+ self.parameter_widgets: Dict[str, BaseWidget] = {}
69
+ self.layout_widgets = self._create_layout_controls()
70
+ self.plot_output = widgets.Output()
71
+
72
+ # Store current figure
73
+ self._current_figure = None
74
+ # Flag to prevent circular updates
75
+ self._updating = False
76
+
77
+ def _create_layout_controls(self) -> Dict[str, widgets.Widget]:
78
+ """Create widgets for controlling the layout."""
79
+ controls: Dict[str, widgets.Widget] = {}
80
+
81
+ # Controls width slider for horizontal layouts
82
+ if self.config.is_horizontal:
83
+ controls["controls_width"] = widgets.IntSlider(
84
+ value=self.config.controls_width_percent,
85
+ min=20,
86
+ max=80,
87
+ description="Controls Width %",
88
+ continuous=True,
89
+ layout=widgets.Layout(width="95%"),
90
+ style={"description_width": "initial"},
91
+ )
92
+ controls["controls_width"].observe(
93
+ self._handle_container_width_change, names="value"
94
+ )
95
+
96
+ return controls
97
+
98
+ def _create_parameter_widgets(self) -> None:
99
+ """Create widget instances for all parameters."""
100
+ for name, param in self.viewer.parameters.items():
101
+ widget = create_widget(
102
+ param,
103
+ continuous=self.continuous,
104
+ )
105
+
106
+ # Store in widget dict
107
+ self.parameter_widgets[name] = widget
108
+
109
+ def _handle_widget_engagement(self, name: str) -> None:
110
+ """Handle engagement with an interactive widget."""
111
+ if self._updating:
112
+ print(
113
+ "Already updating -- there's a circular dependency!"
114
+ "This is probably caused by failing to disable callbacks for a parameter."
115
+ "It's a bug --- tell the developer on github issues please."
116
+ )
117
+ return
118
+
119
+ try:
120
+ self._updating = True
121
+
122
+ # Optionally suppress warnings during parameter updates
123
+ with warnings.catch_warnings():
124
+ if self.suppress_warnings:
125
+ warnings.filterwarnings("ignore", category=ParameterUpdateWarning)
126
+
127
+ widget = self.parameter_widgets[name]
128
+
129
+ if widget._is_action:
130
+ parameter = self.viewer.parameters[name]
131
+ parameter.callback(self.viewer.get_state())
132
+ else:
133
+ self.viewer.set_parameter_value(name, widget.value)
134
+
135
+ # Update any widgets that changed due to dependencies
136
+ self._sync_widgets_with_state(exclude=name)
137
+
138
+ # Update the plot
139
+ self._update_plot()
140
+
141
+ finally:
142
+ self._updating = False
143
+
144
+ def _handle_action(self, name: str) -> None:
145
+ """Handle actions for parameter widgets."""
146
+
147
+ def _sync_widgets_with_state(self, exclude: Optional[str] = None) -> None:
148
+ """Sync widget values with viewer state."""
149
+ for name, parameter in self.viewer.parameters.items():
150
+ if name == exclude:
151
+ continue
152
+
153
+ widget = self.parameter_widgets[name]
154
+ if not widget.matches_parameter(parameter):
155
+ widget.update_from_parameter(parameter)
156
+
157
+ def _handle_figure_size_change(self, change: Dict[str, Any]) -> None:
158
+ """Handle changes to figure dimensions."""
159
+ if self._current_figure is None:
160
+ return
161
+
162
+ self._redraw_plot()
163
+
164
+ def _handle_container_width_change(self, change: Dict[str, Any]) -> None:
165
+ """Handle changes to container width proportions."""
166
+ width_percent = self.layout_widgets["controls_width"].value
167
+ self.config.controls_width_percent = width_percent
168
+
169
+ # Update container widths
170
+ self.widgets_container.layout.width = f"{width_percent}%"
171
+ self.plot_container.layout.width = f"{100 - width_percent}%"
172
+
173
+ def _update_plot(self) -> None:
174
+ """Update the plot with current state."""
175
+ state = self.viewer.get_state()
176
+
177
+ with _plot_context():
178
+ new_fig = self.viewer.plot(state)
179
+ plt.close(self._current_figure) # Close old figure
180
+ self._current_figure = new_fig
181
+
182
+ self._redraw_plot()
183
+
184
+ def _redraw_plot(self) -> None:
185
+ """Clear and redraw the plot in the output widget."""
186
+ self.plot_output.clear_output(wait=True)
187
+ with self.plot_output:
188
+ display(self._current_figure)
189
+
190
+ def _create_layout(self) -> widgets.Widget:
191
+ """Create the main layout combining controls and plot."""
192
+ # Create layout controls section
193
+ layout_box = widgets.VBox(
194
+ [widgets.HTML("<b>Layout Controls</b>")]
195
+ + list(self.layout_widgets.values()),
196
+ layout=widgets.Layout(margin="10px 0px"),
197
+ )
198
+
199
+ # Set up parameter widgets with their observe callbacks
200
+ for name, widget in self.parameter_widgets.items():
201
+ widget.observe(lambda change, n=name: self._handle_widget_engagement(n))
202
+
203
+ # Create parameter controls section
204
+ param_box = widgets.VBox(
205
+ [widgets.HTML("<b>Parameters</b>")]
206
+ + [w.widget for w in self.parameter_widgets.values()],
207
+ layout=widgets.Layout(margin="10px 0px"),
208
+ )
209
+
210
+ # Combine all controls
211
+ self.widgets_container = widgets.VBox(
212
+ [param_box, layout_box],
213
+ layout=widgets.Layout(
214
+ width=(
215
+ f"{self.config.controls_width_percent}%"
216
+ if self.config.is_horizontal
217
+ else "100%"
218
+ ),
219
+ padding="10px",
220
+ overflow_y="auto",
221
+ ),
222
+ )
223
+
224
+ # Create plot container
225
+ self.plot_container = widgets.VBox(
226
+ [self.plot_output],
227
+ layout=widgets.Layout(
228
+ width=(
229
+ f"{100 - self.config.controls_width_percent}%"
230
+ if self.config.is_horizontal
231
+ else "100%"
232
+ ),
233
+ padding="10px",
234
+ ),
235
+ )
236
+
237
+ # Create final layout based on configuration
238
+ if self.config.controls_position == "left":
239
+ return widgets.HBox([self.widgets_container, self.plot_container])
240
+ else:
241
+ return widgets.VBox([self.widgets_container, self.plot_container])
242
+
243
+ def deploy(self) -> None:
244
+ """Deploy the interactive viewer with proper state management."""
245
+ with self.viewer._deploy_app():
246
+ # Create widgets
247
+ self._create_parameter_widgets()
248
+
249
+ # Create and display layout
250
+ layout = self._create_layout()
251
+ display(layout)
252
+
253
+ # Create initial plot
254
+ self._update_plot()