def check_path(self, path): if os.path.exists(path): if os.listdir(path): self.path = path self.text.children = [ v.Row(children=[f'{path} is not empty.']), v.Row(children=['Do you want to replace the files?']) ] self.v_model = True
def __init__(self, message): self.message = v.Alert(children=[f'{message}...'], class_='primary--text') super().__init__(children=[ v.Row(children=[ v.ProgressCircular(indeterminate=True, color='primary', size=70, width=4) ], justify='center'), v.Row(children=[ self.message, ], justify='center') ])
def __init__(self): self.label = v.TextField(label='label', v_model='') self.line_style = v.Select(label='Line style', items=[{ 'text': v, 'value': k } for k, v in Line2D.lineStyles.items()], v_model=plot_config['linestyle']) self.line_width = IntField(label='linewidth', v_model=plot_config['linewidth']) self.marker = v.Select(label='Marker', items=[{ 'text': v, 'value': k } for k, v in Line2D.markers.items()], v_model=plot_config['marker']) self.marker_size = IntField(label='Marker size', v_model=plot_config['markersize']) self.alpha = FloatField(label='alpha', v_model=plot_config['alpha']) self.color = v.ColorPicker(v_model=plot_config['colors'][0]) self.widget = [ self.label, self.line_style, self.line_width, self.marker, self.marker_size, self.alpha, v.Row(children=[self.color], justify='center'), ]
def vuetify_layout_factory(viewer): def on_click(widget, event, data): drawer.v_model = not drawer.v_model sidebar_button = v.AppBarNavIcon() sidebar_button.on_event('click', on_click) options_panel = v.ExpansionPanels( v_model=[0, 1], multiple=True, accordion=True, style_='padding-left: 1px; min-width: 200px', children=[ v.ExpansionPanel(children=[ v.ExpansionPanelHeader(class_='font-weight-bold', children=['Viewer Options']), v.ExpansionPanelContent(children=[viewer.viewer_options]) ]), v.ExpansionPanel(children=[ v.ExpansionPanelHeader(class_='font-weight-bold', children=['Layer Options']), v.ExpansionPanelContent(children=[viewer.layer_options]) ]) ]) drawer = v.NavigationDrawer(v_model=False, absolute=True, right=True, children=[sidebar_button, options_panel], width="min-content") toolbar = v.Toolbar( dense=True, class_='elevation-0', children=[ v.ToolbarItems(children=[ viewer.toolbar_selection_tools, viewer.toolbar_selection_mode, viewer.toolbar_active_subset ]), v.Spacer(), sidebar_button ]) layout = v.Html(tag='div', children=[ toolbar, v.Row(no_gutters=True, children=[ v.Col(cols=12, children=[viewer.figure_widget]), v.Col(cols=12, children=[viewer.output_widget]) ]), drawer ]) return layout
def vuetify_layout_factory(viewer): def on_click(widget, event, data): drawer.v_model = not drawer.v_model sidebar_button = v.AppBarNavIcon() sidebar_button.on_event('click', on_click) options_panel = v.ExpansionPanels( v_model=[0, 1], multiple=True, accordion=True, style_='padding-left: 1px', children=[ v.ExpansionPanel(children=[ v.ExpansionPanelHeader(class_='font-weight-bold', children=['Viewer Options']), v.ExpansionPanelContent(children=[viewer.viewer_options])]), v.ExpansionPanel(children=[ v.ExpansionPanelHeader(class_='font-weight-bold', children=['Layer Options']), v.ExpansionPanelContent(children=[viewer.layer_options])])]) drawer = v.NavigationDrawer(v_model=False, absolute=True, right=True, children=[sidebar_button, options_panel], width="min-content") toolbar_selection_tools = BasicJupyterToolbar(viewer) tool_ids, subtool_ids = get_viewer_tools(viewer.__class__) if subtool_ids: raise ValueError('subtools are not yet supported in Jupyter viewers') for tool_id in tool_ids: mode_cls = viewer_tool.members[tool_id] mode = mode_cls(viewer) toolbar_selection_tools.add_tool(mode) toolbar_active_subset = SubsetSelect(viewer) toolbar_selection_mode = SelectionModeMenu(viewer) toolbar = v.Toolbar(dense=True, class_='elevation-0', children=[v.ToolbarItems(children=[toolbar_selection_tools, toolbar_selection_mode, toolbar_active_subset]), v.Spacer(), sidebar_button]) layout = v.Html(tag='div', children=[ toolbar, v.Row(no_gutters=True, children=[ v.Col(cols=12, children=[viewer.figure_widget]), v.Col(cols=12, children=[viewer.output_widget]) ]), drawer ]) return layout
def row( children=[], align=None, align_content=None, justify=None, dense=False, no_gutters=False, class_="", style_="", ): """ Create a row output container For details see: https://vuetifyjs.com/en/components/grids/ Parameters ---------- children : list (default []) List of elements to display in container align : str (default None) Applies the align-items css property. Available options are start, center, end, baseline and stretch. align_content : str (default None) Applies the align-content css property. Available options are start, center, end, space-between, space-around and stretch. justify : str (default None) Applies the justify-content css property. Available options are start, center, end, space-between and space-around. dense : bool (default False) Reduces the gutter between v-cols. no_gutters : bool (default False) Removes the gutter between v-cols. _class : str (optional, default 'icon ma-2') CSS classes of button _style: str CSS style of button """ ret = ipyvuetify.Row( children=children, align=align, align_content=align_content, justify=justify, dense=dense, no_gutters=no_gutters, class_=class_, style_=style_, ) return ret
id_selection_2d = v.Select(items=[], chips=True, multiple=False, v_model="", label="Select Plant ID", truncate_length=22) parameter_color = v.Select(items=[True, False], label="Group by color", multiple=False, chips=True, v_model=False) menu_plant_3d = v.Row(children=[ v.Col(children=[genotype_selection_3d]), v.Col(children=[parameter_color]) ]) row_param2d = v.Row(children=[ v.Col(children=[genotype_selection_2d]), v.Col(children=[id_selection_2d]) ]) plot3d_growth_developement = widgets.Output(layout=layout_output_wgt) plot3d_floral_intensity = widgets.Output(layout=layout_output_wgt) panel_3d = v.Row(children=[ v.Col(children=[ v.Container(fluid=True, children=[plot3d_growth_developement]) ]),
def digest_layers(self, layer_io=None, question_io=None): """ Digest the layers as a json list. This list should be composed of at least 6 information : id, name, layer, theme and subtheme When digestion, the layout will represent each layer sorted by categories fore each one of them if the layer used is the default one we'll write default, if not the name of the layer. for each one of them the value of the weight will also be set """ if layer_io == None or question_io == None: return self # read the json str into a panda dataframe layer_list = layer_io.layer_list layer_list = pd.DataFrame(layer_list) if layer_list else self.LAYER_LIST # get all the themes themes = np.unique(layer_list.theme) ep_content = [] for theme in themes: # filter the layers tmp_layers = layer_list[layer_list.theme == theme] # add the theme title title = v.ExpansionPanelHeader(children=[theme.capitalize()]) # loop in these layers and create the widgets theme_layer_widgets = [] for i, row in tmp_layers.iterrows(): # get the original layer asset original_asset = self.LAYER_LIST[self.LAYER_LIST.layer_id == row["id"]][ "layer" ].values[0] # cannot make the slots work with icons so I need to move to intermediate layout if row["theme"] == "benefits": # get the weight from questionnaire weight = json.loads(question_io.priorities)[row["id"]] # create the widget theme_layer_widgets.append( v.Row( class_="ml-2 mr-2", children=[ v.TextField( small=True, hint=row["layer"] if row["layer"] != original_asset else "default", persistent_hint=True, color=cp.gradient(5)[weight], readonly=True, v_model=row["name"], ), v.Icon( class_="ml-2", color=cp.gradient(5)[weight], children=[f"mdi-numeric-{weight}-circle"], ), ], ) ) elif row["theme"] == "costs": active = True theme_layer_widgets.append( v.Row( class_="ml-2 mr-2", children=[ v.TextField( small=True, hint=row["layer"] if row["layer"] != original_asset else "default", persistent_hint=True, color=cp.gradient(2)[active], readonly=True, v_model=row["name"], ), v.Icon( class_="ml-2", color=cp.gradient(2)[active], children=["mdi-circle-slice-8"], ), ], ) ) elif row["id"] not in [ "ecozones", "land_cover", "treecover_with_potential", ]: # get the activation from questionnaire_io if constraint active = json.loads(question_io.constraints)[row["name"]] != -1 theme_layer_widgets.append( v.Row( class_="ml-2 mr-2", children=[ v.TextField( small=True, hint=row["layer"] if row["layer"] != original_asset else "default", persistent_hint=True, color=cp.gradient(2)[active], readonly=True, v_model=row["name"], ), v.Icon( class_="ml-2", color=cp.gradient(2)[active], children=["mdi-circle-slice-8"], ), ], ) ) # add the lines to the layout content = v.ExpansionPanelContent(children=theme_layer_widgets) # create the ep ep_content.append(v.ExpansionPanel(children=[title, content])) # add the layout element to the global layout self.children = ep_content return self
v_model=2) slider_n_plant = v.Slider(max=100, min=1, label="#p", thumb_label=True, v_model="", disabled=True) box_n_plant = v.TextField(type_="number", class_="mt-0 pt-0", v_model='', disabled=True) plant_selection = v.Row(children=[ v.Col(cols=12, sm=7, md=7, children=[slider_n_plant]), v.Col(cols=12, sm=1, md=1, children=[box_n_plant]) ]) cb_allplants = v.Checkbox(v_model=False, label="Select all plants", disabled=True) menu_plant = v.Col(cols=12, sm=3, md=3, children=[ files_upload, v.Divider(), files_selection, v.Divider(), genotypes_selection, v.Divider(), plant_selection, v.Divider(), cb_allplants,
def vue(self): import matplotlib.pyplot as plt import matplotlib import io import base64 from traitlets import Unicode try: import ipyvuetify as v import ipywidgets as widgets except ImportError: raise ImportError("Please install ipyvuetify") panels = [] plt.ioff() for k in range(self.nschemes): myslice = slice(self.stencil.nv_ptr[k], self.stencil.nv_ptr[k + 1]) P = [sp.latex(p, mode='equation*') for p in self.P[myslice]] EQ = [ sp.latex(eq, mode='equation*') for eq in self.EQ_no_swap[myslice] ] s = [ sp.latex(s, mode='equation*') for s in self.s_no_swap[myslice] ] view = self.stencil.visualize(k=k) view.fig.canvas.header_visible = False panels.append( v.ExpansionPanel(children=[ v.ExpansionPanelHeader(children=[f'Scheme {k}'], class_='title'), v.ExpansionPanelContent(children=[ v.Card(children=[ v.CardTitle( style_='border-bottom: 1px solid black;', children=['Velocities']), v.CardText(children=[ v.Row(children=[view.fig.canvas], justify='center') ]), ], class_="ma-2", elevation=5), v.Card(children=[ v.CardTitle( style_='border-bottom: 1px solid black;', children=['Polynomials']), v.CardText(children=[ v.Row(children=[widgets.HTMLMath(p)], justify='center') for p in P ]) ], class_="ma-2", elevation=5), v.Card(children=[ v.CardTitle( style_='border-bottom: 1px solid black;', children=['Equilibria']), v.CardText(children=[ v.Row(children=[widgets.HTMLMath(eq)], justify='center') for eq in EQ ]) ], class_="ma-2", elevation=5), v.Card(children=[ v.CardTitle( style_='border-bottom: 1px solid black;', children=['Relaxation parameters']), v.CardText(children=[ v.Row(children=[widgets.HTMLMath(s_i)], justify='center') for s_i in s ]) ], class_="ma-2", elevation=5), ]) ], class_='ma-2 pa-2')) plt.ion() panels.append( v.ExpansionPanel(children=[ v.ExpansionPanelHeader(children=['Moments matrix'], class_='title'), v.ExpansionPanelContent(children=[ v.Row(children=[ widgets.HTMLMath( f"{sp.latex(self.M_no_swap, mode='equation*')}") ], justify='center') ]) ], class_='ma-2 pa-2')) panels.append( v.ExpansionPanel(children=[ v.ExpansionPanelHeader(children=['Inverse of moments matrix'], class_='title'), v.ExpansionPanelContent(children=[ v.Row(children=[ widgets.HTMLMath( f"{sp.latex(self.invM_no_swap, mode='equation*')}") ], justify='center') ]) ], class_='ma-2 pa-2')) return v.ExpansionPanels(children=panels, multiple=True)
def run_parametric_study(): from pathos.multiprocessing import ProcessingPool pool = pp.ProcessPool() output = pool.map(run_simulation, args) dimensions = [ dict(values=np.asarray([o[0] for o in output], dtype=np.float64), label='stability') ] dimensions.extend([ dict(values=sampling[:, ik], label=f'{k}') for ik, k in enumerate(design_space.keys()) ]) for i, r in enumerate(self.responses.widget.v_model): if output[0][i + 1] is not None: dimensions.append( dict(values=np.asarray([o[i + 1] for o in output], dtype=np.float64), label=r)) for isamp in range(len(sampling)): tmp_design = { f'{k}': sampling[isamp, ik] for ik, k in enumerate(design_space.keys()) } tmp_responses = { r: output[isamp][ir + 1] for ir, r in enumerate(self.responses.widget.v_model) } tmp_responses['stability'] = output[isamp][0] simu_path = os.path.join(path, f'simu_{isamp}') save_param_study_for_simu(simu_path, 'param_study.json', tmp_design, tmp_responses) fig = v.Row(children=[ go.FigureWidget(data=go.Parcoords( line=dict(color=dimensions[0]['values']), dimensions=dimensions, )), ], align='center', justify='center') def change_plot(change): if only_stable.v_model: mask = dimensions[0]['values'] == 1 else: mask = slice(dimensions[0]['values'].size) new_data = [] for i in items.v_model: d = dimensions[i] new_data.append( dict(values=d['values'][mask], label=d['label'])) fig.children = [ go.FigureWidget( go.Parcoords( line=dict(color=dimensions[color.v_model] ['values'][mask]), dimensions=new_data, )) ] color = v.Select(label='color', items=[{ 'text': v['label'], 'value': i } for i, v in enumerate(dimensions)], v_model=0) items = v.Select(label='Show items', items=[{ 'text': v['label'], 'value': i } for i, v in enumerate(dimensions)], v_model=[i for i in range(len(dimensions))], multiple=True) only_stable = v.Switch(label='Show only stable results', v_model=False) color.observe(change_plot, 'v_model') items.observe(change_plot, 'v_model') only_stable.observe(change_plot, 'v_model') self.plotly_plot.children = [color, items, only_stable, fig] self.stop_simulation(None)
def __init__(self, test_case_widget, lb_scheme_widget): """ Widget definition for linear stability of a lattice Boltzmann scheme. Parameters ========== - test_case_widget: widget of the test case (see test_case.py). - lb_scheme_widget: widget of the lattice Boltzmann scheme (see lb_scheme.py). This widget is composed by a menu where you can modify the parameters of the lattice Boltzmann scheme. This widget is also composed by a main widget where the linear stability for the states provided by the test case can be tested to check their stability. A user can add its own states. A second tab allows to plot the stability region of a given state. """ self.test_case_widget = test_case_widget self.lb_scheme_widget = lb_scheme_widget ## ## The menu ## self.menu = [self.lb_scheme_widget.panels] ## ## The main ## # Tab 1 test_case = self.test_case_widget.get_case() self.state_widget = StateWidget(test_case.state()) tab1 = v.TabItem(children=[self.state_widget.widget], class_="ma-6") # Tab 2 self.state_list = v.Select(label='States', items=[], v_model=0) plot_stab = v.Btn(children=['Plot stability region'], color='primary') self.alert = v.Alert(children=['Check the stability for this state...'], dense=True, type='info') self.stab_output, self.markers1, self.markers2 = prepare_stab_plot() self.container = Container(children=[v.Row(children=[v.Col(children=[self.alert])]), v.Row(children=[self.stab_output.canvas], align='center', justify='center')], align_content_center=True,) self.container.hide() tab2 = v.TabItem(children=[ v.Card(children=[ v.CardTitle(children=['Plot the linear stability for a given state']), v.CardText(children=[ v.Row(children=[ v.Col(children=[self.state_list], md=9, sm=12), v.Col(children=[plot_stab], md=3, sm=12), ], align='center', justify='space-around' ), self.container ]), ], class_="ma-6", )] ) # main tabs = v.Tabs(v_model=None, children=[v.Tab(children=['Check stability']), v.Tab(children=['Plot stability region']), tab1, tab2 ]) self.main = [tabs] self.update_states(None) self.change_test_case(None) ## ## Widget events ## self.test_case_widget.select_case.observe(self.change_test_case, 'v_model') self.test_case_widget.select_case.observe(self.hide_plot, 'v_model') self.lb_scheme_widget.select_case.observe(self.hide_plot, 'v_model') self.state_widget.eval_stab.on_event('click', self.stability_states) self.state_widget.item_list.observe(self.update_states, 'children') plot_stab.on_event('click', self.plot_stability)
children=[genotypes_selection_extraction, export_extraction]) df_modulescale = create_grid() panel_df = v.Container(fluid=True, children=[df_modulescale]) df_description = create_grid() panel_description = v.Container(fluid=True, children=[df_description]) tab_extraction_content = v.Row(children=[ v.Card(style_=layout_card, children=[info.p4_doc_extraction]), v.Col(cols=12, sm=12, md=12, children=[ menu_plant_extraction, panel_df, panel_description, ]), ]) genotypes_selection_single_genotype = v.Select(items=[], chips=True, multiple=False, v_model="", label="Select Genotype", truncate_length=22) plot_occurence = go.FigureWidget(layout=layout_gofigure) plot_distribution_module_order = go.FigureWidget(layout=layout_gofigure)
children=[genotypes_selection_extraction, export_extraction]) df_plantscale = create_grid() panel_df = v.Container(fluid=True, children=[df_plantscale]) df_description = create_grid() panel_description = v.Container(fluid=True, children=[df_description]) tab_extraction_content = v.Row(children=[ v.Card(style_=layout_card, children=[info.p3_doc_extraction]), v.Col(cols=12, sm=12, md=12, children=[ menu_plant_extraction, panel_df, panel_description, ]), ]) genotypes_selection_analyze = v.Select(items=[], chips=True, multiple=False, v_model="", label="Select Genotype", truncate_length=22) date_selection_analyze = v.Select(items=[], chips=True,
def create_tools(self): self.tools = [] tool_actions = [] tool_actions_map = dict() if 1: # tool_select: self.zoom_brush = bqplot.interacts.BrushSelector( x_scale=self.scale_x, y_scale=self.scale_y, color="blue") self.zoom_brush.observe(self.update_zoom_brush, ["brushing"]) self.click_brush = None # use regular mouse tool_actions_map[ZOOM_SELECT] = self.zoom_brush tool_actions_map[PAN_ZOOM] = self.panzoom tool_actions_map[CLICK_ZOOM] = self.click_brush tool_actions = [PAN_ZOOM, ZOOM_SELECT, CLICK_ZOOM] self.start_limits = copy.deepcopy(self.limits) def change_interact(*args): with self.output: name = tool_actions[self.interaction_tooltips.v_model] self.figure.interaction = tool_actions_map[name] self.interaction_tooltips = \ v.BtnToggle(v_model=0, mandatory=True, multiple=False, children=[ v.Tooltip(bottom=True, v_slots=[{ 'name': 'activator', 'variable': 'tooltip', 'children': v.Btn(v_on='tooltip.on', children=[ v.Icon(children=['pan_tool']) ]) }], children=[PAN_ZOOM]), v.Tooltip(bottom=True, v_slots=[{ 'name': 'activator', 'variable': 'tooltip', 'children': v.Btn(v_on='tooltip.on', children=[ v.Icon(children=['crop']) ]) }], children=[ZOOM_SELECT]), v.Tooltip(bottom=True, v_slots=[{ 'name': 'activator', 'variable': 'tooltip', 'children': v.Btn(v_on='tooltip.on', children=[ v.Icon(children=['mdi-mouse']) ]) }], children=[CLICK_ZOOM]) ]) self.interaction_tooltips.observe(change_interact, "v_model") def reset(*args): (x1, x2), (y1, y2) = self.start_limits self.zoom_sel(x1, x2, y1, y2, smart_zoom=True) with self.zoom_brush.hold_trait_notifications(): self.zoom_brush.selected_x = None self.zoom_brush.selected_y = None self.reset_btn = v.Btn(v_on='tooltip.on', icon=True, children=[v.Icon(children=['refresh'])]) self.reset_btn.on_event('click', lambda *ignore: reset()) self.reset_tooltip = v.Tooltip(bottom=True, v_slots=[{ 'name': 'activator', 'variable': 'tooltip', 'children': self.reset_btn }], children=[RESET_ZOOM]) self.undo_btn = v.Btn(v_on='tooltip.on', icon=True, disabled=True, children=[v.Icon(children=['undo'])]) self.undo_tooltip = v.Tooltip(bottom=True, v_slots=[{ 'name': 'activator', 'variable': 'tooltip', 'children': self.undo_btn }], children=[UNDO]) self.redo_btn = v.Btn(v_on='tooltip.on', icon=True, disabled=True, children=[v.Icon(children=['redo'])]) self.redo_tooltip = v.Tooltip(bottom=True, v_slots=[{ 'name': 'activator', 'variable': 'tooltip', 'children': self.redo_btn }], children=[REDO]) @debounced(0.5) def undo_redo(*args): self.curr_action = args[0] (x1, x2), (y1, y2) = args[1][-1] with self.scale_x.hold_trait_notifications(): with self.scale_y.hold_trait_notifications(): self.scale_x.min, self.scale_x.max = x1, x2 self.scale_y.min, self.scale_y.max = y1, y2 self.undo_btn.on_event( 'click', lambda *ignore: undo_redo(Action.undo, self.undo_actions)) self.redo_btn.on_event( 'click', lambda *ignore: undo_redo(Action.redo, self.redo_actions)) control_lyt = widgets.Layout(width='40px') self.panzoom_x = control_x = widgets.Checkbox(value=True, description='X', indent=False, layout=control_lyt) self.panzoom_y = control_y = widgets.Checkbox(value=True, description='Y', indent=False, layout=control_lyt) def update_panzoom(checkbox): if control_x.value: if control_y.value: self.panzoom = bqplot.PanZoom(scales={ 'x': [self.scale_x], 'y': [self.scale_y] }) else: self.panzoom = bqplot.PanZoom( scales={'x': [self.scale_x]}) else: if control_y.value: self.panzoom = bqplot.PanZoom( scales={'y': [self.scale_y]}) else: self.panzoom = bqplot.PanZoom() tool_actions_map[PAN_ZOOM] = self.panzoom # Update immediately if in PAN_ZOOM mode name = tool_actions[self.interaction_tooltips.v_model] if name == PAN_ZOOM: self.figure.interaction = self.panzoom self.panzoom_x.observe(update_panzoom) self.panzoom_y.observe(update_panzoom) self.panzoom_controls = widgets.VBox( [self.panzoom_x, self.panzoom_y]) self.tooltips = v.Row(children=[ self.panzoom_controls, self.interaction_tooltips, self.reset_tooltip, self.undo_tooltip, self.redo_tooltip ], align='center', justify='center') self.plot.add_to_toolbar(self.tooltips)
def vue(self): import jinja2 try: import ipyvuetify as v import ipywidgets as widgets except ImportError: raise ImportError("Please install ipyvuetify") t, x, y, z, U, Fx, Fy, Fz, Delta = sp.symbols('t, x, y, z, U, F_x, F_y, F_z, Delta_t') Bxx, Bxy, Bxz = sp.symbols('B_{xx}, B_{xy}, B_{xz}') Byx, Byy, Byz = sp.symbols('B_{yx}, B_{yy}, B_{yz}') Bzx, Bzy, Bzz = sp.symbols('B_{zx}, B_{zy}, B_{zz}') phys_equation = sp.Derivative(U, t) + sp.Derivative(Fx, x) if self.dim > 1: phys_equation += sp.Derivative(Fy, y) if self.dim == 3: phys_equation += sp.Derivative(Fz, z) order2 = [] space = [x, y, z] B = [[Bxx, Bxy, Bxz], [Byx, Byy, Byz], [Bzx, Bzy, Bzz], ] phys_equation_rhs = 0 for i in range(self.dim): for j in range(self.dim): phys_equation_rhs += sp.Derivative(B[i][j]*sp.Derivative(U, space[j]), space[i]) order1_dict = {} F = [Fx, Fy, Fz] for d in range(self.dim): order1_dict[sp.latex(F[d])] = [sp.latex(c) for c in self.coeff_order1[d]] order0_template = jinja2.Template(""" {%- macro coeff(order) %} {%- for o in order %} $$ {{ o }} $$ {% endfor %} {%- endmacro %} {{ coeff(consm) }} """) order1_template = jinja2.Template(""" {%- macro coeff_dict(consm, order) %} \\begin{align*} {%- for key, value in order.items() %} {%- for i in range(consm|length) %} {{ key }}^{ {{ consm[i]Â }} } &= {{ value[i] }} \\\\ \\\\ {% endfor %} {% endfor %} \\end{align*} {%- endmacro %} {{ coeff_dict(consm, order1_dict) }} """) order2_template = jinja2.Template(""" {%- macro coeff_dict_2(consm, order) %} \\begin{align*} {%- for key, value in order.items() %} {%- for i in range(consm|length) %} {%- for j in range(consm|length) %} {{ key }}^{ {{ consm[i]Â }}, {{ consm[j] }} } &= {{ value[i*(consm|length) + j] }} \\\\ \\\\ {% endfor %} {% endfor %} {% endfor %} \\end{align*} {%- endmacro %} {{ coeff_dict_2(consm, order2_dict) }} """) order2_dict = {} for i in range(self.dim): for j in range(self.dim): order2_dict[sp.latex(B[i][j])] = [sp.latex(-Delta*c) for c in self.coeff_order2[i][j]] consm = [sp.latex(c) for c in self.consm] return v.Container(children=[ v.Row(children=['The equivalent equation is given by']), v.Row(children=[ widgets.HTMLMath(sp.latex(sp.Eq(phys_equation, phys_equation_rhs), mode='equation*')) ], justify='center', ), v.ExpansionPanels(children=[ v.ExpansionPanel(children=[ v.ExpansionPanelHeader(children=['Conserved moments'], class_="title"), v.ExpansionPanelContent(children=[ v.Row(children=[ widgets.HTMLMath(order0_template.render(consm=consm)) ], justify='center' ) ]) ], class_="ma-2"), v.ExpansionPanel(children=[ v.ExpansionPanelHeader(children=['Order 1'], class_="title"), v.ExpansionPanelContent(children=[ v.Row(children=[ widgets.HTMLMath(order1_template.render(consm=consm, order1_dict=order1_dict)) ], justify='center' ) ]) ], class_="ma-2"), v.ExpansionPanel(children=[ v.ExpansionPanelHeader(children=['Order 2'], class_="title"), v.ExpansionPanelContent(children=[ v.Row(children=[ widgets.HTMLMath(order2_template.render(consm=consm, order2_dict=order2_dict)) ], justify='center' ) ]) ], class_="ma-2"), ]) ])
]) dialog.on_event('keydown.stop', lambda *args: None) v.Container(children=[ v.Row(children=[ v.Btn(class_='ma-2', color='primary', children=['button']), v.Btn( class_='ma-2', color='primary', outlined=True, children=['button' ]), v.Btn( class_='ma-2', color='primary', rounded=True, children=['button']), v.Btn(class_='ma-2', color='primary', fab=True, children=[ v.Icon(children=['mdi-pencil']), ]), v.Btn(class_='ma-2', color='primary', icon=True, children=[ v.Icon(children=['mdi-pencil']), ]), v.Btn(class_='ma-2', color='primary', text=True, children=['button']), ]), v.Row(children=[ v.Btn( class_='ma-2', color='primary', x_small=True, children=['button']), v.Btn(class_='ma-2', color='primary',
def main(): tc = TestCaseWidget(cases, default_case) lb = LBSchemeWidget(tc, known_cases) stability = StabilityWidget(tc, lb) simulation = SimulationWidget(tc, lb) parametric = ParametricStudyWidget(tc, lb, simulation.discret) posttreatment = PostTreatmentWidget() class DebugWidget: def __init__(self): self.menu = [] self.main = [out] tab_widgets = [ tc, lb, stability, simulation, parametric, posttreatment, DebugWidget() ] tab_titles = [ 'Test case', 'Scheme', 'Linear stability', 'LBM Simulation', 'Parametric study', 'Post treatment', 'Debug' ] tab = v.Tabs( v_model=0, center_active=True, fixed_tabs=True, slider_size=4, align_with_title=True, show_arrows=True, children=[v.Tab(children=[k]) for k in tab_titles], ) menu = v.List( children=[], nav=True, v_model='drawer', ) content = v.Content(children=[]) def tab_change(change): tab_id = tab.v_model widget = tab_widgets[tab_id] menu.children = [ v.ListItem(children=[v.ListItemContent(children=[m])]) for m in widget.menu ] content.children = widget.main if tab_id == 5: posttreatment.update(None) tab_change(None) tab.observe(tab_change, 'v_model') navicon = v.AppBarNavIcon() drawer = v.NavigationDrawer(children=[ v.Row(children=[ v.Img( src= 'https://pylbm.readthedocs.io/en/latest/_static/img/pylbm_with_text.svg', max_width=250, class_='ma-5') ], align='center', justify='center'), menu ], v_model=True, width=350, clipped=True, app=True) def show_drawer(widget, event, data): drawer.v_model = not drawer.v_model navicon.on_event("click.stop", show_drawer) return v.App(children=[ v.AppBar( children=[ navicon, tab, ], clipped_left=True, app=True, dark=True, ), drawer, content, ])
def __init__(self, test_case_widget, lb_scheme_widget): """ Widget definition for simulation of lattice Boltzmann methods. Parameters ========== - test_case_widget: widget of the test case (see test_case.py). - lb_scheme_widget: widget of the lattice Boltzmann scheme (see lb_scheme.py). This widget is composed by a menu where you can modify the discretization parameters, the generator used to build the numerical kernel into pylbm and the desired outputs for post treatment. This widget is also composed by a main widget where the simulation can be started and a plot is given in real time for the available fields. A period can be modified to control the plot frequency and a snapshot of the current figure can be made. """ self.test_case_widget = test_case_widget self.lb_scheme_widget = lb_scheme_widget test_case = test_case_widget.get_case() tc_param = test_case_widget.parameters lb_case = lb_scheme_widget.get_case() lb_param = lb_scheme_widget.parameters self.stats = {} ## ## The menu ## # configure the default simulation name self.simulation_name = v.TextField(label='Simulation name', v_model='') self.update_name(None) self.simu_cfg = v.Select(label='Load simulation configuration', items=[], v_model=None) self.update_simu_cfg_list() self.discret = DiscretizationWidget(test_case_widget, lb_scheme_widget) self.codegen = v.Select(items=['auto', 'numpy', 'cython'], v_model='auto') self.save_fields = Save_widget( list(lb_scheme_widget.get_case().equation.get_fields().keys())) self.menu = [ self.simulation_name, self.simu_cfg, v.ExpansionPanels(children=[ self.discret, v.ExpansionPanel(children=[ v.ExpansionPanelHeader(children=['Code generator']), v.ExpansionPanelContent(children=[self.codegen]), ]), v.ExpansionPanel(children=[ v.ExpansionPanelHeader(children=['Field output request']), v.ExpansionPanelContent( children=[self.save_fields.widget]), ]), ], multiple=True, class_='pa-0') ] ## ## The main ## self.simu = simulation() self.simu.reset_fields( lb_scheme_widget.get_case().equation.get_fields()) self.start = v.Btn(v_model=True, children=['Start'], class_='ma-2', style_='width: 100px', color='success') self.startTooltip = Tooltip(self.start, tooltip='click to start the simulation') self.pause = v.Btn(children=['Pause'], class_='ma-2', style_='width: 100px', disabled=True, v_model=False) self.progress_bar = v.ProgressLinear(height=20, value=0, color='light-blue', striped=True) self.result = v.Select(items=list(self.simu.fields.keys()), v_model=list(self.simu.fields.keys())[0]) self.period = StrictlyPositiveIntField( label='Period', v_model=round(self.discret['nt'].value / nb_split_period)) self.snapshot = v.Btn(children=['Snapshot']) self.plot = Plot() self.iplot = 0 self.plot_output = v.Row(justify='center') self.dialog = DialogPath() self.main = [ v.Row(children=[ self.startTooltip, Tooltip(self.pause, tooltip='click to pause the simulation'), self.dialog, ]), self.progress_bar, v.Row( children=[ v.Col(children=[self.result], md=5, sm=12), v.Col(children=[self.period], md=5, sm=12), v.Col(children=[self.snapshot], md=2, sm=12), ], align='center', justify='space-around', ), self.plot_output, ] ## ## Widget events ## self.start.on_event('click', self.start_simulation) self.pause.on_event('click', self.on_pause_click) self.snapshot.on_event('click', self.take_snapshot) self.result.observe(self.replot, 'v_model') self.simu_cfg.observe(self.load_simu_cfg, 'v_model') self.discret['nt'].observe(self.change_period_by_nt, 'v_model') test_case_widget.select_case.observe(self.stop_simulation, 'v_model') lb_scheme_widget.select_case.observe(self.stop_simulation, 'v_model') lb_scheme_widget.select_case.observe(self.update_result, 'v_model') test_case_widget.select_case.observe(self.update_name, 'v_model') lb_scheme_widget.select_case.observe(self.update_name, 'v_model')
items=["matplotlib", 'plotly.imshow', 'plotly.heatmap'], chips=True, multiple=False, v_model="matplotlib", label="Select a plot library", truncate_length=22) order_selection_waffle = v.Select(items=[], chips=True, multiple=False, v_model=None, label="Select Order", truncate_length=22) menu_plant_waffle = v.Row(children=[ genotypes_selection_waffle, date_selection_waffle, variable_selection_waffle, order_selection_waffle, plot_type_waffle ]) waffle = widgets.Output(layout=layout_output_wgt) tab_waffle_content = v.Row(children=[ v.Card(style_=layout_card, children=[info.p5_doc_waffle]), v.Col(col=12, sm=12, md=12, children=[ menu_plant_waffle, waffle, ]), ]) p5 = v.Tabs(children=[ v.Tab(children=['Waffle']), v.TabItem(children=[tab_waffle_content]),
def create_tools(self): self.tools = [] self.tool_actions = [] tool_actions_map = dict() if 1: # tool_select: #### initiaite the 4 types of zoom brushes, which should only highlight axis that are not locked ### self.zoom_brush_full = bqplot.interacts.BrushSelector( x_scale=self.scale_x, y_scale=self.scale_y, color="blue") self.zoom_brush_full.observe(self.update_zoom_brush_full, ["brushing"]) self.zoom_brush_vertical = bqplot.interacts.BrushIntervalSelector( scale=self.scale_y, orientation='vertical', color="blue") self.zoom_brush_vertical.observe(self.update_zoom_brush_vertical, ["brushing"]) self.zoom_brush_horizontal = bqplot.interacts.BrushIntervalSelector( scale=self.scale_x, orientation='horizontal', color="blue") self.zoom_brush_horizontal.observe( self.update_zoom_brush_horizontal, ["brushing"]) self.zoom_brush_none = bqplot.interacts.BrushSelector( x_scale=self.scale_x, y_scale=self.scale_y, color="gray") self.zoom_brush_none.observe(self.update_zoom_brush_none, ["brushing"]) # initiaite measurement tool self.ruler = bqplot.interacts.BrushSelector(x_scale=self.scale_x, y_scale=self.scale_y, color="blue") self.ruler.observe(self.measure_selected_area, ["brushing"]) #### Set the default initial tools #### self.zoom_brush = self.zoom_brush_full self.click_brush = None # use regular mouse self.click_brush_in = None self.click_brush_out = None tool_actions_map[ZOOM_SELECT] = self.zoom_brush tool_actions_map[PAN_ZOOM] = self.panzoom tool_actions_map[CLICK_ZOOM_IN] = self.click_brush_in tool_actions_map[CLICK_ZOOM_OUT] = self.click_brush_out tool_actions_map[RULER] = self.ruler self.tool_actions = [ PAN_ZOOM, ZOOM_SELECT, CLICK_ZOOM_IN, CLICK_ZOOM_OUT, RULER ] self.start_limits = copy.deepcopy(self.limits) def change_interact(*args): with self.output: name = self.tool_actions[self.interaction_tooltips.v_model] self.figure.interaction = tool_actions_map[name] if name == RULER: self.plot.model.legend.openMeasurementPanel() self.interaction_tooltips = \ v.BtnToggle(v_model=0, mandatory=True, multiple=False, children=[ v.Tooltip(bottom=True, v_slots=[{ 'name': 'activator', 'variable': 'tooltip', 'children': v.Btn(v_on='tooltip.on', children=[ v.Icon(children=['pan_tool']) ]) }], children=[PAN_ZOOM]), v.Tooltip(bottom=True, v_slots=[{ 'name': 'activator', 'variable': 'tooltip', 'children': v.Btn(v_on='tooltip.on', children=[ v.Icon(children=['crop']) ]) }], children=[ZOOM_SELECT]), v.Tooltip(bottom=True, v_slots=[{ 'name': 'activator', 'variable': 'tooltip', 'children': v.Btn(v_on='tooltip.on', children=[ v.Icon( children=['mdi-magnify-plus-cursor']) ]) }], children=[CLICK_ZOOM_IN]), v.Tooltip(bottom=True, v_slots=[{ 'name': 'activator', 'variable': 'tooltip', 'children': v.Btn(v_on='tooltip.on', children=[ v.Icon( children=['mdi-magnify-minus-cursor']) ]) }], children=[CLICK_ZOOM_OUT]), v.Tooltip(bottom=True, v_slots=[{ 'name': 'activator', 'variable': 'tooltip', 'children': v.Btn(v_on='tooltip.on', children=[ v.Icon(children=['mdi-ruler']) ]) }], children=[RULER]) # ruler ]) self.interaction_tooltips.observe(change_interact, "v_model") def reset(*args): (x1, x2), (y1, y2) = self.start_limits self.zoom_sel(x1, x2, y1, y2, smart_zoom=True) with self.zoom_brush.hold_trait_notifications(): self.zoom_brush.selected_x = None self.zoom_brush.selected_y = None self.zoom_brush.selected = None self.screenshot_btn = v.Btn( v_on='tooltip.on', icon=True, children=[v.Icon(children=['mdi-camera'])]) self.screenshot_tooltip = v.Tooltip(bottom=True, v_slots=[{ 'name': 'activator', 'variable': 'tooltip', 'children': self.screenshot_btn }], children=[SCREENSHOT]) @debounced(0.5) def screenshot(): def peer(a): print(type(a).__name__) print(type(a).__module__) print(dir(a)) #display(self.pil_image_test) # print(self.core_image.value) #peer(self.figure) #self.figure.save_png("test.png") #display(IPyImage("test.png")) #display(self.core.image) clear_output(wait=True) self.plot.model.plot.show() display(IPyImage(self.core_image.value)) self.screenshot_btn.on_event('click', lambda *ignore: screenshot()) self.reset_btn = v.Btn(v_on='tooltip.on', icon=True, children=[v.Icon(children=['refresh'])]) self.reset_btn.on_event('click', lambda *ignore: reset()) self.reset_tooltip = v.Tooltip(bottom=True, v_slots=[{ 'name': 'activator', 'variable': 'tooltip', 'children': self.reset_btn }], children=[RESET_ZOOM]) self.undo_btn = v.Btn(v_on='tooltip.on', icon=True, disabled=True, children=[v.Icon(children=['undo'])]) self.undo_tooltip = v.Tooltip(bottom=True, v_slots=[{ 'name': 'activator', 'variable': 'tooltip', 'children': self.undo_btn }], children=[UNDO]) self.redo_btn = v.Btn(v_on='tooltip.on', icon=True, disabled=True, children=[v.Icon(children=['redo'])]) self.redo_tooltip = v.Tooltip(bottom=True, v_slots=[{ 'name': 'activator', 'variable': 'tooltip', 'children': self.redo_btn }], children=[REDO]) @debounced(0.5) def undo_redo(*args): self.curr_action = args[0] (x1, x2), (y1, y2) = args[1][-1] with self.scale_x.hold_trait_notifications(): with self.scale_y.hold_trait_notifications(): self.scale_x.min, self.scale_x.max = x1, x2 self.scale_y.min, self.scale_y.max = y1, y2 self.undo_btn.on_event( 'click', lambda *ignore: undo_redo(Action.undo, self.undo_actions)) self.redo_btn.on_event( 'click', lambda *ignore: undo_redo(Action.redo, self.redo_actions)) control_lyt = widgets.Layout(width='100px') self.control_x = widgets.Checkbox(value=False, description='Lock X Axis', indent=False, layout=control_lyt) self.control_y = widgets.Checkbox(value=False, description='Lock Y Axis', indent=False, layout=control_lyt) def axis_lock_update(checkbox): ####### Only allows one checkbox to be locked at a time ###### if checkbox['owner'].description == self.control_x.description: if self.control_y.value: self.control_y.value = False if checkbox['owner'].description == self.control_y.description: if self.control_x.value: self.control_x.value = False ############################################################## # When a axis checkbox is locked. # Updates the panzoom tool to lock eithier the x or y axis. # Also updates the zoombrush tool to use relevant zoom brush if self.control_x.value: if self.control_y.value: self.panzoom = bqplot.PanZoom() self.zoom_brush = self.zoom_brush_none else: self.panzoom = bqplot.PanZoom( scales={'y': [self.scale_y]}) self.zoom_brush = self.zoom_brush_vertical else: if self.control_y.value: self.panzoom = bqplot.PanZoom( scales={'x': [self.scale_x]}) self.zoom_brush = self.zoom_brush_horizontal else: self.panzoom = bqplot.PanZoom(scales={ 'x': [self.scale_x], 'y': [self.scale_y] }) self.zoom_brush = self.zoom_brush_full tool_actions_map[PAN_ZOOM] = self.panzoom tool_actions_map[ZOOM_SELECT] = self.zoom_brush # Update immediately if in PAN_ZOOM mode name = self.tool_actions[self.interaction_tooltips.v_model] if name == PAN_ZOOM: self.figure.interaction = self.panzoom elif name == ZOOM_SELECT: self.figure.interaction = self.zoom_brush self.control_x.observe(axis_lock_update) self.control_y.observe(axis_lock_update) self.axis_controls = widgets.VBox([self.control_x, self.control_y]) self.tooltips = v.Row(children=[ self.axis_controls, self.interaction_tooltips, self.reset_tooltip, self.undo_tooltip, self.redo_tooltip, self.screenshot_tooltip ], align='center', justify='center') self.plot.add_to_toolbar(self.tooltips)
def main(): mc = ModelWidget(cases) tc = TestCaseWidget(mc) lb = LBSchemeWidget(tc) stability = StabilityWidget(tc, lb) simulation = SimulationWidget(tc, lb) parametric = ParametricStudyWidget(tc, lb, simulation.discret, simulation.codegen) posttreatment = PostTreatmentWidget() class DebugWidget: def __init__(self): self.menu = [] self.main = [out] tab_widgets = [ mc, tc, lb, stability, simulation, parametric, posttreatment, DebugWidget() ] tab_titles = [ 'Model', 'Test case', 'Scheme', 'Linear stability', 'LBM Simulation', 'Parametric study', 'Post treatment', 'Debug' ] tab = v.Tabs( v_model=0, center_active=True, fixed_tabs=True, slider_size=4, align_with_title=True, show_arrows=True, children=[v.Tab(children=[k]) for k in tab_titles], ) menu = v.List( children=[], nav=True, v_model='drawer', ) content = v.Content(children=[]) def tab_change(change): tab_id = tab.v_model items = [] if tab_id < 6: items.extend(get_information(tab_id, mc, tc, lb)) widget = tab_widgets[tab_id] items.extend([ v.ListItem( children=[ v.ListItemContent(children=[m]) ] ) for m in widget.menu ]) menu.children = items content.children = widget.main if tab_id == 4: simulation.update_simu_cfg_list() if tab_id == 5: parametric.update_param_cfg_list() if tab_id == 6: posttreatment.update(None) tab_change(None) tab.observe(tab_change, 'v_model') mc.select_category.observe(tab_change, 'v_model') mc.select_model.observe(tab_change, 'v_model') tc.select_case.observe(tab_change, 'v_model') lb.select_case.observe(tab_change, 'v_model') navicon = v.AppBarNavIcon() drawer = v.NavigationDrawer( children=[ v.Row( children=[ v.Img( src='img/pylbm_with_text.svg', max_width=250, class_='ma-5' ) ], align='center', justify='center' ), menu ], v_model=True, width=350, clipped=True, app=True ) def show_drawer(widget, event, data): drawer.v_model = not drawer.v_model navicon.on_event("click.stop", show_drawer) return v.App( children=[ v.AppBar( children=[ navicon, tab, ], clipped_left=True, app=True, dark=True, ), drawer, content, ] )
def init_widgets(self, tag_type): self.all_check = v.Checkbox(v_on='tooltip.on', prepend_icon='fa-globe', label="All", v_model=True, class_='ma-0 mt-1 pa-0') self.all_check_tp = v.Tooltip(bottom=True, v_slots=[{ 'name': 'activator', 'variable': 'tooltip', 'children': self.all_check }], children=["Select all"]) self.all_check.on_event('change', self.check_all) all_row = [v.Row(children=[self.all_check_tp], class_='ml-7')] tag_rows = [] treenodelabel = v.Html( tag='style', children= [(".vuetify-styles .v-treeview-node__label {" "margin-left: 0px;" "overflow: visible;" "}" ".vuetify-styles .v-input--selection-controls:not(.v-input--hide-details) .v-input__slot {" "margin-bottom: 0px;" "}" ".vuetify-styles .v-treeview-node__root .v-icon.v-icon.v-icon--link {" "margin-bottom: 10px;" "}" ".vuetify-styles .v-treeview-node--leaf {" "margin-left: 0px;" "}" ".vuetify-styles .v-treeview--dense .v-treeview-node__root {" "min-height: 21px;" "}")]) for tag in self.model.curr_trace.tags: if tag.tag_type == tag_type: chk = Checkbox(tag) self.checkboxes.append(chk) chk.widget.on_event('change', self.update_all_checkbox) stats = self.get_stats(tag) btn, tooltip = self.create_zoom_button(tag, stats=stats) statss = self.tag_tooltip(tag, stats).splitlines() tag_row = v.Row(children=[btn, chk.widget], class_='ml-0') items = [{ 'id': 1, 'name': '', 'children': [{ 'id': i + 2, 'name': stat } for i, stat in enumerate(statss)], }] treeview = v.Treeview(items=items, dense=True) tag_rows.append( v.Container(row=False, class_="d-flex justify-start ma-0 pa-0", children=[ v.Col(cols=1, children=[treeview], class_="ma-0 pa-0"), v.Col(cols=12, children=[tag_row], class_="pt-0 pb-0") ])) tag_rows.append(v.Container(row=False, children=[treenodelabel])) return VBox([ v.List(children=(all_row + tag_rows), dense=True, nav=True, max_height="300px", max_width="300px") ])
def __init__(self): self.select_dim = v.Select(label='Dimension', items=[1, 2], v_model=1) self.previous_dim = 1 headers = [ { 'text': 'Iteration', 'value': 'iteration' }, { 'text': 'Time', 'value': 'time' }, { 'text': 'Field', 'value': 'field' }, { 'text': 'Test case', 'value': 'test case' }, { 'text': 'LB scheme', 'value': 'lb scheme' }, { 'text': 'Filename', 'value': 'file' }, { 'text': 'Directory', 'value': 'directory' }, ] headers_select = v.Select(label='Show columns', items=[{ 'text': v['text'], 'value': i } for i, v in enumerate(headers)], v_model=list(range(5)), multiple=True) search = v.TextField( v_model=None, append_icon="mdi-magnify", label="Search", single_line=True, hide_details=True, ) self.table = v.DataTable( v_model=[], headers=[headers[i] for i in headers_select.v_model], items=[], item_key="id", single_select=False, show_select=True, search='', ) self.selected_cache = [[]] * 3 self.select_item_cache = [[]] * 3 self.palette_cache = [[]] * 3 self.select_table = SelectedDataTable( self.table, headers=[headers[i] for i in headers_select.v_model] + [{ 'text': 'Action', 'value': 'action' }], ) self.plot = Plot() def select(change): with out: for e in list(self.table.v_model): self.select_table.items.append(e) self.select_table.palette.append({ 'color': plot_config['colors'][0], 'alpha': plot_config['alpha'], 'linewidth': plot_config['linewidth'], 'linestyle': plot_config['linestyle'], 'marker': plot_config['marker'], 'markersize': plot_config['markersize'] }) self.table.items.remove(e) self.table.v_model = [] self.select_table.notify_change({ 'name': 'items', 'type': 'change' }) self.table.notify_change({'name': 'items', 'type': 'change'}) def search_text(change): self.table.search = search.v_model self.update(None) self.select_table.observe(self.plot_result, 'items') self.select_table.observe(self.plot_result, 'palette') self.select_table.observe(self.plot_result, 'selected') search.observe(search_text, 'v_model') self.table.observe(select, 'v_model') self.select_dim.observe(self.cache, 'v_model') def update_headers(change): with out: self.table.headers = [ headers[i] for i in headers_select.v_model ] self.select_table.headers = [ headers[i] for i in headers_select.v_model ] + [{ 'text': 'Action', 'value': 'action' }] self.select_table.notify_change({ 'name': 'items', 'type': 'change' }) self.table.notify_change({'name': 'items', 'type': 'change'}) headers_select.observe(update_headers, 'v_model') download_zip = v.Btn(children=['Download results']) def create_zip(widget, event, data): from zipfile import ZipFile import webbrowser import tempfile zipdir = tempfile.TemporaryDirectory().name if not os.path.exists(zipdir): os.makedirs(zipdir) zipfilename = os.path.join(zipdir, 'results.zip') with ZipFile(zipfilename, 'w') as zipObj: for folderName, subfolders, filenames in os.walk(default_path): for filename in filenames: #create complete filepath of file in directory filePath = os.path.join(folderName, filename) # Add file to zip zipObj.write(filePath, filePath.replace(default_path, '')) webbrowser.open(f'file://{zipfilename}') download_zip.on_event('click', create_zip) self.menu = [self.select_dim, headers_select, download_zip] self.main = [ v.Card( children=[ v.CardTitle( children=['Available results', v.Spacer(), search]), self.table, ], class_='ma-2', ), v.Card( children=[ v.CardTitle(children=[ 'Selected results', ]), self.select_table, self.select_table.dialog, ], class_='ma-2', ), v.Row(children=[self.plot.fig.canvas], justify='center'), # out ]
def __init__(self, backend, dataset, x, y=None, z=None, w=None, grid=None, limits=None, shape=128, what="count(*)", f=None, vshape=16, selection=None, grid_limits=None, normalize=None, colormap="afmhot", figure_key=None, fig=None, what_kwargs={}, grid_before=None, vcount_limits=None, show_drawer=False, controls_selection=True, model=None, x_col=None, y_col=None, x_label='Access Number', y_label='Address', update_stats=None, **kwargs): super(PlotBase, self).__init__(x=x, y=y, z=z, w=w, what=what, vcount_limits=vcount_limits, grid_limits=grid_limits, f=f, **kwargs) self.backend = backend self.vgrids = [None, None, None] self.vcount = None self.dataset = dataset self.limits = self.get_limits(limits) self.shape = shape self.shape = 512 self.selection = selection self.grid_limits_visible = None self.normalize = normalize self.colormap = colormap self.what_kwargs = what_kwargs self.grid_before = grid_before self.figure_key = figure_key self.fig = fig self.vshape = vshape self.scales = [[self.limits[0][0], self.limits[0][1]], [self.limits[1][0], self.limits[1][1]]] self._new_progressbar() self.output = widgets.Output() def output_changed(*ignore): self.widget.new_output = True self.output.observe(output_changed, 'outputs') # with self.output: if 1: self._cleanups = [] self.progress = widgets.FloatProgress(value=0.0, min=0.0, max=1.0, step=0.01) self.progress.layout.width = "95%" self.progress.layout.max_width = '500px' self.progress.description = "progress" self.toolbar = v.Row(pa_1=True, children=[]) # Vaextended arguments if [x for x in (model, x_col, y_col, update_stats) if x == None]: raise Exception( 'The following arguments are required for using plot_widget() with Vaextended: model, x_col, y_col, update_stats\n\nSee docs/README_VAEXTENDED.md for more information' ) self.model = model self.x_col = x_col self.y_col = y_col self.x_label = x_label self.y_label = y_label self.cache_size = self.model.cache_size() self.update_stats = update_stats self.backend.create_widget(self.output, self, self.dataset, self.limits) self.widget = PlotTemplate(components={ 'main-widget': widgets.VBox([self.backend.widget, self.progress, self.output]), 'output-widget': self.output, 'toolbar': self.toolbar, 'default_title': self.model.plot_title(), 'main-legend': self.model.legend.widgets, 'legend-control': self.model.legend.legend_button }, model=show_drawer) if grid is None: self.update_grid() else: self.grid = grid # checkboxes work because of this callback = self.dataset.signal_selection_changed.connect( lambda *x: self.update_grid()) def _on_limits_change(*args): self._progressbar.cancel() self.update_grid() self.backend.observe(_on_limits_change, "limits") for attrname in "x y z vx vy vz".split(): def _on_change(change, attrname=attrname): limits_index = {'x': 0, 'y': 1, 'z': 2}.get(attrname) if limits_index is not None: self.backend.limits[limits_index] = None self.update_grid() self.observe(_on_change, attrname)
def __init__(self, spark_controller, ipywidget_factory, ipython_display, endpoints, refresh_method, state, db): super(AddEndpointWidget, self).__init__(spark_controller, ipywidget_factory, ipython_display, True) self.endpoints = endpoints self.refresh_method = refresh_method self.state = state self.delete_pressed = False self.db = db self.auth = GoogleAuth() add_endpoint_button = v.Btn(class_='ma-2', color='primary', children=['Add Endpoint']) add_endpoint_button.on_event('click', self._add_endpoint) cancel_button = v.Btn(class_='ma-2', color='primary', children=['Cancel']) cancel_button.on_event('click', self._on_cancel_click) backicon = v.Icon(children=['mdi-arrow-left']) backicon.on_event('click', self._on_back_click) back_toolbar = v.Toolbar( elevation="0", children=[ v.ToolbarItems(children=[backicon]), v.ToolbarTitle(children=['Create new endpoint']), v.Spacer() ], app=True, # If true, the other widgets float under on scroll ) self.create_endpoint_widget = v.Container( style_=f'width: {WIDGET_WIDTH};', class_='ma-2', children=[ back_toolbar, v.Row(class_='ma-2', children=[ v.Col(children=[self.auth.account_widget]), v.Col(children=[self.auth.project_widget]), v.Col(children=[self.auth.region_widget]) ]), v.Row(class_='ma-2', children=[ v.Col(children=[self.auth.cluster_widget]), v.Col(children=[self.auth.filter_widget]), v.Col(children=[v.Spacer()]), ]), v.Row(class_='ma-2', children=[add_endpoint_button, cancel_button]) ]) endpoint_table_values = self._generate_endpoint_values() new_endpoint = v.Btn(class_='ma-2', color='primary', children=['New Endpoint']) new_endpoint.on_event('click', self._on_new_endpoint_click) no_back_toolbar = v.Toolbar( elevation="0", children=[ v.ToolbarTitle(titleMarginStart='12dp', contentInsetStartWithNavigation="56dp", children=['Endpoints']), v.Spacer() ], app=True, # If true, the other widgets float under on scroll ) toolbar = v.Row(children=[no_back_toolbar, new_endpoint]) delete_icon = v.Icon(children=['mdi-delete']) delete_icon.on_event('click', self._on_delete_icon_pressed) endpoint_table = v.DataTable(style_=f'width: {WIDGET_WIDTH};', no_data_text='No endpoints', hide_default_footer=True, disable_pagination=True, item_key='url', headers=[ { 'text': 'Cluster', 'align': 'start', 'sortable': False, 'value': 'name' }, { 'text': 'Project', 'sortable': False, 'value': 'project' }, { 'text': 'Region', 'sortable': False, 'value': 'region' }, { 'text': 'Account', 'sortable': False, 'value': 'account' }, { 'text': 'Url', 'sortable': False, 'value': 'url' }, { 'text': '', 'sortable': False, 'value': 'actions' }, ], items=endpoint_table_values, dense=False, v_slots=[{ 'name': 'item.actions', 'children': [delete_icon] }, { 'name': 'no-data', 'children': ['No endpoints'] }]) endpoint_table.on_event('click:row', self._remove_row_from_table) self.toolbar_with_table = v.Container( style_=f'width: {WIDGET_WIDTH};', class_='mx-auto', children=[ v.Row(class_='mx-auto', children=[toolbar]), v.Row(class_='mx-auto', children=[endpoint_table]) ]) self.children = [self.create_endpoint_widget, self.toolbar_with_table] for child in self.children: child.parent_widget = self self._update_view()
def __init__(self, test_case_widget, lb_scheme_widget, discret_widget): """ Widget definition for parametric study of lattice Boltzmann methods. Parameters ========== - test_case_widget: widget of the test case (see test_case.py). - lb_scheme_widget: widget of the lattice Boltzmann scheme (see lb_scheme.py). This widget is composed by a menu where you can define the design space of the parametric study, the responses computed on each sample and the method used to generate the sampling as well as the number of points. This widget is also composed by a main widget where the result of the parametric study is represented by a parallel coordinates plot using plotly. """ self.test_case_widget = test_case_widget self.lb_scheme_widget = lb_scheme_widget self.discret_widget = discret_widget self.tmp_dir = tempfile.TemporaryDirectory() ## ## The menu ## self.study_name = v.TextField(label='Study name', v_model='PS_0') # self.space_step = v.TextField(label='Space step', v_model=0.01, type='number') self.codegen = v.Select(label='Code generator', items=['auto', 'numpy', 'cython'], v_model='auto') self.design = DesignWidget(test_case_widget, lb_scheme_widget, discret_widget) self.responses = ResponsesWidget(test_case_widget, lb_scheme_widget) self.sampling_method = v.Select(label='Method', items=list(skopt_method.keys()), v_model=list(skopt_method.keys())[0]) self.sample_size = v.TextField(label='Number of samples', v_model=10, type='number') self.run = v.Btn(v_model=True, children=['Run parametric study'], class_="ma-5", color='success') self.menu = [ self.study_name, # self.space_step, self.codegen, v.ExpansionPanels(children=[ v.ExpansionPanel(children=[ v.ExpansionPanelHeader(children=['Design space']), v.ExpansionPanelContent(children=[self.design.widget]), ]), v.ExpansionPanel(children=[ v.ExpansionPanelHeader(children=['Responses']), v.ExpansionPanelContent(children=[self.responses.widget]), ]), v.ExpansionPanel(children=[ v.ExpansionPanelHeader(children=['Sampling method']), v.ExpansionPanelContent( children=[self.sampling_method, self.sample_size]), ]), ], multiple=True), v.Row(children=[self.run], align='center', justify='center'), ] ## ## The main ## self.dialog = DialogPath() self.plotly_plot = v.Container(align_content_center=True) self.main = [v.Row(children=[self.plotly_plot]), self.dialog] ## ## Widget events ## self.run.on_event('click', self.start_PS) self.test_case_widget.select_case.observe(self.purge, 'v_model') self.lb_scheme_widget.select_case.observe(self.purge, 'v_model') self.codegen.observe(self.purge, 'v_model')
def __init__(self): self.select_dim = v.Select(label='Dimension', items=[1, 2], v_model=1) self.previous_dim = 1 headers = [ { 'text': 'Id', 'value': 'id' }, { 'text': 'Iteration', 'value': 'iteration' }, { 'text': 'Time', 'value': 'time' }, { 'text': 'Field', 'value': 'field' }, { 'text': 'Model', 'value': 'model' }, { 'text': 'Test case', 'value': 'test case' }, { 'text': 'LB scheme', 'value': 'lb scheme' }, { 'text': 'Filename', 'value': 'file' }, { 'text': 'Directory', 'value': 'directory' }, ] headers_select = v.Select(label='Show columns', items=[{ 'text': v['text'], 'value': i + 1 } for i, v in enumerate(headers[1:])], v_model=list(range(1, 7)), multiple=True) search = v.TextField( v_model=None, append_icon="mdi-magnify", label="Search", single_line=True, hide_details=True, ) self.table = v.DataTable( v_model=[], headers=[headers[i] for i in headers_select.v_model], items=[], item_key="id", single_select=False, show_select=True, search='', ) self.selected_cache = [[]] * 3 self.select_item_cache = [[]] * 3 self.properties_cache = [[]] * 3 self.select_table = SelectedDataTable( self.table, headers=[headers[i] for i in headers_select.v_model] + [{ 'text': 'Action', 'value': 'action' }], ) self.plot = Plot() def select(change): with out: for e in list(self.table.v_model): self.select_table.items.append(e) if e['dim'] == 1: self.select_table.properties.append({ 'label': e['field'], 'color': plot_config['colors'][0], 'alpha': plot_config['alpha'], 'linewidth': plot_config['linewidth'], 'linestyle': plot_config['linestyle'], 'marker': plot_config['marker'], 'markersize': plot_config['markersize'] }) elif e['dim'] == 2: h5 = os.path.join(e['directory'], e['file']) h5_data = h5py.File(h5) data = h5_data[e['field']][:] self.select_table.properties.append({ 'label': e['field'], 'min_value': np.nanmin(data), 'max_value': np.nanmax(data), 'cmap': plt.colormaps().index(plot_config['cmap']) }) self.table.items.remove(e) self.table.v_model = [] self.select_table.notify_change({ 'name': 'items', 'type': 'change' }) self.table.notify_change({'name': 'items', 'type': 'change'}) def search_text(change): self.table.search = search.v_model # self.update(None) self.select_table.observe(self.plot_result, 'items') self.select_table.observe(self.plot_result, 'properties') self.select_table.observe(self.plot_result, 'selected') search.observe(search_text, 'v_model') self.table.observe(select, 'v_model') self.select_dim.observe(self.cache, 'v_model') def update_headers(change): with out: self.table.headers = [ headers[i] for i in headers_select.v_model ] self.select_table.headers = [ headers[i] for i in headers_select.v_model ] + [{ 'text': 'Action', 'value': 'action' }] self.select_table.notify_change({ 'name': 'items', 'type': 'change' }) self.table.notify_change({'name': 'items', 'type': 'change'}) headers_select.observe(update_headers, 'v_model') download_zip = v.Btn(children=['Download results']) def create_zip(widget, event, data): from zipfile import ZipFile zipfilename = os.path.join(voila_notebook, 'results.zip') with ZipFile(zipfilename, 'w') as zipObj: for folderName, subfolders, filenames in os.walk(default_path): for filename in filenames: #create complete filepath of file in directory filePath = os.path.join(folderName, filename) # Add file to zip zipObj.write(filePath, filePath.replace(default_path, '')) dialog.children = [ v.Card(children=[ v.CardTitle(children=[ widgets.HTML( f'<a href="./results.zip" download="results.zip">Download the archive</a>' ) ]) ]) ] dialog.v_model = True self.title = v.TextField(label='Plot title', v_model='') self.xlabel = v.TextField(label='x label', v_model='') self.ylabel = v.TextField(label='y label', v_model='') self.legend = v.Switch(label='Add legend', v_model=False) self.title.observe(self.set_plot_properties, 'v_model') self.xlabel.observe(self.set_plot_properties, 'v_model') self.ylabel.observe(self.set_plot_properties, 'v_model') self.legend.observe(self.set_plot_properties, 'v_model') dialog = v.Dialog() dialog.v_model = False dialog.width = '200' download_zip.on_event('click', create_zip) self.menu = [ self.select_dim, headers_select, self.title, self.xlabel, self.ylabel, self.legend, download_zip, dialog ] self.main = [ v.Card( children=[ v.CardTitle( children=['Available results', v.Spacer(), search]), self.table, ], class_='ma-2', ), v.Card( children=[ v.CardTitle(children=[ 'Selected results', ]), self.select_table, self.select_table.dialog, ], class_='ma-2', ), v.Row(children=[self.plot.fig.canvas], justify='center'), ]