Ejemplo n.º 1
0
 def trigger(self, *args):
     image = os.path.join(matplotlib.rcParams['datapath'], 'images',
                          'matplotlib.png')
     parent = self.canvas.manager.window
     dia = SubplotToolQt(self.figure, parent)
     dia.setWindowIcon(QtGui.QIcon(image))
     dia.exec_()
 def set_color(self, color):
     if color != self._color:
         self._color = color
         self.colorChanged.emit(self._color)
         pixmap = QtGui.QPixmap(self.iconSize())
         pixmap.fill(color)
         self.setIcon(QtGui.QIcon(pixmap))
Ejemplo n.º 3
0
 def _icon(self, name):
     if is_pyqt5():
         name = name.replace('.png', '_large.png')
     pm = QtGui.QPixmap(os.path.join(self.basedir, name))
     if hasattr(pm, 'setDevicePixelRatio'):
         pm.setDevicePixelRatio(self.canvas._dpi_ratio)
     return QtGui.QIcon(pm)
Ejemplo n.º 4
0
    def __init__(self, cesta_projekt):
        super().__init__()
        self.setWindowIcon(QtGui.QIcon('foto.jpg'))
        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate("Dialog", "Grafika"))
        self._main = QtWidgets.QWidget()
        self.cesta = cesta_projekt

        self.setCentralWidget(self._main)
        layout = QtWidgets.QVBoxLayout(self._main)

        static_canvas = FigureCanvas(Figure(figsize=(20, 20)))
        layout.addWidget(static_canvas)
        self.addToolBar(NavigationToolbar(static_canvas, self))

        self._static_ax = static_canvas.figure.subplots()

        query = "select Y, X, CB from gps_sour"
        sour = Databaze.sql_query(self.cesta, query)

        y = []
        x = []
        for i in range(0, len(sour)):
            Y = -sour[i][0]
            X = -sour[i][1]
            CB = sour[i][2]
            y.append(Y)
            x.append(X)
            self._static_ax.text(Y, X, CB)

        self._static_ax.plot(y, x, "+")
        self._static_ax.axis('equal')

        self.show()
Ejemplo n.º 5
0
 def _icon(name):
     direct = os.path.dirname(__file__)
     name = os.path.join(direct, name)
     pm = QtGui.QPixmap(name)
     if hasattr(pm, 'setDevicePixelRatio'):
         pm.setDevicePixelRatio(fig.canvas._dpi_ratio)
     return QtGui.QIcon(pm)
Ejemplo n.º 6
0
    def __init__(self, l, r, u, d, parent=None):
        """"""
        QtWidgets.QDialog.__init__(self, parent)
        self.setWindowTitle('Set Heatmap Domain')
        self.setWindowIcon(QtGui.QIcon('kiwi.png'))
        self.setMinimumWidth(400)

        self.header = QtWidgets.QLabel("All distances are relative to the array center.")

        self.leftLabel = QtWidgets.QLabel("Left/West:")
        self.lledit = QtWidgets.QLineEdit(self)
        self.lledit.setText(str(l))

        self.rightLabel = QtWidgets.QLabel("Right/East:")
        self.rledit = QtWidgets.QLineEdit(self)
        self.rledit.setText(str(r))

        self.upLabel = QtWidgets.QLabel("Up/North:")
        self.uledit = QtWidgets.QLineEdit(self)
        self.uledit.setText(str(u))

        self.downLabel = QtWidgets.QLabel("Down/South:")
        self.dledit = QtWidgets.QLineEdit(self)
        self.dledit.setText(str(d))

        self.activate = QtWidgets.QPushButton("Set")

        Box = QtWidgets.QVBoxLayout()

        Box.addWidget(self.header)

        left = QtWidgets.QHBoxLayout()
        left.addWidget(self.leftLabel)
        left.addWidget(self.lledit)

        right = QtWidgets.QHBoxLayout()
        right.addWidget(self.rightLabel)
        right.addWidget(self.rledit)

        up = QtWidgets.QHBoxLayout()
        up.addWidget(self.upLabel)
        up.addWidget(self.uledit)

        down = QtWidgets.QHBoxLayout()
        down.addWidget(self.downLabel)
        down.addWidget(self.dledit)

        Box.addLayout(left)
        Box.addLayout(right)
        Box.addLayout(up)
        Box.addLayout(down)

        Box.addWidget(self.activate)

        # Now put everything into the frame
        self.setLayout(Box)
Ejemplo n.º 7
0
    def _init_toolbar(self):
        #self.basedir = os.path.join(matplotlib.rcParams['datapath'], 'images')
        iconDir = os.path.join(os.path.dirname(os.path.abspath(__file__)),'icons', '')
        for text, tooltip_text, image_file, callback in self.toolitems:
            if text is None:
                self.addSeparator()
            else:
                # a = self.addAction(self._icon(iconDir + image_file + '.png'),
                #                          text, getattr(self, callback))
                a = self.addAction(QtGui.QIcon(iconDir + image_file + '.png'),
                                         text, getattr(self, callback))
                self._actions[callback] = a
                if callback in ['zoom', 'pan', 'cursorcluster', 'radiomode', 'shapemode', 'selectedmode']:
                    a.setCheckable(True)
                if tooltip_text is not None:
                    a.setToolTip(tooltip_text)

        if figureoptions is not None:
            # a = self.addAction(self._icon("qt4_editor_options.png"),
            #                    'Customize', self.edit_parameters)
            a = self.addAction(QtGui.QIcon("qt4_editor_options.png"),
                               'Customize', self.edit_parameters)
            a.setToolTip('Edit curves line and axes parameters')

        self.buttons = {}

        # Add the x,y location widget at the right side of the toolbar
        # The stretch factor is 1 which means any resizing of the toolbar
        # will resize this label instead of the buttons.
        if self.coordinates:
            self.locLabel = QtWidgets.QLabel("", self)
            self.locLabel.setAlignment(
                    QtCore.Qt.AlignRight | QtCore.Qt.AlignTop)
            self.locLabel.setSizePolicy(
                QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                  QtWidgets.QSizePolicy.Ignored))
            labelAction = self.addWidget(self.locLabel)
            labelAction.setVisible(True)

        # reference holder for subplots_adjust window
        self.adj_window = None
 def _icon(self, name, color=None):
     if is_pyqt5():
         name = name.replace('.png', '_large.png')
     pm = QtGui.QPixmap(os.path.join(self.basedir, name))
     if hasattr(pm, 'setDevicePixelRatio'):
         pm.setDevicePixelRatio(self.canvas._dpi_ratio)
     if color is not None:
         mask = pm.createMaskFromColor(QtGui.QColor('black'),
                                       QtCore.Qt.MaskOutColor)
         pm.fill(color)
         pm.setMask(mask)
     return QtGui.QIcon(pm)
Ejemplo n.º 9
0
    def setup_file_actions(self):
        self.actions['exit'] = create_action(
            '&Exit',
            parent=self,
            tip='Exit application',
            shortcut='Ctrl+Q',
            icon=QtGui.QIcon('exit.png'),
            connect=QtWidgets.qApp.quit,
            add_to=self.file_menu
        )
        self.actions['remove_interval_markings'] = create_action(
            '&Remove markings in displayed interval',
            parent=self,
            connect=self.delete_visible_markings_in_displayed_interval,
            add_to=self.file_menu,
            shortcut='Ctrl+R'
        )

        self.actions['load_markings'] = create_action(
            '&Load markings for visible series',
            parent=self,
            connect=lambda: self.model.load_markings(only_visible=True),
            add_to=self.file_menu,
        )
        self.actions['save_markings'] = create_action(
            'Save &markings for visible series',
            parent=self,
            connect=lambda: self.model.save_markings(only_visible=True),
            add_to=self.file_menu
        )
        self.actions['save_interval_cleaned'] = create_action(
            'Save visible series as cleaned',
            parent=self,
            connect=lambda: self.model.tag_items(
                tag=CLEANED,
                only_visible=True
            ),
            add_to=self.file_menu,
        )
        self.actions['save_interval_cleaned_between_markings'] = create_action(
            'Save visible series as cleaned between outer markings',
            parent=self,
            connect=lambda: self.model.tag_items_between_outer_markings(
                tag=CLEANED,
                only_visible=True
            ),
            add_to=self.file_menu,
        )
Ejemplo n.º 10
0
 def __init__(self):
     # Set window param
     super(ApplicationWindow, self).__init__()
     self._main = QtWidgets.QWidget()
     self.setCentralWidget(self._main)
     layout = QtWidgets.QVBoxLayout(self._main)
     self.setWindowTitle('Visited Countries World Map')
     self.setWindowIcon(QtGui.QIcon('icon.ico'))
     # Initialize canvas
     self.canvas = WorldMapCanvas()
     layout.addWidget(self.canvas)
     # Add toolbar
     self.addToolBar(NavigationToolbar(self.canvas, self))
     # Set up event handlers
     self.canvas.mpl_connect('button_press_event', self.on_click)
     self.canvas.mpl_connect('motion_notify_event', self.on_move)
Ejemplo n.º 11
0
    def __init__(self, cur_locs=[[0, 0], [0, 1], [1, 0], [1, 1]], parent=None):
        """"""
        QtWidgets.QDialog.__init__(self, parent)
        self.setWindowTitle('Set Array Configuration Information')
        self.setWindowIcon(QtGui.QIcon('kiwi.png'))
        self.setMinimumWidth(400)

        self.coordsLabel = QtWidgets.QLabel("Coordinates")
        self.name1 = QtWidgets.QPlainTextEdit(self)
        self.name1.setPlainText(self.arrayToStr(cur_locs))

        self.activate = QtWidgets.QPushButton("Set")

        Box = QtWidgets.QVBoxLayout()
        Box.addWidget(self.coordsLabel)
        Box.addWidget(self.name1)
        Box.addWidget(self.activate)

        # Now put everything into the frame
        self.setLayout(Box)
Ejemplo n.º 12
0
    def __init__(self, coords=(0., 0.), EPSG=4326, pEPSG=2193, tEPSG=3857, parent=None):
        """"""
        QtWidgets.QDialog.__init__(self, parent)
        self.setWindowTitle('Set GPS Array Information')
        self.setWindowIcon(QtGui.QIcon('kiwi.png'))
        self.setMinimumWidth(400)

        self.coordsLabel = QtWidgets.QLabel("Coordinates")
        self.name1 = QtWidgets.QLineEdit(self)
        self.name1.setText(str(coords)[1:-1])

        self.EPSGLabel = QtWidgets.QLabel("EPSG")
        self.name2 = QtWidgets.QLineEdit(self)
        self.name2.setText(str(EPSG))

        self.EPSGLabel2 = QtWidgets.QLabel("Local Projected EPSG")
        self.name3 = QtWidgets.QLineEdit(self)
        self.name3.setText(str(pEPSG))

        self.EPSGLabel3 = QtWidgets.QLabel("Target EPSG")
        self.name4 = QtWidgets.QLineEdit(self)
        self.name4.setText(str(tEPSG))
        self.name4.setStatusTip("Save the current display to a PNG file.")

        self.activate = QtWidgets.QPushButton("Set")

        Box = QtWidgets.QVBoxLayout()
        Box.addWidget(self.coordsLabel)
        Box.addWidget(self.name1)
        Box.addWidget(self.EPSGLabel)
        Box.addWidget(self.name2)
        Box.addWidget(self.EPSGLabel2)
        Box.addWidget(self.name3)
        Box.addWidget(self.EPSGLabel3)
        Box.addWidget(self.name4)
        Box.addWidget(self.activate)

        # Now put everything into the frame
        self.setLayout(Box)
Ejemplo n.º 13
0
 def _icon(self, name):
     return QtGui.QIcon(os.path.join(self.media, name))
Ejemplo n.º 14
0
    def __init__(self, canvas, num):
        FigureManagerBase.__init__(self, canvas, num)
        self.canvas = canvas
        self.window = MainWindow()
        self.window.closing.connect(canvas.close_event)
        self.window.closing.connect(self._widgetclosed)

        self.window.setWindowTitle("Figure %d" % num)
        image = os.path.join(matplotlib.rcParams['datapath'], 'images',
                             'matplotlib.svg')
        self.window.setWindowIcon(QtGui.QIcon(image))

        # Give the keyboard focus to the figure instead of the
        # manager; StrongFocus accepts both tab and click to focus and
        # will enable the canvas to process event w/o clicking.
        # ClickFocus only takes the focus is the window has been
        # clicked
        # on. http://qt-project.org/doc/qt-4.8/qt.html#FocusPolicy-enum or
        # http://doc.qt.digia.com/qt/qt.html#FocusPolicy-enum
        self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.canvas.setFocus()

        self.window._destroying = False

        self.toolmanager = self._get_toolmanager()
        self.toolbar = self._get_toolbar(self.canvas, self.window)
        self.statusbar = None

        if self.toolmanager:
            backend_tools.add_tools_to_manager(self.toolmanager)
            if self.toolbar:
                backend_tools.add_tools_to_container(self.toolbar)
                self.statusbar = StatusbarQt(self.window, self.toolmanager)

        if self.toolbar is not None:
            self.window.addToolBar(self.toolbar)
            if not self.toolmanager:
                # add text label to status bar
                statusbar_label = QtWidgets.QLabel()
                self.window.statusBar().addWidget(statusbar_label)
                self.toolbar.message.connect(statusbar_label.setText)
            tbs_height = self.toolbar.sizeHint().height()
        else:
            tbs_height = 0

        # resize the main window so it will display the canvas with the
        # requested size:
        cs = canvas.sizeHint()
        sbs = self.window.statusBar().sizeHint()
        self._status_and_tool_height = tbs_height + sbs.height()
        height = cs.height() + self._status_and_tool_height
        self.window.resize(cs.width(), height)

        self.window.setCentralWidget(self.canvas)

        if matplotlib.is_interactive():
            self.window.show()
            self.canvas.draw_idle()

        def notify_axes_change(fig):
            # This will be called whenever the current axes is changed
            if self.toolbar is not None:
                self.toolbar.update()

        self.canvas.figure.add_axobserver(notify_axes_change)
        self.window.raise_()
Ejemplo n.º 15
0
    def __init__(self):
        super(ApplicationWindow, self).__init__()
        # self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
        self._main = QtWidgets.QStackedWidget()
        self.file_name = "NO NAME"
        # self._main = QtWidgets.QWidget()
        self.setCentralWidget(self._main)
        # self.setWindowTitle("UHSLC QC Software")
        self.setWindowIcon(QtGui.QIcon('uhslclogotext72_pfL_icon.ico'))
        self.resize(1837, 1200)

        # Create Screen objects
        self.start_screen = Start(self)
        self.second_screen = HelpScreen(self)
        self._main.addWidget(self.start_screen)
        self._main.addWidget(self.second_screen)

        self._main.setCurrentWidget(self.start_screen)

        self.start_screen.clicked.connect(
            lambda: self._main.setCurrentWidget(self.second_screen))
        self.second_screen.clicked.connect(
            lambda: self._main.setCurrentWidget(self.start_screen))

        self.setStatusTip("Permanent status bar")
        # Create an action in the menu bar that is later on assigned to one of
        # the options (e.g. File, Edit, View etc) in the menu bar
        close_app = QtWidgets.QAction("&Exit", self)
        close_app.setShortcut("Ctrl+Q")
        # Show the tip in the status bar on hover
        close_app.setStatusTip('Leave the app')
        close_app.triggered.connect(self.close_application)

        open_help_menu = QtWidgets.QAction("&Instructions", self)
        open_help_menu.setShortcut("F1")
        open_help_menu.triggered.connect(self.start_screen.clicked.emit)
        # open_help_menu.triggered.connect(self.open_help_menu)

        open_file = QtWidgets.QAction("&Open monp", self)
        open_file.setShortcut("Ctrl+O")
        open_file.setStatusTip('Load a File')
        open_file.triggered.connect(self.file_open)

        reload_file = QtWidgets.QAction("&Reload", self)
        reload_file.setShortcut("Ctrl+R")
        reload_file.setStatusTip('Reload all file(s) that were loaded')
        reload_file.triggered.connect(self.get_loaded_files)

        opents_file = QtWidgets.QAction("&Open ts", self)
        opents_file.setShortcut("Ctrl+T")
        opents_file.setStatusTip('Opens ts folder')
        opents_file.triggered.connect(self.open_ts)

        self.statusBar()

        # Create dropwon menu
        main_menu = self.menuBar()

        # Add options to the menuBar
        file_menu = main_menu.addMenu('&File')
        help_menu = main_menu.addMenu('&Help')

        # Connect action with the option
        file_menu.addAction(open_file)
        file_menu.addAction(reload_file)
        file_menu.addAction(opents_file)
        file_menu.addAction(close_app)
        help_menu.addAction(open_help_menu)
Ejemplo n.º 16
0
 def configure_subplots(self):
     image = os.path.join(matplotlib.rcParams['datapath'], 'images', 'matplotlib.png')
     dia = CustomSubplotTool(self.canvas.figure, self.parent)
     dia.setWindowIcon(QtGui.QIcon(image))
     dia.exec_()
Ejemplo n.º 17
0
 def _icon(self, name):
     pm = QtGui.QPixmap(os.path.join(self.basedir, name))
     if hasattr(pm, 'setDevicePixelRatio'):
         pm.setDevicePixelRatio(self.canvas._dpi_ratio)
     return QtGui.QIcon(pm)
Ejemplo n.º 18
0
    def __init__(self):
        """Initialise the application - includes loading settings from disc, initialising a lakeator, and setting up the GUI."""
        super().__init__()
        self._load_settings()

        self._main = QtWidgets.QWidget()
        self.setCentralWidget(self._main)
        layout = QtWidgets.QHBoxLayout(self._main)

        self.setWindowTitle('Locator')
        self.setWindowIcon(QtGui.QIcon("./kiwi.png"))

        self.loadAction = QtWidgets.QAction("&Load File", self)
        self.loadAction.setShortcut("Ctrl+L")
        self.loadAction.setStatusTip("Load a multichannel .wav file.")
        self.loadAction.triggered.connect(self.file_open)

        self.saveAction = QtWidgets.QAction("&Save Image", self)
        self.saveAction.setShortcut("Ctrl+S")
        self.saveAction.setStatusTip("Save the current display to a PNG file.")
        self.saveAction.triggered.connect(self.save_display)
        self.saveAction.setDisabled(True)

        self.saveGisAction = QtWidgets.QAction("&Save to GIS", self)
        self.saveGisAction.setShortcut("Ctrl+G")
        self.saveGisAction.setStatusTip(
            "Save the heatmap as a QGIS-readable georeferenced TIFF file.")
        self.saveGisAction.triggered.connect(self.exportGIS)
        self.saveGisAction.setDisabled(True)

        self.statusBar()

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu("&File")
        fileMenu.addAction(self.loadAction)
        fileMenu.addAction(self.saveAction)
        fileMenu.addAction(self.saveGisAction)

        setArrayDesign = QtWidgets.QAction("&Configure Array Design", self)
        setArrayDesign.setShortcut("Ctrl+A")
        setArrayDesign.setStatusTip(
            "Input relative microphone positions and array bearing.")
        setArrayDesign.triggered.connect(self.get_array_info)

        setGPSCoords = QtWidgets.QAction("&Set GPS Coordinates", self)
        setGPSCoords.setShortcut("Ctrl+C")
        setGPSCoords.setStatusTip(
            "Set the GPS coordinates for the array, and ESPG code for the CRS."
        )
        setGPSCoords.triggered.connect(self.get_GPS_info)

        arrayMenu = mainMenu.addMenu("&Array")
        arrayMenu.addAction(setArrayDesign)
        arrayMenu.addAction(setGPSCoords)

        setDomain = QtWidgets.QAction("&Set Heatmap Domain", self)
        setDomain.setShortcut("Ctrl+D")
        setDomain.setStatusTip(
            "Configure distances left/right up/down at which to generate the heatmap."
        )
        setDomain.triggered.connect(self.getBoundsInfo)

        self.refreshHeatmap = QtWidgets.QAction("&Calculate", self)
        self.refreshHeatmap.setShortcut("Ctrl+H")
        self.refreshHeatmap.setStatusTip("(Re)calculate heatmap.")
        self.refreshHeatmap.triggered.connect(self.generate_heatmap)
        self.refreshHeatmap.setDisabled(True)

        self.refreshView = QtWidgets.QAction("&Recalculate on View", self)
        self.refreshView.setShortcut("Ctrl+R")
        self.refreshView.setStatusTip(
            "Recalculate heatmap at current zoom level.")
        self.refreshView.triggered.connect(self.recalculateOnView)
        self.refreshView.setDisabled(True)

        heatmapMenu = mainMenu.addMenu("&Heatmap")
        heatmapMenu.addAction(setDomain)

        # Initialise canvas
        self.static_canvas = FigureCanvas(Figure(figsize=(5, 3)))
        layout.addWidget(self.static_canvas)

        # Add a navbar
        navbar = NavigationToolbar(self.static_canvas, self)
        self.addToolBar(QtCore.Qt.BottomToolBarArea, navbar)

        # Override the default mpl save functionality to change default filename
        navbar._actions['save_figure'].disconnect()
        navbar._actions['save_figure'].triggered.connect(self.save_display)

        navbar._actions['home'].triggered.connect(lambda: print("testing"))

        self.img = None

        # Dynamically generate menu full of all available colourmaps. Do not add the inverted ones.
        self.colMenu = heatmapMenu.addMenu("&Choose Colour Map")
        self.colMenu.setDisabled(True)
        colGroup = QtWidgets.QActionGroup(self)
        for colour in sorted(colormaps(), key=str.casefold):
            if colour[-2:] != "_r":
                cm = self.colMenu.addAction(colour)
                cm.setCheckable(True)
                if colour == self.settings["heatmap"]["cmap"][:-2]:
                    cm.setChecked(True)
                receiver = lambda checked, cmap=colour: self.img.set_cmap(cmap)
                cm.triggered.connect(receiver)
                cm.triggered.connect(self._setcol)
                cm.triggered.connect(self.static_canvas.draw)
                colGroup.addAction(cm)

        self.invert = QtWidgets.QAction("&Invert Colour Map", self)
        self.invert.setShortcut("Ctrl+I")
        self.invert.setStatusTip("Invert the current colourmap.")
        self.invert.triggered.connect(self.invert_heatmap)
        self.invert.setCheckable(True)
        self.invert.setDisabled(True)
        heatmapMenu.addAction(self.invert)

        heatmapMenu.addSeparator()
        heatmapMenu.addAction(self.refreshHeatmap)
        heatmapMenu.addAction(self.refreshView)

        algoMenu = mainMenu.addMenu("Algorithm")
        self.algChoice = algoMenu.addMenu("&Change Algorithm")
        algGroup = QtWidgets.QActionGroup(self)
        for alg in sorted(["GCC", "MUSIC", "AF-MUSIC"], key=str.casefold):
            cm = self.algChoice.addAction(alg)
            cm.setCheckable(True)
            if alg == self.settings["algorithm"]["current"]:
                cm.setChecked(True)
            receiver = lambda checked, al=alg: self.setAlg(al)
            cm.triggered.connect(receiver)
            colGroup.addAction(cm)

        self.params = QtWidgets.QAction("&Algorithm Settings", self)
        self.params.setStatusTip("Alter algorithm-specific settings.")
        self.params.triggered.connect(self.getAlgoInfo)
        algoMenu.addAction(self.params)

        # Display a "ready" message
        self.statusBar().showMessage('Ready')

        # Boolean to keep track of whether we have GPS information for the array, and an image
        self._has_GPS = False
        self._has_heatmap = False

        # Keep track of the currently opened file
        self.open_filename = ""

        self.loc = lakeator.Lakeator(self.settings["array"]["mic_locations"])
Ejemplo n.º 19
0
 def _icon(self, name):
     return QtGui.QIcon(os.path.join(self.basedir, name))
Ejemplo n.º 20
0
    def trigger(self, *args, **kwargs):
        all_axes = self.figure.get_axes()
        if not all_axes:
            QMessageBox.warning(
                self.figure.canvas.parent(),
                "Error", "There are no axes to edit.")
            return
        elif len(all_axes) == 1:
            axis = all_axes[0]
        elif self.x_axis_type in {"GST", "LST", "UT"}:
            # edit all axes at the same time, 
            # only makes sense if same data shape is edited
            axis = all_axes[-1]
        else:
            titles = [
                ax.get_label() or
                ax.get_title() or
                " - ".join(filter(None, [ax.get_xlabel(), ax.get_ylabel()])) or
                f"<anonymous {type(ax).__name__}>"
                for ax in all_axes]
            duplicate_titles = [
                title for title in titles if titles.count(title) > 1]
            for i, ax in enumerate(all_axes):
                if titles[i] in duplicate_titles:
                    titles[i] += f" (id: {id(ax):#x})"  # Deduplicate titles.
            item, ok = QInputDialog.getItem(
                self.figure.canvas.parent(), "Customize", "Select axes:",
                titles, 0, False)
            if not ok:
                return
            axis = all_axes[titles.index(item)]

        sep = (None, None)  # separator

        has_curve = len(axis.get_lines()) > 0

        # Get / General
        if self.x_axis_type in ["GST", "LST"]:
            xmin, xmax = (matplotlib.dates._from_ordinalf(l) 
                          for l in axis.get_xlim())
        elif self.x_axis_type == "UT":
            xmin, xmax = (matplotlib.dates._from_ordinalf(l) 
                          for l in axis.get_xlim())
        else:
            xmin, xmax = axis.get_xlim()
        ymin, ymax = axis.get_ylim()

        general = [('Title', axis.get_title()),
                   sep,
                   (None, "<b>X-Axis</b>"),
                   ('Min', xmin), 
                   ('Max', xmax),
                   ('Scale', [axis.get_xscale(), 'linear', 'log']),
                   sep,
                   (None, "<b>Y-Axis</b>"),
                   ('Min', ymin), 
                   ('Max', ymax),
                   ('Scale', [axis.get_yscale(), 'linear', 'log']),
                   sep,
                   ('(Re-)Generate automatic legend', False),
                   ]
        xmin_row = 3
        xmax_row = 4

        # Save the unit data
        xconverter = axis.xaxis.converter
        yconverter = axis.yaxis.converter
        xunits = axis.xaxis.get_units()
        yunits = axis.yaxis.get_units()
        xformatter = axis.xaxis.get_major_formatter()
        yformatter = axis.yaxis.get_major_formatter()

        if has_curve:
            # Get / Curves
            linedict = {}
            for line in axis.get_lines():
                label = line.get_label()
                if label == '_nolegend_':
                    continue
                linedict[label] = line
            curves = []
            linestyles = list(six.iteritems(figureoptions.LINESTYLES))
            drawstyles = list(six.iteritems(figureoptions.DRAWSTYLES))
            markers = list(six.iteritems(figureoptions.MARKERS))
            curvelabels = sorted(linedict.keys())
            for label in curvelabels:
                line = linedict[label]
                color = rgb2hex(colorConverter.to_rgb(line.get_color()))
                ec = rgb2hex(colorConverter.to_rgb(line.get_markeredgecolor()))
                fc = rgb2hex(colorConverter.to_rgb(line.get_markerfacecolor()))
                curvedata = [('Label', label),
                             sep,
                             (None, '<b>Line</b>'),
                             ('Line Style',
                              [line.get_linestyle()] + linestyles),
                             ('Draw Style',
                              [line.get_drawstyle()] + drawstyles),
                             ('Width', line.get_linewidth()),
                             ('Color', color),
                             sep,
                             (None, '<b>Marker</b>'),
                             ('Style', [line.get_marker()] + markers),
                             ('Size', line.get_markersize()),
                             ('Facecolor', fc),
                             ('Edgecolor', ec),
                             ]
                curves.append([curvedata, label, ""])

            # make sure that there is at least one displayed curve
            has_curve = bool(curves)

        datalist = [(general, "Axes", "")]
        if has_curve:
            datalist.append((curves, "Curves", ""))

        def apply_callback(data):
            """This function will be called to apply changes"""
            if has_curve:
                general, curves = data
            else:
                general, = data

            # Set / General
            title, xmin, xmax, xscale, ymin, ymax, yscale, \
                generate_legend = general

            axes_to_apply = [axis]
            if self.x_axis_type in {"GST", "LST", "UT"}:
                axes_to_apply = all_axes
            for apply_to_axis in axes_to_apply:
                apply_to_axis.set_xscale(xscale)
                apply_to_axis.set_yscale(yscale)
                apply_to_axis.set_title(title)
                apply_to_axis.set_xlim(xmin, xmax)
                apply_to_axis.set_ylim(ymin, ymax)

                # Restore the unit data
                apply_to_axis.xaxis.converter = xconverter
                apply_to_axis.yaxis.converter = yconverter
                apply_to_axis.xaxis.set_units(xunits)
                apply_to_axis.yaxis.set_units(yunits)
                apply_to_axis.xaxis.set_major_formatter(xformatter)
                apply_to_axis.yaxis.set_major_formatter(yformatter)
                apply_to_axis.xaxis._update_axisinfo()
                apply_to_axis.yaxis._update_axisinfo()

                if has_curve:
                    # Set / Curves
                    for index, curve in enumerate(curves):
                        line = linedict[curvelabels[index]]
                        label, linestyle, drawstyle, linewidth, color, \
                            marker, markersize, markerfacecolor, \
                            markeredgecolor = curve
                        line.set_label(label)
                        line.set_linestyle(linestyle)
                        line.set_drawstyle(drawstyle)
                        line.set_linewidth(linewidth)
                        line.set_color(color)
                        if marker != 'none':
                            line.set_marker(marker)
                            line.set_markersize(markersize)
                            line.set_markerfacecolor(markerfacecolor)
                            line.set_markeredgecolor(markeredgecolor)

                # re-generate legend, if checkbox is checked

                if generate_legend:
                    draggable = None
                    ncol = 1
                    if apply_to_axis.legend_ is not None:
                        old_legend = apply_to_axis.get_legend()
                        draggable = old_legend.get_draggable()
                        ncol = old_legend._ncol
                    new_legend = apply_to_axis.legend(ncol=ncol)
                    if new_legend:
                        new_legend.set_draggable(draggable)

            # Redraw
            figure = apply_to_axis.get_figure()
            figure.canvas.draw()

        dialog = FormDialogWrapper(
            datalist, 
            title="Figure options", 
            icon=QtGui.QIcon(self.image), 
            apply=apply_callback)
        axes_tab = dialog.formwidget.widgetlist[0]
        if LooseVersion(formlayout.__version__) >= LooseVersion("1.2"):
            # in version >= 1.2 the widgetlist elements are
            # (title, widget) tuples
            axes_tab = axes_tab[1]

        if self.x_axis_type in ["GST", "LST"]:
            layout = axes_tab.formlayout
            for (value, row) in ((xmin, xmin_row), (xmax, xmax_row)):
                layout.removeRow(row)
                widget = LstWidget(value, axis.xaxis.lst_base_date, axes_tab)
                layout.insertRow(row, general[row][0], widget)
                axes_tab.widgets[row] = widget
        elif self.x_axis_type == "UT":
            for row in (xmin_row, xmax_row):
                axes_tab.widgets[row].setDisplayFormat("yyyy-MM-dd hh:mm:ss")

        if dialog.exec_():
            apply_callback(dialog.get())
Ejemplo n.º 21
0
    def __init__(self, algSettingsDict, parent=None):
        """"""
        QtWidgets.QDialog.__init__(self, parent)
        self.setWindowTitle('Change Algorithm-Specific Settings')
        self.setWindowIcon(QtGui.QIcon('kiwi.png'))
        self.setMinimumWidth(400)
        self.cur = algSettingsDict["current"]

        # Set the font to be used for section headings
        fnt = QtGui.QFont()
        fnt.setBold(True)

        # AF-MUSIC
        self.afTitle = QtWidgets.QLabel("AF-MUSIC:")
        self.afTitle.setFont(fnt)

        self.fmax_l = QtWidgets.QLabel(u"\u0192_max (Hz):")
        self.fmax = QtWidgets.QLineEdit(self)
        self.fmax.setText(str(algSettingsDict["AF-MUSIC"]["f_max"]))

        self.fmin_l = QtWidgets.QLabel(u"\u0192_min (Hz):")
        self.fmin = QtWidgets.QLineEdit(self)
        self.fmin.setText(str(algSettingsDict["AF-MUSIC"]["f_min"]))

        self.f0_l = QtWidgets.QLabel("Focusing Frequency (Hz):")
        self.f0 = QtWidgets.QLineEdit(self)
        self.f0.setText(str(algSettingsDict["AF-MUSIC"]["f_0"]))

        # GCC
        self.GCCTitle = QtWidgets.QLabel("GCC:")
        self.GCCTitle.setFont(fnt)

        # Available processors: PHAT, p-PHAT, CC, RIR, SCOT, HB
        self.GCC_l = QtWidgets.QLabel("Processor:")
        # self.GCC.setText(algSettingsDict["GCC"]["processor"])

        self.possible_processors = ["PHAT", "p-PHAT", "CC", "RIR", "SCOT", "HB"]
        self.cb = QtWidgets.QComboBox()
        self.cb.addItems(self.possible_processors)
        self.cb.setCurrentIndex(self.possible_processors.index(algSettingsDict["GCC"]["processor"]))


        self.def_rho = algSettingsDict["GCC"]["rho"]
        self.sl_l = QtWidgets.QLabel(u"0 \u2265 \u03C1={} \u2265 1:".format(self.def_rho))
        self.sl = QtWidgets.QSlider(QtCore.Qt.Horizontal)
        self.sl.setMinimum(0)
        self.sl.setMaximum(100)
        self.sl.setTickInterval(10)
        self.sl.setTickPosition(QtWidgets.QSlider.TicksBelow)
        self.sl.setValue(int(self.def_rho*100))
        self.sl.valueChanged.connect(self.changeRho)

        # MUSIC
        self.MUSICTitle = QtWidgets.QLabel("MUSIC:")
        self.MUSICTitle.setFont(fnt)

        self.MUSIC_l = QtWidgets.QLabel("Frequency:")
        self.MUSIC = QtWidgets.QLineEdit(self)
        self.MUSIC.setText(str(algSettingsDict["MUSIC"]["freq"]))

        self.activate = QtWidgets.QPushButton("Set")

        Box = QtWidgets.QVBoxLayout()

        Box.addWidget(self.afTitle)
        f_min = QtWidgets.QHBoxLayout()
        f_min.addWidget(self.fmin_l)
        f_min.addWidget(self.fmin)
        Box.addLayout(f_min)

        f_max = QtWidgets.QHBoxLayout()
        f_max.addWidget(self.fmax_l)
        f_max.addWidget(self.fmax)
        Box.addLayout(f_max)

        f_0 = QtWidgets.QHBoxLayout()
        f_0.addWidget(self.f0_l)
        f_0.addWidget(self.f0)
        Box.addLayout(f_0)

        Box.addSpacerItem(QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum,
                                                QtWidgets.QSizePolicy.Expanding))

        Box.addWidget(self.GCCTitle)
        procBox = QtWidgets.QHBoxLayout()
        procBox.addWidget(self.GCC_l)
        procBox.addWidget(self.cb)
        Box.addLayout(procBox)

        rhoBox = QtWidgets.QHBoxLayout()
        rhoBox.addWidget(self.sl_l)
        rhoBox.addWidget(self.sl)
        Box.addLayout(rhoBox)

        Box.addSpacerItem(QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum,
                                                QtWidgets.QSizePolicy.Expanding))

        Box.addWidget(self.MUSICTitle)
        MUSICBox = QtWidgets.QHBoxLayout()
        MUSICBox.addWidget(self.MUSIC_l)
        MUSICBox.addWidget(self.MUSIC)
        Box.addLayout(MUSICBox)

        Box.addWidget(self.activate)

        # Now put everything into the frame
        self.setLayout(Box)
Ejemplo n.º 22
0
def figure_edit(axes, parent=None):
    """Edit matplotlib figure options"""
    sep = (None, None)  # separator

    # Get / General
    # Cast to builtin floats as they have nicer reprs.
    xmin, xmax = map(float, axes.get_xlim())
    ymin, ymax = map(float, axes.get_ylim())
    general = [
        ('Title', axes.get_title()),
        sep,
        (None, "<b>X-Axis</b>"),
        ('Left', xmin),
        ('Right', xmax),
        ('Label', axes.get_xlabel()),
        ('Scale', [axes.get_xscale(), 'linear', 'log', 'logit']),
        sep,
        (None, "<b>Y-Axis</b>"),
        ('Bottom', ymin),
        ('Top', ymax),
        ('Label', axes.get_ylabel()),
        ('Scale', [axes.get_yscale(), 'linear', 'log', 'logit']),
        sep,
        ('(Re-)Generate automatic legend', False),
    ]

    # Save the unit data
    xconverter = axes.xaxis.converter
    yconverter = axes.yaxis.converter
    xunits = axes.xaxis.get_units()
    yunits = axes.yaxis.get_units()

    # Sorting for default labels (_lineXXX, _imageXXX).
    def cmp_key(label):
        match = re.match(r"(_line|_image)(\d+)", label)
        if match:
            return match.group(1), int(match.group(2))
        else:
            return label, 0

    # Get / Curves
    linedict = {}
    for line in axes.get_lines():
        label = line.get_label()
        if label == '_nolegend_':
            continue
        linedict[label] = line
    curves = []

    def prepare_data(d, init):
        """
        Prepare entry for FormLayout.

        *d* is a mapping of shorthands to style names (a single style may
        have multiple shorthands, in particular the shorthands `None`,
        `"None"`, `"none"` and `""` are synonyms); *init* is one shorthand
        of the initial style.

        This function returns an list suitable for initializing a
        FormLayout combobox, namely `[initial_name, (shorthand,
        style_name), (shorthand, style_name), ...]`.
        """
        if init not in d:
            d = {**d, init: str(init)}
        # Drop duplicate shorthands from dict (by overwriting them during
        # the dict comprehension).
        name2short = {name: short for short, name in d.items()}
        # Convert back to {shorthand: name}.
        short2name = {short: name for name, short in name2short.items()}
        # Find the kept shorthand for the style specified by init.
        canonical_init = name2short[d[init]]
        # Sort by representation and prepend the initial value.
        return ([canonical_init] + sorted(
            short2name.items(), key=lambda short_and_name: short_and_name[1]))

    curvelabels = sorted(linedict, key=cmp_key)
    for label in curvelabels:
        line = linedict[label]
        color = mcolors.to_hex(mcolors.to_rgba(line.get_color(),
                                               line.get_alpha()),
                               keep_alpha=True)
        ec = mcolors.to_hex(mcolors.to_rgba(line.get_markeredgecolor(),
                                            line.get_alpha()),
                            keep_alpha=True)
        fc = mcolors.to_hex(mcolors.to_rgba(line.get_markerfacecolor(),
                                            line.get_alpha()),
                            keep_alpha=True)
        curvedata = [
            ('Label', label), sep, (None, '<b>Line</b>'),
            ('Line style', prepare_data(LINESTYLES, line.get_linestyle())),
            ('Draw style', prepare_data(DRAWSTYLES, line.get_drawstyle())),
            ('Width', line.get_linewidth()), ('Color (RGBA)', color), sep,
            (None, '<b>Marker</b>'),
            ('Style', prepare_data(MARKERS, line.get_marker())),
            ('Size', line.get_markersize()), ('Face color (RGBA)', fc),
            ('Edge color (RGBA)', ec)
        ]
        curves.append([curvedata, label, ""])
    # Is there a curve displayed?
    has_curve = bool(curves)

    # Get ScalarMappables.
    mappabledict = {}
    for mappable in [*axes.images, *axes.collections]:
        label = mappable.get_label()
        if label == '_nolegend_' or mappable.get_array() is None:
            continue
        mappabledict[label] = mappable
    mappablelabels = sorted(mappabledict, key=cmp_key)
    mappables = []
    cmaps = [(cmap, name) for name, cmap in sorted(cm._cmap_registry.items())]
    for label in mappablelabels:
        mappable = mappabledict[label]
        cmap = mappable.get_cmap()
        if cmap not in cm._cmap_registry.values():
            cmaps = [(cmap, cmap.name), *cmaps]
        low, high = mappable.get_clim()
        mappabledata = [
            ('Label', label),
            ('Colormap', [cmap.name] + cmaps),
            ('Min. value', low),
            ('Max. value', high),
        ]
        if hasattr(mappable, "get_interpolation"):  # Images.
            interpolations = [(name, name)
                              for name in sorted(mimage.interpolations_names)]
            mappabledata.append(
                ('Interpolation',
                 [mappable.get_interpolation(), *interpolations]))
        mappables.append([mappabledata, label, ""])
    # Is there a scalarmappable displayed?
    has_sm = bool(mappables)

    datalist = [(general, "Axes", "")]
    if curves:
        datalist.append((curves, "Curves", ""))
    if mappables:
        datalist.append((mappables, "Images, etc.", ""))

    def apply_callback(data):
        """A callback to apply changes."""
        orig_xlim = axes.get_xlim()
        orig_ylim = axes.get_ylim()

        general = data.pop(0)
        curves = data.pop(0) if has_curve else []
        mappables = data.pop(0) if has_sm else []
        if data:
            raise ValueError("Unexpected field")

        # Set / General
        (title, xmin, xmax, xlabel, xscale, ymin, ymax, ylabel, yscale,
         generate_legend) = general

        if axes.get_xscale() != xscale:
            axes.set_xscale(xscale)
        if axes.get_yscale() != yscale:
            axes.set_yscale(yscale)

        axes.set_title(title)
        axes.set_xlim(xmin, xmax)
        axes.set_xlabel(xlabel)
        axes.set_ylim(ymin, ymax)
        axes.set_ylabel(ylabel)

        # Restore the unit data
        axes.xaxis.converter = xconverter
        axes.yaxis.converter = yconverter
        axes.xaxis.set_units(xunits)
        axes.yaxis.set_units(yunits)
        axes.xaxis._update_axisinfo()
        axes.yaxis._update_axisinfo()

        # Set / Curves
        for index, curve in enumerate(curves):
            line = linedict[curvelabels[index]]
            (label, linestyle, drawstyle, linewidth, color, marker, markersize,
             markerfacecolor, markeredgecolor) = curve
            line.set_label(label)
            line.set_linestyle(linestyle)
            line.set_drawstyle(drawstyle)
            line.set_linewidth(linewidth)
            rgba = mcolors.to_rgba(color)
            line.set_alpha(None)
            line.set_color(rgba)
            if marker != 'none':
                line.set_marker(marker)
                line.set_markersize(markersize)
                line.set_markerfacecolor(markerfacecolor)
                line.set_markeredgecolor(markeredgecolor)

        # Set ScalarMappables.
        for index, mappable_settings in enumerate(mappables):
            mappable = mappabledict[mappablelabels[index]]
            if len(mappable_settings) == 5:
                label, cmap, low, high, interpolation = mappable_settings
                mappable.set_interpolation(interpolation)
            elif len(mappable_settings) == 4:
                label, cmap, low, high = mappable_settings
            mappable.set_label(label)
            mappable.set_cmap(cm.get_cmap(cmap))
            mappable.set_clim(*sorted([low, high]))

        # re-generate legend, if checkbox is checked
        if generate_legend:
            draggable = None
            ncol = 1
            if axes.legend_ is not None:
                old_legend = axes.get_legend()
                draggable = old_legend._draggable is not None
                ncol = old_legend._ncol
            new_legend = axes.legend(ncol=ncol)
            if new_legend:
                new_legend.set_draggable(draggable)

        # Redraw
        figure = axes.get_figure()
        figure.canvas.draw()
        if not (axes.get_xlim() == orig_xlim and axes.get_ylim() == orig_ylim):
            figure.canvas.toolbar.push_current()

    data = _formlayout.fedit(
        datalist,
        title="Figure options",
        parent=parent,
        icon=QtGui.QIcon(
            str(cbook._get_data_path('images', 'qt4_editor_options.svg'))),
        apply=apply_callback)
    if data is not None:
        apply_callback(data)
 def configure_subplots(self):
     image = str(cbook._get_data_path('images/matplotlib.png'))
     dia = SubplotToolQt(self.canvas.figure, self.canvas.parent())
     dia.setWindowIcon(QtGui.QIcon(image))
     dia.exec_()
Ejemplo n.º 24
0
def get_icon(name):
    import matplotlib
    basedir = osp.join(matplotlib.rcParams['datapath'], 'images')
    return QtGui.QIcon(osp.join(basedir, name))
Ejemplo n.º 25
0
 def _icon(self, name):
     pm = QtGui.QPixmap(name)
     if hasattr(pm, 'setDevicePixelRatio'):
         pm.setDevicePixelRatio(self.toolmanager.canvas._dpi_ratio)
     return QtGui.QIcon(pm)