def save_figure_widget(self, image_data, title='', caption = '', pvals=None, colors=None): image_widget = Image() image_widget.value = image_data children = [i for i in self.figures_widget.children] html_str = '<b>Figure '+str(len(children)+1)+'. '+title+'</b>' + caption html_widget = HTML(value=html_str) restore_pvals = Button(description='Restore Parameter Values') restore_pvals.pvals = pvals if pvals is None: restore_pvals.visible = False if old_ipython is True: image_widget = Image() image_widget.value = image_data tab_widget = VBox(children=[image_widget, html_widget]) if colors is not None: html_widgets = self.colorbar_tabs(colors) tab_widget.description='Figure' tab_widget = Tab(children=[tab_widget]+html_widgets) else: image_widget = self._image_widget_new(image_data, colors=colors) tab_widget = VBox(children=[image_widget, html_widget]) restore_pvals.on_click(self.restore_figure_pvals) if old_ipython is True: wi = Popup(children=[tab_widget, restore_pvals]) else: contents = VBox(children=[tab_widget, restore_pvals]) contents.width = '100%' wi = Popup(children=[contents]) wi.border = '1px solid black' children.append(wi) self.figures_widget.children = children if colors is not None: if old_ipython is True: tab_widget.set_title(0, 'Figure') tab_widget.set_title(1, 'Colorbar')
def make_plot(self, b): controller = self.controller b.description = 'Creating plot... Please Wait.' b.disabled = True try: b.pvals = controller.pvals.copy() if b.plot_type.value == 'Design Space (interactive)': self.make_interactive_plot(b) elif b.plot_type.value == 'Design Space': self.make_static_plot(b) elif b.plot_type.value == 'Stability': self.make_stability_plot(b) elif b.plot_type.value == 'Eigenvalues': self.make_eigenvalue_plot(b) else: self.make_function_plot(b) except Exception as e: close_button = Button(description="Close") error_message = '<div width="200px" style="float:center; text-align:center;">' error_message += '<b>An error occured while plotting</b></div>' error_window = Popup(children=[HTML(value=error_message),close_button]) close_button.window = error_window close_button.on_click(lambda x: x.window.close()) if old_ipython is False: error_window.box_style='danger' close_button.float = 'center' error_window.width='250px' error_window.height='150px' display(error_window) b.description = 'Add Plot' b.disabled = False else: b.description = 'Add Plot' b.disabled = False
def add_table_widget(self, table_data): html_widget = HTML(value=table_data) wi = Popup(children=[html_widget]) if ipy_old is True: wi.set_css('height', '300px') children = [i for i in self.tables_widget.children] children.append(wi) self.tables_widget.children = children
def add_figure_widget(self, image_data, title='', caption = '', pvals=None, colors=None): children = [i for i in self.unsaved.children] if len(title) > 0: title = title + '.' if len(caption) > 0: caption = ' ' + caption html_str = '<b>'+title+'</b>' + caption html_widget = HTML(value=html_str) save_button = Button(description='Save Figure') save_button.image_data = image_data save_button.title = title save_button.caption = caption save_button.on_click(self.save_unsaved_figure) save_button.pvals = pvals save_button.colors = colors close_button = Button(description='Remove Figure') close_button.on_click(self.remove_unsaved_figure) restore_pvals = Button(description='Restore Parameter Values') restore_pvals.pvals = pvals if pvals is None: restore_pvals.visible = False if old_ipython is True: image_widget = Image() image_widget.value = image_data tab_widget = VBox(children=[image_widget, html_widget]) if colors is not None: html_widgets = self.colorbar_tabs(colors) tab_widget.description='Figure' tab_widget = Tab(children=[tab_widget]+html_widgets) else: image_widget = self._image_widget_new(image_data, colors=colors) tab_widget = VBox(children=[image_widget, html_widget]) toggle = Button(description='Hide') restore_pvals.on_click(self.restore_figure_pvals) if old_ipython is True: wi = Popup(children=[close_button, save_button, tab_widget, restore_pvals]) else: contents = VBox(children=[close_button, save_button, tab_widget, restore_pvals]) contents.width = '100%' wi = Popup(children=[contents]) wi.border = '1px solid black' save_button.wi = wi close_button.wi = wi children.append(wi) self.unsaved.children = children if colors is not None: if old_ipython is True: tab_widget.set_title(0, 'Figure') tab_widget.set_title(1, 'Colorbar')
def create_case_widget(self): controller = self.controller if controller.ds is None: return case = self.case self.info = VBox() self.equations = VBox() self.log_gains = VBox() self.parameter_table = VBox() self.tolerances_table = VBox() self.bounding_box_table = VBox() calculate_pvals = Button(description='Determine values for the parameters') calculate_pvals.visible = False calculate_pvals.on_click(self.identify_parameters) if case.is_valid() is True and case.is_cyclical is False: if self.pvals is None: calculate_pvals.visible = True close_button = Button(description='Close Tab') close_button.on_click(self.close_widget) wi = Popup(children=[self.info, self.equations, self.log_gains, self.bounding_box_table, calculate_pvals, self.parameter_table, self.tolerances_table, close_button]) if ipy_old is True: wi.set_css('height', '400px') else: wi.width = '700px' self.update_display() subtitle = self.subtitle if subtitle != '': subtitle = ' (' + subtitle + ')' self.title = 'Case ' + self.case.case_number + subtitle controller.update_child(self.title, wi)
def visualize_images(images, figure_size=(7, 7), popup=False, **kwargs): r""" Widget that allows browsing through a list of images. Parameters ----------- images : `list` of :map:`Image` or subclass The list of images to be displayed. Note that the images can have different attributes between them, i.e. different landmark groups and labels, different number of channels etc. figure_size : (`int`, `int`), optional The initial size of the plotted figures. popup : `boolean`, optional If enabled, the widget will appear as a popup window. kwargs : `dict`, optional Passed through to the viewer. """ from menpo.image import MaskedImage import matplotlib.pyplot as plt # make sure that images is a list even with one image member if not isinstance(images, Sized): images = [images] # find number of images n_images = len(images) # find initial groups and labels that will be passed to the landmark options # widget creation first_has_landmarks = images[0].landmarks.n_groups != 0 if first_has_landmarks: initial_groups_keys, initial_labels_keys = \ _extract_groups_labels(images[0]) else: initial_groups_keys = [' '] initial_labels_keys = [[' ']] # define plot function def plot_function(name, value): # clear current figure, but wait until the new data to be displayed are # generated clear_output(wait=True) # get selected image number im = 0 if n_images > 1: im = image_number_wid.selected_index # update info text widget image_has_landmarks = images[im].landmarks.n_groups != 0 image_is_masked = isinstance(images[im], MaskedImage) update_info(images[im], image_is_masked, image_has_landmarks, landmark_options_wid.group) # get the current figure id figure_id = save_figure_wid.figure_id # show image with selected options new_figure_id = _plot_figure( image=images[im], figure_id=figure_id, image_enabled=True, landmarks_enabled=landmark_options_wid.landmarks_enabled, image_is_masked=channel_options_wid.image_is_masked, masked_enabled=(channel_options_wid.masked_enabled and image_is_masked), channels=channel_options_wid.channels, glyph_enabled=channel_options_wid.glyph_enabled, glyph_block_size=channel_options_wid.glyph_block_size, glyph_use_negative=channel_options_wid.glyph_use_negative, sum_enabled=channel_options_wid.sum_enabled, groups=[landmark_options_wid.group], with_labels=[landmark_options_wid.with_labels], groups_colours=dict(), subplots_enabled=False, subplots_titles=dict(), image_axes_mode=True, legend_enabled=landmark_options_wid.legend_enabled, numbering_enabled=landmark_options_wid.numbering_enabled, x_scale=figure_options_wid.x_scale, y_scale=figure_options_wid.x_scale, axes_visible=figure_options_wid.axes_visible, figure_size=figure_size, **kwargs) # save the current figure id save_figure_wid.figure_id = new_figure_id # define function that updates info text def update_info(image, image_is_masked, image_has_landmarks, group): # Prepare masked (or non-masked) string masked_str = 'Masked Image' if image_is_masked else 'Image' # Display masked pixels if image is masked masked_pixels_str = (r'{} masked pixels (attached mask {:.1%} true)'. format(image.n_true_pixels(), image.mask.proportion_true()) if image_is_masked else '') # Display number of landmarks if image is landmarked landmarks_str = (r'{} landmark points.'. format(image.landmarks[group].lms.n_points) if image_has_landmarks else '') path_str = image.path if hasattr(image, 'path') else 'NO PATH' # Create info string info_txt = r""" {} of size {} with {} channel{} {} {} min={:.3f}, max={:.3f} {} """.format(masked_str, image._str_shape, image.n_channels, 's' * (image.n_channels > 1), path_str, masked_pixels_str, image.pixels.min(), image.pixels.max(), landmarks_str) # update info widget text info_wid.children[1].value = _raw_info_string_to_latex(info_txt) # create options widgets channel_options_wid = channel_options(images[0].n_channels, isinstance(images[0], MaskedImage), plot_function, masked_default=False, toggle_show_default=True, toggle_show_visible=False) # The landmarks checkbox default value if the first image doesn't have # landmarks landmark_options_wid = landmark_options( initial_groups_keys, initial_labels_keys, plot_function, toggle_show_default=True, landmarks_default=first_has_landmarks, legend_default=True, numbering_default=False, toggle_show_visible=False) # if only a single image is passed in and it doesn't have landmarks, then # landmarks checkbox should be disabled landmark_options_wid.children[1].children[0].disabled = \ not first_has_landmarks figure_options_wid = figure_options(plot_function, scale_default=1., show_axes_default=False, toggle_show_default=True, figure_scale_bounds=(0.1, 2), figure_scale_step=0.1, figure_scale_visible=True, toggle_show_visible=False) info_wid = info_print(toggle_show_default=True, toggle_show_visible=False) initial_figure_id = plt.figure() save_figure_wid = save_figure_options(initial_figure_id, toggle_show_default=True, toggle_show_visible=False) # define function that updates options' widgets state def update_widgets(name, value): # get new groups and labels, update landmark options and format them group_keys, labels_keys = _extract_groups_labels(images[value]) update_landmark_options(landmark_options_wid, group_keys, labels_keys, plot_function) format_landmark_options(landmark_options_wid, container_padding='6px', container_margin='6px', container_border='1px solid black', toggle_button_font_weight='bold', border_visible=False) # update channel options update_channel_options(channel_options_wid, n_channels=images[value].n_channels, image_is_masked=isinstance(images[value], MaskedImage)) # create final widget if n_images > 1: # image selection slider image_number_wid = animation_options( index_min_val=0, index_max_val=n_images-1, plot_function=plot_function, update_function=update_widgets, index_step=1, index_default=0, index_description='Image Number', index_minus_description='<', index_plus_description='>', index_style='buttons', index_text_editable=True, loop_default=True, interval_default=0.3, toggle_show_title='Image Options', toggle_show_default=True, toggle_show_visible=False) # final widget cont_wid = TabWidget(children=[info_wid, channel_options_wid, landmark_options_wid, figure_options_wid, save_figure_wid]) wid = ContainerWidget(children=[image_number_wid, cont_wid]) button_title = 'Images Menu' else: # final widget wid = TabWidget(children=[info_wid, channel_options_wid, landmark_options_wid, figure_options_wid, save_figure_wid]) button_title = 'Image Menu' # create popup widget if asked if popup: wid = PopupWidget(children=[wid], button_text=button_title) # display final widget display(wid) # set final tab titles tab_titles = ['Image info', 'Channels options', 'Landmarks options', 'Figure options', 'Save figure'] if popup: if n_images > 1: for (k, tl) in enumerate(tab_titles): wid.children[0].children[1].set_title(k, tl) else: for (k, tl) in enumerate(tab_titles): wid.children[0].set_title(k, tl) else: if n_images > 1: for (k, tl) in enumerate(tab_titles): wid.children[1].set_title(k, tl) else: for (k, tl) in enumerate(tab_titles): wid.set_title(k, tl) # align-start the image number widget and the rest if n_images > 1: wid.add_class('align-start') # format options' widgets if n_images > 1: format_animation_options(image_number_wid, index_text_width='0.5cm', container_padding='6px', container_margin='6px', container_border='1px solid black', toggle_button_font_weight='bold', border_visible=False) format_channel_options(channel_options_wid, container_padding='6px', container_margin='6px', container_border='1px solid black', toggle_button_font_weight='bold', border_visible=False) format_landmark_options(landmark_options_wid, container_padding='6px', container_margin='6px', container_border='1px solid black', toggle_button_font_weight='bold', border_visible=False) format_figure_options(figure_options_wid, container_padding='6px', container_margin='6px', container_border='1px solid black', toggle_button_font_weight='bold', border_visible=False) format_info_print(info_wid, font_size_in_pt='9pt', container_padding='6px', container_margin='6px', container_border='1px solid black', toggle_button_font_weight='bold', border_visible=False) format_save_figure_options(save_figure_wid, container_padding='6px', container_margin='6px', container_border='1px solid black', toggle_button_font_weight='bold', tab_top_margin='0cm', border_visible=False) # update widgets' state for image number 0 update_widgets('', 0) # Reset value to trigger initial visualization landmark_options_wid.children[1].children[1].value = False
def visualize_shapes(shapes, figure_size=(7, 7), popup=False, **kwargs): r""" Widget that allows browsing through a list of shapes. Parameters ----------- shapes : `list` of :map:`LandmarkManager` or subclass The list of shapes to be displayed. Note that the shapes can have different attributes between them, i.e. different landmark groups and labels etc. figure_size : (`int`, `int`), optional The initial size of the plotted figures. popup : `boolean`, optional If enabled, the widget will appear as a popup window. kwargs : `dict`, optional Passed through to the viewer. """ import matplotlib.pyplot as plt # make sure that shapes is a list even with one shape member if not isinstance(shapes, list): shapes = [shapes] # find number of shapes n_shapes = len(shapes) # find initial groups and labels that will be passed to the landmark options # widget creation first_has_landmarks = shapes[0].n_groups != 0 if first_has_landmarks: initial_groups_keys, initial_labels_keys = \ _exrtact_group_labels_landmarks(shapes[0]) else: initial_groups_keys = [' '] initial_labels_keys = [[' ']] # Define plot function def plot_function(name, value): # clear current figure, but wait until the new data to be displayed are # generated clear_output(wait=True) # get params s = 0 if n_shapes > 1: s = image_number_wid.selected_index axis_mode = axes_mode_wid.value x_scale = figure_options_wid.x_scale y_scale = figure_options_wid.y_scale axes_visible = figure_options_wid.axes_visible # get the current figure id figure_id = plt.figure(save_figure_wid.figure_id.number) # plot if (landmark_options_wid.landmarks_enabled and landmark_options_wid.group != ' '): # invert axis if image mode is enabled if axis_mode == 1: plt.gca().invert_yaxis() # plot shapes[s].view( group=landmark_options_wid.group, with_labels=landmark_options_wid.with_labels, image_view=axis_mode == 1, render_legend=landmark_options_wid.legend_enabled, render_numbering=landmark_options_wid.numbering_enabled, **kwargs) plt.hold(False) plt.gca().axis('equal') # set figure size plt.gcf().set_size_inches([x_scale, y_scale] * np.asarray(figure_size)) # turn axis on/off if not axes_visible: plt.axis('off') plt.show() # save the current figure id save_figure_wid.figure_id = figure_id # info_wid string if landmark_options_wid.group != ' ': info_txt = r""" {} landmark points. Shape range: {:.1f} x {:.1f}. Shape centre: {:.1f} x {:.1f}. Shape norm is {:.2f}. """.format(shapes[s][landmark_options_wid.group][None].n_points, shapes[s][landmark_options_wid.group][None].range()[0], shapes[s][landmark_options_wid.group][None].range()[1], shapes[s][landmark_options_wid.group][None].centre()[0], shapes[s][landmark_options_wid.group][None].centre()[1], shapes[s][landmark_options_wid.group][None].norm()) else: info_txt = "There are no landmarks." info_wid.children[1].value = _raw_info_string_to_latex(info_txt) # create options widgets # The landmarks checkbox default value if the first image doesn't have # landmarks landmark_options_wid = landmark_options( initial_groups_keys, initial_labels_keys, plot_function, toggle_show_default=True, landmarks_default=first_has_landmarks, legend_default=True, numbering_default=False, toggle_show_visible=False) # if only a single image is passed in and it doesn't have landmarks, then # landmarks checkbox should be disabled landmark_options_wid.children[1].children[0].disabled = \ not first_has_landmarks figure_options_wid = figure_options(plot_function, scale_default=1., show_axes_default=False, toggle_show_default=True, toggle_show_visible=False) axes_mode_wid = RadioButtonsWidget(values={'Image': 1, 'Point cloud': 2}, description='Axes mode:', value=1) axes_mode_wid.on_trait_change(plot_function, 'value') ch = list(figure_options_wid.children) ch.insert(3, axes_mode_wid) figure_options_wid.children = ch info_wid = info_print(toggle_show_default=True, toggle_show_visible=False) initial_figure_id = plt.figure() save_figure_wid = save_figure_options(initial_figure_id, toggle_show_default=True, toggle_show_visible=False) # define function that updates options' widgets state def update_widgets(name, value): # get new groups and labels, update landmark options and format them group_keys, labels_keys = _exrtact_group_labels_landmarks(shapes[value]) update_landmark_options(landmark_options_wid, group_keys, labels_keys, plot_function) format_landmark_options(landmark_options_wid, container_padding='6px', container_margin='6px', container_border='1px solid black', toggle_button_font_weight='bold', border_visible=False) # create final widget if n_shapes > 1: # image selection slider image_number_wid = animation_options( index_min_val=0, index_max_val=n_shapes-1, plot_function=plot_function, update_function=update_widgets, index_step=1, index_default=0, index_description='Shape Number', index_minus_description='<', index_plus_description='>', index_style='buttons', index_text_editable=True, loop_default=True, interval_default=0.3, toggle_show_title='Shape Options', toggle_show_default=True, toggle_show_visible=False) # final widget cont_wid = TabWidget(children=[info_wid, landmark_options_wid, figure_options_wid, save_figure_wid]) wid = ContainerWidget(children=[image_number_wid, cont_wid]) button_title = 'Shapes Menu' else: # final widget wid = TabWidget(children=[info_wid, landmark_options_wid, figure_options_wid, save_figure_wid]) button_title = 'Shape Menu' # create popup widget if asked if popup: wid = PopupWidget(children=[wid], button_text=button_title) # display final widget display(wid) # set final tab titles tab_titles = ['Shape info', 'Landmarks options', 'Figure options', 'Save figure'] if popup: if n_shapes > 1: for (k, tl) in enumerate(tab_titles): wid.children[0].children[1].set_title(k, tl) else: for (k, tl) in enumerate(tab_titles): wid.children[0].set_title(k, tl) else: if n_shapes > 1: for (k, tl) in enumerate(tab_titles): wid.children[1].set_title(k, tl) else: for (k, tl) in enumerate(tab_titles): wid.set_title(k, tl) # align-start the image number widget and the rest if n_shapes > 1: wid.add_class('align-start') # format options' widgets if n_shapes > 1: format_animation_options(image_number_wid, index_text_width='0.5cm', container_padding='6px', container_margin='6px', container_border='1px solid black', toggle_button_font_weight='bold', border_visible=False) format_landmark_options(landmark_options_wid, container_padding='6px', container_margin='6px', container_border='1px solid black', toggle_button_font_weight='bold', border_visible=False) format_figure_options(figure_options_wid, container_padding='6px', container_margin='6px', container_border='1px solid black', toggle_button_font_weight='bold', border_visible=False) format_info_print(info_wid, font_size_in_pt='9pt', container_padding='6px', container_margin='6px', container_border='1px solid black', toggle_button_font_weight='bold', border_visible=False) format_save_figure_options(save_figure_wid, container_padding='6px', container_margin='6px', container_border='1px solid black', toggle_button_font_weight='bold', tab_top_margin='0cm', border_visible=False) # update widgets' state for image number 0 update_widgets('', 0) # Reset value to trigger initial visualization landmark_options_wid.children[1].children[1].value = False