|
| 1 | +# Copyright (C) 2021 - 2025 ANSYS, Inc. and/or its affiliates. |
| 2 | +# SPDX-License-Identifier: MIT |
| 3 | +# |
| 4 | +# |
| 5 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 6 | +# of this software and associated documentation files (the "Software"), to deal |
| 7 | +# in the Software without restriction, including without limitation the rights |
| 8 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 9 | +# copies of the Software, and to permit persons to whom the Software is |
| 10 | +# furnished to do so, subject to the following conditions: |
| 11 | +# |
| 12 | +# The above copyright notice and this permission notice shall be included in all |
| 13 | +# copies or substantial portions of the Software. |
| 14 | +# |
| 15 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 16 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 17 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 18 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 19 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 20 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 21 | +# SOFTWARE. |
| 22 | + |
| 23 | +"""Render ui UI in Jupyter notebook.""" |
| 24 | + |
| 25 | +from ansys.fluent.core.ui.utils import ( |
| 26 | + _parse_path, |
| 27 | + _render_widget_from_props_generic, |
| 28 | + _safe_get_properties, |
| 29 | +) |
| 30 | + |
| 31 | +try: |
| 32 | + import ipywidgets as widgets |
| 33 | +except ModuleNotFoundError as exc: |
| 34 | + raise ModuleNotFoundError( |
| 35 | + "Missing dependencies, use 'pip install ansys-fluent-core[ui-jupyter]' to install them." |
| 36 | + ) from exc |
| 37 | + |
| 38 | +from ansys.fluent.core.solver.flobject import ( |
| 39 | + BaseCommand, |
| 40 | + Group, |
| 41 | + NamedObject, |
| 42 | +) |
| 43 | + |
| 44 | + |
| 45 | +def set_auto_refresh(): |
| 46 | + """Refreshes the UI w.r.t. server state for each command execution or parameter invocation.""" |
| 47 | + raise NotImplementedError("This is yet to be implemented in jupyter environment.") |
| 48 | + |
| 49 | + |
| 50 | +def _render_widgets_from_props(settings_obj, label, props): |
| 51 | + """Render widget using pre-fetched props instead of repeated calls.""" |
| 52 | + return _render_widget_from_props_generic(settings_obj, label, props, widgets) |
| 53 | + |
| 54 | + |
| 55 | +def _param_ui(settings_obj, props): |
| 56 | + label = props["python_name"].replace("_", " ").capitalize() |
| 57 | + |
| 58 | + def get_fn(): |
| 59 | + try: |
| 60 | + return getattr(props["parent"], props["python_name"]) |
| 61 | + except AttributeError: |
| 62 | + return props["parent"][props["obj_name"]] |
| 63 | + |
| 64 | + def set_fn(v): |
| 65 | + return setattr(settings_obj.parent, props["python_name"], v) |
| 66 | + |
| 67 | + widget = _render_widgets_from_props(get_fn(), label, props) |
| 68 | + output = widgets.Output() |
| 69 | + with output: |
| 70 | + output.clear_output() |
| 71 | + print(_parse_path(settings_obj)) |
| 72 | + if hasattr(widget, "_is_list_text"): |
| 73 | + typ, parse_csv = widget._is_list_text |
| 74 | + |
| 75 | + def commit_text_list(change): |
| 76 | + if change["name"] == "value": |
| 77 | + raw = change["new"] |
| 78 | + vals = ( |
| 79 | + [typ(v.strip()) for v in raw.split(",") if v.strip()] |
| 80 | + if parse_csv |
| 81 | + else list(change["new"]) |
| 82 | + ) |
| 83 | + with output: |
| 84 | + output.clear_output() |
| 85 | + set_fn(vals) |
| 86 | + print(f"{_parse_path(settings_obj)} = {vals}") |
| 87 | + |
| 88 | + widget.observe(commit_text_list) |
| 89 | + else: |
| 90 | + |
| 91 | + def on_change(change): |
| 92 | + if change["name"] == "value": |
| 93 | + with output: |
| 94 | + output.clear_output() |
| 95 | + try: |
| 96 | + set_fn(change["new"]) |
| 97 | + print(f"{_parse_path(settings_obj)} = {change['new']}") |
| 98 | + except Exception as e: |
| 99 | + print(f"Error setting {label}: {e}") |
| 100 | + |
| 101 | + widget.observe(on_change) |
| 102 | + return widgets.VBox([widget, output]) |
| 103 | + |
| 104 | + |
| 105 | +def _command_ui(func, props): |
| 106 | + """ |
| 107 | + Renders input widgets for function arguments based on .argument_names() |
| 108 | + and executes func(**kwargs) on button click. |
| 109 | + """ |
| 110 | + |
| 111 | + # Get argument names from the function object |
| 112 | + if not hasattr(func, "argument_names"): |
| 113 | + return widgets.HTML("Command has no 'argument_names()'.") |
| 114 | + |
| 115 | + arg_names = func.argument_names |
| 116 | + arg_widgets = {} |
| 117 | + controls = [] |
| 118 | + for name in arg_names: |
| 119 | + child_obj = getattr(func, name) |
| 120 | + child_props = _safe_get_properties(child_obj) |
| 121 | + widget = _render_widgets_from_props(child_obj, name, child_props) |
| 122 | + arg_widgets[name] = widget |
| 123 | + controls.append(widget) |
| 124 | + |
| 125 | + # Run button |
| 126 | + button = widgets.Button( |
| 127 | + description=f"Run {props['python_name']}", button_style="success" |
| 128 | + ) |
| 129 | + output = widgets.Output() |
| 130 | + with output: |
| 131 | + output.clear_output() |
| 132 | + print(_parse_path(func)) |
| 133 | + |
| 134 | + def on_click(_): |
| 135 | + kwargs = {name: w.value for name, w in arg_widgets.items()} |
| 136 | + with output: |
| 137 | + output.clear_output() |
| 138 | + try: |
| 139 | + func(**kwargs) |
| 140 | + kwargs_str = "(" |
| 141 | + for k, v in kwargs.items(): |
| 142 | + if type(v) is str: |
| 143 | + if v != "": |
| 144 | + kwargs_str += f"{k}='{v}', " |
| 145 | + else: |
| 146 | + kwargs_str += f"{k}={v}, " |
| 147 | + print(f"{_parse_path(func)}" + kwargs_str.strip()[:-1] + ")") |
| 148 | + except Exception as e: |
| 149 | + print("Error:", e) |
| 150 | + |
| 151 | + button.on_click(on_click) |
| 152 | + return widgets.VBox(controls + [button, output]) |
| 153 | + |
| 154 | + |
| 155 | +def settings_ui(obj, indent=0): |
| 156 | + """Render settings objects into ui graphics.""" |
| 157 | + props = _safe_get_properties(obj) |
| 158 | + if isinstance(obj, (Group, NamedObject)): |
| 159 | + if isinstance(obj, Group): |
| 160 | + command_names = obj.get_active_command_names() |
| 161 | + child_names = obj.get_active_child_names() + command_names |
| 162 | + else: |
| 163 | + command_names = obj.command_names |
| 164 | + child_names = list(obj) + command_names |
| 165 | + accordions = [] |
| 166 | + for child_name in child_names: |
| 167 | + |
| 168 | + def lazy_loader(name=child_name, parent=obj, lvl=indent + 1): |
| 169 | + try: |
| 170 | + child_obj = getattr(parent, name) |
| 171 | + except AttributeError: |
| 172 | + child_obj = parent[name] |
| 173 | + return settings_ui(child_obj, lvl) |
| 174 | + |
| 175 | + acc = widgets.Accordion(children=[widgets.HTML("Loading...")]) |
| 176 | + if child_name in command_names: |
| 177 | + acc.set_title(0, f"⚡ {child_name}") |
| 178 | + else: |
| 179 | + acc.set_title(0, child_name) |
| 180 | + |
| 181 | + def on_selected(change, loader=lazy_loader, accordion=acc): |
| 182 | + if change["name"] == "selected_index" and change["new"] == 0: |
| 183 | + if isinstance(accordion.children[0], widgets.HTML): |
| 184 | + accordion.children = [loader()] |
| 185 | + |
| 186 | + acc.observe(on_selected, names="selected_index") |
| 187 | + accordions.append(acc) |
| 188 | + |
| 189 | + return widgets.VBox(accordions) |
| 190 | + |
| 191 | + else: |
| 192 | + if isinstance(obj, BaseCommand): |
| 193 | + return ( |
| 194 | + widgets.VBox([_command_ui(obj, props)]) |
| 195 | + if props["is_active"] |
| 196 | + else widgets.HTML("") |
| 197 | + ) |
| 198 | + else: |
| 199 | + return ( |
| 200 | + widgets.VBox([_param_ui(obj, props)]) |
| 201 | + if props["is_active"] |
| 202 | + else widgets.HTML("") |
| 203 | + ) |
0 commit comments