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 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 __init__(self, title, **kwargs): super().__init__( children=[v.ExpansionPanelHeader(children=[title]), v.ExpansionPanelContent(children=[])], **kwargs ) self.data = None
def __init__(self, aoi_tile, questionnaire_tile): # gather the io self.layer_model = questionnaire_tile.layer_model self.aoi_model = aoi_tile.view.model self.question_model = questionnaire_tile.question_model # gather the tiles that need to be filled self.aoi_tile = aoi_tile self.questionnaire_tile = questionnaire_tile # add the naming textField self.w_name = v.TextField(label=cm.custom.recipe.name, v_model=None) # link the widget to the model self.question_model.bind(self.w_name, "recipe_name") # create the layer list widget self.layers_recipe = cw.layerRecipe().hide() mkd = sw.Markdown(" \n".join(cm.valid.txt)) # add the recipe loader self.reset_to_recipe = sw.Btn(text=cm.custom.recipe.apply, icon="mdi-download", class_="ml-2") self.file_select = sw.FileInput([".json"], cp.result_dir, cm.custom.recipe.file) ep = v.ExpansionPanels( class_="mt-5", children=[ v.ExpansionPanel(children=[ v.ExpansionPanelHeader(disable_icon_rotate=True, children=[cm.custom.recipe.title]), v.ExpansionPanelContent( children=[self.file_select, self.reset_to_recipe]), ]) ], ) # create the tile super().__init__( id_="compute_widget", inputs=[ep, mkd, self.w_name, self.layers_recipe], title=cm.valid.title, btn=sw.Btn(cm.valid.display, class_="ma-1"), alert=sw.Alert(), ) # decorate the custom recipe btn self.load_recipe = su.loading_button(self.alert, self.reset_to_recipe, debug=True)(self.load_recipe) # js behaviours aoi_tile.view.observe(self._recipe_placeholder, "updated") self.btn.on_event("click", self._validate_data) self.reset_to_recipe.on_event("click", self.load_recipe) self.w_name.on_event("blur", self._normalize_name)
def __init__(self): # add a btn to click self.btn = sw.Btn(cm.map.shapes.btn, icon="mdi-download", class_="ml-2") # and the vector selector self.w_vector = CustomVector(label=cm.map.shapes.file) self.alert = sw.Alert() header = v.ExpansionPanelHeader(disable_icon_rotate=True, children=[cm.map.shapes.title]) content = v.ExpansionPanelContent( children=[self.w_vector, self.btn, self.alert]) # create the widget super().__init__( class_="mb-5 mt-2", children=[v.ExpansionPanel(children=[header, content])])
def __init__(self): self.label = v.TextField(label='label', v_model='') self.min_value = FloatField(label='minimum value') self.max_value = FloatField(label='maximum value') headers = [{ 'text': 'Name', 'value': 'name' }, { 'text': 'Color', 'value': 'color' }] self.cmap = v.ListItemGroup( v_model=plt.colormaps().index('RdBu'), children=[ v.ListItem(children=[ v.ListItemContent(children=[ v.ListItemTitle(children=[name]), v.ListItemSubtitle(children=[ v.Img(src=f'pylbm_ui/widgets/cmap/{name}.png', height=30, width=400) ]) ]) ]) for name in plt.colormaps() ]) self.widget = [ self.label, self.min_value, self.max_value, v.ExpansionPanels( v_model=None, children=[ v.ExpansionPanel(children=[ v.ExpansionPanelHeader(children=['Colormaps']), v.ExpansionPanelContent(children=[self.cmap]) ]) ]) ]
def __init__(self, category, criterias): # save title name self.title = category # create a header, as nothing is selected by defaul it should only display the title self.header = v.ExpansionPanelHeader( children=[cp.criteria_types[category]]) # link the criterias to the select self.criterias = [ c.disable() for c in criterias if c.header == category ] self.select = v.Select( disabled=True, # disabled until the aoi is selected class_="mt-5", small_chips=True, v_model=None, items=[c.name for c in self.criterias], label=cm.constraints.criteria_lbl, multiple=True, deletable_chips=True, persistent_hint=True, hint="select an AOI first", ) # create the content, nothing is selected by default so Select should be empty and criterias hidden criteria_flex = [ v.Flex(xs12=True, children=[c]) for c in self.criterias ] self.content = v.ExpansionPanelContent(children=[ v.Layout(row=True, children=[self.select] + criteria_flex) ]) # create the actual panel super().__init__(children=[self.header, self.content]) # link the js behaviour self.select.observe(self._show_crit, "v_model")
def initialize(self): """ All ipyvuetify widgets to display for the nonlinear solver """ solver = solversnonlinear.broyden.BroydenSolver() maxiter = v.TextField( v_model=solver.options.__dict__["_dict"]["maxiter"].get("value"), min=0, max=10000, label="Maxiter :", type='number', outlined=True, style_='width:500px;margin-top:5px;', ) atol = v.TextField( v_model=solver.options.__dict__["_dict"]["atol"].get("value"), min=0, max=1, label="Absolute Error Tolerance :", type='number', outlined=True, style_='width:500px;margin-top:5px;margin-left:50px;', ) rtol = v.TextField( v_model=solver.options.__dict__["_dict"]["rtol"].get("value"), min=0, max=1, label="Relative Error Tolerance :", type='number', outlined=True, style_='width:500px;', ) iprint = v.TextField( v_model=solver.options.__dict__["_dict"]["iprint"].get("value"), min=0, max=1, label="Print the output :", type='number', outlined=True, style_='width:500px;margin-left:50px;', ) err_on_non_converge = v.Checkbox( v_model=solver.options.__dict__["_dict"] ["err_on_non_converge"].get("value"), label="Err on non converge", style_='margin-bottom:20px;', ) debug_print = v.Checkbox( v_model=solver.options.__dict__["_dict"]["debug_print"].get( "value"), label="Debug Print", style_='margin-left:50px;margin-bottom:20px;', ) stall_limit = v.TextField( v_model=solver.options.__dict__["_dict"]["stall_limit"].get( "value"), min=0, max=100, label="Stall Limit :", type='number', outlined=True, style_='width:500px;', ) stall_tol = v.TextField( v_model=solver.options.__dict__["_dict"]["stall_tol"].get("value"), min=0, max=1, label="Stall tol :", type='number', outlined=True, style_='width:500px;margin-left:50px;', ) alpha = v.TextField( v_model=solver.options.__dict__["_dict"]["alpha"].get("value"), min=0, max=10, label="Alpha :", type='number', outlined=True, style_='width:500px;', ) compute_jacobian = v.Checkbox( v_model=solver.options.__dict__["_dict"]["compute_jacobian"].get( "value"), label="Compute Jacobian", style_='margin-left:50px;margin-bottom:35px;', ) converge_limit = v.TextField( v_model=solver.options.__dict__["_dict"]["converge_limit"].get( "value"), min=0, max=100, label="Converge limit :", type='number', outlined=True, style_='width:500px;', ) cs_reconvergebroyden = v.Checkbox( v_model=solver.options.__dict__["_dict"]["cs_reconverge"].get( "value"), label="Cs reconverge", style_='margin-left:50px;margin-bottom:20px;', ) diverge_limit = v.TextField( v_model=solver.options.__dict__["_dict"]["diverge_limit"].get( "value"), min=0, max=100, label="Diverge Limit :", type='number', outlined=True, style_='width:500px;', ) max_converge_failures = v.TextField( v_model=solver.options.__dict__["_dict"] ["max_converge_failures"].get("value"), min=0, max=100, label="Max Converge Failures :", type='number', outlined=True, style_='width:500px;margin-left:50px;', ) max_jacobians = v.TextField( v_model=solver.options.__dict__["_dict"]["max_jacobians"].get( "value"), min=0, max=100, label="Max Jacobians :", type='number', outlined=True, style_='width:500px;', ) state_vars = v.TextField( v_model="[]", label="State Vars :", outlined=True, style_='width:500px;margin-left:50px;', ) update_broyden = v.Checkbox( v_model=solver.options.__dict__["_dict"]["update_broyden"].get( "value"), label="Update Broyden", ) reraise_child_analysiserrorbroyden = v.Checkbox( v_model=solver.options.__dict__["_dict"] ["reraise_child_analysiserror"].get("value"), label="Reraise child Analysis Error", style_='margin-left:50px;', ) def broyden_change(): """ Adapt widgets & vbox widgets to only display widgets you need in this non-linear solver """ self.vboxsubsolves.children[0].children = [] self.vboxaitken.children[0].children = [] self.vboxaitken.children[1].children = [] self.vboxnonlinearsolver.children[0].children = [ maxiter, rtol, err_on_non_converge, stall_limit, alpha, converge_limit, diverge_limit, max_jacobians, update_broyden ] self.vboxnonlinearsolver.children[1].children = [ atol, iprint, debug_print, stall_tol, compute_jacobian, cs_reconvergebroyden, max_converge_failures, state_vars, reraise_child_analysiserrorbroyden ] solver = solversnonlinear.newton.NewtonSolver() solve_subsystems = v.Checkbox( v_model=False, label="Solve Subsystems", ) max_sub_solves = v.TextField( v_model=solver.options.__dict__["_dict"]["max_sub_solves"].get( "value"), min=0, max=100, label="Max Sub Solves :", type='number', outlined=True, style_='width:500px;margin-top:5px;', ) cs_reconvergenewton = v.Checkbox( v_model=solver.options.__dict__["_dict"]["cs_reconverge"].get( "value"), label="Cs reconverge", ) reraise_child_analysiserrornewton = v.Checkbox( v_model=solver.options.__dict__["_dict"] ["reraise_child_analysiserror"].get("value"), label="Reraise child Analysis Error", style_='margin-left:50px;') def change_use_solve_subsystems(widget, event, data): """ A function which display or not the 'max_sub_solves' widget, dependent on if you use solve subsystems """ if data: self.vboxsubsolves.children[0].children = [max_sub_solves] else: self.vboxsubsolves.children[0].children = [] solve_subsystems.on_event('change', change_use_solve_subsystems) def newton_change(): """ Adapt widgets & vbox widgets to only display widgets you need in this non-linear solver """ solve_subsystems.v_model = False self.vboxaitken.children[0].children = [] self.vboxaitken.children[1].children = [] self.vboxnonlinearsolver.children[0].children = [ maxiter, rtol, err_on_non_converge, stall_limit, solve_subsystems, cs_reconvergenewton ] self.vboxnonlinearsolver.children[1].children = [ atol, iprint, debug_print, stall_tol, reraise_child_analysiserrornewton ] solver = solversnonlinear.nonlinear_block_gs.NonlinearBlockGS() use_aitken = v.Checkbox( v_model=solver.options.__dict__["_dict"]["use_aitken"].get( "value"), label="Use Aitken relaxation", ) aitken_min_factor = v.TextField( v_model=solver.options.__dict__["_dict"]["aitken_min_factor"].get( "value"), min=0, max=100, label="Aitken min factor :", type='number', outlined=True, style_='width:500px;margin-top:5px;', ) aitken_max_factor = v.TextField( v_model=solver.options.__dict__["_dict"]["aitken_max_factor"].get( "value"), min=0, max=100, label="Aitken max factor :", type='number', outlined=True, style_='width:500px;margin-top:5px;margin-left:50px;', ) aitken_initial_factor = v.TextField( v_model=solver.options.__dict__["_dict"] ["aitken_initial_factor"].get("value"), min=0, max=1, label="Aitken initial factor :", type='number', outlined=True, style_='width:500px;', ) cs_reconvergegs = v.Checkbox( v_model=solver.options.__dict__["_dict"]["cs_reconverge"].get( "value"), label="Cs reconverge", style_='margin-left:50px;', ) use_apply_nonlinear = v.Checkbox( v_model=solver.options.__dict__["_dict"] ["use_apply_nonlinear"].get("value"), label="Use apply nonlinear", style_='width:500px;margin-left:50px;', ) reraise_child_analysiserrorgs = v.Checkbox( v_model=solver.options.__dict__["_dict"] ["reraise_child_analysiserror"].get("value"), label="Reraise child Analysis Error", ) def change_use_aitken(widget, event, data): """ A function which display or not the aitken options widgets, dependent on if you use aitken """ if data: self.vboxaitken.children[0].children = [ aitken_min_factor, aitken_initial_factor ] self.vboxaitken.children[1].children = [aitken_max_factor] else: self.vboxaitken.children[0].children = [] self.vboxaitken.children[1].children = [] use_aitken.on_event('change', change_use_aitken) def nonlinear_block_gs_change(): """ Adapt widgets & vbox widgets to only display widgets you need in this non-linear solver """ self.vboxsubsolves.children[0].children = [] use_aitken.v_model = False self.vboxnonlinearsolver.children[0].children = [ maxiter, rtol, err_on_non_converge, stall_limit, use_aitken, reraise_child_analysiserrorgs ] self.vboxnonlinearsolver.children[1].children = [ atol, iprint, debug_print, stall_tol, cs_reconvergegs, use_apply_nonlinear ] def nonlinear_block_jac_change(): """ Adapt widgets & vbox widgets to only display widgets you need in this non-linear solver """ self.vboxsubsolves.children[0].children = [] self.vboxaitken.children[0].children = [] self.vboxaitken.children[1].children = [] self.vboxnonlinearsolver.children[0].children = [ maxiter, rtol, err_on_non_converge, stall_limit ] self.vboxnonlinearsolver.children[1].children = [ atol, iprint, debug_print, stall_tol ] iprintrunonce = v.TextField( v_model=solver.options.__dict__["_dict"]["iprint"].get("value"), min=0, max=1, label="Print the output :", type='number', outlined=True, style_='width:500px;margin-top:5px;', ) def nonlinear_runonce_change(): """ Adapt widgets & vbox widgets to only display widgets you need in this non-linear solver """ self.vboxsubsolves.children[0].children = [] self.vboxnonlinearsolver.children[0].children = [iprintrunonce] self.vboxnonlinearsolver.children[1].children = [] def onchange(widget, event, data): """ A function which start the function you need for your non-linear driver """ if data == "broyden": broyden_change() elif data == "newton": newton_change() elif data == "nonlinear_block_gs": nonlinear_block_gs_change() elif data == "nonlinear_block_jac": nonlinear_block_jac_change() elif data == "nonlinear_runonce": nonlinear_runonce_change() self.select = v.Select( items=[ "broyden", "newton", "nonlinear_block_gs", "nonlinear_block_jac", "nonlinear_runonce" ], v_model="nonlinear_block_gs", label="Nonlinear solver :", outlined=True, style_="margin-top:5px;", ) self.select.on_event('change', onchange) self.panel = v.ExpansionPanel(children=[ v.ExpansionPanelHeader(color='#eaeaea', children=['Nonlinear Solver'], style_='margin-bottom:25px;'), v.ExpansionPanelContent(children=[ self.select, self.vboxnonlinearsolver, self.vboxaitken, self.vboxsubsolves ]), ]) self.expansionPanel = v.ExpansionPanels( focusable=True, children=[self.panel], ) display(self.expansionPanel) nonlinear_block_gs_change()
def add_panel(self, name, contents): acc = v.ExpansionPanel(children=[ v.ExpansionPanelHeader(children=[name]), v.ExpansionPanelContent(children=[contents], class_='ma-0 pa-0') ]) self.panels.children = self.panels.children + [acc]
def dev_set_summary(self, json_themes_values, aoi_names, colors): benefits_layer = [] constraints_layer = [] costs_layer = [] for k, val in json_themes_values.items(): for layer in json_themes_values[k]: if k == "name": # have name column as it will be good to add this while displaying at some point continue name = layer try: values = json_themes_values[k][layer]["values"] if k == "benefits": benefits_layer.append( cw.LayerFull(name, values, aoi_names[::-1], colors) ) elif k == "costs": costs_layer.append( cw.LayerFull(name, values, aoi_names[::-1], colors) ) elif k == "constraints": constraints_layer.append( cw.LayerPercentage(name, values, colors) ) except Exception as e: print(name, "not found", e) continue benefits = v.Html(tag="h2", children=["Benefits"]) benefits_txt = sw.Markdown(" \n".join(cm.dashboard.theme.benefit)) costs = v.Html(tag="h2", children=["Costs"]) costs_txt = sw.Markdown(" \n".join(cm.dashboard.theme.cost)) constraints = v.Html(tag="h2", children=["Constraints"]) constraints_txt = sw.Markdown(" \n".join(cm.dashboard.theme.constraint)) # create an expansion panel to store everything ep = v.ExpansionPanels( children=[ v.ExpansionPanel( children=[ v.ExpansionPanelHeader(children=[benefits]), v.ExpansionPanelContent( children=[benefits_txt] + benefits_layer ), ] ), v.ExpansionPanel( children=[ v.ExpansionPanelHeader(children=[costs]), v.ExpansionPanelContent(children=[costs_txt] + costs_layer), ] ), v.ExpansionPanel( children=[ v.ExpansionPanelHeader(children=[constraints]), v.ExpansionPanelContent( children=[constraints_txt] + constraints_layer ), ] ), ] ) self.set_content([ep]) return self
def __init__(self, test_case_widget, lb_scheme_widget): self.test_case_widget = test_case_widget self.lb_scheme_widget = lb_scheme_widget test_case = test_case_widget.get_case() lb_param = lb_scheme_widget.parameters tc_param = test_case_widget.parameters dx = default_dx nx = int(test_case.size()[0]/dx) + 1 ny = 1 dt = dx/lb_param['la'].value nt = int(test_case.duration/dt) self.discret = { 'nx': NbPointsField(label='Number of points in x', v_model=nx, disabled=True), 'ny': NbPointsField(label='Number of points in y', v_model=ny, disabled=True, class_='d-none'), 'dx': StrictlyPositiveFloatField(label='Space step', v_model=dx), 'nt': StrictlyPositiveIntField(label='Number of steps', v_model=nt, disable=True), 'dt': StrictlyPositiveFloatField(label='Time step', v_model=dt), } self.la_vue = v.CardText(children=[lb_param['la']]) for value in self.discret.values(): value.observe(self.observer, 'v_model') lb_param['la'].observe(self.observer, 'v_model') tc_param['xmin'].observe(self.observer, 'v_model') tc_param['xmax'].observe(self.observer, 'v_model') if test_case_widget.get_case().dim > 1: tc_param['ymin'].observe(self.observer, 'v_model') tc_param['ymax'].observe(self.observer, 'v_model') test_case_widget.select_case.observe(self.change_test_case, 'v_model') lb_scheme_widget.select_case.observe(self.change_test_case, 'v_model') super().__init__(children=[ v.ExpansionPanelHeader(children=['Discretization']), v.ExpansionPanelContent(children=[ v.Card(children=[ v.CardTitle(children=['In space']), v.CardText(children=[ self.discret['nx'], self.discret['ny'], self.discret['dx'], ]), ], class_="ma-1"), v.Card(children=[ v.CardTitle(children=['In time']), v.CardText(children=[ self.discret['nt'], self.discret['dt'], ]), ], class_="ma-1"), v.Card(children=[ v.CardTitle(children=['Scheme velocity']), self.la_vue, ], class_="ma-1"), ], class_="px-1"), ]),
def __init__(self): # create the different widgets # I will not use Io as the information doesn't need to be communicated to any other tile self.folder = cw.FolderSelect() self.out_dir = cw.OutDirSelect() self.tiles = cw.TilesSelect() self.poly = v.Select(label=cm.widget.harmonic.label, v_model=3, items=[i for i in range(3, 11)]) self.freq = v.Slider(label=cm.widget.freq.label, v_model=365, min=1, max=365, thumb_label="always", class_='mt-5') self.trend = v.Switch(v_model=False, label=cm.widget.trend.label) self.hfrac = v.Select(label=cm.widget.hfrac.label, v_model=.25, items=[.25, .5, 1.]) self.level = v.Slider(label=cm.widget.level.label, v_model=.95, step=.001, min=.95, max=1, thumb_label="always", class_='mt-5') self.backend = cw.BackendSelect() self.monitoring = cw.DateRangeSlider(label=cm.widget.monitoring.label) self.history = cw.DateSlider(label=cm.widget.history.label) # stack the advance parameters in a expandpanel advance_params = v.ExpansionPanels( class_='mb-5', popout=True, children=[ v.ExpansionPanel(children=[ v.ExpansionPanelHeader( children=[cm.widget.advance_params]), v.ExpansionPanelContent(children=[ v.Flex(xs12=True, children=[self.hfrac]), v.Flex(xs12=True, children=[self.level]), v.Flex(xs12=True, children=[self.backend]) ]) ]) ]) # create the tile super().__init__( "bfast_tile", cm.bfast. folder, # the title is used to describe the first section inputs=[ self.folder, self.out_dir, self.tiles, v.Html(tag="h2", children=[cm.bfast.process]), self.poly, self.freq, self.trend, advance_params, v.Html(tag="h2", children=[cm.bfast.periods]), self.history, self.monitoring ], output=cw.CustomAlert(), btn=sw.Btn(cm.bfast.btn)) # add js behaviour self.folder.observe(self._on_folder_change, 'v_model') self.btn.on_event('click', self._start_process) self.monitoring.observe(self._check_periods, 'v_model') self.history.observe(self._check_periods, 'v_model')
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')
def __init__(self, title, surfaces=[0] * 6): # get the total surface for ratio total_surface = sum(surfaces) # normalize surfaces norm_surfaces = [(s / total_surface) * 100 for s in surfaces] # create a matplotlib stack horizontal bar chart chart = Output() with chart: # create the chart fig, ax = plt.subplots(figsize=[50, 2], facecolor=((0, 0, 0, 0))) # add the axis for i, surface in enumerate(norm_surfaces): ax.barh(title, surface, left=sum(norm_surfaces[:i]), color=self.COLORS[i]) # cosmetic tuning ax.set_xlim(0, 100) ax.set_axis_off() plt.show() # init the table head = [ v.Html( tag="thead", children=[ v.Html( tag="tr", children=[ v.Html(tag="th", children=[name]) for name in self.NAMES ], ) ], ) ] self.rows = [] for clr, ptl, val, norm in zip(self.COLORS, self.POTENTIALS, surfaces, norm_surfaces): row = v.Html( tag="tr", children=[ v.Html( tag="td", children=[ptl], style_=f"color: {clr}", ), v.Html(tag="td", children=[f"{float(val):.1f}"]), v.Html(tag="td", children=[f"{float(norm):.1f}"]), ], ) self.rows.append(row) body = [v.Html(tag="tbody", children=self.rows)] table = v.SimpleTable(small=True, xs12=True, children=head + body) # the table should not be displayed by default but as a detail expansion panel ep = v.ExpansionPanels(children=[ v.ExpansionPanel(children=[ v.ExpansionPanelHeader(children=[cm.dashboard.region.detail]), v.ExpansionPanelContent(children=[table]), ]) ]) # init the title title = v.Html(xs12=True, class_="mb-2", tag="h2", children=[title]) # create the widget super().__init__( row=True, class_="ma-5", children=[ v.Flex(xs12=True, children=[title]), v.Flex(xs12=True, children=[chart]), v.Flex(xs12=True, children=[ep]), ], )
style_='\ display: none; \ ' ) smooth_expp = v.ExpansionPanel(children=[ v.ExpansionPanelHeader( children=['Smoothing'] ), v.ExpansionPanelContent(children=[ smooth_dropd, column([smooth_slider], cols=12), sigma_container, sharp_cb, sharp_row, ], ), ], style_=' \ display: none; \ background-color: #000000BF; \ ' ) def smooth(img, op_type, k_size, sigma1, sigma2, \ apply_sharp=False, alpha=0.5, beta=0.5, gamma=0.0):
def initialize(self): """ All ipyvuetify widgets to display for the driver """ drive = driver.scipy_optimizer.ScipyOptimizeDriver() optimizers = v.Select( items=list(drive.options.__dict__["_dict"]["optimizer"].get("values")), v_model=drive.options.__dict__["_dict"]["optimizer"].get("value"), label="Optimizers :", outlined=True, style_="width:500px;margin-top:5px", ) tol = v.TextField( v_model=drive.options.__dict__["_dict"]["tol"].get("value"), min=drive.options.__dict__["_dict"]["tol"].get("lower"), max=1, label="Tol :", type="number", outlined=True, style_="width:500px;margin-left:50px;margin-top:6px", ) maxiter = v.TextField( v_model=drive.options.__dict__["_dict"]["maxiter"].get("value"), min=drive.options.__dict__["_dict"]["maxiter"].get("lower"), max=1000, label="Maxiter :", type="number", outlined=True, ) disp = v.Checkbox( v_model=drive.options.__dict__["_dict"]["disp"].get("value"), label="Disp", style_="margin-left:50px", ) def scipy_optimizer_change(): """ Adapt widgets & vbox widgets to only display widgets you need in this driver """ self.vboxgenerator.children[0].children = [] self.vboxdoedriver.children[0].children = [] self.vboxdoedriver.children[1].children = [] self.vboxdriver.children[0].children = [optimizers, maxiter] self.vboxdriver.children[1].children = [tol, disp] drive = driver.differential_evolution_driver.DifferentialEvolutionDriver() maxgendiff = v.TextField( v_model=drive.options.__dict__["_dict"]["max_gen"].get("value"), min=0, max=1000, label="Max generations :", type='number', outlined=True, style_='width:500px;margin-top:5px' ) popsizediff = v.TextField( v_model=drive.options.__dict__["_dict"]["pop_size"].get("value"), min=0, max=100, label="Number of points in the GA :", type="number", outlined=True, style_='width:500px;margin-left:50px;margin-top:5px' ) runparalleldiff = v.Checkbox( v_model=drive.options.__dict__["_dict"]["run_parallel"].get("value"), label="Run parallel", style_='margin-bottom:20px' ) procspermodeldiff = v.TextField( v_model=drive.options.__dict__["_dict"]["procs_per_model"].get("value"), min=drive.options.__dict__["_dict"]["procs_per_model"].get("lower"), max=100, label="Processors per model :", type="number", outlined=True, style_='width:500px;margin-left:50px' ) penaltyparameterdiff = v.TextField( v_model=drive.options.__dict__["_dict"]["penalty_parameter"].get("value"), min=drive.options.__dict__["_dict"]["penalty_parameter"].get("lower"), max=100, label="Penalty parameter :", type="number", outlined=True, style_='width:500px' ) penaltyexponentdiff = v.TextField( v_model=drive.options.__dict__["_dict"]["penalty_exponent"].get("value"), min=0, max=100, label="Penalty exponent :", type="number", outlined=True, style_='width:500px;margin-left:50px' ) cross_probdiff = v.TextField( v_model=drive.options.__dict__["_dict"]["Pc"].get("value"), min=drive.options.__dict__["_dict"]["Pc"].get("lower"), max=drive.options.__dict__["_dict"]["Pc"].get("upper"), label="Crossover probability :", type="number", outlined=True, style_='width:500px' ) diff_rate = v.TextField( v_model=drive.options.__dict__["_dict"]["F"].get("value"), min=drive.options.__dict__["_dict"]["F"].get("lower"), max=drive.options.__dict__["_dict"]["F"].get("upper"), label="Differential rate :", type="number", outlined=True, style_='width:500px;margin-left:50px' ) multiobjweightsdiff = v.TextField( v_model="{}", label="Multi objective weights :", outlined=True, style_='width:500px' ) multiobjexponentdiff = v.TextField( v_model=drive.options.__dict__["_dict"]["multi_obj_exponent"].get("value"), min=drive.options.__dict__["_dict"]["multi_obj_exponent"].get("lower"), max=100, label="Multi-objective weighting exponent :", type="number", outlined=True, style_='width:500px;margin-left:50px' ) def differential_evolution_driver_change(): """ Adapt widgets & vbox widgets to only display widgets you need in this driver """ self.vboxgenerator.children[0].children = [] self.vboxdoedriver.children[0].children = [] self.vboxdoedriver.children[1].children = [] self.vboxdriver.children[0].children = [maxgendiff, runparalleldiff, penaltyparameterdiff, cross_probdiff, multiobjweightsdiff] self.vboxdriver.children[1].children = [popsizediff, procspermodeldiff, penaltyexponentdiff, diff_rate, multiobjexponentdiff] def doe_driver_change(): """ Adapt widgets & vbox widgets to only display widgets you need in this driver """ self.vboxdriver.children[0].children = [] self.vboxdriver.children[1].children = [] drive = driver.doe_driver.DOEDriver() def onchangegenerator(widget, event, data): """ A function which start the function you need for your generator """ if data == "DOEGenerator": doe_generator() elif data == "ListGenerator": list_generator() elif data == "CSVGenerator": csv_generator() elif data == "UniformGenerator": uniform_generator() elif data == "_pyDOE_Generator": pydoe_generator() elif data == "FullFactorialGenerator": full_factorial_generator() elif data == "GeneralizedSubsetGenerator": generalized_subset_generator() elif data == "PlackettBurmanGenerator": plackett_burman_generator() elif data == "BoxBehnkenGenerator": box_behnken_generator() elif data == "LatinHypercubeGenerator": latin_hypercube_generator() self.generator = v.Select( items=[ "DOEGenerator", "ListGenerator", "CSVGenerator", "UniformGenerator", "_pyDOE_Generator", "FullFactorialGenerator", "GeneralizedSubsetGenerator", "PlackettBurmanGenerator", "BoxBehnkenGenerator", "LatinHypercubeGenerator", ], v_model="DOEGenerator", label="Generator :", outlined=True, style_="width:500px;margin-top:5px", ) self.vboxgenerator.children[0].children = [self.generator] self.generator.on_event("change", onchangegenerator) procspermodeldoe = v.TextField( v_model=drive.options.__dict__["_dict"]["procs_per_model"].get("value"), min=drive.options.__dict__["_dict"]["procs_per_model"].get("lower"), max=100, label="Processors per model :", outlined=True, type='number', style_='width:500px;margin-top:5px' ) runparalleldoe = v.Checkbox( v_model=drive.options.__dict__["_dict"]["run_parallel"].get("value"), label="Run parallel", outlined=True, type='number', style_='width:500px;margin-left:50px' ) drive = driver.doe_generators.DOEGenerator() def doe_generator(): """ Adapt widgets & vbox widgets to only display widgets you need in this generator """ self.vboxdoedriver.children[0].children = [procspermodeldoe] self.vboxdoedriver.children[1].children = [runparalleldoe] drive = driver.doe_generators.ListGenerator() _data = v.TextField( v_model="[]", label="List of collections of name :", outlined=True, style_='width:500px;margin-top:5px' ) def list_generator(): """ Adapt widgets & vbox widgets to only display widgets you need in this generator """ self.vboxdoedriver.children[0].children = [_data, runparalleldoe] self.vboxdoedriver.children[1].children = [procspermodeldoe] _filename = v.TextField( label="File name :", outlined=True, style_='width:500px;margin-top:5px' ) def csv_generator(): """ Adapt widgets & vbox widgets to only display widgets you need in this generator """ self.vboxdoedriver.children[0].children = [_filename, runparalleldoe] self.vboxdoedriver.children[1].children = [procspermodeldoe] drive = driver.doe_generators.UniformGenerator() _num_samples = v.TextField( v_model=drive.__dict__["_num_samples"], min=0, max=100, label="Number of samples :", outlined=True, type='number', style_='width:500px;margin-top:5px' ) _seeduniform = v.TextField( v_model=drive.__dict__["_seed"], min=0, max=100, label="Seed :", outlined=True, type='number', style_='width:500px;margin-left:50px;margin-top:5px', ) def uniform_generator(): """ Adapt widgets & vbox widgets to only display widgets you need in this generator """ self.vboxdoedriver.children[0].children = [_num_samples, procspermodeldoe] self.vboxdoedriver.children[1].children = [_seeduniform, runparalleldoe] drive = driver.doe_generators._pyDOE_Generator() def onchangelevels(widget, event, data): """ A function which change the type of the levels widget ( Int or Dict ) """ if self.generator.v_model == '_pyDOE_Generator': drive = drive = driver.doe_generators._pyDOE_Generator() if data == "Int": _levelspydoe = v.TextField( v_model=drive.__dict__["_levels"], label="Levels :", min=0, max=1000, outlined=True, type='number', style_='width:500px;margin-top:27px' ) elif data == "Dict": _levelspydoe = v.TextField( v_model="[]", label="Levels :", outlined=True, style_='width:500px;margin-top:27px' ) self.vboxdoedriver.children[1].children = [_levelspydoe, procspermodeldoe] elif self.generator.v_model == 'FullFactorialGenerator': drive = driver.doe_generators.FullFactorialGenerator() if data == "Int": _levelsfull = v.TextField( v_model=drive.__dict__["_levels"], label="Levels :", min=0, max=1000, outlined=True, type='number', style_='width:500px;margin-top:27px' ) elif data == "Dict": _levelsfull = v.TextField( v_model="[]", label="Levels :", outlined=True, style_='width:500px;margin-top:27px' ) self.vboxdoedriver.children[1].children = [_levelsfull, procspermodeldoe] elif self.generator.v_model == 'PlackettBurmanGenerator': drive = driver.doe_generators.PlackettBurmanGenerator() if data == "Int": _levelsplackett = v.TextField( v_model=drive.__dict__["_levels"], label="Levels :", min=0, max=1000, outlined=True, type='number', style_='width:500px;margin-top:27px' ) elif data == "Dict": _levelsplackett = v.TextField( v_model="[]", label="Levels :", outlined=True, style_='width:500px;margin-top:27px' ) self.vboxdoedriver.children[1].children = [_levelsplackett, procspermodeldoe] elif self.generator.v_model == 'BoxBehnkenGenerator': drive = driver.doe_generators.BoxBehnkenGenerator() if data == "Int": _levelsbox = v.TextField( v_model=drive.__dict__["_levels"], label="Levels :", min=0, max=1000, outlined=True, type='number', style_='width:500px;margin-top:27px' ) elif data == "Dict": _levelsbox = v.TextField( v_model="[]", label="Levels :", outlined=True, style_='width:500px;margin-top:27px' ) self.vboxdoedriver.children[1].children = [_levelsbox, procspermodeldoe] selectlevels = v.RadioGroup( children=[ v.Radio(label='Int', value='Int'), v.Radio(label='Dict', value='Dict'), ], v_model="Int", label="Levels type :", ) selectlevels.on_event('change', onchangelevels) _levelspydoe = v.TextField( v_model=drive.__dict__["_levels"], label="Levels :", min=0, max=1000, outlined=True, type='number', style_='width:500px;margin-top:27px' ) _sizespy = v.TextField( v_model=drive.__dict__["_sizes"], min=0, max=100, label="Sizes :", outlined=True, type='number', style_='width:500px' ) def pydoe_generator(): """ Adapt widgets & vbox widgets to only display widgets you need in this generator """ self.vboxdoedriver.children[0].children = [selectlevels, _sizespy, runparalleldoe] self.vboxdoedriver.children[1].children = [_levelspydoe, procspermodeldoe] drive = driver.doe_generators.FullFactorialGenerator() _levelsfull = v.TextField( v_model=drive.__dict__["_levels"], label="Levels :", min=0, max=1000, outlined=True, type='number', style_='width:500px;margin-top:27px' ) _sizesfull = v.TextField( v_model=drive.__dict__["_sizes"], min=0, max=100, label="Sizes :", outlined=True, type='number', style_='width:500px' ) def full_factorial_generator(): """ Adapt widgets & vbox widgets to only display widgets you need in this generator """ self.vboxdoedriver.children[0].children = [selectlevels, _sizesfull, runparalleldoe] self.vboxdoedriver.children[1].children = [_levelsfull, procspermodeldoe] def generalized_subset_generator(): """ Adapt widgets & vbox widgets to only display widgets you need in this generator """ self.vboxdoedriver.children[0].children = [procspermodeldoe] self.vboxdoedriver.children[1].children = [runparalleldoe] drive = driver.doe_generators.PlackettBurmanGenerator() _levelsplackett = v.TextField( v_model=drive.__dict__["_levels"], label="Levels :", min=0, max=1000, outlined=True, type='number', style_='width:500px;margin-top:27px' ) _sizesplackett = v.TextField( v_model=drive.__dict__["_sizes"], min=0, max=100, label="Sizes :", outlined=True, type='number', style_='width:500px' ) def plackett_burman_generator(): """ Adapt widgets & vbox widgets to only display widgets you need in this generator """ self.vboxdoedriver.children[0].children = [selectlevels, _sizesplackett, runparalleldoe] self.vboxdoedriver.children[1].children = [_levelsplackett, procspermodeldoe] drive = driver.doe_generators.BoxBehnkenGenerator() _levelsbox = v.TextField( v_model=drive.__dict__["_levels"], label="Levels :", min=0, max=1000, outlined=True, type='number', style_='width:500px;margin-top:27px;margin-left:50px' ) _sizesbox = v.TextField( v_model=drive.__dict__["_sizes"], min=0, max=100, label="Sizes :", outlined=True, type='number', style_='width:500px' ) _center = v.TextField( v_model=drive.__dict__["_center"], min=0, max=100, label="Center :", type='number', outlined=True, style_='width:500px;margin-top:5px;margin-left:50px' ) def box_behnken_generator(): """ Adapt widgets & vbox widgets to only display widgets you need in this generator """ self.vboxdoedriver.children[0].children = [selectlevels, _sizesbox, procspermodeldoe] self.vboxdoedriver.children[1].children = [_levelsbox, _center, runparalleldoe] drive = driver.doe_generators.LatinHypercubeGenerator() _samples = v.TextField( v_model=drive.__dict__["_samples"], min=0, max=100, label="Number of samples to generate :", type='number', outlined=True, style_="width:500px;margin-top:5px", ) _criterion = v.Select( items=["None", "center", "maximin", "centermaximin", "correlation"], v_model=drive.__dict__["_criterion"], label="Criterion :", outlined=True, style_="width:500px;margin-top:5px;margin-left:50px", ) _iterations = v.TextField( v_model=drive.__dict__["_iterations"], min=0, max=100, label="Iterations :", outlined=True, type='number', style_="width:500px;margin-top:5px", ) _seedlatin = v.TextField( v_model=drive.__dict__["_seed"], min=0, max=100, label="Seed :", outlined=True, type='number', style_="width:500px;margin-top:5px;margin-left:50px", ) def latin_hypercube_generator(): """ Adapt widgets & vbox widgets to only display widgets you need in this generator """ self.vboxdoedriver.children[0].children = [_samples, _iterations, procspermodeldoe] self.vboxdoedriver.children[1].children = [_criterion, _seedlatin, runparalleldoe] doe_generator() drive = driver.genetic_algorithm_driver.SimpleGADriver() bits = v.TextField( v_model="{}", label="Number of bits of resolution :", outlined=True, style_='width:500px;margin-top:5px', ) elitism = v.Checkbox( v_model=drive.options.__dict__["_dict"]["elitism"].get("value"), label="Elitism", style_='width:500px;margin-left:50px;margin-bottom:40px', ) gray = v.Checkbox( v_model=drive.options.__dict__["_dict"]["gray"].get("value"), label="Gray", style_='width:500px;margin-bottom:20px', ) crossbits = v.Checkbox( v_model=drive.options.__dict__["_dict"]["cross_bits"].get("value"), label="Cross bits", style_='width:500px;margin-left:50px;margin-bottom:20px', ) maxgengenetic = v.TextField( v_model=drive.options.__dict__["_dict"]["max_gen"].get("value"), min=0, max=1000, label="Number of generations :", type='number', outlined=True, style_='width:500px', ) popsizegenetic = v.TextField( v_model=drive.options.__dict__["_dict"]["pop_size"].get("value"), min=0, max=100, label="Number of points in the GA :", type='number', outlined=True, style_='width:500px;margin-left:50px', ) runparallelgenetic = v.Checkbox( v_model=drive.options.__dict__["_dict"]["run_parallel"].get("value"), label="Run parallel", style_='width:500px;margin-bottom:20px', ) procspermodelgenetic = v.TextField( v_model=drive.options.__dict__["_dict"]["procs_per_model"].get("value"), min=drive.options.__dict__["_dict"]["procs_per_model"].get("lower"), max=100, label="Processors per model :", type='number', outlined=True, style_='width:500px;margin-left:50px', ) penaltyparametergenetic = v.TextField( v_model=drive.options.__dict__["_dict"]["penalty_parameter"].get("value"), min=drive.options.__dict__["_dict"]["penalty_parameter"].get("lower"), max=100, label="Penalty parameter :", type='number', outlined=True, style_='width:500px', ) penaltyexponentgenetic = v.TextField( v_model=drive.options.__dict__["_dict"]["penalty_exponent"].get("value"), min=0, max=100, label="Penalty exponent :", type='number', outlined=True, style_='width:500px;margin-left:50px', ) cross_probgenetic = v.TextField( v_model=drive.options.__dict__["_dict"]["Pc"].get("value"), min=drive.options.__dict__["_dict"]["Pc"].get("lower"), max=drive.options.__dict__["_dict"]["Pc"].get("upper"), label="Crossover probability :", type='number', outlined=True, style_='width:500px', ) mut_rate = v.TextField( v_model=drive.options.__dict__["_dict"]["Pm"].get("value"), min=drive.options.__dict__["_dict"]["Pm"].get("lower"), max=drive.options.__dict__["_dict"]["Pm"].get("upper"), label="Mutation rate :", type='number', outlined=True, style_='width:500px;margin-left:50px', ) multiobjweightsgenetic = v.TextField( v_model="{}", label="Multi objective weights :", outlined=True, style_='width:500px', ) multiobjexponentgenetic = v.TextField( v_model=drive.options.__dict__["_dict"]["multi_obj_exponent"].get("value"), min=drive.options.__dict__["_dict"]["multi_obj_exponent"].get("lower"), max=100, label="Multi-objective weighting exponent :", type='number', outlined=True, style_='width:500px;margin-left:50px', ) computepareto = v.Checkbox( v_model=drive.options.__dict__["_dict"]["compute_pareto"].get("value"), label="Compute pareto", style_='width:500px', ) def genetic_algorithm_driver_change(): """ Adapt widgets & vbox widgets to only display widgets you need in this driver """ self.vboxgenerator.children[0].children = [] self.vboxdoedriver.children[0].children = [] self.vboxdoedriver.children[1].children = [] self.vboxdriver.children[0].children = [bits, gray, maxgengenetic, runparallelgenetic, penaltyparametergenetic, cross_probgenetic, multiobjweightsgenetic, computepareto] self.vboxdriver.children[1].children = [elitism, crossbits, popsizegenetic, procspermodelgenetic, penaltyexponentgenetic, mut_rate, multiobjexponentgenetic] def pyoptsparse_driver_change(): """ Adapt widgets & vbox widgets to only display widgets you need in this driver """ self.vboxgenerator.children[0].children = [] self.vboxdoedriver.children[0].children = [] self.vboxdoedriver.children[1].children = [] self.vboxdriver.children[0].children = [] self.vboxdriver.children[1].children = [] def onchange(widget, event, data): """ A function which start the function you need for your driver """ if data == "scipy_optimizer": scipy_optimizer_change() elif data == "differential_evolution_driver": differential_evolution_driver_change() elif data == "doe_driver": doe_driver_change() elif data == "genetic_algorithm_driver": genetic_algorithm_driver_change() elif data == "pyoptsparse_driver": pyoptsparse_driver_change() self.selectDriver = v.Select( items=[ "differential_evolution_driver", "doe_driver", "genetic_algorithm_driver", "pyoptsparse_driver", "scipy_optimizer", ], v_model="scipy_optimizer", label="Driver :", outlined=True, style_="margin-top:5px", ) self.selectDriver.on_event("change", onchange) panel = v.ExpansionPanel( children=[ v.ExpansionPanelHeader( color='#eaeaea', children=['Driver'], style_='margin-bottom:25px;' ), v.ExpansionPanelContent( children=[self.selectDriver,self.vboxdriver,self.vboxgenerator,self.vboxdoedriver] ), ] ) expansionPanel = v.ExpansionPanels( focusable=True, children=[panel], ) display(expansionPanel) scipy_optimizer_change()
display: none; \ background-color: #000000BF; \ ' ) threshold_expp = v.ExpansionPanel(children=[ v.ExpansionPanelHeader( children=['Thresholding'] ), v.ExpansionPanelContent(children=[ apply_contours, threshold_dropd, threshold_slider, threshold_adapt_row, ], #style='\' ) ], style_='display: none;' ) def threshold(img, op_type, value, bs, Cbs): if op_type == 'threshold-binary': ret,thresh = cv2.threshold(img,value,255,cv2.THRESH_BINARY) elif op_type == 'threshold-binary-inverse':
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 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"), ]) ])
items=cfg['options']['Morphological Operations'], ) morpho_slider = slider( #label='Iterations', min=0, max=10, step=1, v_model=3, ticks=False, ) morpho_expp = v.ExpansionPanel(children=[ v.ExpansionPanelHeader(children=['Morphological Operations']), v.ExpansionPanelContent(children=[ morpho_dropd, morpho_slider, ], ) ], style_=' \ display: none; \ background-color: #000000BF; \ ') def morphology(img, op_type, number): kernel = np.ones((5, 5), np.uint8) if op_type == 'erosion': morpho = cv2.erode(img, kernel, iterations=number) return morpho
def statistics_tile(w_selector, statistics_io): def on_click(widget, event, data, path_selector, date_selector, statistic, alert, out): # Clear output if there is something printed before out.clear_output() # Once the button is clicked, disable it btn.disable() # Clear old alert messages alert.clear() @out.capture() def run_process(path_selector, date_selector, statistic, alert): stack_composed(path_selector, date_selector, statistic, alert) run_process(path_selector, date_selector, statistic, alert) # Reactivate button btn.activate() def field_change(change, date_selector, alert): alert.clear() months_and_years = get_months_years(w_selector.get_current_path(), alert) if months_and_years: years, months = months_and_years else: # Stop the excecution return date_selector.clear_season() parsed_months = date_selector.numbers_to_months(months) date_selector.months_items = parsed_months date_selector.years_items = years alert = s.Alert() btn = s.Btn(text="Calculate statistics") out = Output() date_selector = DateSelector(season=True, remove_method=['Single date']) field_widget = w_selector.widget_field() field_widget.observe( partial(field_change, date_selector=date_selector, alert=alert), 'v_model') date_tile = date_picker_tile(date_selector) w_stats = v.Select( label='Statistic', items=statistics_io.items, v_model=statistics_io.selected, ) link((w_stats, 'items'), (statistics_io, 'items')) link((w_stats, 'v_model'), (statistics_io, 'selected')) w_cores = v.Slider(v_model=statistics_io.cores, thumb_label='Always', step=1, label='Processors', min=1, max=statistics_io.cores) link((w_cores, 'v_model'), (statistics_io, 'cores')) w_chunk = v.Slider(v_model=200, thumb_label='Always', step=20, label='Chunk size', max=1000, min=20) link((w_chunk, 'v_model'), (statistics_io, 'chunks')) advanced_settings = v.ExpansionPanels( flat=False, children=[ v.ExpansionPanel(children=[ v.ExpansionPanelHeader(children=['Advanced settings']), v.ExpansionPanelContent(children=[w_cores, w_chunk]) ], ), ]) btn.on_event( 'click', partial( on_click, path_selector=w_selector, date_selector=date_selector, statistic=statistics_io, alert=alert, out=out, )) content = v.Layout(dark=True, _metadata={'mount-id': 'data-input'}, class_="pa-5", row=True, align_center=True, children=[ v.Flex(xs12=True, children=[ statistics_text, v.Subheader(children=['Area selection']), v.Divider(), w_selector, v.Subheader(children=['Date selection']), v.Divider(), date_tile, v.Divider(), w_stats, advanced_settings, btn, alert, out ]), ]) return content
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
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')
items=cfg['neural_style_transfer']['models'], v_model='candy.t7', ) nst_quality = slider( #label='Transfer Quality', min=300, max=1000, step=50, v_model=500, ticks=False, ) nst_expp = v.ExpansionPanel(children=[ v.ExpansionPanelHeader(children=['Neural Style Transfer']), v.ExpansionPanelContent(children=[nst_style, nst_quality], ) ], style_='\ display: block; \ background-color: #000000BF; \ ') def get_model_from_path(style_model_path): model = cv2.dnn.readNetFromTorch(style_model_path) return model def style_transfer(img, model, quality, out): img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)