def run(self, args, extra_args): if args.items: items = [] for path in args.items: items.append(os.path.realpath(path)) data = SimpleDataInfo.from_paths(items) else: data = SimpleDataInfo.from_paths([os.getcwd()]) to_file = None if args.to_file: to_file = os.path.realpath(args.to_file) config = None if args.config: filename = os.path.realpath(args.config) if os.path.exists(filename): with open(filename, 'r') as f: config = f.read() figure_options = {} if to_file: if args.width: figure_options.update({'width': args.width}) if args.height: figure_options.update({'height': args.height}) if args.dpi: figure_options.update({'dpi': args.dpi}) view_maps(data, config, figure_options=figure_options, save_filename=to_file) else: view_maps(data, config, show_maximized=args.maximize)
def view_mask(self): data = SimpleDataInfo({'Original mask': load_nifti(self.selectedMaskText.text()).get_data(), 'Slice mask': load_nifti(self.selectedOutputFileText.text()).get_data()}) config = MapPlotConfig() config.dimension = self.dimensionInput.value() config.slice_index = self.sliceInput.value() config.maps_to_show = ['Original mask', 'Slice mask'] start_gui(data=data, config=config, app_exec=False)
def start_gui(data=None, config=None, controller=None, app_exec=True, show_maximized=False, window_title=None): """Start the GUI with the given data and configuration. Args: data (DataInfo): the initial set of data config (MapPlotConfig): the initial configuration controller (mdt.gui.maps_visualizer.base.QtController): the controller to use in the application app_exec (boolean): if true we execute the Qt application, set to false to disable. show_maximized (true): if we want to show the window in a maximized state window_title (str): the title of the window Returns: MapsVisualizerWindow: the generated window """ controller = controller or QtController() enable_pyqt_exception_hook() app = QtManager.get_qt_application_instance() # catches the sigint timer = QTimer() timer.start(500) timer.timeout.connect(lambda: None) main = MapsVisualizerWindow(controller) main.set_window_title(window_title) signal.signal(signal.SIGINT, main.send_sigint) center_window(main) if show_maximized: main.showMaximized() main.show() if data is None: data = SimpleDataInfo({}) controller.apply_action(NewDataAction(data, config=config), store_in_history=False) QtManager.add_window(main) if app_exec: QtManager.exec_() return main
def _start_maps_visualizer(self): folder = self.selectedOutputFolder.text( ) + '/' + self._get_current_model_name() maps = mdt.load_volume_maps(folder) a_map = maps[list(maps.keys())[0]] config = MapPlotConfig() config.dimension = 2 if len(a_map.shape) > 2: config.slice_index = a_map.shape[2] // 2 start_gui(data=SimpleDataInfo.from_paths([folder]), config=config, app_exec=False)
def view_mask(self): mask = np.expand_dims(load_brain_mask(self.selectedOutputText.text()), axis=3) image_data = load_nifti(self.selectedImageText.text()).get_data() masked_image = image_data * mask data = SimpleDataInfo({ 'Masked': masked_image, 'DWI': image_data, 'Mask': mask }) config = MapPlotConfig() config.dimension = 2 config.slice_index = image_data.shape[2] // 2 config.maps_to_show = ['DWI', 'Masked', 'Mask'] start_gui(data=data, config=config, app_exec=False)
def view_maps(self): if self._folder is None: return maps_to_show = [] for item in [ self.selectMaps.item(index) for index in range(self.selectMaps.count()) ]: if item.isSelected(): maps_to_show.append(item.text()) data = SimpleDataInfo.from_paths([self._folder]) config = MapPlotConfig() config.maps_to_show = maps_to_show config.dimension = self.initialDimensionChooser.value() config.slice_index = self.initialSliceChooser.value() start_gui(data=data, config=config, app_exec=False)
def write_view_maps_figure(data, output_filename, config=None, width=None, height=None, dpi=None, figure_options=None, savefig_settings=None): """Saves the view maps figure to a file. Args: data (str, dict, :class:`~mdt.visualization.maps.base.DataInfo`, list, tuple): the data we are showing, either a dictionary with result maps, a string with a path name, a DataInfo object or a list with filenames and or directories. config (str, dict, :class:`~mdt.visualization.maps.base import MapPlotConfig`): either a Yaml string or a dictionary with configuration settings or a ValidatedMapPlotConfig object to use directly output_filename (str): the output filename width (int): the width of the figure, if set it takes precedence over the value in figure_options height (int): the height of the figure, if set it takes precedence over the value in figure_options dpi (int): the dpi of the figure, if set it takes precedence over the value in figure_options figure_options (dict): additional figure options for the matplotlib Figure, supports the same settings as :func:`view_maps`, that is, if the arguments 'width' and 'height' are not set directly in this function we can also use those in the figure_options savefig_settings (dict): extra output options for the savefig command from matplotlib, if dpi is not given, we use the dpi from the figure_options. """ from mdt.gui.maps_visualizer.main import start_gui from mdt.visualization.maps.base import MapPlotConfig from mdt.visualization.maps.matplotlib_renderer import MapsVisualizer import matplotlib.pyplot as plt from mdt.visualization.maps.base import SimpleDataInfo if isinstance(data, string_types): data = SimpleDataInfo.from_paths([data]) elif isinstance(data, dict): data = SimpleDataInfo(data) elif isinstance(data, collections.Sequence): data = SimpleDataInfo.from_paths(data) elif data is None: data = SimpleDataInfo({}) if config is None: config = MapPlotConfig() elif isinstance(config, string_types): if config.strip(): config = MapPlotConfig.from_yaml(config) else: config = MapPlotConfig() elif isinstance(config, dict): config = MapPlotConfig.from_dict(config) figure_options = figure_options or {} if dpi is not None: figure_options['dpi'] = dpi else: figure_options['dpi'] = figure_options.get('dpi', 80) if height is not None and width is not None: figure_options['figsize'] = (width / figure_options['dpi'], height / figure_options['dpi']) elif height is not None and width is None: width = figure_options.get('width', 800) figure_options['figsize'] = (width / figure_options['dpi'], height / figure_options['dpi']) elif width is not None and height is None: height = figure_options.get('height', 640) figure_options['figsize'] = (width / figure_options['dpi'], height / figure_options['dpi']) elif 'figsize' in figure_options: pass else: width = figure_options.get('width', 800) height = figure_options.get('height', 640) figure_options['figsize'] = (width / figure_options['dpi'], height / figure_options['dpi']) if 'width' in figure_options: del figure_options['width'] if 'height' in figure_options: del figure_options['height'] figure = plt.figure(**figure_options) viz = MapsVisualizer(data, figure) savefig_settings = savefig_settings or {} savefig_settings['dpi'] = savefig_settings.get('dpi', figure_options['dpi']) viz.to_file(output_filename, config, **savefig_settings)
def view_maps(data, config=None, figure_options=None, block=True, show_maximized=False, use_qt=True, window_title=None): """View a number of maps using the MDT Maps Visualizer. Args: data (str, dict, :class:`~mdt.visualization.maps.base.DataInfo`, list, tuple): the data we are showing, either a dictionary with result maps, a string with a path name, a DataInfo object or a list with filenames and/or directories. config (str, dict, :class:`~mdt.visualization.maps.base import MapPlotConfig`): either a Yaml string or a dictionary with configuration settings or a ValidatedMapPlotConfig object to use directly figure_options (dict): figure options for the matplotlib Figure, if figsizes is not given you can also specify two ints, width and height, to indicate the pixel size of the resulting figure, together with the dpi they are used to calculate the figsize. Only used if use_qt=False. block (boolean): if we block the plots or not show_maximized (boolean): if we show the window maximized or not window_title (str): the title for the window use_qt (boolean): if we want to use the Qt GUI, or show the results directly in matplotlib """ from mdt.gui.maps_visualizer.main import start_gui from mdt.visualization.maps.base import MapPlotConfig from mdt.visualization.maps.matplotlib_renderer import MapsVisualizer from mdt.visualization.maps.base import SimpleDataInfo import matplotlib.pyplot as plt if isinstance(data, string_types): data = SimpleDataInfo.from_paths([data]) elif isinstance(data, collections.MutableMapping): data = SimpleDataInfo(data) elif isinstance(data, collections.Sequence): if all(isinstance(el, string_types) for el in data): data = SimpleDataInfo.from_paths(data) else: data = SimpleDataInfo({str(ind): v for ind, v in enumerate(data)}) elif data is None: data = SimpleDataInfo({}) if config is None: config = MapPlotConfig() elif isinstance(config, string_types): if config.strip(): config = MapPlotConfig.from_yaml(config) else: config = MapPlotConfig() elif isinstance(config, dict): config = MapPlotConfig.from_dict(config) if use_qt: start_gui(data, config, app_exec=block, show_maximized=show_maximized, window_title=window_title) else: figure_options = figure_options or {} figure_options['dpi'] = figure_options.get('dpi', 100) if 'figsize' not in figure_options: figure_options['figsize'] = (figure_options.pop('width', 1800) / figure_options['dpi'], figure_options.pop('height', 1600) / figure_options['dpi']) figure = plt.figure(**figure_options) viz = MapsVisualizer(data, figure) viz.show(config, block=block, maximize=show_maximized)
def _remove_files(self): data = SimpleDataInfo({}) config = MapPlotConfig() self._controller.apply_action(NewDataAction(data, config))
def _add_new_maps(self, paths): """Add the given set of file paths to the current visualization. This looks at the current set of file paths (from ``self._controller.get_config().get_data()``) and the given new set of file paths and creates a new merged dataset with all files. Since it is possible that adding new maps leads to naming collisions this function can rename both the old and the new maps to better reflect the map names. Args: paths (list of str): the list of file paths to add to the visualization Returns: list of str: the display names of the newly added maps """ def get_file_paths(data_info): """Get the file paths""" paths = [] for map_name in data_info.get_map_names(): file_path = data_info.get_file_path(map_name) if file_path: paths.append(file_path) else: paths.append(map_name) return paths def get_changes(old_data_info, new_data_info): additions = {} removals = [] name_updates = {} paths = get_file_paths(old_data_info) + get_file_paths(new_data_info) unique_names = get_shortest_unique_names(paths) new_map_names = unique_names[len(old_data_info.get_map_names()):] for old_name, new_name in zip(old_data_info.get_map_names(), unique_names): if old_name != new_name: removals.append(old_name) additions[new_name] = old_data_info.get_single_map_info(old_name) name_updates[old_name] = new_name for new_map_name, new_map_rename in zip(new_data_info.get_map_names(), new_map_names): additions[new_map_rename] = new_data_info.get_single_map_info(new_map_name) return additions, removals, name_updates, new_map_names current_model = self._controller.get_model() current_data = current_model.get_data() adds, rems, name_updates, new_map_names = get_changes(current_data, SimpleDataInfo.from_paths(paths)) data = current_data.get_updated(adds, removals=rems) config = copy.deepcopy(current_model.get_config()) new_maps_to_show = [] for map_name in config.maps_to_show: if map_name in name_updates: new_maps_to_show.append(name_updates[map_name]) else: new_maps_to_show.append(map_name) config.maps_to_show = new_maps_to_show new_map_plot_options = {} for map_name, plot_options in config.map_plot_options.items(): if map_name in name_updates: new_map_plot_options[name_updates[map_name]] = plot_options else: new_map_plot_options[map_name] = plot_options config.map_plot_options = new_map_plot_options if not len(current_data.get_map_names()): config.slice_index = data.get_max_slice_index(config.dimension) // 2 self._controller.apply_action(NewDataAction(data, config=config)) return new_map_names
def __init__(self): super(QtController, self).__init__() self._current_model = SimpleDataConfigModel(SimpleDataInfo({}), MapPlotConfig()) self._actions_history = [] self._redoable_actions = []
def view_maps(data, config=None, figure_options=None, block=True, show_maximized=False, use_qt=True, window_title=None, save_filename=None): """View a number of maps using the MDT Maps Visualizer. Args: data (str, dict, :class:`~mdt.visualization.maps.base.DataInfo`, list, tuple): the data we are showing, either a dictionary with result maps, a string with a path name, a DataInfo object or a list with filenames and/or directories. config (str, dict, :class:`~mdt.visualization.maps.base import MapPlotConfig`): either a Yaml string or a dictionary with configuration settings or a ValidatedMapPlotConfig object to use directly figure_options (dict): Used when ``use_qt`` is False or when ``write_figure`` is used. Sets the figure options for the matplotlib Figure. If figsizes is not given you can also specify two ints, width and height, to indicate the pixel size of the resulting figure, together with the dpi they are used to calculate the figsize. block (boolean): if we block the plots or not show_maximized (boolean): if we show the window maximized or not window_title (str): the title for the window use_qt (boolean): if we want to use the Qt GUI, or show the results directly in matplotlib save_filename (str): save the figure to file. If set, we will not display the viewer. """ from mdt.gui.maps_visualizer.main import start_gui from mdt.visualization.maps.base import MapPlotConfig from mdt.visualization.maps.matplotlib_renderer import MapsVisualizer from mdt.visualization.maps.base import SimpleDataInfo import matplotlib.pyplot as plt from mdt.gui.maps_visualizer.actions import NewDataAction from mdt.gui.maps_visualizer.base import SimpleDataConfigModel if isinstance(data, str): data = SimpleDataInfo.from_paths([data]) elif isinstance(data, collections.MutableMapping): data = SimpleDataInfo(data) elif isinstance(data, collections.Sequence): if all(isinstance(el, str) for el in data): data = SimpleDataInfo.from_paths(data) else: data = SimpleDataInfo({str(ind): v for ind, v in enumerate(data)}) elif data is None: data = SimpleDataInfo({}) if config is None: config = MapPlotConfig() elif isinstance(config, str): if config.strip(): config = MapPlotConfig.from_yaml(config) else: config = MapPlotConfig() elif isinstance(config, dict): config = MapPlotConfig.from_dict(config) config = config.create_valid(data) if not use_qt or save_filename: settings = {'dpi': 100, 'width': 1800, 'height': 1600} if save_filename: settings = {'dpi': 80, 'width': 800, 'height': 600} settings.update(figure_options or {}) if 'figsize' not in settings: settings['figsize'] = (settings['width'] / settings['dpi'], settings['height'] / settings['dpi']) del settings['width'] del settings['height'] figure = plt.figure(**settings) viz = MapsVisualizer(data, figure) if save_filename: viz.to_file(save_filename, config, dpi=settings['dpi']) else: viz.show(config, block=block, maximize=show_maximized) else: start_gui(data, config, app_exec=block, show_maximized=show_maximized, window_title=window_title)