def export_image(self, filename, width, height, dpi=100): width_inch = width / dpi height_inch = height / dpi figure = Figure(figsize=(width_inch, height_inch), dpi=dpi) visualizer = MapsVisualizer(self._controller.get_data(), figure) FigureCanvas(figure) visualizer.to_file(filename, self._controller.get_config(), dpi=dpi)
def __init__(self, controller, parent=None, plotting_info_viewer=None): super(MatplotlibPlotting, self).__init__(controller, plotting_info_viewer=plotting_info_viewer) self._controller.new_data.connect(self.set_new_data) self._controller.new_config.connect(self.set_new_config) self._auto_render = True self.figure = Figure() self.visualizer = MapsVisualizer(self._controller.get_data(), self.figure) self._axes_data = self.visualizer.render(self._controller.get_config()) self.canvas = FigureCanvas(self.figure) self.canvas.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.canvas.updateGeometry() layout = QVBoxLayout() layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.canvas) self.setLayout(layout) self.setParent(parent) self.setFocusPolicy(QtCore.Qt.StrongFocus) self.setFocus() self._redraw_timer = QTimer() self._redraw_timer.timeout.connect(self._timer_event) self._redraw_timer.timeout.connect(self._redraw_timer.stop) self._mouse_interaction = _MouseInteraction(self.figure, self._plotting_info_viewer) self._mouse_interaction.update_axes_data(self._axes_data) self._previous_config = None self.setMinimumWidth(100)
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 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)
def set_new_data(self, data_info): self.visualizer = MapsVisualizer(data_info, self.figure) self._redraw_timer.start(300)
class MatplotlibPlotting(PlottingFrame, QWidget): def __init__(self, controller, parent=None, plotting_info_viewer=None): super(MatplotlibPlotting, self).__init__(controller, plotting_info_viewer=plotting_info_viewer) self._controller.new_data.connect(self.set_new_data) self._controller.new_config.connect(self.set_new_config) self._auto_render = True self.figure = Figure() self.visualizer = MapsVisualizer(self._controller.get_data(), self.figure) self._axes_data = self.visualizer.render(self._controller.get_config()) self.canvas = FigureCanvas(self.figure) self.canvas.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.canvas.updateGeometry() layout = QVBoxLayout() layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.canvas) self.setLayout(layout) self.setParent(parent) self.setFocusPolicy(QtCore.Qt.StrongFocus) self.setFocus() self._redraw_timer = QTimer() self._redraw_timer.timeout.connect(self._timer_event) self._redraw_timer.timeout.connect(self._redraw_timer.stop) self._mouse_interaction = _MouseInteraction(self.figure, self._plotting_info_viewer) self._mouse_interaction.update_axes_data(self._axes_data) self._previous_config = None self.setMinimumWidth(100) def export_image(self, filename, width, height, dpi=100): width_inch = width / dpi height_inch = height / dpi figure = Figure(figsize=(width_inch, height_inch), dpi=dpi) visualizer = MapsVisualizer(self._controller.get_data(), figure) FigureCanvas(figure) visualizer.to_file(filename, self._controller.get_config(), dpi=dpi) def set_auto_rendering(self, auto_render): self._auto_render = auto_render def redraw(self): self._redraw() @pyqtSlot() def _timer_event(self): self._redraw() @pyqtSlot(DataInfo) def set_new_data(self, data_info): self.visualizer = MapsVisualizer(data_info, self.figure) self._redraw_timer.start(300) @pyqtSlot(MapPlotConfig) def set_new_config(self, configuration): if not self._previous_config or configuration.visible_changes( self._previous_config): self._previous_config = configuration if self._auto_render: self._redraw_timer.start(300) def _redraw(self): self.figure.clf() self._axes_data = self.visualizer.render(self._controller.get_config()) self._mouse_interaction.update_axes_data(self._axes_data) self.figure.canvas.draw()
def update(): self._previous_model = model self.visualizer = MapsVisualizer(model.get_data(), self.figure) if self._auto_render: self._redraw_timer.start(300)
class MatplotlibPlotting(PlottingFrame, QWidget): def __init__(self, controller, parent=None, plotting_info_viewer=None): super().__init__(controller, plotting_info_viewer=plotting_info_viewer) self._controller.model_updated.connect(self.update_model) self._auto_render = True current_model = self._controller.get_model() self.figure = Figure(facecolor='#bfbfbf') self.visualizer = MapsVisualizer(current_model.get_data(), self.figure) self._axes_data = self.visualizer.render(current_model.get_config()) self.canvas = FigureCanvas(self.figure) self.canvas.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus) self.canvas.setFocus() self.canvas.updateGeometry() layout = QVBoxLayout() layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.canvas) self.setLayout(layout) self.setParent(parent) self.setFocusPolicy(QtCore.Qt.StrongFocus) self.setFocus() self._redraw_timer = QTimer() self._redraw_timer.timeout.connect(self._timer_event) self._redraw_timer.timeout.connect(self._redraw_timer.stop) self._mouse_interaction = _MouseInteraction(self.figure, self._plotting_info_viewer, self._controller) self._mouse_interaction.update_axes_data(self._axes_data) self._previous_model = None self.setMinimumWidth(100) def export_image(self, filename, width, height, dpi=100): current_model = self._controller.get_model() width_inch = width / dpi height_inch = height / dpi figure = Figure(figsize=(width_inch, height_inch), dpi=dpi) visualizer = MapsVisualizer(current_model.get_data(), figure) FigureCanvas(figure) visualizer.to_file(filename, current_model.get_config(), dpi=dpi) def set_auto_rendering(self, auto_render): self._auto_render = auto_render def redraw(self): self._redraw() @pyqtSlot() def _timer_event(self): self._redraw() @pyqtSlot(DataConfigModel) def update_model(self, model): def update(): self._previous_model = model self.visualizer = MapsVisualizer(model.get_data(), self.figure) if self._auto_render: self._redraw_timer.start(300) if not self._previous_model: update() elif model.get_config().visible_changes( self._previous_model.get_config()): update() elif model.get_data() != self._previous_model.get_data(): update() def _redraw(self): current_model = self._controller.get_model() self.figure.clf() self._axes_data = self.visualizer.render(current_model.get_config()) self._mouse_interaction.update_axes_data(self._axes_data) try: self.figure.canvas.draw() except ValueError as exception: logger = logging.getLogger(__name__) logger.error(exception)
def view_maps(data, config=None, to_file=None, to_file_options=None, block=True, show_maximized=False, use_qt=True, figure_options=None, window_title=None, enable_directory_watcher=True): """View a number of maps using the MDT Maps Visualizer. To save a file to an image, you can use (the simplest) the following two options:: to_file='filename.png', figure_options={'width': 1200, 'height': 750, 'dpi': 100} Args: data (str, dict, :class:`~mdt.visualization.maps.base.DataInfo`): the data we are showing, either a dictionary with result maps, a string with a path name or a DataInfo object 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 to_file (str): if set we output the figure to a file and do not launch a GUI to_file_options (dict): extra output options for the savefig command from matplotlib, if dpi is not given, we use the dpi from the figure_options. block (boolean): if we block the plots or not show_maximized (boolean): if we show the window maximized or not use_qt (boolean): if we want to use the Qt GUI, or show the results directly in matplotlib 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. window_title (str): the title for the window enable_directory_watcher (boolean): if the directory watcher should be enabled/disabled, only applicable for the QT GUI. If the directory watcher is enabled, the viewer will automatically add new maps when added to the folder and also automatically remove maps when they are removed from the directory. It is useful to disable this if you want to have multiple viewers open with old results. """ 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 DataInfo if isinstance(data, string_types): data = DataInfo.from_dir(data) elif isinstance(data, dict): data = DataInfo(data) elif data is None: data = DataInfo({}) 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 to_file: figure_options = figure_options or {} figure_options['dpi'] = figure_options.get('dpi', 80) if 'figsize' not in figure_options: figure_options['figsize'] = (figure_options.pop('width', 800) / figure_options['dpi'], figure_options.pop('height', 640) / figure_options['dpi']) figure = plt.figure(**figure_options) viz = MapsVisualizer(data, figure) to_file_options = to_file_options or {} to_file_options['dpi'] = to_file_options.get('dpi', figure_options['dpi']) viz.to_file(to_file, config, **to_file_options) elif use_qt: start_gui(data, config, app_exec=block, show_maximized=show_maximized, window_title=window_title, enable_directory_watcher=enable_directory_watcher) 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)