def __init__(self, parent=None):
        super(PrintGeometryWidget, self).__init__(parent)
        self.mainLayout = qt.QGridLayout(self)
        self.mainLayout.setContentsMargins(0, 0, 0, 0)
        self.mainLayout.setSpacing(2)
        hbox = qt.QWidget(self)
        hboxLayout = qt.QHBoxLayout(hbox)
        hboxLayout.setContentsMargins(0, 0, 0, 0)
        hboxLayout.setSpacing(2)
        label = qt.QLabel(self)
        label.setText("Units")
        label.setAlignment(qt.Qt.AlignCenter)
        self._pageButton = qt.QRadioButton()
        self._pageButton.setText("Page")
        self._inchButton = qt.QRadioButton()
        self._inchButton.setText("Inches")
        self._cmButton = qt.QRadioButton()
        self._cmButton.setText("Centimeters")
        self._buttonGroup = qt.QButtonGroup(self)
        self._buttonGroup.addButton(self._pageButton)
        self._buttonGroup.addButton(self._inchButton)
        self._buttonGroup.addButton(self._cmButton)
        self._buttonGroup.setExclusive(True)

        # units
        self.mainLayout.addWidget(label, 0, 0, 1, 4)
        hboxLayout.addWidget(self._pageButton)
        hboxLayout.addWidget(self._inchButton)
        hboxLayout.addWidget(self._cmButton)
        self.mainLayout.addWidget(hbox, 1, 0, 1, 4)
        self._pageButton.setChecked(True)

        # xOffset
        label = qt.QLabel(self)
        label.setText("X Offset:")
        self.mainLayout.addWidget(label, 2, 0)
        self._xOffset = FloatEdit(self, 0.1)
        self.mainLayout.addWidget(self._xOffset, 2, 1)

        # yOffset
        label = qt.QLabel(self)
        label.setText("Y Offset:")
        self.mainLayout.addWidget(label, 2, 2)
        self._yOffset = FloatEdit(self, 0.1)
        self.mainLayout.addWidget(self._yOffset, 2, 3)

        # width
        label = qt.QLabel(self)
        label.setText("Width:")
        self.mainLayout.addWidget(label, 3, 0)
        self._width = FloatEdit(self, 0.9)
        self.mainLayout.addWidget(self._width, 3, 1)

        # height
        label = qt.QLabel(self)
        label.setText("Height:")
        self.mainLayout.addWidget(label, 3, 2)
        self._height = FloatEdit(self, 0.9)
        self.mainLayout.addWidget(self._height, 3, 3)

        # aspect ratio
        self._aspect = qt.QCheckBox(self)
        self._aspect.setText("Keep screen aspect ratio")
        self._aspect.setChecked(True)
        self.mainLayout.addWidget(self._aspect, 4, 1, 1, 2)
Ejemplo n.º 2
0
 def createCenteredLabel(self, text, parent=None):
     label = qt.QLabel(parent)
     label.setAlignment(qt.Qt.AlignCenter)
     label.setText(text)
     return label
Ejemplo n.º 3
0
    def __init__(self,
                 parent=None,
                 title="Subtract strip background prior to estimation"):
        super(BackgroundPage, self).__init__(parent)
        self.setTitle(title)
        self.setCheckable(True)
        self.setToolTip(
            "The strip algorithm strips away peaks to compute the " +
            "background signal.\nAt each iteration, a sample is compared " +
            "to the average of the two samples at a given distance in both" +
            " directions,\n and if its value is higher than the average,"
            "it is replaced by the average.")

        layout = qt.QGridLayout(self)
        self.setLayout(layout)

        for i, label_text in enumerate([
                "Strip width (in samples)", "Number of iterations",
                "Strip threshold factor"
        ]):
            label = qt.QLabel(label_text)
            layout.addWidget(label, i, 0)

        self.stripWidthSpin = qt.QSpinBox(self)
        self.stripWidthSpin.setToolTip(
            "Width, in number of samples, of the strip operator")
        self.stripWidthSpin.setRange(1, 999999)

        layout.addWidget(self.stripWidthSpin, 0, 1)

        self.numIterationsSpin = qt.QSpinBox(self)
        self.numIterationsSpin.setToolTip(
            "Number of iterations of the strip algorithm")
        self.numIterationsSpin.setRange(1, 999999)
        layout.addWidget(self.numIterationsSpin, 1, 1)

        self.thresholdFactorEntry = qt.QLineEdit(self)
        self.thresholdFactorEntry.setToolTip(
            "Factor used by the strip algorithm to decide whether a sample" +
            "value should be stripped.\nThe value must be higher than the " +
            "average of the 2 samples at +- w times this factor.\n")
        self.thresholdFactorEntry.setValidator(qt.QDoubleValidator())
        layout.addWidget(self.thresholdFactorEntry, 2, 1)

        self.smoothStripGB = qt.QGroupBox("Apply smoothing prior to strip",
                                          self)
        self.smoothStripGB.setCheckable(True)
        self.smoothStripGB.setToolTip(
            "Apply a smoothing before subtracting strip background" +
            " in fit and estimate processes")
        smoothlayout = qt.QHBoxLayout(self.smoothStripGB)
        label = qt.QLabel("Smoothing width (Savitsky-Golay)")
        smoothlayout.addWidget(label)
        self.smoothingWidthSpin = qt.QSpinBox(self)
        self.smoothingWidthSpin.setToolTip(
            "Width parameter for Savitsky-Golay smoothing (number of samples, must be odd)"
        )
        self.smoothingWidthSpin.setRange(3, 101)
        self.smoothingWidthSpin.setSingleStep(2)
        smoothlayout.addWidget(self.smoothingWidthSpin)

        layout.addWidget(self.smoothStripGB, 3, 0, 1, 2)

        layout.setRowStretch(4, 1)

        self.setDefault()
Ejemplo n.º 4
0
    def __init__(self, parent=None):
        qt.QWidget.__init__(self, parent)

        self.mainLayout = qt.QGridLayout(self)
        self.mainLayout.setColumnStretch(1, 1)

        # Algorithm choice ---------------------------------------------------
        self.algorithmComboLabel = qt.QLabel(self)
        self.algorithmComboLabel.setText("Background algorithm")
        self.algorithmCombo = qt.QComboBox(self)
        self.algorithmCombo.addItem("Strip")
        self.algorithmCombo.addItem("Snip")
        self.algorithmCombo.activated[int].connect(
            self._algorithmComboActivated)

        # Strip parameters ---------------------------------------------------
        self.stripWidthLabel = qt.QLabel(self)
        self.stripWidthLabel.setText("Strip Width")

        self.stripWidthSpin = qt.QSpinBox(self)
        self.stripWidthSpin.setMaximum(100)
        self.stripWidthSpin.setMinimum(1)
        self.stripWidthSpin.valueChanged[int].connect(self._emitSignal)

        self.stripIterLabel = qt.QLabel(self)
        self.stripIterLabel.setText("Strip Iterations")
        self.stripIterValue = qt.QLineEdit(self)
        validator = qt.QIntValidator(self.stripIterValue)
        self.stripIterValue._v = validator
        self.stripIterValue.setText("0")
        self.stripIterValue.editingFinished[()].connect(self._emitSignal)
        self.stripIterValue.setToolTip(
            "Number of iterations for strip algorithm.\n" +
            "If greater than 999, an 2nd pass of strip filter is " +
            "applied to remove artifacts created by first pass.")

        # Snip parameters ----------------------------------------------------
        self.snipWidthLabel = qt.QLabel(self)
        self.snipWidthLabel.setText("Snip Width")

        self.snipWidthSpin = qt.QSpinBox(self)
        self.snipWidthSpin.setMaximum(300)
        self.snipWidthSpin.setMinimum(0)
        self.snipWidthSpin.valueChanged[int].connect(self._emitSignal)

        # Smoothing parameters -----------------------------------------------
        self.smoothingFlagCheck = qt.QCheckBox(self)
        self.smoothingFlagCheck.setText("Smoothing Width (Savitsky-Golay)")
        self.smoothingFlagCheck.toggled.connect(self._smoothingToggled)

        self.smoothingSpin = qt.QSpinBox(self)
        self.smoothingSpin.setMinimum(3)
        #self.smoothingSpin.setMaximum(40)
        self.smoothingSpin.setSingleStep(2)
        self.smoothingSpin.valueChanged[int].connect(self._emitSignal)

        # Anchors ------------------------------------------------------------

        self.anchorsGroup = qt.QWidget(self)
        anchorsLayout = qt.QHBoxLayout(self.anchorsGroup)
        anchorsLayout.setSpacing(2)
        anchorsLayout.setContentsMargins(0, 0, 0, 0)

        self.anchorsFlagCheck = qt.QCheckBox(self.anchorsGroup)
        self.anchorsFlagCheck.setText("Use anchors")
        self.anchorsFlagCheck.setToolTip(
            "Define X coordinates of points that must remain fixed")
        self.anchorsFlagCheck.stateChanged[int].connect(self._anchorsToggled)
        anchorsLayout.addWidget(self.anchorsFlagCheck)

        maxnchannel = 16384 * 4  # Fixme ?
        self.anchorsList = []
        num_anchors = 4
        for i in range(num_anchors):
            anchorSpin = qt.QSpinBox(self.anchorsGroup)
            anchorSpin.setMinimum(0)
            anchorSpin.setMaximum(maxnchannel)
            anchorSpin.valueChanged[int].connect(self._emitSignal)
            anchorsLayout.addWidget(anchorSpin)
            self.anchorsList.append(anchorSpin)

        # Layout ------------------------------------------------------------
        self.mainLayout.addWidget(self.algorithmComboLabel, 0, 0)
        self.mainLayout.addWidget(self.algorithmCombo, 0, 2)
        self.mainLayout.addWidget(self.stripWidthLabel, 1, 0)
        self.mainLayout.addWidget(self.stripWidthSpin, 1, 2)
        self.mainLayout.addWidget(self.stripIterLabel, 2, 0)
        self.mainLayout.addWidget(self.stripIterValue, 2, 2)
        self.mainLayout.addWidget(self.snipWidthLabel, 3, 0)
        self.mainLayout.addWidget(self.snipWidthSpin, 3, 2)
        self.mainLayout.addWidget(self.smoothingFlagCheck, 4, 0)
        self.mainLayout.addWidget(self.smoothingSpin, 4, 2)
        self.mainLayout.addWidget(self.anchorsGroup, 5, 0, 1, 4)

        # Initialize interface -----------------------------------------------
        self._setAlgorithm("strip")
        self.smoothingFlagCheck.setChecked(False)
        self._smoothingToggled(is_checked=False)
        self.anchorsFlagCheck.setChecked(False)
        self._anchorsToggled(is_checked=False)
    def __createConfigurationPanel(self, parent):
        panel = qt.QWidget(parent=parent)
        layout = qt.QVBoxLayout()
        panel.setLayout(layout)

        self.__kind = qt.QButtonGroup(self)
        self.__kind.setExclusive(True)

        group = qt.QGroupBox(self)
        group.setTitle("Image")
        layout.addWidget(group)
        groupLayout = qt.QVBoxLayout(group)

        button = qt.QRadioButton(parent=panel)
        button.setText("Island")
        button.clicked.connect(self.generateIsland)
        button.setCheckable(True)
        button.setChecked(True)
        groupLayout.addWidget(button)
        self.__kind.addButton(button)

        button = qt.QRadioButton(parent=panel)
        button.setText("Gravity")
        button.clicked.connect(self.generateGravityField)
        button.setCheckable(True)
        groupLayout.addWidget(button)
        self.__kind.addButton(button)

        button = qt.QRadioButton(parent=panel)
        button.setText("Magnetic")
        button.clicked.connect(self.generateMagneticField)
        button.setCheckable(True)
        groupLayout.addWidget(button)
        self.__kind.addButton(button)

        button = qt.QRadioButton(parent=panel)
        button.setText("Spiral")
        button.clicked.connect(self.generateSpiral)
        button.setCheckable(True)
        groupLayout.addWidget(button)
        self.__kind.addButton(button)

        button = qt.QRadioButton(parent=panel)
        button.setText("Gradient")
        button.clicked.connect(self.generateGradient)
        button.setCheckable(True)
        groupLayout.addWidget(button)
        self.__kind.addButton(button)

        button = qt.QRadioButton(parent=panel)
        button.setText("Composite gradient")
        button.clicked.connect(self.generateCompositeGradient)
        button.setCheckable(True)
        groupLayout.addWidget(button)
        self.__kind.addButton(button)

        button = qt.QPushButton(parent=panel)
        button.setText("Generate a new image")
        button.clicked.connect(self.generate)
        groupLayout.addWidget(button)

        # Contours

        group = qt.QGroupBox(self)
        group.setTitle("Contours")
        layout.addWidget(group)
        groupLayout = qt.QVBoxLayout(group)

        button = qt.QCheckBox(parent=panel)
        button.setText("Use the plot's mask")
        button.setCheckable(True)
        button.setChecked(True)
        button.clicked.connect(self.updateContours)
        groupLayout.addWidget(button)
        self.__useMaskButton = button

        button = qt.QPushButton(parent=panel)
        button.setText("Update contours")
        button.clicked.connect(self.updateContours)
        groupLayout.addWidget(button)

        # Implementations

        group = qt.QGroupBox(self)
        group.setTitle("Implementation")
        layout.addWidget(group)
        groupLayout = qt.QVBoxLayout(group)

        self.__impl = qt.QButtonGroup(self)
        self.__impl.setExclusive(True)

        button = qt.QRadioButton(parent=panel)
        button.setText("silx")
        button.clicked.connect(self.updateContours)
        button.setCheckable(True)
        button.setChecked(True)
        groupLayout.addWidget(button)
        self.__implMerge = button
        self.__impl.addButton(button)

        button = qt.QRadioButton(parent=panel)
        button.setText("silx with cache")
        button.clicked.connect(self.updateContours)
        button.setCheckable(True)
        groupLayout.addWidget(button)
        self.__implMergeCache = button
        self.__impl.addButton(button)

        button = qt.QRadioButton(parent=panel)
        button.setText("skimage")
        button.clicked.connect(self.updateContours)
        button.setCheckable(True)
        groupLayout.addWidget(button)
        self.__implSkimage = button
        self.__impl.addButton(button)
        if MarchingSquaresSciKitImage is None:
            button.setEnabled(False)
            button.setToolTip("skimage is not installed or not compatible")

        # Processing

        group = qt.QGroupBox(self)
        group.setTitle("Processing")
        layout.addWidget(group)
        group.setLayout(self.__createInfoLayout(group))

        # Processing

        group = qt.QGroupBox(self)
        group.setTitle("Custom level")
        layout.addWidget(group)
        groupLayout = qt.QVBoxLayout(group)

        label = qt.QLabel(parent=panel)
        self.__value = qt.QSlider(panel)
        self.__value.setOrientation(qt.Qt.Horizontal)
        self.__value.sliderMoved.connect(self.__updateCustomContours)
        self.__value.valueChanged.connect(self.__updateCustomContours)
        groupLayout.addWidget(self.__value)

        return panel
Ejemplo n.º 6
0
 def createCenteredLabel(self, text):
     label = qt.QLabel(self)
     label.setAlignment(qt.Qt.AlignCenter)
     label.setText(text)
     return label
Ejemplo n.º 7
0
    def __init__(self, plot, curve, **kwargs):

        super(XsocsPlot2DColorDialog, self).__init__(plot, **kwargs)

        colormap = plot.getPlotColormap(curve)

        self.__plot = weakref.ref(plot)
        self.__curve = curve
        self.__histogram = histo = plot.getHistogram(curve, colormap.nColors)

        if colormap is None:
            minVal = histo.edges[0][0]
            maxVal = histo.edges[0][-1]
            cmap = cm.jet
            nColors = _defaultNColors
        else:
            minVal = colormap.minVal
            maxVal = colormap.maxVal
            cmap = colormap.colormap
            if cmap not in self.colormaps:
                self.colormaps[cmap.name] = cmap
            nColors = colormap.nColors
            if minVal is None:
                minVal = histo.edges[0][0]
            if maxVal is None:
                maxVal = histo.edges[0][-1]

        index = self.colormaps.keys().index(cmap.name)

        self.__colormap = XsocsPlot2DColormap(colormap=cmap,
                                              minVal=minVal,
                                              maxVal=maxVal,
                                              nColors=nColors)

        layout = Qt.QGridLayout(self)

        grpBox = GroupBox('Colormap')
        grpBoxLayout = Qt.QGridLayout(grpBox)
        self.__cmapCBox = cmapCBox = Qt.QComboBox()

        for key, value in self.colormaps.items():
            cmapCBox.addItem(key, userData=value)
        cmapCBox.setCurrentIndex(index)

        grpBoxLayout.addWidget(cmapCBox, 0, 0, Qt.Qt.AlignCenter)

        cmapCBox.currentIndexChanged.connect(self.__cmapCBoxChanged)

        self.__colorLabel = colorLabel = Qt.QLabel()
        colorLabel.setFrameStyle(Qt.QFrame.Panel | Qt.QFrame.Sunken)
        colorLabel.setLineWidth(2)
        colorLabel.setMidLineWidth(2)
        grpBoxLayout.addWidget(colorLabel, 1, 0)
        grpBox.setSizePolicy(Qt.QSizePolicy.Fixed, Qt.QSizePolicy.Fixed)
        layout.addWidget(grpBox, 0, 0)

        grpBox = GroupBox('Range')
        grpBoxLayout = Qt.QGridLayout(grpBox)
        self.__rngSlider = rngSlider = RangeSlider()
        grpBoxLayout.addWidget(rngSlider, 0, 0, 1, 2)

        self.__filledProfile = filledProfile = ColorFilledProfile()
        filledProfile.setFixedHeight(100)
        grpBoxLayout.addWidget(filledProfile, 1, 0, 1, 2)

        self.__minEdit = minEdit = StyledLineEdit(nChar=6)
        self.__maxEdit = maxEdit = StyledLineEdit(nChar=6)
        minEdit.setValidator(Qt.QDoubleValidator())
        maxEdit.setValidator(Qt.QDoubleValidator())
        minEdit.editingFinished.connect(self.__lineEditFinished)
        maxEdit.editingFinished.connect(self.__lineEditFinished)
        grpBoxLayout.addWidget(minEdit, 2, 0)
        grpBoxLayout.addWidget(maxEdit, 2, 1)
        grpBox.setSizePolicy(Qt.QSizePolicy.Fixed, Qt.QSizePolicy.Fixed)
        layout.addWidget(grpBox, 1, 0, Qt.Qt.AlignCenter)

        bnBox = Qt.QDialogButtonBox(Qt.QDialogButtonBox.Close)
        bnBox.button(Qt.QDialogButtonBox.Close).clicked.connect(self.accept)

        layout.addWidget(bnBox, 2, 0)

        self.__setupWidgets()

        rngSlider.sigSliderMoved.connect(self.__rngSliderMoved)
Ejemplo n.º 8
0
    def __init__(self,
                 read_only=False,
                 **kwargs):
        super(AcqParamsWidget, self).__init__(**kwargs)
        layout = Qt.QGridLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)

        self.__read_only = read_only

        self.__beam_energy = None
        self.__dir_beam_h = None
        self.__dir_beam_v = None
        self.__chpdeg_h = None
        self.__chpdeg_v = None

        class DblValidator(Qt.QDoubleValidator):
            def validate(self, text, pos):
                if len(text) == 0:
                    return Qt.QValidator.Acceptable, text, pos
                return super(DblValidator, self).validate(text, pos)

        def dblLineEditWidget(width):
            wid = StyledLineEdit(nChar=width,
                                 readOnly=read_only)
            wid.setValidator(DblValidator())

            return wid

        # ===========
        # beam energy
        # ===========
        row = 0
        h_layout = Qt.QHBoxLayout()
        beam_nrg_edit = dblLineEditWidget(8)
        h_layout.addWidget(beam_nrg_edit)
        h_layout.addWidget(Qt.QLabel('<b>eV</b>'))

        layout.addWidget(Qt.QLabel('Beam energy :'), row, 0)
        layout.addLayout(h_layout, row, 1,
                         alignment=Qt.Qt.AlignLeft | Qt.Qt.AlignTop)
        # ===

        row += 1
        h_line = Qt.QFrame()
        h_line.setFrameShape(Qt.QFrame.HLine)
        h_line.setFrameShadow(Qt.QFrame.Sunken)
        layout.addWidget(h_line, row, 0, 1, 2)

        # ===========
        # direct beam
        # ===========

        row += 1
        h_layout = Qt.QHBoxLayout()
        layout.addLayout(h_layout, row, 1,
                         alignment=Qt.Qt.AlignLeft | Qt.Qt.AlignTop)
        dir_beam_h_edit = dblLineEditWidget(6)
        h_layout.addWidget(Qt.QLabel('v='))
        h_layout.addWidget(dir_beam_h_edit)
        dir_beam_v_edit = dblLineEditWidget(6)
        h_layout.addWidget(Qt.QLabel(' h='))
        h_layout.addWidget(dir_beam_v_edit)
        h_layout.addWidget(Qt.QLabel('<b>px</b>'))
        layout.addWidget(Qt.QLabel('Direct beam :'), row, 0)

        # ===

        row += 1
        h_line = Qt.QFrame()
        h_line.setFrameShape(Qt.QFrame.HLine)
        h_line.setFrameShadow(Qt.QFrame.Sunken)
        layout.addWidget(h_line, row, 0, 1, 3)

        # ===========
        # chan per degree
        # ===========

        row += 1
        h_layout = Qt.QHBoxLayout()
        layout.addLayout(h_layout, row, 1,
                         alignment=Qt.Qt.AlignLeft | Qt.Qt.AlignTop)
        chpdeg_h_edit = dblLineEditWidget(6)
        h_layout.addWidget(Qt.QLabel('v='))
        h_layout.addWidget(chpdeg_h_edit)
        chpdeg_v_edit = dblLineEditWidget(6)
        h_layout.addWidget(Qt.QLabel(' h='))
        h_layout.addWidget(chpdeg_v_edit)
        h_layout.addWidget(Qt.QLabel('<b>px</b>'))
        layout.addWidget(Qt.QLabel('Chan. per deg. :'), row, 0)

        # ===

        row += 1
        h_line = Qt.QFrame()
        h_line.setFrameShape(Qt.QFrame.HLine)
        h_line.setFrameShadow(Qt.QFrame.Sunken)
        layout.addWidget(h_line, row, 0, 1, 3)

        # ===========
        # size constraints
        # ===========
        self.setSizePolicy(Qt.QSizePolicy(Qt.QSizePolicy.Fixed,
                                          Qt.QSizePolicy.Fixed))

        # named tuple with references to all the important widgets
        self.__beam_nrg_edit = beam_nrg_edit
        self.__dir_beam_h_edit = dir_beam_h_edit
        self.__dir_beam_v_edit = dir_beam_v_edit
        self.__chpdeg_h_edit = chpdeg_h_edit
        self.__chpdeg_v_edit = chpdeg_v_edit
Ejemplo n.º 9
0
def main(argv=None):
    """Display an image from a file in an :class:`ImageView` widget.

    :param argv: list of command line arguments or None (the default)
                 to use sys.argv.
    :type argv: list of str
    :return: Exit status code
    :rtype: int
    :raises IOError: if no image can be loaded from the file
    """
    import argparse
    import os.path

    from silx.third_party.EdfFile import EdfFile

    # Command-line arguments
    parser = argparse.ArgumentParser(
        description='Browse the images of an EDF file.')
    parser.add_argument('-o',
                        '--origin',
                        nargs=2,
                        type=float,
                        default=(0., 0.),
                        help="""Coordinates of the origin of the image: (x, y).
        Default: 0., 0.""")
    parser.add_argument('-s',
                        '--scale',
                        nargs=2,
                        type=float,
                        default=(1., 1.),
                        help="""Scale factors applied to the image: (sx, sy).
        Default: 1., 1.""")
    parser.add_argument(
        '-l',
        '--log',
        action="store_true",
        help="Use logarithm normalization for colormap, default: Linear.")
    parser.add_argument('filename',
                        nargs='?',
                        help='EDF filename of the image to open')
    args = parser.parse_args(args=argv)

    # Open the input file
    if not args.filename:
        logger.warning('No image file provided, displaying dummy data')
        edfFile = None
        size = 512
        xx, yy = numpy.ogrid[-size:size, -size:size]
        data = numpy.cos(xx / (size // 5)) + numpy.cos(yy / (size // 5))
        data = numpy.random.poisson(numpy.abs(data))
        nbFrames = 1

    else:
        if not os.path.isfile(args.filename):
            raise IOError('No input file: %s' % args.filename)

        else:
            edfFile = EdfFile(args.filename)
            data = edfFile.GetData(0)

            nbFrames = edfFile.GetNumImages()
            if nbFrames == 0:
                raise IOError('Cannot read image(s) from file: %s' %
                              args.filename)

    global app  # QApplication must be global to avoid seg fault on quit
    app = qt.QApplication([])
    sys.excepthook = qt.exceptionHandler

    mainWindow = ImageViewMainWindow()
    mainWindow.setAttribute(qt.Qt.WA_DeleteOnClose)

    if args.log:  # Use log normalization by default
        colormap = mainWindow.getDefaultColormap()
        colormap.setNormalization(colormap.LOGARITHM)

    mainWindow.setImage(data, origin=args.origin, scale=args.scale)

    if edfFile is not None and nbFrames > 1:
        # Add a toolbar for multi-frame EDF support
        multiFrameToolbar = qt.QToolBar('Multi-frame')
        multiFrameToolbar.addWidget(qt.QLabel('Frame [0-%d]:' %
                                              (nbFrames - 1)))

        spinBox = qt.QSpinBox()
        spinBox.setRange(0, nbFrames - 1)

        def updateImage(index):
            mainWindow.setImage(edfFile.GetData(index),
                                origin=args.origin,
                                scale=args.scale,
                                reset=False)

        spinBox.valueChanged[int].connect(updateImage)
        multiFrameToolbar.addWidget(spinBox)

        mainWindow.addToolBar(multiFrameToolbar)

    mainWindow.show()
    mainWindow.setFocus(qt.Qt.OtherFocusReason)

    return app.exec_()
Ejemplo n.º 10
0
 def createWidget(self, parent):
     widget = qt.QLabel(parent)
     widget.setWordWrap(True)
     widget.setStyleSheet("QLabel { color : red; }")
     return widget
Ejemplo n.º 11
0
    def __init__(self,
                 spec_file=None,
                 img_dir=None,
                 spec_version=1,
                 output_dir=None,
                 tmp_dir=None,
                 **kwargs):
        super(MergeWidget, self).__init__(**kwargs)

        Qt.QGridLayout(self)

        # ################
        # input QGroupBox
        # ################

        if spec_file is not None:
            specFile = spec_file
        else:
            specFile = ''

        if img_dir is not None:
            imgDir = img_dir
        else:
            imgDir = ''

        if spec_version is not None:
            specVersion = spec_version
        else:
            specVersion = self._defaultVersion

        if output_dir is not None:
            outputDir = output_dir
        else:
            outputDir = ''

        # parameters
        self.__input = {
            'specfile': specFile,
            'imgdir': imgDir,
            'version': specVersion,
            'padding': None,
            'offset': None
        }

        self.__output = {'outdir': outputDir, 'prefix': ''}

        inputGbx = GroupBox("Input")
        layout = Qt.QGridLayout(inputGbx)
        self.layout().addWidget(inputGbx, 0, 0, Qt.Qt.AlignTop)

        first_col = 0
        file_bn_col = 4
        last_col = file_bn_col + 1

        spec_row = 0
        img_path_row = 1
        version_row = 2
        apply_bn_row = 3

        # spec file input
        specFileChooser = FileChooser(fileMode=Qt.QFileDialog.ExistingFile,
                                      noLabel=True)
        specFileChooser.lineEdit.setText(specFile)
        specFileChooser.sigSelectionChanged.connect(self.__slotSpecFileChanged)
        layout.addWidget(Qt.QLabel('Spec file :'), spec_row, 0)
        layout.addWidget(specFileChooser, spec_row, 1)

        # image folder input
        imgDirChooser = FileChooser(fileMode=Qt.QFileDialog.Directory,
                                    noLabel=True)
        imgDirChooser.lineEdit.setText(imgDir)
        imgDirChooser.sigSelectionChanged.connect(self.__slotImgDirChanged)
        layout.addWidget(Qt.QLabel('Img dir. :'), img_path_row, 0)
        layout.addWidget(imgDirChooser, img_path_row, 1)

        # version selection
        optionLayout = Qt.QHBoxLayout()
        optionLayout.addStretch(1)

        lab = Qt.QLabel('Version :')
        self.__versionCBx = versionCBx = Qt.QComboBox()

        for version in range(len(self._versions)):
            versionCBx.addItem(str(version))
        versionCBx.addItem('')
        optionLayout.addWidget(lab, Qt.Qt.AlignLeft)
        optionLayout.addWidget(versionCBx, Qt.Qt.AlignLeft)

        # filename padding for the nextNr counter
        self.__padSpinBox = padSpinBox = Qt.QSpinBox()
        optionLayout.addWidget(_vLine())
        optionLayout.addWidget(Qt.QLabel('nextNr padding:'))
        optionLayout.addWidget(padSpinBox, Qt.Qt.AlignLeft)
        padSpinBox.valueChanged[int].connect(self.__slotPaddingValueChanged)

        # filename offset for the nextNr counter
        self.__nextNrSpinBox = nextNrSpinBox = Qt.QSpinBox()
        nextNrSpinBox.setMinimum(-100)
        nextNrSpinBox.setMaximum(100)
        optionLayout.addWidget(_vLine())
        optionLayout.addWidget(Qt.QLabel('nextNr offset:'))
        optionLayout.addWidget(nextNrSpinBox, Qt.Qt.AlignLeft)
        nextNrSpinBox.valueChanged[int].connect(self.__slotNextNrValueChanged)

        optionLayout.addStretch(100)
        layout.addLayout(optionLayout, version_row, 0, 1, layout.columnCount(),
                         Qt.Qt.AlignLeft)

        # last row : apply button
        self.__parseBn = parseBn = FixedSizePushButon('Parse file')
        parseBn.clicked.connect(self.__slotParseBnClicked,
                                Qt.Qt.QueuedConnection)
        layout.addWidget(parseBn, apply_bn_row, 0, 1, last_col - first_col,
                         Qt.Qt.AlignHCenter)

        # ################
        # scans + edf QGroupBox
        # ################
        self.__scansGbx = scansGbx = GroupBox("Spec + EDF")
        grpLayout = Qt.QHBoxLayout(scansGbx)
        self.layout().addWidget(scansGbx, 1, 0,
                                Qt.Qt.AlignLeft | Qt.Qt.AlignTop)

        # ===========
        # valid scans
        # ===========
        scanLayout = Qt.QGridLayout()
        grpLayout.addLayout(scanLayout)

        hLayout = Qt.QHBoxLayout()
        label = Qt.QLabel('<span style=" font-weight:600; color:#00916a;">'
                          'Matched scans</span>')
        label.setTextFormat(Qt.Qt.RichText)
        editScansBn = FixedSizePushButon('Edit')
        editScansBn.clicked.connect(self.__slotEditScansClicked)
        hLayout.addWidget(label)
        hLayout.addWidget(editScansBn)
        scanLayout.addLayout(hLayout, 0, 0, 1, 2)

        label = Qt.QLabel('Total :')
        self.__totalScansEdit = totalScansEdit = Qt.QLineEdit('0')
        totalScansEdit.setReadOnly(True)
        fm = totalScansEdit.fontMetrics()
        width = (fm.boundingRect('0123456').width() +
                 fm.boundingRect('00').width())
        totalScansEdit.setMaximumWidth(width)
        totalScansEdit.setAlignment(Qt.Qt.AlignRight)

        scanLayout.addWidget(label, 1, 0, Qt.Qt.AlignLeft)
        scanLayout.addWidget(totalScansEdit, 1, 1, Qt.Qt.AlignLeft)

        # ====

        label = Qt.QLabel('Selected :')
        self.__selectedScansEdit = selectedScansEdit = Qt.QLineEdit('0')
        selectedScansEdit.setReadOnly(True)
        fm = selectedScansEdit.fontMetrics()
        width = (fm.boundingRect('0123456').width() +
                 fm.boundingRect('00').width())
        selectedScansEdit.setMaximumWidth(width)
        selectedScansEdit.setAlignment(Qt.Qt.AlignRight)

        scanLayout.addWidget(label, 2, 0, Qt.Qt.AlignLeft)
        scanLayout.addWidget(selectedScansEdit, 2, 1, Qt.Qt.AlignLeft)

        # ===

        grpLayout.addWidget(_vLine())

        # ===========
        # "other" scans
        # ===========

        scanLayout = Qt.QGridLayout()
        grpLayout.addLayout(scanLayout)

        hLayout = Qt.QHBoxLayout()
        label = Qt.QLabel('<span style=" font-weight:600; color:#ff6600;">'
                          'Other scans</span>')
        otherScansBn = FixedSizePushButon('View')
        otherScansBn.clicked.connect(self.__slotOtherScansClicked)
        hLayout.addWidget(label)
        hLayout.addWidget(otherScansBn)

        scanLayout.addLayout(hLayout, 0, 0, 1, 2)

        label = Qt.QLabel('No match :')
        self.__noMatchScansEdit = noMatchScansEdit = Qt.QLineEdit('0')
        noMatchScansEdit.setReadOnly(True)
        fm = noMatchScansEdit.fontMetrics()
        width = (fm.boundingRect('0123456').width() +
                 fm.boundingRect('00').width())
        noMatchScansEdit.setMaximumWidth(width)
        noMatchScansEdit.setAlignment(Qt.Qt.AlignRight)

        scanLayout.addWidget(label, 1, 0, Qt.Qt.AlignLeft)
        scanLayout.addWidget(noMatchScansEdit, 1, 1, Qt.Qt.AlignLeft)

        # ====

        label = Qt.QLabel('No img info :')
        self.__noImgInfoEdit = noImgInfoEdit = Qt.QLineEdit('0')
        noImgInfoEdit.setReadOnly(True)
        fm = noImgInfoEdit.fontMetrics()
        width = (fm.boundingRect('0123456').width() +
                 fm.boundingRect('00').width())
        noImgInfoEdit.setMaximumWidth(width)
        noImgInfoEdit.setAlignment(Qt.Qt.AlignRight)

        scanLayout.addWidget(label, 2, 0, Qt.Qt.AlignLeft)
        scanLayout.addWidget(noImgInfoEdit, 2, 1, Qt.Qt.AlignLeft)

        # ===

        grpLayout.addWidget(_vLine())

        # ################
        # parameters
        # ################
        self.__acqParamsGbx = acqParamsGbx = GroupBox("Acq. Parameters")
        grpLayout = Qt.QVBoxLayout(acqParamsGbx)

        self.__acqParamWid = acqParamWid = AcqParamsWidget()
        self.layout().addWidget(acqParamsGbx, 2, 0,
                                Qt.Qt.AlignLeft | Qt.Qt.AlignTop)
        grpLayout.addWidget(acqParamWid)

        # ################
        # output options
        # ################

        self.__outputGbx = outputGbx = GroupBox("Output")
        layout = Qt.QGridLayout(outputGbx)
        self.layout().addWidget(outputGbx, 3, 0, Qt.Qt.AlignTop)

        # ===========
        # master
        # ===========

        lab = Qt.QLabel('Prefix :')
        self.__prefixEdit = prefixEdit = StyledLineEdit(nChar=20)
        prefixEdit.textChanged.connect(self.__slotPrefixChanged)
        hLayout = Qt.QHBoxLayout()
        layout.addLayout(hLayout, 0, 1, Qt.Qt.AlignLeft)
        resetPrefixBn = Qt.QToolButton()
        icon = Qt.qApp.style().standardIcon(Qt.QStyle.SP_BrowserReload)
        resetPrefixBn.setIcon(icon)
        resetPrefixBn.clicked.connect(self.__slotResetPrefixClicked)
        layout.addWidget(lab, 0, 0, Qt.Qt.AlignLeft)
        sp = prefixEdit.sizePolicy()
        sp.setHorizontalPolicy(Qt.QSizePolicy.Maximum)
        prefixEdit.setSizePolicy(sp)
        hLayout.addWidget(prefixEdit, Qt.Qt.AlignLeft)
        hLayout.addWidget(resetPrefixBn, Qt.Qt.AlignLeft)

        # ===========
        # output folder
        # ===========

        outDirChooser = FileChooser(fileMode=Qt.QFileDialog.Directory,
                                    noLabel=True)
        outDirChooser.lineEdit.setText(outputDir)
        outDirChooser.sigSelectionChanged.connect(self.__slotOutDirChanged)
        layout.addWidget(Qt.QLabel('Output directory :'), 1, 0)
        layout.addWidget(outDirChooser, 1, 1)

        # ################
        # merge button
        # ################

        self.__mergeBn = mergeBn = Qt.QPushButton('Merge')
        cancelBn = Qt.QPushButton('Cancel')
        hLayout = Qt.QHBoxLayout()
        self.layout().addLayout(hLayout, 4, 0, 1, 1,
                                Qt.Qt.AlignHCenter | Qt.Qt.AlignTop)
        hLayout.addWidget(mergeBn)
        hLayout.addWidget(cancelBn)
        mergeBn.clicked.connect(self.__slotMergeBnClicked)
        cancelBn.clicked.connect(self.reject)

        # #################
        # setting initial state
        # #################

        # scansGbx.setEnabled(False)
        # acqParamsGbx.setEnabled(False)
        # outputGbx.setEnabled(False)
        # mergeBn.setEnabled(False)
        parseBn.setEnabled(False)

        self.__merger = None
        self.__parser = None
        self.info_wid = None

        if tmp_dir is None:
            tmp_dir, delete_tmp, q_tmp_dir = _create_tmp_dir()
        else:
            delete_tmp = False
            q_tmp_dir = None

        self.__tmp_root = tmp_dir
        self.__delete_tmp_root = delete_tmp
        self.__q_tmp_dir = q_tmp_dir

        tmp_dir = os.path.join(self.__tmp_root, 'xsocs_merge')
        if not os.path.exists(tmp_dir):
            os.makedirs(tmp_dir)

        self.__tmp_dir_merge = tmp_dir

        print('Using temporary folder : {0}.'.format(tmp_dir))

        self.__widgetIsSetup = False

        self.__xsocs_h5 = None

        versionCBx.setCurrentIndex(spec_version)
        self.__slotVersionChanged(spec_version)
        versionCBx.currentIndexChanged[int].connect(self.__slotVersionChanged)

        self.__resetState()

        self.__sigParsed.connect(self.__slotParsed, Qt.Qt.QueuedConnection)
    def _initThresholdGroupBox(self):
        """Init thresholding widgets"""

        self.belowThresholdAction = qt.QAction(
            icons.getQIcon('plot-roi-below'), 'Mask below threshold', self)
        self.belowThresholdAction.setToolTip(
            'Mask image where values are below given threshold')
        self.belowThresholdAction.setCheckable(True)
        self.belowThresholdAction.setChecked(True)

        self.betweenThresholdAction = qt.QAction(
            icons.getQIcon('plot-roi-between'), 'Mask within range', self)
        self.betweenThresholdAction.setToolTip(
            'Mask image where values are within given range')
        self.betweenThresholdAction.setCheckable(True)

        self.aboveThresholdAction = qt.QAction(
            icons.getQIcon('plot-roi-above'), 'Mask above threshold', self)
        self.aboveThresholdAction.setToolTip(
            'Mask image where values are above given threshold')
        self.aboveThresholdAction.setCheckable(True)

        self.thresholdActionGroup = qt.QActionGroup(self)
        self.thresholdActionGroup.setExclusive(True)
        self.thresholdActionGroup.addAction(self.belowThresholdAction)
        self.thresholdActionGroup.addAction(self.betweenThresholdAction)
        self.thresholdActionGroup.addAction(self.aboveThresholdAction)
        self.thresholdActionGroup.triggered.connect(
            self._thresholdActionGroupTriggered)

        self.loadColormapRangeAction = qt.QAction(
            icons.getQIcon('view-refresh'), 'Set min-max from colormap', self)
        self.loadColormapRangeAction.setToolTip(
            'Set min and max values from current colormap range')
        self.loadColormapRangeAction.setCheckable(False)
        self.loadColormapRangeAction.triggered.connect(
            self._loadRangeFromColormapTriggered)

        widgets = []
        for action in self.thresholdActionGroup.actions():
            btn = qt.QToolButton()
            btn.setDefaultAction(action)
            widgets.append(btn)

        spacer = qt.QWidget(parent=self)
        spacer.setSizePolicy(qt.QSizePolicy.Expanding,
                             qt.QSizePolicy.Preferred)
        widgets.append(spacer)

        loadColormapRangeBtn = qt.QToolButton()
        loadColormapRangeBtn.setDefaultAction(self.loadColormapRangeAction)
        widgets.append(loadColormapRangeBtn)

        toolBar = self._hboxWidget(*widgets, stretch=False)

        config = qt.QGridLayout()
        config.setContentsMargins(0, 0, 0, 0)

        self.minLineLabel = qt.QLabel("Min:", self)
        self.minLineEdit = FloatEdit(self, value=0)
        config.addWidget(self.minLineLabel, 0, 0)
        config.addWidget(self.minLineEdit, 0, 1)

        self.maxLineLabel = qt.QLabel("Max:", self)
        self.maxLineEdit = FloatEdit(self, value=0)
        config.addWidget(self.maxLineLabel, 1, 0)
        config.addWidget(self.maxLineEdit, 1, 1)

        self.applyMaskBtn = qt.QPushButton('Apply mask')
        self.applyMaskBtn.clicked.connect(self._maskBtnClicked)

        layout = qt.QVBoxLayout()
        layout.addWidget(toolBar)
        layout.addLayout(config)
        layout.addWidget(self.applyMaskBtn)
        layout.addStretch(1)

        self.thresholdGroup = qt.QGroupBox('Threshold')
        self.thresholdGroup.setLayout(layout)

        # Init widget state
        self._thresholdActionGroupTriggered(self.belowThresholdAction)
        return self.thresholdGroup
    def _initMaskGroupBox(self):
        """Init general mask operation widgets"""

        # Mask level
        self.levelSpinBox = qt.QSpinBox()
        self.levelSpinBox.setRange(1, self._maxLevelNumber)
        self.levelSpinBox.setToolTip(
            'Choose which mask level is edited.\n'
            'A mask can have up to 255 non-overlapping levels.')
        self.levelSpinBox.valueChanged[int].connect(self._updateColors)
        self._levelWidget = self._hboxWidget(qt.QLabel('Mask level:'),
                                             self.levelSpinBox)
        # Transparency
        self._transparencyWidget = self._initTransparencyWidget()

        style = qt.QApplication.style()

        def getIcon(*identifiyers):
            for i in identifiyers:
                if isinstance(i, str):
                    if qt.QIcon.hasThemeIcon(i):
                        return qt.QIcon.fromTheme(i)
                elif isinstance(i, qt.QIcon):
                    return i
                else:
                    return style.standardIcon(i)
            return qt.QIcon()

        undoAction = qt.QAction(self)
        undoAction.setText('Undo')
        icon = getIcon("edit-undo", qt.QStyle.SP_ArrowBack)
        undoAction.setIcon(icon)
        undoAction.setShortcut(qt.QKeySequence.Undo)
        undoAction.setToolTip('Undo last mask change <b>%s</b>' %
                              undoAction.shortcut().toString())
        self._mask.sigUndoable.connect(undoAction.setEnabled)
        undoAction.triggered.connect(self._mask.undo)

        redoAction = qt.QAction(self)
        redoAction.setText('Redo')
        icon = getIcon("edit-redo", qt.QStyle.SP_ArrowForward)
        redoAction.setIcon(icon)
        redoAction.setShortcut(qt.QKeySequence.Redo)
        redoAction.setToolTip('Redo last undone mask change <b>%s</b>' %
                              redoAction.shortcut().toString())
        self._mask.sigRedoable.connect(redoAction.setEnabled)
        redoAction.triggered.connect(self._mask.redo)

        loadAction = qt.QAction(self)
        loadAction.setText('Load...')
        icon = icons.getQIcon("document-open")
        loadAction.setIcon(icon)
        loadAction.setToolTip('Load mask from file')
        loadAction.triggered.connect(self._loadMask)

        saveAction = qt.QAction(self)
        saveAction.setText('Save...')
        icon = icons.getQIcon("document-save")
        saveAction.setIcon(icon)
        saveAction.setToolTip('Save mask to file')
        saveAction.triggered.connect(self._saveMask)

        invertAction = qt.QAction(self)
        invertAction.setText('Invert')
        icon = icons.getQIcon("mask-invert")
        invertAction.setIcon(icon)
        invertAction.setShortcut(qt.Qt.CTRL + qt.Qt.Key_I)
        invertAction.setToolTip('Invert current mask <b>%s</b>' %
                                invertAction.shortcut().toString())
        invertAction.triggered.connect(self._handleInvertMask)

        clearAction = qt.QAction(self)
        clearAction.setText('Clear')
        icon = icons.getQIcon("mask-clear")
        clearAction.setIcon(icon)
        clearAction.setShortcut(qt.QKeySequence.Delete)
        clearAction.setToolTip('Clear current mask level <b>%s</b>' %
                               clearAction.shortcut().toString())
        clearAction.triggered.connect(self._handleClearMask)

        clearAllAction = qt.QAction(self)
        clearAllAction.setText('Clear all')
        icon = icons.getQIcon("mask-clear-all")
        clearAllAction.setIcon(icon)
        clearAllAction.setToolTip('Clear all mask levels')
        clearAllAction.triggered.connect(self.resetSelectionMask)

        # Buttons group
        margin1 = qt.QWidget(self)
        margin1.setMinimumWidth(6)
        margin2 = qt.QWidget(self)
        margin2.setMinimumWidth(6)

        actions = (loadAction, saveAction, margin1, undoAction, redoAction,
                   margin2, invertAction, clearAction, clearAllAction)
        widgets = []
        for action in actions:
            if isinstance(action, qt.QWidget):
                widgets.append(action)
                continue
            btn = qt.QToolButton()
            btn.setDefaultAction(action)
            widgets.append(btn)
            if action is clearAllAction:
                self._clearAllBtn = btn
        container = self._hboxWidget(*widgets)
        container.layout().setSpacing(1)

        layout = qt.QVBoxLayout()
        layout.addWidget(container)
        layout.addWidget(self._levelWidget)
        layout.addWidget(self._transparencyWidget)
        layout.addStretch(1)

        maskGroup = qt.QGroupBox('Mask')
        maskGroup.setLayout(layout)
        return maskGroup
Ejemplo n.º 14
0
    def __init__(self, qspaceFile, **kwargs):
        super(FitWidget, self).__init__(**kwargs)

        self.__qspaceH5 = qspaceH5 = QSpaceH5(qspaceFile)
        self.__progTimer = None

        self.__outputFile = None

        self.__nPeaks = 1

        layout = Qt.QGridLayout(self)

        self.__roiWidget = roiWidget = Roi3DSelectorWidget()

        layout.addWidget(roiWidget)

        fileLayout = Qt.QHBoxLayout()
        self.__fileEdit = fileEdit = StyledLineEdit(nChar=20, readOnly=True)
        fileLayout.addWidget(Qt.QLabel('File :'))
        fileLayout.addWidget(fileEdit)
        layout.addLayout(fileLayout, 1, 0)

        fitLayout = Qt.QHBoxLayout()
        self.__fitTypeCb = fitTypeCb = Qt.QComboBox()
        fitTypeCb.addItems(list(FitWidget.FitTypes.keys()))
        fitTypeCb.setCurrentIndex(0)
        fitLayout.addWidget(Qt.QLabel('Fit :'))
        fitLayout.addWidget(fitTypeCb)
        fitTypeCb.currentIndexChanged[str].connect(
            self.__slotCurrentTextChanged)

        layout.addLayout(fitLayout, 2, 0, alignment=Qt.Qt.AlignLeft)

        self.__nPeaksSpinBox = spinbox = Qt.QSpinBox()
        # spinbox.setMinimum(1)
        # spinbox.setMaximum(20)
        # spinbox.setValue(self.__nPeaks)
        # spinbox.setToolTip('Max. number of expected peaks.')
        # spinbox.valueChanged.connect(self.__slotValueChanged)
        # fitLayout.addWidget(spinbox)
        # fitLayout.addWidget(Qt.QLabel('peak(s)'))

        runLayout = Qt.QHBoxLayout()
        self.__runButton = runButton = Qt.QPushButton('Run')
        runButton.setEnabled(False)
        runButton.clicked.connect(self.__slotRunClicked)
        runLayout.addWidget(runButton)

        self.__progBar = progBar = Qt.QProgressBar()
        runLayout.addWidget(progBar)
        layout.addLayout(runLayout, 3, 0, alignment=Qt.Qt.AlignCenter)

        self.__statusLabel = statusLabel = Qt.QLabel('Ready')
        statusLabel.setFrameStyle(Qt.QFrame.Panel | Qt.QFrame.Sunken)
        layout.addWidget(statusLabel, 4, 0)

        with qspaceH5:
            qx = qspaceH5.qx
            qy = qspaceH5.qy
            qz = qspaceH5.qz

        roiWidget.xSlider().setRange([qx[0], qx[-1]])
        roiWidget.ySlider().setRange([qy[0], qy[-1]])
        roiWidget.zSlider().setRange([qz[0], qz[-1]])

        self.__sigFitDone.connect(self.__slotFitDone)

        layout.setRowStretch(layout.rowCount(), 1)
        layout.setColumnStretch(layout.columnCount(), 1)
Ejemplo n.º 15
0
    def setArrayData(self, data, labels=None, copy=True, editable=False):
        """Set the data array. Update frame browsers and labels.

        :param data: Numpy array or similar object (e.g. nested sequence,
            h5py dataset...)
        :param labels: list of labels for each dimension of the array, or
            boolean ``True`` to use default labels ("dimension 0",
            "dimension 1", ...). `None` to disable labels (default).
        :param bool copy: If *True*, store a copy of *data* in the model. If
            *False*, store a reference to *data* if possible (only possible if
            *data* is a proper numpy array or an object that implements the
            same methods).
        :param bool editable: Flag to enable editing data. Default is *False*
        """
        self._data_shape = _get_shape(data)

        n_widgets = len(self._browserWidgets)
        n_dimensions = len(self._data_shape)

        # Reset text of labels
        self._dimensionLabelsText = []
        for i in range(n_dimensions):
            if labels in [True, 1]:
                label_text = "Dimension %d" % i
            elif labels is None or i >= len(labels):
                label_text = ""
            else:
                label_text = labels[i]
            self._dimensionLabelsText.append(label_text)

        # not enough widgets, create new ones (we need n_dim - 2)
        for i in range(n_widgets, n_dimensions - 2):
            browser = HorizontalSliderWithBrowser(self.browserContainer)
            self.browserLayout.addWidget(browser, i, 1)
            self._browserWidgets.append(browser)
            browser.valueChanged.connect(self._browserSlot)
            browser.setEnabled(False)
            browser.hide()

            label = qt.QLabel(self.browserContainer)
            self._browserLabels.append(label)
            self.browserLayout.addWidget(label, i, 0)
            label.hide()

        n_widgets = len(self._browserWidgets)
        for i in range(n_widgets):
            label = self._browserLabels[i]
            browser = self._browserWidgets[i]

            if (i + 2) < n_dimensions:
                label.setText(self._dimensionLabelsText[i])
                browser.setRange(0, self._data_shape[i] - 1)
                browser.setEnabled(True)
                browser.show()
                if labels is not None:
                    label.show()
                else:
                    label.hide()
            else:
                browser.setEnabled(False)
                browser.hide()
                label.hide()

        # set model
        self.model.setArrayData(data, copy=copy, editable=editable)
        # some linux distributions need this call
        self.view.setModel(self.model)
        if editable:
            self.view.enableCut()
            self.view.enablePaste()

        # initialize & connect axesSelector
        self.axesSelector.setNDimensions(n_dimensions)
        self.axesSelector.sigDimensionsChanged.connect(self.setFrameAxes)
    def _initMaskGroupBox(self):
        """Init general mask operation widgets"""

        # Mask level
        self.levelSpinBox = qt.QSpinBox()
        self.levelSpinBox.setRange(1, self._maxLevelNumber)
        self.levelSpinBox.setToolTip(
            'Choose which mask level is edited.\n'
            'A mask can have up to 255 non-overlapping levels.')
        self.levelSpinBox.valueChanged[int].connect(self._updateColors)
        self.levelWidget = self._hboxWidget(qt.QLabel('Mask level:'),
                                            self.levelSpinBox)
        # Transparency
        self.transparencyWidget = self._initTransparencyWidget()

        # Buttons group
        invertBtn = qt.QPushButton('Invert')
        invertBtn.setShortcut(qt.Qt.CTRL + qt.Qt.Key_I)
        invertBtn.setToolTip('Invert current mask <b>%s</b>' %
                             invertBtn.shortcut().toString())
        invertBtn.clicked.connect(self._handleInvertMask)

        clearBtn = qt.QPushButton('Clear')
        clearBtn.setShortcut(qt.QKeySequence.Delete)
        clearBtn.setToolTip('Clear current mask level <b>%s</b>' %
                            clearBtn.shortcut().toString())
        clearBtn.clicked.connect(self._handleClearMask)

        invertClearWidget = self._hboxWidget(invertBtn,
                                             clearBtn,
                                             stretch=False)

        undoBtn = qt.QPushButton('Undo')
        undoBtn.setShortcut(qt.QKeySequence.Undo)
        undoBtn.setToolTip('Undo last mask change <b>%s</b>' %
                           undoBtn.shortcut().toString())
        self._mask.sigUndoable.connect(undoBtn.setEnabled)
        undoBtn.clicked.connect(self._mask.undo)

        redoBtn = qt.QPushButton('Redo')
        redoBtn.setShortcut(qt.QKeySequence.Redo)
        redoBtn.setToolTip('Redo last undone mask change <b>%s</b>' %
                           redoBtn.shortcut().toString())
        self._mask.sigRedoable.connect(redoBtn.setEnabled)
        redoBtn.clicked.connect(self._mask.redo)

        undoRedoWidget = self._hboxWidget(undoBtn, redoBtn, stretch=False)

        self.clearAllBtn = qt.QPushButton('Clear all')
        self.clearAllBtn.setToolTip('Clear all mask levels')
        self.clearAllBtn.clicked.connect(self.resetSelectionMask)

        loadBtn = qt.QPushButton('Load...')
        loadBtn.clicked.connect(self._loadMask)

        saveBtn = qt.QPushButton('Save...')
        saveBtn.clicked.connect(self._saveMask)

        self.loadSaveWidget = self._hboxWidget(loadBtn, saveBtn, stretch=False)

        layout = qt.QVBoxLayout()
        layout.addWidget(self.levelWidget)
        layout.addWidget(self.transparencyWidget)
        layout.addWidget(invertClearWidget)
        layout.addWidget(undoRedoWidget)
        layout.addWidget(self.clearAllBtn)
        layout.addWidget(self.loadSaveWidget)
        layout.addStretch(1)

        maskGroup = qt.QGroupBox('Mask')
        maskGroup.setLayout(layout)
        return maskGroup
Ejemplo n.º 17
0
    def __init__(self,
                 parent=None,
                 resetzoom=True,
                 backend=None,
                 autoScale=False,
                 logScale=False,
                 grid=False,
                 colormap=True,
                 aspectRatio=True,
                 yinverted=True,
                 copy=True,
                 save=True,
                 print_=True,
                 control=False,
                 position=None,
                 mask=True):
        qt.QMainWindow.__init__(self, parent)
        if parent is not None:
            # behave as a widget
            self.setWindowFlags(qt.Qt.Widget)
        else:
            self.setWindowTitle('StackView')

        self._stack = None
        """Loaded stack, as a 3D array, a 3D dataset or a list of 2D arrays."""
        self.__transposed_view = None
        """View on :attr:`_stack` with the axes sorted, to have
        the orthogonal dimension first"""
        self._perspective = 0
        """Orthogonal dimension (depth) in :attr:`_stack`"""

        self._stackItem = ImageStack()
        """Hold the item displaying the stack"""
        imageLegend = '__StackView__image' + str(id(self))
        self._stackItem.setName(imageLegend)

        self.__autoscaleCmap = False
        """Flag to disable/enable colormap auto-scaling
        based on the min/max values of the entire 3D volume"""
        self.__dimensionsLabels = ["Dimension 0", "Dimension 1", "Dimension 2"]
        """These labels are displayed on the X and Y axes.
        :meth:`setLabels` updates this attribute."""

        self._first_stack_dimension = 0
        """Used for dimension labels and combobox"""

        self._titleCallback = self._defaultTitleCallback
        """Function returning the plot title based on the frame index.
        It can be set to a custom function using :meth:`setTitleCallback`"""

        self.calibrations3D = (calibration.NoCalibration(),
                               calibration.NoCalibration(),
                               calibration.NoCalibration())

        central_widget = qt.QWidget(self)

        self._plot = PlotWindow(parent=central_widget,
                                backend=backend,
                                resetzoom=resetzoom,
                                autoScale=autoScale,
                                logScale=logScale,
                                grid=grid,
                                curveStyle=False,
                                colormap=colormap,
                                aspectRatio=aspectRatio,
                                yInverted=yinverted,
                                copy=copy,
                                save=save,
                                print_=print_,
                                control=control,
                                position=position,
                                roi=False,
                                mask=mask)
        self._plot.addItem(self._stackItem)
        self._plot.getIntensityHistogramAction().setVisible(True)
        self.sigInteractiveModeChanged = self._plot.sigInteractiveModeChanged
        self.sigActiveImageChanged = self._plot.sigActiveImageChanged
        self.sigPlotSignal = self._plot.sigPlotSignal

        if silx.config.DEFAULT_PLOT_IMAGE_Y_AXIS_ORIENTATION == 'downward':
            self._plot.getYAxis().setInverted(True)

        self._addColorBarAction()

        self._profileToolBar = Profile3DToolBar(parent=self._plot,
                                                stackview=self)
        self._plot.addToolBar(self._profileToolBar)
        self._plot.getXAxis().setLabel('Columns')
        self._plot.getYAxis().setLabel('Rows')
        self._plot.sigPlotSignal.connect(self._plotCallback)
        self._plot.getSaveAction().setFileFilter(
            'image',
            self.IMAGE_STACK_FILTER_NXDATA,
            func=self._saveImageStack,
            appendToFile=True)

        self.__planeSelection = PlanesWidget(self._plot)
        self.__planeSelection.sigPlaneSelectionChanged.connect(
            self.setPerspective)

        self._browser_label = qt.QLabel("Image index (Dim0):")

        self._browser = HorizontalSliderWithBrowser(central_widget)
        self._browser.setRange(0, 0)
        self._browser.valueChanged[int].connect(self.__updateFrameNumber)
        self._browser.setEnabled(False)

        layout = qt.QGridLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self._plot, 0, 0, 1, 3)
        layout.addWidget(self.__planeSelection, 1, 0)
        layout.addWidget(self._browser_label, 1, 1)
        layout.addWidget(self._browser, 1, 2)

        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

        # clear profile lines when the perspective changes (plane browsed changed)
        self.__planeSelection.sigPlaneSelectionChanged.connect(
            self._profileToolBar.clearProfile)
Ejemplo n.º 18
0
    def gui(self, log=False, maximize=False, pick=True):
        """
        :param log: show z in log scale
        """
        if self.fig is None:
            self.fig = pyplot.figure()
            self.fig.subplots_adjust(right=0.75)
            # add 3 subplots at the same position for debye-sherrer image, contour-plot and massif contour
            self.ax = self.fig.add_subplot(111)
            self.ct = self.fig.add_subplot(111)
            self.msp = self.fig.add_subplot(111)
            toolbar = self.fig.canvas.toolbar
            toolbar.addSeparator()

            a = toolbar.addAction('Opts', self.on_option_clicked)
            a.setToolTip('open options window')
            if pick:
                label = qt.QLabel("Ring #", toolbar)
                toolbar.addWidget(label)
                self.spinbox = qt.QSpinBox(toolbar)
                self.spinbox.setMinimum(0)
                self.sb_action = toolbar.addWidget(self.spinbox)
                a = toolbar.addAction('Refine', self.on_refine_clicked)
                a.setToolTip('switch to refinement mode')
                self.ref_action = a
                self.mpl_connectId = self.fig.canvas.mpl_connect(
                    'button_press_event', self.onclick)

        if log:
            data_disp = numpy.log1p(self.data - self.data.min())
            txt = 'Log colour scale (skipping lowest/highest per mille)'
        else:
            data_disp = self.data
            txt = 'Linear colour scale (skipping lowest/highest per mille)'

        # skip lowest and highest per mille of image values via vmin/vmax
        sorted_list = data_disp.flatten()  # explicit copy
        sorted_list.sort()
        show_min = sorted_list[int(round(1e-3 * (sorted_list.size - 1)))]
        show_max = sorted_list[int(round(0.999 * (sorted_list.size - 1)))]
        im = self.ax.imshow(
            data_disp,
            vmin=show_min,
            vmax=show_max,
            origin="lower",
            interpolation="nearest",
        )
        self.ax.set_ylabel('y in pixels')
        self.ax.set_xlabel('x in pixels')

        if self.detector:
            s1, s2 = self.data.shape
            s1 -= 1
            s2 -= 1
            self.ax.set_xlim(0, s2)
            self.ax.set_ylim(0, s1)
            d1 = numpy.array([0, s1, s1, 0])
            d2 = numpy.array([0, 0, s2, s2])
            p1, p2, _ = self.detector.calc_cartesian_positions(d1=d1, d2=d2)
            ax = self.fig.add_subplot(1,
                                      1,
                                      1,
                                      xbound=False,
                                      ybound=False,
                                      xlabel=r'dim2 ($\approx m$)',
                                      ylabel=r'dim1 ($\approx m$)',
                                      xlim=(p2.min(), p2.max()),
                                      ylim=(p1.min(), p1.max()),
                                      aspect='equal',
                                      zorder=-1)
            ax.xaxis.set_label_position('top')
            ax.yaxis.set_label_position('right')
            ax.yaxis.label.set_color('blue')
            ax.xaxis.label.set_color('blue')
            ax.tick_params(colors="blue",
                           labelbottom='off',
                           labeltop='on',
                           labelleft='off',
                           labelright='on')
            # ax.autoscale_view(False, False, False)

        else:
            _cbar = self.fig.colorbar(im, label=txt)
        # self.ax.autoscale_view(False, False, False)
        update_fig(self.fig)
        if maximize:
            maximize_fig(self.fig)
        if not gui_utils.main_loop:
            self.fig.show()
Ejemplo n.º 19
0
    def __init__(self, parent=None):
        super(SearchPage, self).__init__(parent)
        layout = qt.QVBoxLayout(self)

        self.manualFwhmGB = qt.QGroupBox("Define FWHM manually", self)
        self.manualFwhmGB.setCheckable(True)
        self.manualFwhmGB.setToolTip(
            "If disabled, the FWHM parameter used for peak search is " +
            "estimated based on the highest peak in the data")
        layout.addWidget(self.manualFwhmGB)
        # ------------ GroupBox fwhm--------------------------
        layout2 = qt.QHBoxLayout(self.manualFwhmGB)
        self.manualFwhmGB.setLayout(layout2)

        label = qt.QLabel("Fwhm Points", self.manualFwhmGB)
        layout2.addWidget(label)

        self.fwhmPointsSpin = qt.QSpinBox(self.manualFwhmGB)
        self.fwhmPointsSpin.setRange(0, 999999)
        self.fwhmPointsSpin.setToolTip(
            "Typical peak fwhm (number of data points)")
        layout2.addWidget(self.fwhmPointsSpin)
        # ----------------------------------------------------

        self.manualScalingGB = qt.QGroupBox("Define scaling manually", self)
        self.manualScalingGB.setCheckable(True)
        self.manualScalingGB.setToolTip(
            "If disabled, the Y scaling used for peak search is " +
            "estimated automatically")
        layout.addWidget(self.manualScalingGB)
        # ------------ GroupBox scaling-----------------------
        layout3 = qt.QHBoxLayout(self.manualScalingGB)
        self.manualScalingGB.setLayout(layout3)

        label = qt.QLabel("Y Scaling", self.manualScalingGB)
        layout3.addWidget(label)

        self.yScalingEntry = qt.QLineEdit(self.manualScalingGB)
        self.yScalingEntry.setToolTip(
            "Data values will be multiplied by this value prior to peak" +
            " search")
        self.yScalingEntry.setValidator(qt.QDoubleValidator())
        layout3.addWidget(self.yScalingEntry)
        # ----------------------------------------------------

        # ------------------- grid layout --------------------
        containerWidget = qt.QWidget(self)
        layout4 = qt.QHBoxLayout(containerWidget)
        containerWidget.setLayout(layout4)

        label = qt.QLabel("Sensitivity", containerWidget)
        layout4.addWidget(label)

        self.sensitivityEntry = qt.QLineEdit(containerWidget)
        self.sensitivityEntry.setToolTip(
            "Peak search sensitivity threshold, expressed as a multiple " +
            "of the standard deviation of the noise.\nMinimum value is 1 " +
            "(to be detected, peak must be higher than the estimated noise)")
        sensivalidator = qt.QDoubleValidator()
        sensivalidator.setBottom(1.0)
        self.sensitivityEntry.setValidator(sensivalidator)
        layout4.addWidget(self.sensitivityEntry)
        # ----------------------------------------------------
        layout.addWidget(containerWidget)

        self.forcePeakPresenceCB = qt.QCheckBox("Force peak presence", self)
        self.forcePeakPresenceCB.setToolTip(
            "If peak search algorithm is unsuccessful, place one peak " +
            "at the maximum of the curve")
        layout.addWidget(self.forcePeakPresenceCB)

        layout.addStretch()

        self.setDefault()
Ejemplo n.º 20
0
 def createWidget(self, parent):
     return qt.QLabel(parent)
Ejemplo n.º 21
0
    def __init__(self,
                 parent=None,
                 resetzoom=True,
                 backend=None,
                 autoScale=False,
                 logScale=False,
                 grid=False,
                 colormap=True,
                 aspectRatio=True,
                 yinverted=True,
                 copy=True,
                 save=True,
                 print_=True,
                 control=False,
                 position=None,
                 mask=True):
        qt.QMainWindow.__init__(self, parent)
        if parent is not None:
            # behave as a widget
            self.setWindowFlags(qt.Qt.Widget)
        else:
            self.setWindowTitle('StackView')

        self._stack = None
        """Loaded stack, as a 3D array, a 3D dataset or a list of 2D arrays."""
        self.__transposed_view = None
        """View on :attr:`_stack` with the axes sorted, to have
        the orthogonal dimension first"""
        self._perspective = 0
        """Orthogonal dimension (depth) in :attr:`_stack`"""

        self.__imageLegend = '__StackView__image' + str(id(self))
        self.__autoscaleCmap = False
        """Flag to disable/enable colormap auto-scaling
        based on the min/max values of the entire 3D volume"""
        self.__dimensionsLabels = ["Dimension 0", "Dimension 1", "Dimension 2"]
        """These labels are displayed on the X and Y axes.
        :meth:`setLabels` updates this attribute."""

        self._first_stack_dimension = 0
        """Used for dimension labels and combobox"""

        central_widget = qt.QWidget(self)

        self._plot = PlotWindow(parent=central_widget,
                                backend=backend,
                                resetzoom=resetzoom,
                                autoScale=autoScale,
                                logScale=logScale,
                                grid=grid,
                                curveStyle=False,
                                colormap=colormap,
                                aspectRatio=aspectRatio,
                                yInverted=yinverted,
                                copy=copy,
                                save=save,
                                print_=print_,
                                control=control,
                                position=position,
                                roi=False,
                                mask=mask)
        self.sigInteractiveModeChanged = self._plot.sigInteractiveModeChanged
        self.sigActiveImageChanged = self._plot.sigActiveImageChanged
        self.sigPlotSignal = self._plot.sigPlotSignal

        self._plot.profile = Profile3DToolBar(parent=self._plot, plot=self)
        self._plot.addToolBar(self._plot.profile)
        self._plot.setGraphXLabel('Columns')
        self._plot.setGraphYLabel('Rows')
        self._plot.sigPlotSignal.connect(self._plotCallback)

        self.__planeSelection = PlanesWidget(self._plot)
        self.__planeSelection.sigPlaneSelectionChanged.connect(
            self.__setPerspective)

        self._browser_label = qt.QLabel("Image index (Dim0):")

        self._browser = HorizontalSliderWithBrowser(central_widget)
        self._browser.valueChanged[int].connect(self.__updateFrameNumber)
        self._browser.setEnabled(False)

        layout = qt.QGridLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self._plot, 0, 0, 1, 3)
        layout.addWidget(self.__planeSelection, 1, 0)
        layout.addWidget(self._browser_label, 1, 1)
        layout.addWidget(self._browser, 1, 2)

        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

        # clear profile lines when the perspective changes (plane browsed changed)
        self.__planeSelection.sigPlaneSelectionChanged.connect(
            self._plot.profile.getProfilePlot().clear)
        self.__planeSelection.sigPlaneSelectionChanged.connect(
            self._plot.profile.clearProfile)