def __init__(self, model): self.model = model self.panels = v.ExpansionPanels(accordion=True, multiple=True, v_model=[]) up = 'keyboard_arrow_up' down = 'keyboard_arrow_down' legend_icon = v.Icon(children=[down]) self.legend_button = v.Btn(icon=True, children=[legend_icon]) # Style to remove gray background in panels, and remove padding in panel contents panel_style = v.Html(tag='style', children=[( ".v-application--wrap{background-color: white!important}" ".v-expansion-panel-content__wrap{padding:0!important}" ".v-input__slot .v-label{color: black!important}" )]) def a(): self.widgets = VBox([self.panels, panel_style], layout=Layout(padding='0px', border='1px solid black', width='400px')) def b(): self.accesses = Accesses(model, self.update_selection) def c(): self.stats = PlotStats(model) def d(): self.tags = Tags(model, self.update_selection, tag_type=TAG_TYPE_SPACETIME) def e(): self.threads = Tags(model, self.update_selection, tag_type=TAG_TYPE_THREAD) def m(): self.mearsurement = PlotMeasure(model) def f(): self.add_panel(LEGEND_MEM_ACCESS_TITLE, self.accesses.widgets) def g(): self.add_panel(LEGEND_TAGS_TITLE, self.tags.widgets) def h(): self.add_panel(LEGEND_THREADS_TITLE, self.threads.widgets) #def i(): self.add_panel(LEGEND_STATS_TITLE, self.stats.widgets) def n(): self.add_panel(LEGEND_MEASUREMENT_TITLE, self.mearsurement.widgets) self.progress_bar([ a, b, c, d, e, m, f, g, h, #i, n ]) # give accesses nformation about tags and threads for layers def update_legend_icon(_panels, _, selected): if len(selected) == len(self.panels.children): legend_icon.children = [up] elif selected == []: legend_icon.children = [down] self.panels.on_event('change', update_legend_icon) def update_panels(*args): if legend_icon.children[0] == up: legend_icon.children = [down] self.panels.v_model = [] else: legend_icon.children = [up] self.panels.v_model = list(range(len(self.panels.children))) self.legend_button.on_event('click', update_panels)
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 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, model): self.model = model self.panels = v.ExpansionPanels(accordion=True, multiple=True, v_model=[]) up = 'keyboard_arrow_up' down = 'keyboard_arrow_down' legend_icon = v.Icon(children=[down]) self.legend_button = v.Btn(icon=True, children=[legend_icon]) # Style to remove gray background in panels, and remove padding in panel contents panel_style = v.Html( tag='style', children=[ ".v-application--wrap{background-color: white!important} .v-expansion-panel-content__wrap{padding:0!important}" ]) self.widgets = VBox([self.panels, panel_style], layout=Layout(padding='0px', border='1px solid black', width='400px')) self.accesses = Accesses(model, self.update_selection) self.stats = PlotStats(model) self.tags = Tags(model, self.update_selection) self.add_panel(LEGEND_MEM_ACCESS_TITLE, self.accesses.widgets) self.add_panel(LEGEND_TAGS_TITLE, self.tags.widgets) self.add_panel(LEGEND_STATS_TITLE, self.stats.widgets) def update_legend_icon(_panels, _, selected): if len(selected) == len(self.panels.children): legend_icon.children = [up] elif selected == []: legend_icon.children = [down] self.panels.on_event('change', update_legend_icon) def update_panels(*args): if legend_icon.children[0] == up: legend_icon.children = [down] self.panels.v_model = [] else: legend_icon.children = [up] self.panels.v_model = list(range(len(self.panels.children))) self.legend_button.on_event('click', update_panels)
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, test_case, known_cases): """ Widget definition for lattice Boltzmann schemes. Parameters ========== - test_case: the selected test case. - known_cases: dict A dictionary of all known cases the keys are an instance of a test case the values are a list of available lattice Boltzmann schemes for this test case This widget is composed by a menu where you can Choose the lb scheme and modify its default parameters. If you change any of the parameters, you will see a reset button to revover the default parameters of this scheme. This widget is also composed by a main widget where we have 3 tabs - the description of the lb scheme, - the properties of the lb scheme, - the equivalent equations of the lb scheme. """ self.test_case = test_case self.known_cases = known_cases self.default_cases = {c.name: c for c in known_cases[test_case.get_case()]} self.cases = {c.name: copy.copy(c) for c in known_cases[test_case.get_case()]} self.parameters = {} ## ## The menu ## default_case = list(self.cases.keys())[0] self.select_case = v.Select(items=list(self.cases.keys()), v_model=default_case, label='LBM schemes') self.panels = v.ExpansionPanels(v_model=None, children=[ParametersPanel('Show parameters')]) self.reset = v.Btn(children=['reset to default'], class_='d-none') self.menu = [self.select_case, self.panels, self.reset] ## ## The main ## self.description = Markdown() self.properties = v.Layout() self.eq_pde = v.Layout() self.tabs = v.Tabs( v_model=0, children= [ v.Tab(children=['Description']), v.Tab(children=['Properties']), v.Tab(children=['Equivalent equations']), v.TabItem(children=[self.description]), v.TabItem(children=[self.properties]), v.TabItem(children=[self.eq_pde]), ] ) self.main = [self.tabs] # populate the parameters and the description of the selected # lb scheme self.change_case(None) ## ## Widget events ## self.select_case.observe(self.change_case, 'v_model') # Allow to go back to the default parameters self.reset.on_event('click', self.reset_btn) # Check the tab id to activate the computation # of the equivalent equations or the scheme properties # since it can take time. self.tabs.observe(self.change_tab, 'v_model') # If the test case is changed, we need to list the available # lb schemes for this test. self.test_case.select_case.observe(self.change_test_case, 'v_model') # Bind each parameter to change_param # to make the reset button available if needed. self.panels.children[0].bind(self.change_param)
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): # 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 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 __init__(self, aoi_view, layer_model): # get the models self.aoi_model = aoi_view.model self.layer_model = layer_model # name the tile title = cm.constraints.title id_ = "nested_widget" # write a quick explaination tile_txt = sw.Markdown(cm.constraints.desc) # read the layer list and find the layer information based on the layer name layer_list = pd.read_csv(cp.layer_list).fillna("") # create the criteria list self.criterias = [] for key, c in cp.criterias.items(): layer_row = layer_list[layer_list.layer_id == c["layer"]] unit = layer_row.unit.values[0] header = c["header"] value = c["content"] id_ = c["layer"] hint = cm.constraints.info[c["tooltip"]].format(key) if value == "BINARY": # binary criteria crit = cw.Binary(key, header, id_=id_, hint=hint) elif isinstance(value, list): # dropdown values crit = cw.Dropdown(key, value, header, id_=id_, hint=hint) elif value == "RANGE": # range values crit = cw.Range(key, header, unit, id_=id_, hint=hint) self.criterias.append(crit) # create each expansion-panel content self.panels = v.ExpansionPanels( focusable=True, v_model=None, hover=True, accordion=True, children=[ cw.CustomPanel(k, self.criterias) for k in cp.criteria_types.keys() ], ) # default custom_v_model default_v_model = {c.name: c.custom_v_model for c in self.criterias} self.custom_v_model = json.dumps(default_v_model) # cration of the tile super().__init__(id_, title, inputs=[tile_txt, self.panels]) # hide the tile border self.children[0].elevation = 0 # link the visibility of each criteria to the select widget [c.observe(self._on_change, "custom_v_model") for c in self.criterias] self.panels.observe(self._on_panel_change, "v_model") aoi_view.observe(self._update_constraints, "updated")
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 __init__(self, flip_func): f = open('app/config.json') self.cfg = json.load(f) self.output = Output() # Colorspace Seletor self.colorspace_sel = select( items=['RGB', 'HSV', 'LAB', 'GRAY'], v_model='RGB', ) # Image Selector self.img_selector = select( items=self.cfg['images']['images_files'], v_model='img_1.jpeg', style_='height: 15px', ) # Upload button self.upload_btn = button( class_='ma-4', style_='width:35px; height: 35px', size='small', fab=True, color='primary', icon='mdi-upload', outlined=True, ) self.f_input = v.FileInput(show_progress=True) # Turn Histogram Up Switch self.flip_hist_btn = button( class_='ma-4', style_='width:35px; height: 35px', color='primary', size='small', fab=True, icon='mdi-chart-histogram', outlined=True, on_click=flip_func, ) self.save_op_btn = button( class_='ma-4', style_='width:35px; height: 35px', color='primary', size='small', fab=True, icon='mdi-content-save', outlined=True, #on_click=flip_func, ) self.github_btn = button( class_='ma-4', style_='width:35px; height: 35px', size='small', fab=True, color='primary', icon='mdi-source-repository', outlined=True, href='https://github.com/Mateus-M-Reis/grancv', target='_blank', ) self.save_chart_btn = button( class_='ma-4', style_='width:35px; height: 35px', size='small', fab=True, color='secondary', icon='mdi-chart-histogram', #outlined=True, ) self.save_img_btn = button( class_='ma-4', style_='width:35px; height: 35px', size='small', fab=True, color='secondary', icon='mdi-image-plus', #outlined=True, ) self.show_console_btn = button( class_='ma-4', style_='width:35px; height: 35px', size='small', fab=True, color='secondary', icon='mdi-console-line', ##outlined=True, ) # Operations Selector self.op_selector = select_or_create( items=list(self.cfg['operations'].values()), v_model='neural-style-transfer', multiple=True, ) self.op_selector.on_event('change', self.update_expansion_panel) # Operations Panel self.op_panel = v.ExpansionPanels(children=[ smooth_expp, morpho_expp, threshold_expp, nst_expp, watershed_expp ], ) # Sidebar Layout self.drawer = v.Card( children=[ v.NavigationDrawer( width='325px', dark=True, color='#FF000000', #expand_on_hover=True, mini_variant_width='75px', fixed=True, # * floating=True, #permanent=True, #mini_variant=True, #app=True, #disable_route_watcher=True, #disable_resize_watcher=True, #v_model='drawer', #hide_overlay=True, #clipped=True, #absolute=True, #touchless=True, children=[ v.List( children=[ v.ListItem(children=[ self.upload_btn, self.img_selector ], class_='d-flex align-stretch mb-6', style_='height: 40px;'), v.ListItem(children=[ self.flip_hist_btn, self.colorspace_sel ], class_='d-flex align-stretch mb-6', style_='height: 40px;'), #v.ListItem( # children=[ # self.save_op_btn, # self.save_img_btn, # self.save_chart_btn, # self.show_console_btn, # ], # class_='d-flex align-stretch mb-6', # style_='\ # height: 40px; \ # ' # ), v.ListItem(children=[ self.github_btn, self.op_selector, ], class_='d-flex align-stretch mb-6', style_='\ height: 100%; \ '), ], style_='background-color: #000000BF'), v.Divider(), v.List(children=[ v.ListItem(children=[ self.op_panel, ], class_='d-flex align-stretch mb-6', style_='\ width: 100%; \ height: 100%; \ '), ]) ]) ], class_='d-flex flex-column mb-12', )
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"), ]) ])
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 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()
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]), ], )
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, cases, default_case): """ Widget definition for test cases. Parameters ========== - cases: dict the keys of this dictionary are the name of the test case, the values of this dictionary are an instance of the test case. - default_case: str one of the keys found into the dictionary cases. This widget is composed by a menu where you can choose the test case and modify its default parameters. If you change any of the parameters, you will see a reset button to revover the default parameters of this case. This widget is also composed by a main widget where a description of the test cases is given and a plot of the reference solution if it exists. """ self.default_cases = cases # make a copy to not modify the input instances self.cases = copy.deepcopy(cases) self.parameters = {} ## ## The menu ## # widget to select the test case self.select_case = v.Select(items=list(self.cases.keys()), v_model=default_case, label='Test cases') self.panels = v.ExpansionPanels( v_model=None, children=[ParametersPanel('Show parameters')]) self.reset = v.Btn(children=['reset to default'], class_='d-none') self.menu = [self.select_case, self.panels, self.reset] ## ## The main ## self.description = Markdown() plt.ioff() self.fig = plt.figure(figsize=(12, 6)) self.fig.canvas.header_visible = False tabs_content = [ v.TabItem(children=[self.description]), v.TabItem(children=[self.fig.canvas]) ] self.tabs = v.Tabs(v_model=None, children=[ v.Tab(children=['Description']), v.Tab(children=['Reference results']) ] + tabs_content) self.main = [self.tabs] # Add the widget events self.reset.on_event('click', self.reset_btn) self.select_case.observe(self.change_case, 'v_model') self.panels.children[0].bind(self.change_param) self.change_case(None)