def testRelativePositionLinear(self): self.colorMapLin1 = Colormap(name='gray', normalization=Colormap.LINEAR, vmin=0.0, vmax=1.0) self.colorScaleWidget.setColormap(self.colorMapLin1) self.assertTrue( self.colorScaleWidget.getValueFromRelativePosition(0.25) == 0.25) self.assertTrue( self.colorScaleWidget.getValueFromRelativePosition(0.5) == 0.5) self.assertTrue( self.colorScaleWidget.getValueFromRelativePosition(1.0) == 1.0) self.colorMapLin2 = Colormap(name='viridis', normalization=Colormap.LINEAR, vmin=-10, vmax=0) self.colorScaleWidget.setColormap(self.colorMapLin2) self.assertTrue( self.colorScaleWidget.getValueFromRelativePosition(0.25) == -7.5) self.assertTrue( self.colorScaleWidget.getValueFromRelativePosition(0.5) == -5.0) self.assertTrue( self.colorScaleWidget.getValueFromRelativePosition(1.0) == 0.0)
def testPlotAssocation(self): """Make sure the ColorBarWidget is properly connected with the plot""" colormap = Colormap(name='gray', normalization=Colormap.LINEAR, vmin=None, vmax=None) # make sure that default settings are the same (but a copy of the self.colorBar.setPlot(self.plot) self.assertTrue( self.colorBar.getColormap() is self.plot.getDefaultColormap()) data = numpy.linspace(0, 10, 100).reshape(10, 10) self.plot.addImage(data=data, colormap=colormap, legend='toto') self.plot.setActiveImage('toto') # make sure the modification of the colormap has been done self.assertFalse( self.colorBar.getColormap() is self.plot.getDefaultColormap()) self.assertTrue( self.colorBar.getColormap() is colormap) # test that colorbar is updated when default plot colormap changes self.plot.clear() plotColormap = Colormap(name='gray', normalization=Colormap.LOGARITHM, vmin=None, vmax=None) self.plot.setDefaultColormap(plotColormap) self.assertTrue(self.colorBar.getColormap() is plotColormap)
def testColomap(self): dialog = self.createDialog() colormap = dialog.colormap() self.assertEqual(colormap.getNormalization(), "linear") colormap = Colormap(normalization=Colormap.LOGARITHM) dialog.setColormap(colormap) self.assertEqual(colormap.getNormalization(), "log")
def setUp(self): TestCaseQt.setUp(self) ParametricTestCase.setUp(self) self.colormap = Colormap(name='gray', vmin=10.0, vmax=20.0, normalization='linear') self.colormapDiag = ColormapDialog.ColormapDialog() self.colormapDiag.setAttribute(qt.Qt.WA_DeleteOnClose)
def testMissingKeysFromDict(self): """Make sure we can create a Colormap object from a dictionnary even if there is missing keys excepts if those keys are 'colors' or 'name' """ colormap = Colormap._fromDict({'name': 'toto'}) self.assertTrue(colormap.getVMin() is None) colormap = Colormap._fromDict({'colors': numpy.zeros(10)}) self.assertTrue(colormap.getName() is None) with self.assertRaises(ValueError): Colormap._fromDict({})
def testGetNColors(self): """Test getNColors method""" # specific LUT colormap = Colormap(name=None, colors=((0, 0, 0), (1, 1, 1)), vmin=1000, vmax=2000) colors = colormap.getNColors() self.assertTrue( numpy.all( numpy.equal(colors, ((0, 0, 0, 255), (255, 255, 255, 255)))))
def testUnknowNorm(self): """Make sure an error is raised if the given normalization is not knowed """ clm_dict = { 'name': 'temperature', 'vmin': 1.0, 'vmax': 2.0, 'normalization': 'toto', 'colors': None, 'autoscale': False } with self.assertRaises(ValueError): Colormap._fromDict(clm_dict)
def testColormapEditableMode(self): """Test that the colormapDialog is correctly updated when changing the colormap editable status""" colormap = Colormap(normalization='linear', vmin=1.0, vmax=10.0) self.colormapDiag.setColormap(colormap) for editable in (True, False): with self.subTest(editable=editable): colormap.setEditable(editable) self.assertTrue( self.colormapDiag._comboBoxColormap.isEnabled() is editable ) self.assertTrue( self.colormapDiag._minValue.isEnabled() is editable) self.assertTrue( self.colormapDiag._maxValue.isEnabled() is editable) self.assertTrue( self.colormapDiag._normButtonLinear.isEnabled() is editable ) self.assertTrue( self.colormapDiag._normButtonLog.isEnabled() is editable) # Make sure the reset button is also set to enable when edition mode is # False self.colormapDiag.setModal(False) colormap.setEditable(True) self.colormapDiag._normButtonLog.setChecked(True) resetButton = self.colormapDiag._buttonsNonModal.button( qt.QDialogButtonBox.Reset) self.assertTrue(resetButton.isEnabled()) colormap.setEditable(False) self.assertFalse(resetButton.isEnabled())
def testUpdateColorMap(self): colormap = Colormap(name='gray', normalization='linear', vmin=0, vmax=1) # check inital state self.plot.addImage(data=self.data, colormap=colormap, legend='toto') self.plot.setActiveImage('toto') self.assertTrue(self.colorBar.getColorScaleBar().minVal == 0) self.assertTrue(self.colorBar.getColorScaleBar().maxVal == 1) self.assertTrue( self.colorBar.getColorScaleBar().getTickBar()._vmin == 0) self.assertTrue( self.colorBar.getColorScaleBar().getTickBar()._vmax == 1) self.assertTrue( self.colorBar.getColorScaleBar().getTickBar()._norm == "linear") # update colormap colormap.setVMin(0.5) self.assertTrue(self.colorBar.getColorScaleBar().minVal == 0.5) self.assertTrue( self.colorBar.getColorScaleBar().getTickBar()._vmin == 0.5) colormap.setVMax(0.8) self.assertTrue(self.colorBar.getColorScaleBar().maxVal == 0.8) self.assertTrue( self.colorBar.getColorScaleBar().getTickBar()._vmax == 0.8) colormap.setNormalization('log') self.assertTrue( self.colorBar.getColorScaleBar().getTickBar()._norm == 'log')
def printState(self): """ Print state of the ImageFileDialog. Can be used to add or regenerate `STATE_VERSION1_QT4` or `STATE_VERSION1_QT5`. >>> ./run_tests.py -v silx.gui.dialog.test.test_imagefiledialog.TestImageFileDialogApi.printState """ dialog = self.createDialog() colormap = Colormap(normalization=Colormap.LOGARITHM) dialog.setDirectory("") dialog.setHistory([]) dialog.setColormap(colormap) dialog.setSidebarUrls([]) state = dialog.saveState() string = "" strings = [] for i in range(state.size()): d = state.data()[i] if not isinstance(d, int): d = ord(d) if d > 0x20 and d < 0x7F: string += chr(d) else: string += "\\x%02X" % d if len(string) > 60: strings.append(string) string = "" strings.append(string) strings = ["b'%s'" % s for s in strings] print() print("\\\n".join(strings))
def getFirstNotPreferredColormap(): cms = Colormap.getSupportedColormaps() preferred = preferredColormaps() for cm in cms: if cm not in preferred: return cm return None
def setColormap(self, name='gray', norm=None, vmin=None, vmax=None): """Set the colormap to use. By either providing a :class:`Colormap` object or its name, normalization and range. :param name: Name of the colormap in 'gray', 'reversed gray', 'temperature', 'red', 'green', 'blue'. Or Colormap object. :type name: str or Colormap :param str norm: Colormap mapping: 'linear' or 'log'. :param float vmin: The minimum value of the range or None for autoscale :param float vmax: The maximum value of the range or None for autoscale """ _logger.debug('setColormap %s %s (%s, %s)', name, str(norm), str(vmin), str(vmax)) self._colormap.sigChanged.disconnect(self._colormapChanged) if isinstance(name, Colormap): # Use it as it is assert (norm, vmin, vmax) == (None, None, None) self._colormap = name else: if norm is None: norm = 'linear' self._colormap = Colormap(name=name, normalization=norm, vmin=vmin, vmax=vmax) self._colormap.sigChanged.connect(self._colormapChanged) self._colormapChanged()
def testColormapWithoutRange(self): """Test with a colormap with vmin==vmax""" colormap = Colormap(name='gray', normalization=Colormap.LINEAR, vmin=1.0, vmax=1.0) self.colorBar.setColormap(colormap)
def generateCompositeGradient(self): shape = 512 hole = 1 / 4.0 dx = numpy.random.random() * hole - hole / 2.0 dy = numpy.random.random() * hole - hole * 2 sx = numpy.random.random() * 10.0 + 1 sy = numpy.random.random() * 10.0 + 1 image = create_composite_gradient(shape, dx, dy, sx, sy) image *= 1000.0 def styleCallback(value, ivalue, ipolygon): colors = [ "#9400D3", "#4B0082", "#0000FF", "#00FF00", "#FFFF00", "#FF7F00", "#FF0000" ] color = colors[ivalue % len(colors)] style = {"linestyle": "-", "linewidth": 2.0, "color": color} return style delta = (image.max() - image.min()) / 9.0 values = numpy.arange(image.min(), image.max(), delta) values = values[1:8] self.__colormap = Colormap("Greys") self.setData(image=image, mask=None) self.__drawContours(values, styleCallback) self.__defineDefaultValues()
def testSetValidDict(self): """Test that if a colormap is created from a dict then it is correctly created and the values are copied (so if some values from the dict is changing, this won't affect the Colormap object""" clm_dict = { 'name': 'temperature', 'vmin': 1.0, 'vmax': 2.0, 'normalization': 'linear', 'colors': None, 'autoscale': False } # Test that the colormap is correctly created colormapObject = Colormap._fromDict(clm_dict) self.assertTrue(colormapObject.getName() == clm_dict['name']) self.assertTrue(colormapObject.getColormapLUT() == clm_dict['colors']) self.assertTrue(colormapObject.getVMin() == clm_dict['vmin']) self.assertTrue(colormapObject.getVMax() == clm_dict['vmax']) self.assertTrue(colormapObject.isAutoscale() == clm_dict['autoscale']) # Check that the colormap has copied the values clm_dict['vmin'] = None clm_dict['vmax'] = None clm_dict['colors'] = [1.0, 2.0] clm_dict['autoscale'] = True clm_dict['normalization'] = Colormap.LOGARITHM clm_dict['name'] = 'viridis' self.assertFalse(colormapObject.getName() == clm_dict['name']) self.assertFalse(colormapObject.getColormapLUT() == clm_dict['colors']) self.assertFalse(colormapObject.getVMin() == clm_dict['vmin']) self.assertFalse(colormapObject.getVMax() == clm_dict['vmax']) self.assertFalse(colormapObject.isAutoscale() == clm_dict['autoscale'])
def generateMagneticField(self): shape = 512 x1 = numpy.random.random() * 2 - 1 y1 = numpy.random.random() * 2 - 1 x2 = numpy.random.random() * 2 - 1 y2 = numpy.random.random() * 2 - 1 image = create_magnetic_field(shape, x1, y1, x2, y2) self.__colormap = Colormap("coolwarm") self.setData(image=image, mask=None) maximum = abs(image.max()) m = abs(image.min()) if m > maximum: maximum = m maximum = int(maximum) values = range(-maximum, maximum, maximum // 20) def styleCallback(value, ivalue, ipolygon): if (ivalue % 2) == 0: style = {"linestyle": "-", "linewidth": 0.5, "color": "black"} else: style = {"linestyle": "-", "linewidth": 0.5, "color": "white"} return style self.__drawContours(values, styleCallback) self.__defineDefaultValues(value=0)
def testNegativeColormaps(self): """test the behavior of the ColorBarWidget in the case of negative values Note : colorbar is modified by the Plot directly not ColorBarWidget """ colormapLog = Colormap(name='gray', normalization=Colormap.LOGARITHM, vmin=None, vmax=None) data = numpy.array([-5, -4, 0, 2, 3, 5, 10, 20, 30]) data = data.reshape(3, 3) self.plot.addImage(data=data, colormap=colormapLog, legend='toto') self.plot.setActiveImage('toto') # default behavior when with log and negative values: should set vmin # to 1 and vmax to 10 self.assertTrue(self.colorBar.getColorScaleBar().minVal == 2) self.assertTrue(self.colorBar.getColorScaleBar().maxVal == 30) # if data is positive data[data<1] = data.max() self.plot.addImage(data=data, colormap=colormapLog, legend='toto', replace=True) self.plot.setActiveImage('toto') self.assertTrue(self.colorBar.getColorScaleBar().minVal == data.min()) self.assertTrue(self.colorBar.getColorScaleBar().maxVal == data.max())
def _updateSceneColormap(self): """Synchronizes scene's colormap with Colormap object""" colormap = self.getColormap() sceneCMap = self._plane.colormap indices = numpy.linspace(0., 1., 256) colormapDisp = Colormap(name=colormap.getName(), normalization=Colormap.LINEAR, vmin=None, vmax=None, colors=colormap.getColormapLUT()) colors = colormapDisp.applyToData(indices) sceneCMap.colormap = colors sceneCMap.norm = colormap.getNormalization() range_ = colormap.getColormapRange(data=self._dataRange) sceneCMap.range_ = range_
def defaultColormap(): """Returns a shared colormap as default for all the views. :rtype: Colormap """ if DataView._defaultColormap is None: DataView._defaultColormap = Colormap(name="viridis") return DataView._defaultColormap
def __init__(self, parent=None, plot=None, mask=None): """ :param parent: Parent QWidget :param plot: Plot widget on which to operate :param mask: Instance of subclass of :class:`BaseMask` (e.g. :class:`ImageMask`) """ super(BaseMaskToolsWidget, self).__init__(parent) # register if the user as force a color for the corresponding mask level self._defaultColors = numpy.ones((self._maxLevelNumber + 1), dtype=numpy.bool) # overlays colors set by the user self._overlayColors = numpy.zeros((self._maxLevelNumber + 1, 3), dtype=numpy.float32) # as parent have to be the first argument of the widget to fit # QtDesigner need but here plot can't be None by default. assert plot is not None self._plot = plot self._maskName = '__MASK_TOOLS_%d' % id(self) # Legend of the mask self._colormap = Colormap(name="", normalization='linear', vmin=0, vmax=self._maxLevelNumber, colors=None) self._defaultOverlayColor = rgba('gray') # Color of the mask self._setMaskColors(1, 0.5) if not isinstance(mask, BaseMask): raise TypeError("mask is not an instance of BaseMask") self._mask = mask self._mask.sigChanged.connect(self._updatePlotMask) self._mask.sigChanged.connect(self._emitSigMaskChanged) self._drawingMode = None # Store current drawing mode self._lastPencilPos = None self._multipleMasks = 'exclusive' self._maskFileDir = qt.QDir.home().absolutePath() self.plot.sigInteractiveModeChanged.connect( self._interactiveModeChanged) self._initWidgets()
def __init__(self, parent=None): super(ScalarFieldView, self).__init__(parent) self._colormap = Colormap( name='gray', normalization='linear', vmin=None, vmax=None) self._selectedRange = None # Store iso-surfaces self._isosurfaces = [] # Transformations self._dataScale = transform.Scale() self._dataTranslate = transform.Translate() self._foregroundColor = 1., 1., 1., 1. self._highlightColor = 0.7, 0.7, 0., 1. self._data = None self._dataRange = None self._group = _BoundedGroup() self._group.transforms = [self._dataTranslate, self._dataScale] self._selectionBox = primitives.Box() self._selectionBox.strokeSmooth = False self._selectionBox.strokeWidth = 1. # self._selectionBox.fillColor = 1., 1., 1., 0.3 # self._selectionBox.fillCulling = 'back' self._selectionBox.visible = False self._group.children.append(self._selectionBox) self._cutPlane = CutPlane(sfView=self) self._cutPlane.sigVisibilityChanged.connect( self._planeVisibilityChanged) self._group.children.append(self._cutPlane._get3DPrimitive()) self._isogroup = primitives.GroupDepthOffset() self._isogroup.transforms = [ # Convert from z, y, x from marching cubes to x, y, z transform.Matrix(( (0., 0., 1., 0.), (0., 1., 0., 0.), (1., 0., 0., 0.), (0., 0., 0., 1.))), # Offset to match cutting plane coords transform.Translate(0.5, 0.5, 0.5) ] self._group.children.append(self._isogroup) self._bbox = axes.LabelledAxes() self._bbox.children = [self._group] self.getPlot3DWidget().viewport.scene.children.append(self._bbox) self._initPanPlaneAction() self._updateColors() self.getPlot3DWidget().viewport.light.shininess = 32
def setUp(self): TestCaseQt.setUp(self) self.plot = PlotWindow() self.plot.setAttribute(qt.Qt.WA_DeleteOnClose) self.colormap1 = Colormap(name='blue', vmin=0.0, vmax=1.0, normalization='linear') self.colormap2 = Colormap(name='red', vmin=10.0, vmax=100.0, normalization='log') self.defaultColormap = self.plot.getDefaultColormap() self.plot.getColormapAction()._actionTriggered(checked=True) self.colormapDialog = self.plot.getColormapAction()._dialog self.colormapDialog.setAttribute(qt.Qt.WA_DeleteOnClose)
def generateSpiral(self): shape = 512 nb_spiral = numpy.random.randint(1, 8) freq = numpy.random.randint(2, 50) image = create_spiral(shape, nb_spiral, freq) image *= 1000.0 self.__colormap = Colormap("cool") self.setData(image=image, mask=None) self.__defineDefaultValues()
def testApplyColormapToData(self): """Simple test of applyColormapToData function""" colormap = Colormap(name='gray', normalization='linear', vmin=0, vmax=255) size = 10 expected = numpy.empty((size, 4), dtype='uint8') expected[:, 0] = numpy.arange(size, dtype='uint8') expected[:, 1] = expected[:, 0] expected[:, 2] = expected[:, 0] expected[:, 3] = 255 for dtype in ('uint8', 'int32', 'float32', 'float64'): with self.subTest(dtype=dtype): array = numpy.arange(size, dtype=dtype) result = colormap.applyToData(data=array) self.assertTrue(numpy.all(numpy.equal(result, expected)))
def testApplyToData(self): """Test applyToData on different datasets""" datasets = [ numpy.zeros((0, 0)), # Empty array numpy.array((numpy.nan, numpy.inf)), # All non-finite numpy.array((-numpy.inf, numpy.inf, 1.0, 2.0)), # Some infinite ] for normalization in ('linear', 'log'): colormap = Colormap(name='gray', normalization=normalization, vmin=None, vmax=None) for data in datasets: with self.subTest(data=data): image = colormap.applyToData(data) self.assertEqual(image.dtype, numpy.uint8) self.assertEqual(image.shape[-1], 4) self.assertEqual(image.shape[:-1], data.shape)
def testGetItem(self): """test the item getter API ([xxx])""" colormap = Colormap(name='viridis', normalization=Colormap.LINEAR, vmin=self.vmin, vmax=self.vmax) self.assertTrue(colormap['name'] == 'viridis') self.assertTrue(colormap['normalization'] == Colormap.LINEAR) self.assertTrue(colormap['vmin'] == self.vmin) self.assertTrue(colormap['vmax'] == self.vmax) with self.assertRaises(KeyError): colormap['toto']
def testSetColormapScenario(self): """Test of a simple scenario of a colormap dialog editing several colormap""" colormap1 = Colormap(name='gray', vmin=10.0, vmax=20.0, normalization='linear') colormap2 = Colormap(name='red', vmin=10.0, vmax=20.0, normalization='log') colormap3 = Colormap(name='blue', vmin=None, vmax=None, normalization='linear') self.colormapDiag.setColormap(self.colormap) self.colormapDiag.setColormap(colormap1) del colormap1 self.colormapDiag.setColormap(colormap2) del colormap2 self.colormapDiag.setColormap(colormap3) del colormap3
def __init__(self, parent=None): super(ColormapDialogExample, self).__init__(parent) self.setWindowTitle("Colormap dialog example") self.colormap1 = Colormap("viridis") self.colormap2 = Colormap("gray") self.colorBar = ColorBarWidget(self) self.colorDialogs = [] options = qt.QWidget(self) options.setLayout(qt.QVBoxLayout()) self.createOptions(options.layout()) mainWidget = qt.QWidget(self) mainWidget.setLayout(qt.QHBoxLayout()) mainWidget.layout().addWidget(options) mainWidget.layout().addWidget(self.colorBar) self.mainWidget = mainWidget self.setCentralWidget(mainWidget) self.createColorDialog()
def testSaveRestoreState(self): dialog = self.createDialog() dialog.setDirectory(_tmpDirectory) colormap = Colormap(normalization=Colormap.LOGARITHM) dialog.setColormap(colormap) self.qWaitForPendingActions(dialog) state = dialog.saveState() dialog = None dialog2 = self.createDialog() result = dialog2.restoreState(state) self.qWaitForPendingActions(dialog2) self.assertTrue(result) self.assertTrue(dialog2.colormap().getNormalization(), "log")
def testRelativePositionLog(self): self.colorMapLog1 = Colormap(name='temperature', normalization=Colormap.LOGARITHM, vmin=1.0, vmax=100.0) self.colorScaleWidget.setColormap(self.colorMapLog1) val = self.colorScaleWidget.getValueFromRelativePosition(1.0) self.assertTrue(val == 100.0) val = self.colorScaleWidget.getValueFromRelativePosition(0.5) self.assertTrue(val == 10.0) val = self.colorScaleWidget.getValueFromRelativePosition(0.0) self.assertTrue(val == 1.0)