repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
titusjan/argos
argos/config/qtctis.py
createPenStyleCti
def createPenStyleCti(nodeName, defaultData=0, includeNone=False): """ Creates a ChoiceCti with Qt PenStyles. If includeEmtpy is True, the first option will be None. """ displayValues=PEN_STYLE_DISPLAY_VALUES configValues=PEN_STYLE_CONFIG_VALUES if includeNone: displayValues = [''] + list(displayValues) configValues = [None] + list(configValues) return ChoiceCti(nodeName, defaultData, displayValues=displayValues, configValues=configValues)
python
def createPenStyleCti(nodeName, defaultData=0, includeNone=False): """ Creates a ChoiceCti with Qt PenStyles. If includeEmtpy is True, the first option will be None. """ displayValues=PEN_STYLE_DISPLAY_VALUES configValues=PEN_STYLE_CONFIG_VALUES if includeNone: displayValues = [''] + list(displayValues) configValues = [None] + list(configValues) return ChoiceCti(nodeName, defaultData, displayValues=displayValues, configValues=configValues)
Creates a ChoiceCti with Qt PenStyles. If includeEmtpy is True, the first option will be None.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L41-L51
titusjan/argos
argos/config/qtctis.py
createPenWidthCti
def createPenWidthCti(nodeName, defaultData=1.0, zeroValueText=None): """ Creates a FloatCti with defaults for configuring a QPen width. If specialValueZero is set, this string will be displayed when 0.0 is selected. If specialValueZero is None, the minValue will be 0.1 """ # A pen line width of zero indicates a cosmetic pen. This means that the pen width is # always drawn one pixel wide, independent of the transformation set on the painter. # Note that line widths other than 1 may be slow when anti aliasing is on. return FloatCti(nodeName, defaultData=defaultData, specialValueText=zeroValueText, minValue=0.1 if zeroValueText is None else 0.0, maxValue=100, stepSize=0.1, decimals=1)
python
def createPenWidthCti(nodeName, defaultData=1.0, zeroValueText=None): """ Creates a FloatCti with defaults for configuring a QPen width. If specialValueZero is set, this string will be displayed when 0.0 is selected. If specialValueZero is None, the minValue will be 0.1 """ # A pen line width of zero indicates a cosmetic pen. This means that the pen width is # always drawn one pixel wide, independent of the transformation set on the painter. # Note that line widths other than 1 may be slow when anti aliasing is on. return FloatCti(nodeName, defaultData=defaultData, specialValueText=zeroValueText, minValue=0.1 if zeroValueText is None else 0.0, maxValue=100, stepSize=0.1, decimals=1)
Creates a FloatCti with defaults for configuring a QPen width. If specialValueZero is set, this string will be displayed when 0.0 is selected. If specialValueZero is None, the minValue will be 0.1
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L54-L65
titusjan/argos
argos/config/qtctis.py
fontFamilyIndex
def fontFamilyIndex(qFont, families): """ Searches the index of qFont.family in the families list. If qFont.family() is not in the list, the index of qFont.defaultFamily() is returned. If that is also not present an error is raised. """ try: return families.index(qFont.family()) except ValueError: if False and DEBUGGING: raise else: logger.warn("{} not found in font families, using default.".format(qFont.family())) return families.index(qFont.defaultFamily())
python
def fontFamilyIndex(qFont, families): """ Searches the index of qFont.family in the families list. If qFont.family() is not in the list, the index of qFont.defaultFamily() is returned. If that is also not present an error is raised. """ try: return families.index(qFont.family()) except ValueError: if False and DEBUGGING: raise else: logger.warn("{} not found in font families, using default.".format(qFont.family())) return families.index(qFont.defaultFamily())
Searches the index of qFont.family in the families list. If qFont.family() is not in the list, the index of qFont.defaultFamily() is returned. If that is also not present an error is raised.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L68-L80
titusjan/argos
argos/config/qtctis.py
fontWeightIndex
def fontWeightIndex(qFont, weights): """ Searches the index of qFont.family in the weight list. If qFont.weight() is not in the list, the index of QFont.Normal is returned. If that is also not present an error is raised. """ try: return weights.index(qFont.weight()) except ValueError: if False and DEBUGGING: raise else: logger.warn("{} not found in font weights, using normal.".format(qFont.weight())) return weights.index(QtGui.QFont.Normal)
python
def fontWeightIndex(qFont, weights): """ Searches the index of qFont.family in the weight list. If qFont.weight() is not in the list, the index of QFont.Normal is returned. If that is also not present an error is raised. """ try: return weights.index(qFont.weight()) except ValueError: if False and DEBUGGING: raise else: logger.warn("{} not found in font weights, using normal.".format(qFont.weight())) return weights.index(QtGui.QFont.Normal)
Searches the index of qFont.family in the weight list. If qFont.weight() is not in the list, the index of QFont.Normal is returned. If that is also not present an error is raised.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L83-L95
titusjan/argos
argos/config/qtctis.py
ColorCti._enforceDataType
def _enforceDataType(self, data): """ Converts to str so that this CTI always stores that type. """ qColor = QtGui.QColor(data) # TODO: store a RGB string? if not qColor.isValid(): raise ValueError("Invalid color specification: {!r}".format(data)) return qColor
python
def _enforceDataType(self, data): """ Converts to str so that this CTI always stores that type. """ qColor = QtGui.QColor(data) # TODO: store a RGB string? if not qColor.isValid(): raise ValueError("Invalid color specification: {!r}".format(data)) return qColor
Converts to str so that this CTI always stores that type.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L107-L113
titusjan/argos
argos/config/qtctis.py
ColorCti._nodeGetNonDefaultsDict
def _nodeGetNonDefaultsDict(self): """ Retrieves this nodes` values as a dictionary to be used for persistence. Non-recursive auxiliary function for getNonDefaultsDict """ dct = {} if self.data != self.defaultData: dct['data'] = self.data.name() return dct
python
def _nodeGetNonDefaultsDict(self): """ Retrieves this nodes` values as a dictionary to be used for persistence. Non-recursive auxiliary function for getNonDefaultsDict """ dct = {} if self.data != self.defaultData: dct['data'] = self.data.name() return dct
Retrieves this nodes` values as a dictionary to be used for persistence. Non-recursive auxiliary function for getNonDefaultsDict
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L127-L134
titusjan/argos
argos/config/qtctis.py
ColorCti.createEditor
def createEditor(self, delegate, parent, option): """ Creates a ColorCtiEditor. For the parameters see the AbstractCti constructor documentation. """ return ColorCtiEditor(self, delegate, parent=parent)
python
def createEditor(self, delegate, parent, option): """ Creates a ColorCtiEditor. For the parameters see the AbstractCti constructor documentation. """ return ColorCtiEditor(self, delegate, parent=parent)
Creates a ColorCtiEditor. For the parameters see the AbstractCti constructor documentation.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L145-L149
titusjan/argos
argos/config/qtctis.py
ColorCtiEditor.finalize
def finalize(self): """ Is called when the editor is closed. Disconnect signals. """ self.pickButton.clicked.disconnect(self.openColorDialog) super(ColorCtiEditor, self).finalize()
python
def finalize(self): """ Is called when the editor is closed. Disconnect signals. """ self.pickButton.clicked.disconnect(self.openColorDialog) super(ColorCtiEditor, self).finalize()
Is called when the editor is closed. Disconnect signals.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L177-L181
titusjan/argos
argos/config/qtctis.py
ColorCtiEditor.openColorDialog
def openColorDialog(self): """ Opens a QColorDialog for the user """ try: currentColor = self.getData() except InvalidInputError: currentColor = self.cti.data qColor = QtWidgets.QColorDialog.getColor(currentColor, self) if qColor.isValid(): self.setData(qColor) self.commitAndClose()
python
def openColorDialog(self): """ Opens a QColorDialog for the user """ try: currentColor = self.getData() except InvalidInputError: currentColor = self.cti.data qColor = QtWidgets.QColorDialog.getColor(currentColor, self) if qColor.isValid(): self.setData(qColor) self.commitAndClose()
Opens a QColorDialog for the user
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L184-L196
titusjan/argos
argos/config/qtctis.py
ColorCtiEditor.getData
def getData(self): """ Gets data from the editor widget. """ text = self.lineEditor.text() if not text.startswith('#'): text = '#' + text validator = self.lineEditor.validator() if validator is not None: state, text, _ = validator.validate(text, 0) if state != QtGui.QValidator.Acceptable: raise InvalidInputError("Invalid input: {!r}".format(text)) return QtGui.QColor(text)
python
def getData(self): """ Gets data from the editor widget. """ text = self.lineEditor.text() if not text.startswith('#'): text = '#' + text validator = self.lineEditor.validator() if validator is not None: state, text, _ = validator.validate(text, 0) if state != QtGui.QValidator.Acceptable: raise InvalidInputError("Invalid input: {!r}".format(text)) return QtGui.QColor(text)
Gets data from the editor widget.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L205-L218
titusjan/argos
argos/config/qtctis.py
FontCti.data
def data(self, data): """ Sets the font data of this item. Does type conversion to ensure data is always of the correct type. Also updates the children (which is the reason for this property to be overloaded. """ self._data = self._enforceDataType(data) # Enforce self._data to be a QFont self.familyCti.data = fontFamilyIndex(self.data, list(self.familyCti.iterConfigValues)) self.pointSizeCti.data = self.data.pointSize() self.weightCti.data = fontWeightIndex(self.data, list(self.weightCti.iterConfigValues)) self.italicCti.data = self.data.italic()
python
def data(self, data): """ Sets the font data of this item. Does type conversion to ensure data is always of the correct type. Also updates the children (which is the reason for this property to be overloaded. """ self._data = self._enforceDataType(data) # Enforce self._data to be a QFont self.familyCti.data = fontFamilyIndex(self.data, list(self.familyCti.iterConfigValues)) self.pointSizeCti.data = self.data.pointSize() self.weightCti.data = fontWeightIndex(self.data, list(self.weightCti.iterConfigValues)) self.italicCti.data = self.data.italic()
Sets the font data of this item. Does type conversion to ensure data is always of the correct type. Also updates the children (which is the reason for this property to be overloaded.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L269-L279
titusjan/argos
argos/config/qtctis.py
FontCti.defaultData
def defaultData(self, defaultData): """ Sets the data of this item. Does type conversion to ensure default data is always of the correct type. """ self._defaultData = self._enforceDataType(defaultData) # Enforce to be a QFont self.familyCti.defaultData = fontFamilyIndex(self.defaultData, list(self.familyCti.iterConfigValues)) self.pointSizeCti.defaultData = self.defaultData.pointSize() self.weightCti.defaultData = self.defaultData.weight() self.italicCti.defaultData = self.defaultData.italic()
python
def defaultData(self, defaultData): """ Sets the data of this item. Does type conversion to ensure default data is always of the correct type. """ self._defaultData = self._enforceDataType(defaultData) # Enforce to be a QFont self.familyCti.defaultData = fontFamilyIndex(self.defaultData, list(self.familyCti.iterConfigValues)) self.pointSizeCti.defaultData = self.defaultData.pointSize() self.weightCti.defaultData = self.defaultData.weight() self.italicCti.defaultData = self.defaultData.italic()
Sets the data of this item. Does type conversion to ensure default data is always of the correct type.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L290-L299
titusjan/argos
argos/config/qtctis.py
FontCti._updateTargetFromNode
def _updateTargetFromNode(self): """ Applies the font config settings to the target widget's font. That is the targetWidget.setFont() is called with a font create from the config values. """ font = self.data if self.familyCti.configValue: font.setFamily(self.familyCti.configValue) else: font.setFamily(QtGui.QFont().family()) # default family font.setPointSize(self.pointSizeCti.configValue) font.setWeight(self.weightCti.configValue) font.setItalic(self.italicCti.configValue) self._targetWidget.setFont(font)
python
def _updateTargetFromNode(self): """ Applies the font config settings to the target widget's font. That is the targetWidget.setFont() is called with a font create from the config values. """ font = self.data if self.familyCti.configValue: font.setFamily(self.familyCti.configValue) else: font.setFamily(QtGui.QFont().family()) # default family font.setPointSize(self.pointSizeCti.configValue) font.setWeight(self.weightCti.configValue) font.setItalic(self.italicCti.configValue) self._targetWidget.setFont(font)
Applies the font config settings to the target widget's font. That is the targetWidget.setFont() is called with a font create from the config values.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L324-L337
titusjan/argos
argos/config/qtctis.py
FontCti._nodeGetNonDefaultsDict
def _nodeGetNonDefaultsDict(self): """ Retrieves this nodes` values as a dictionary to be used for persistence. Non-recursive auxiliary function for getNonDefaultsDict """ dct = {} if self.data != self.defaultData: dct['data'] = self.data.toString() # calls QFont.toString() return dct
python
def _nodeGetNonDefaultsDict(self): """ Retrieves this nodes` values as a dictionary to be used for persistence. Non-recursive auxiliary function for getNonDefaultsDict """ dct = {} if self.data != self.defaultData: dct['data'] = self.data.toString() # calls QFont.toString() return dct
Retrieves this nodes` values as a dictionary to be used for persistence. Non-recursive auxiliary function for getNonDefaultsDict
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L340-L347
titusjan/argos
argos/config/qtctis.py
FontCti._nodeSetValuesFromDict
def _nodeSetValuesFromDict(self, dct): """ Sets values from a dictionary in the current node. Non-recursive auxiliary function for setValuesFromDict """ if 'data' in dct: qFont = QtGui.QFont() success = qFont.fromString(dct['data']) if not success: msg = "Unable to create QFont from string {!r}".format(dct['data']) logger.warn(msg) if DEBUGGING: raise ValueError(msg) self.data = qFont
python
def _nodeSetValuesFromDict(self, dct): """ Sets values from a dictionary in the current node. Non-recursive auxiliary function for setValuesFromDict """ if 'data' in dct: qFont = QtGui.QFont() success = qFont.fromString(dct['data']) if not success: msg = "Unable to create QFont from string {!r}".format(dct['data']) logger.warn(msg) if DEBUGGING: raise ValueError(msg) self.data = qFont
Sets values from a dictionary in the current node. Non-recursive auxiliary function for setValuesFromDict
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L350-L362
titusjan/argos
argos/config/qtctis.py
FontCti.createEditor
def createEditor(self, delegate, parent, option): """ Creates a FontCtiEditor. For the parameters see the AbstractCti documentation. """ return FontCtiEditor(self, delegate, parent=parent)
python
def createEditor(self, delegate, parent, option): """ Creates a FontCtiEditor. For the parameters see the AbstractCti documentation. """ return FontCtiEditor(self, delegate, parent=parent)
Creates a FontCtiEditor. For the parameters see the AbstractCti documentation.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L365-L369
titusjan/argos
argos/config/qtctis.py
FontCtiEditor.finalize
def finalize(self): """ Is called when the editor is closed. Disconnect signals. """ self.pickButton.clicked.disconnect(self.execFontDialog) super(FontCtiEditor, self).finalize()
python
def finalize(self): """ Is called when the editor is closed. Disconnect signals. """ self.pickButton.clicked.disconnect(self.execFontDialog) super(FontCtiEditor, self).finalize()
Is called when the editor is closed. Disconnect signals.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L396-L400
titusjan/argos
argos/config/qtctis.py
FontCtiEditor.execFontDialog
def execFontDialog(self): """ Opens a QColorDialog for the user """ currentFont = self.getData() newFont, ok = QtGui.QFontDialog.getFont(currentFont, self) if ok: self.setData(newFont) else: self.setData(currentFont) self.commitAndClose()
python
def execFontDialog(self): """ Opens a QColorDialog for the user """ currentFont = self.getData() newFont, ok = QtGui.QFontDialog.getFont(currentFont, self) if ok: self.setData(newFont) else: self.setData(currentFont) self.commitAndClose()
Opens a QColorDialog for the user
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L403-L412
titusjan/argos
argos/config/qtctis.py
FontChoiceCti.createEditor
def createEditor(self, delegate, parent, option): """ Creates a ChoiceCtiEditor. For the parameters see the AbstractCti constructor documentation. """ return FontChoiceCtiEditor(self, delegate, parent=parent)
python
def createEditor(self, delegate, parent, option): """ Creates a ChoiceCtiEditor. For the parameters see the AbstractCti constructor documentation. """ return FontChoiceCtiEditor(self, delegate, parent=parent)
Creates a ChoiceCtiEditor. For the parameters see the AbstractCti constructor documentation.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L464-L468
titusjan/argos
argos/config/qtctis.py
FontChoiceCtiEditor.finalize
def finalize(self): """ Is called when the editor is closed. Disconnect signals. """ self.comboBox.activated.disconnect(self.comboBoxActivated) super(FontChoiceCtiEditor, self).finalize()
python
def finalize(self): """ Is called when the editor is closed. Disconnect signals. """ self.comboBox.activated.disconnect(self.comboBoxActivated) super(FontChoiceCtiEditor, self).finalize()
Is called when the editor is closed. Disconnect signals.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L498-L502
titusjan/argos
argos/config/qtctis.py
PenCti.configValue
def configValue(self): """ Creates a QPen made of the children's config values. """ if not self.data: return None else: pen = QtGui.QPen() pen.setCosmetic(True) pen.setColor(self.colorCti.configValue) style = self.styleCti.configValue if style is not None: pen.setStyle(style) pen.setWidthF(self.widthCti.configValue) return pen
python
def configValue(self): """ Creates a QPen made of the children's config values. """ if not self.data: return None else: pen = QtGui.QPen() pen.setCosmetic(True) pen.setColor(self.colorCti.configValue) style = self.styleCti.configValue if style is not None: pen.setStyle(style) pen.setWidthF(self.widthCti.configValue) return pen
Creates a QPen made of the children's config values.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L560-L573
titusjan/argos
argos/config/qtctis.py
PenCti.createPen
def createPen(self, altStyle=None, altWidth=None): """ Creates a pen from the config values with the style overridden by altStyle if the None-option is selected in the combo box. """ pen = self.configValue if pen is not None: style = self.findByNodePath('style').configValue if style is None and altStyle is not None: pen.setStyle(altStyle) width = self.findByNodePath('width').configValue if width == 0.0 and altWidth is not None: #logger.debug("Setting altWidth = {!r}".format(altWidth)) pen.setWidthF(altWidth) return pen
python
def createPen(self, altStyle=None, altWidth=None): """ Creates a pen from the config values with the style overridden by altStyle if the None-option is selected in the combo box. """ pen = self.configValue if pen is not None: style = self.findByNodePath('style').configValue if style is None and altStyle is not None: pen.setStyle(altStyle) width = self.findByNodePath('width').configValue if width == 0.0 and altWidth is not None: #logger.debug("Setting altWidth = {!r}".format(altWidth)) pen.setWidthF(altWidth) return pen
Creates a pen from the config values with the style overridden by altStyle if the None-option is selected in the combo box.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L576-L592
titusjan/argos
argos/utils/masks.py
replaceMaskedValue
def replaceMaskedValue(data, mask, replacementValue, copyOnReplace=True): """ Replaces values where the mask is True with the replacement value. :copyOnReplace makeCopy: If True (the default) it makes a copy if data is replaced. """ if mask is False: result = data elif mask is True: result = np.copy(data) if copyOnReplace else data result[:] = replacementValue else: #logger.debug("############ count_nonzero: {}".format(np.count_nonzero(mask))) if copyOnReplace and np.any(mask): #logger.debug("Making copy") result = np.copy(data) else: result = data result[mask] = replacementValue return result
python
def replaceMaskedValue(data, mask, replacementValue, copyOnReplace=True): """ Replaces values where the mask is True with the replacement value. :copyOnReplace makeCopy: If True (the default) it makes a copy if data is replaced. """ if mask is False: result = data elif mask is True: result = np.copy(data) if copyOnReplace else data result[:] = replacementValue else: #logger.debug("############ count_nonzero: {}".format(np.count_nonzero(mask))) if copyOnReplace and np.any(mask): #logger.debug("Making copy") result = np.copy(data) else: result = data result[mask] = replacementValue return result
Replaces values where the mask is True with the replacement value. :copyOnReplace makeCopy: If True (the default) it makes a copy if data is replaced.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/masks.py#L231-L251
titusjan/argos
argos/utils/masks.py
replaceMaskedValueWithFloat
def replaceMaskedValueWithFloat(data, mask, replacementValue, copyOnReplace=True): """ Replaces values where the mask is True with the replacement value. Will change the data type to float if the data is an integer. If the data is not a float (or int) the function does nothing. Otherwise it will call replaceMaskedValue with the same parameters. :copyOnReplace makeCopy: If True (the default) it makes a copy if data is replaced. """ kind = data.dtype.kind if kind == 'i' or kind == 'u': # signed/unsigned int data = data.astype(np.float, casting='safe') if data.dtype.kind != 'f': return # only replace for floats else: return replaceMaskedValue(data, mask, replacementValue, copyOnReplace=copyOnReplace)
python
def replaceMaskedValueWithFloat(data, mask, replacementValue, copyOnReplace=True): """ Replaces values where the mask is True with the replacement value. Will change the data type to float if the data is an integer. If the data is not a float (or int) the function does nothing. Otherwise it will call replaceMaskedValue with the same parameters. :copyOnReplace makeCopy: If True (the default) it makes a copy if data is replaced. """ kind = data.dtype.kind if kind == 'i' or kind == 'u': # signed/unsigned int data = data.astype(np.float, casting='safe') if data.dtype.kind != 'f': return # only replace for floats else: return replaceMaskedValue(data, mask, replacementValue, copyOnReplace=copyOnReplace)
Replaces values where the mask is True with the replacement value. Will change the data type to float if the data is an integer. If the data is not a float (or int) the function does nothing. Otherwise it will call replaceMaskedValue with the same parameters. :copyOnReplace makeCopy: If True (the default) it makes a copy if data is replaced.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/masks.py#L254-L270
titusjan/argos
argos/utils/masks.py
maskedNanPercentile
def maskedNanPercentile(maskedArray, percentiles, *args, **kwargs): """ Calculates np.nanpercentile on the non-masked values """ #https://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html#accessing-the-data awm = ArrayWithMask.createFromMaskedArray(maskedArray) maskIdx = awm.maskIndex() validData = awm.data[~maskIdx] if len(validData) >= 1: result = np.nanpercentile(validData, percentiles, *args, **kwargs) else: # If np.nanpercentile on an empty list only returns a single Nan. We correct this here. result = len(percentiles) * [np.nan] assert len(result) == len(percentiles), \ "shape mismatch: {} != {}".format(len(result), len(percentiles)) return result
python
def maskedNanPercentile(maskedArray, percentiles, *args, **kwargs): """ Calculates np.nanpercentile on the non-masked values """ #https://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html#accessing-the-data awm = ArrayWithMask.createFromMaskedArray(maskedArray) maskIdx = awm.maskIndex() validData = awm.data[~maskIdx] if len(validData) >= 1: result = np.nanpercentile(validData, percentiles, *args, **kwargs) else: # If np.nanpercentile on an empty list only returns a single Nan. We correct this here. result = len(percentiles) * [np.nan] assert len(result) == len(percentiles), \ "shape mismatch: {} != {}".format(len(result), len(percentiles)) return result
Calculates np.nanpercentile on the non-masked values
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/masks.py#L274-L293
titusjan/argos
argos/utils/masks.py
maskedEqual
def maskedEqual(array, missingValue): """ Mask an array where equal to a given (missing)value. Unfortunately ma.masked_equal does not work with structured arrays. See: https://mail.scipy.org/pipermail/numpy-discussion/2011-July/057669.html If the data is a structured array the mask is applied for every field (i.e. forming a logical-and). Otherwise ma.masked_equal is called. """ if array_is_structured(array): # Enforce the array to be masked if not isinstance(array, ma.MaskedArray): array = ma.MaskedArray(array) # Set the mask separately per field for nr, field in enumerate(array.dtype.names): if hasattr(missingValue, '__len__'): fieldMissingValue = missingValue[nr] else: fieldMissingValue = missingValue array[field] = ma.masked_equal(array[field], fieldMissingValue) check_class(array, ma.MaskedArray) # post-condition check return array else: # masked_equal works with missing is None result = ma.masked_equal(array, missingValue, copy=False) check_class(result, ma.MaskedArray) # post-condition check return result
python
def maskedEqual(array, missingValue): """ Mask an array where equal to a given (missing)value. Unfortunately ma.masked_equal does not work with structured arrays. See: https://mail.scipy.org/pipermail/numpy-discussion/2011-July/057669.html If the data is a structured array the mask is applied for every field (i.e. forming a logical-and). Otherwise ma.masked_equal is called. """ if array_is_structured(array): # Enforce the array to be masked if not isinstance(array, ma.MaskedArray): array = ma.MaskedArray(array) # Set the mask separately per field for nr, field in enumerate(array.dtype.names): if hasattr(missingValue, '__len__'): fieldMissingValue = missingValue[nr] else: fieldMissingValue = missingValue array[field] = ma.masked_equal(array[field], fieldMissingValue) check_class(array, ma.MaskedArray) # post-condition check return array else: # masked_equal works with missing is None result = ma.masked_equal(array, missingValue, copy=False) check_class(result, ma.MaskedArray) # post-condition check return result
Mask an array where equal to a given (missing)value. Unfortunately ma.masked_equal does not work with structured arrays. See: https://mail.scipy.org/pipermail/numpy-discussion/2011-July/057669.html If the data is a structured array the mask is applied for every field (i.e. forming a logical-and). Otherwise ma.masked_equal is called.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/masks.py#L338-L367
titusjan/argos
argos/utils/masks.py
ArrayWithMask.mask
def mask(self, mask): """ The mask values. Must be an array or a boolean scalar.""" check_class(mask, (np.ndarray, bool, np.bool_)) if isinstance(mask, (bool, np.bool_)): self._mask = bool(mask) else: self._mask = mask
python
def mask(self, mask): """ The mask values. Must be an array or a boolean scalar.""" check_class(mask, (np.ndarray, bool, np.bool_)) if isinstance(mask, (bool, np.bool_)): self._mask = bool(mask) else: self._mask = mask
The mask values. Must be an array or a boolean scalar.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/masks.py#L84-L90
titusjan/argos
argos/utils/masks.py
ArrayWithMask.checkIsConsistent
def checkIsConsistent(self): """ Raises a ConsistencyError if the mask has an incorrect shape. """ if is_an_array(self.mask) and self.mask.shape != self.data.shape: raise ConsistencyError("Shape mismatch mask={}, data={}" .format(self.mask.shape != self.data.shape))
python
def checkIsConsistent(self): """ Raises a ConsistencyError if the mask has an incorrect shape. """ if is_an_array(self.mask) and self.mask.shape != self.data.shape: raise ConsistencyError("Shape mismatch mask={}, data={}" .format(self.mask.shape != self.data.shape))
Raises a ConsistencyError if the mask has an incorrect shape.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/masks.py#L105-L110
titusjan/argos
argos/utils/masks.py
ArrayWithMask.createFromMaskedArray
def createFromMaskedArray(cls, masked_arr): """ Creates an ArrayWithMak :param masked_arr: a numpy MaskedArray or numpy array :return: ArrayWithMask """ if isinstance(masked_arr, ArrayWithMask): return masked_arr check_class(masked_arr, (np.ndarray, ma.MaskedArray)) # A MaskedConstant (i.e. masked) is a special case of MaskedArray. It does not seem to have # a fill_value so we use None to use the default. # https://docs.scipy.org/doc/numpy/reference/maskedarray.baseclass.html#numpy.ma.masked fill_value = getattr(masked_arr, 'fill_value', None) return cls(masked_arr.data, masked_arr.mask, fill_value)
python
def createFromMaskedArray(cls, masked_arr): """ Creates an ArrayWithMak :param masked_arr: a numpy MaskedArray or numpy array :return: ArrayWithMask """ if isinstance(masked_arr, ArrayWithMask): return masked_arr check_class(masked_arr, (np.ndarray, ma.MaskedArray)) # A MaskedConstant (i.e. masked) is a special case of MaskedArray. It does not seem to have # a fill_value so we use None to use the default. # https://docs.scipy.org/doc/numpy/reference/maskedarray.baseclass.html#numpy.ma.masked fill_value = getattr(masked_arr, 'fill_value', None) return cls(masked_arr.data, masked_arr.mask, fill_value)
Creates an ArrayWithMak :param masked_arr: a numpy MaskedArray or numpy array :return: ArrayWithMask
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/masks.py#L114-L130
titusjan/argos
argos/utils/masks.py
ArrayWithMask.asMaskedArray
def asMaskedArray(self): """ Creates converts to a masked array """ return ma.masked_array(data=self.data, mask=self.mask, fill_value=self.fill_value)
python
def asMaskedArray(self): """ Creates converts to a masked array """ return ma.masked_array(data=self.data, mask=self.mask, fill_value=self.fill_value)
Creates converts to a masked array
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/masks.py#L133-L136
titusjan/argos
argos/utils/masks.py
ArrayWithMask.maskAt
def maskAt(self, index): """ Returns the mask at the index. It the mask is a boolean it is returned since this boolean representes the mask for all array elements. """ if isinstance(self.mask, bool): return self.mask else: return self.mask[index]
python
def maskAt(self, index): """ Returns the mask at the index. It the mask is a boolean it is returned since this boolean representes the mask for all array elements. """ if isinstance(self.mask, bool): return self.mask else: return self.mask[index]
Returns the mask at the index. It the mask is a boolean it is returned since this boolean representes the mask for all array elements.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/masks.py#L139-L148
titusjan/argos
argos/utils/masks.py
ArrayWithMask.maskIndex
def maskIndex(self): """ Returns a boolean index with True if the value is masked. Always has the same shape as the maksedArray.data, event if the mask is a single boolan. """ if isinstance(self.mask, bool): return np.full(self.data.shape, self.mask, dtype=np.bool) else: return self.mask
python
def maskIndex(self): """ Returns a boolean index with True if the value is masked. Always has the same shape as the maksedArray.data, event if the mask is a single boolan. """ if isinstance(self.mask, bool): return np.full(self.data.shape, self.mask, dtype=np.bool) else: return self.mask
Returns a boolean index with True if the value is masked. Always has the same shape as the maksedArray.data, event if the mask is a single boolan.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/masks.py#L151-L159
titusjan/argos
argos/utils/masks.py
ArrayWithMask.transpose
def transpose(self, *args, **kwargs): """ Transposes the array and mask separately :param awm: ArrayWithMask :return: copy/view with transposed """ tdata = np.transpose(self.data, *args, **kwargs) tmask = np.transpose(self.mask, *args, **kwargs) if is_an_array(self.mask) else self.mask return ArrayWithMask(tdata, tmask, self.fill_value)
python
def transpose(self, *args, **kwargs): """ Transposes the array and mask separately :param awm: ArrayWithMask :return: copy/view with transposed """ tdata = np.transpose(self.data, *args, **kwargs) tmask = np.transpose(self.mask, *args, **kwargs) if is_an_array(self.mask) else self.mask return ArrayWithMask(tdata, tmask, self.fill_value)
Transposes the array and mask separately :param awm: ArrayWithMask :return: copy/view with transposed
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/masks.py#L184-L192
titusjan/argos
argos/utils/masks.py
ArrayWithMask.replaceMaskedValue
def replaceMaskedValue(self, replacementValue): """ Replaces values where the mask is True with the replacement value. """ if self.mask is False: pass elif self.mask is True: self.data[:] = replacementValue else: self.data[self.mask] = replacementValue
python
def replaceMaskedValue(self, replacementValue): """ Replaces values where the mask is True with the replacement value. """ if self.mask is False: pass elif self.mask is True: self.data[:] = replacementValue else: self.data[self.mask] = replacementValue
Replaces values where the mask is True with the replacement value.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/masks.py#L195-L203
titusjan/argos
argos/utils/masks.py
ArrayWithMask.replaceMaskedValueWithNan
def replaceMaskedValueWithNan(self): """ Replaces values where the mask is True with the replacement value. Will change the data type to float if the data is an integer. If the data is not a float (or int) the function does nothing. """ kind = self.data.dtype.kind if kind == 'i' or kind == 'u': # signed/unsigned int self.data = self.data.astype(np.float, casting='safe') if self.data.dtype.kind != 'f': return # only replace for floats if self.mask is False: pass elif self.mask is True: self.data[:] = np.NaN else: self.data[self.mask] = np.NaN
python
def replaceMaskedValueWithNan(self): """ Replaces values where the mask is True with the replacement value. Will change the data type to float if the data is an integer. If the data is not a float (or int) the function does nothing. """ kind = self.data.dtype.kind if kind == 'i' or kind == 'u': # signed/unsigned int self.data = self.data.astype(np.float, casting='safe') if self.data.dtype.kind != 'f': return # only replace for floats if self.mask is False: pass elif self.mask is True: self.data[:] = np.NaN else: self.data[self.mask] = np.NaN
Replaces values where the mask is True with the replacement value. Will change the data type to float if the data is an integer. If the data is not a float (or int) the function does nothing.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/masks.py#L206-L224
titusjan/argos
argos/widgets/pluginsdialog.py
RegistryTab.importRegItem
def importRegItem(self, regItem): """ Imports the regItem Writes this in the statusLabel while the import is in progress. """ self.statusLabel.setText("Importing {}...".format(regItem.fullName)) QtWidgets.qApp.processEvents() regItem.tryImportClass() self.tableView.model().emitDataChanged(regItem) self.statusLabel.setText("") QtWidgets.qApp.processEvents()
python
def importRegItem(self, regItem): """ Imports the regItem Writes this in the statusLabel while the import is in progress. """ self.statusLabel.setText("Importing {}...".format(regItem.fullName)) QtWidgets.qApp.processEvents() regItem.tryImportClass() self.tableView.model().emitDataChanged(regItem) self.statusLabel.setText("") QtWidgets.qApp.processEvents()
Imports the regItem Writes this in the statusLabel while the import is in progress.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/pluginsdialog.py#L133-L142
titusjan/argos
argos/widgets/pluginsdialog.py
RegistryTab.tryImportAllPlugins
def tryImportAllPlugins(self): """ Tries to import all underlying plugin classes """ for regItem in self.registeredItems: if not regItem.triedImport: self.importRegItem(regItem) logger.debug("Importing finished.")
python
def tryImportAllPlugins(self): """ Tries to import all underlying plugin classes """ for regItem in self.registeredItems: if not regItem.triedImport: self.importRegItem(regItem) logger.debug("Importing finished.")
Tries to import all underlying plugin classes
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/pluginsdialog.py#L145-L152
titusjan/argos
argos/widgets/pluginsdialog.py
RegistryTab.setCurrentRegItem
def setCurrentRegItem(self, regItem): """ Sets the current item to the regItem """ check_class(regItem, ClassRegItem, allow_none=True) self.tableView.setCurrentRegItem(regItem)
python
def setCurrentRegItem(self, regItem): """ Sets the current item to the regItem """ check_class(regItem, ClassRegItem, allow_none=True) self.tableView.setCurrentRegItem(regItem)
Sets the current item to the regItem
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/pluginsdialog.py#L162-L166
titusjan/argos
argos/widgets/pluginsdialog.py
RegistryTab.currentItemChanged
def currentItemChanged(self, _currentIndex=None, _previousIndex=None): """ Updates the description text widget when the user clicks on a selector in the table. The _currentIndex and _previousIndex parameters are ignored. """ self.editor.clear() self.editor.setTextColor(QCOLOR_REGULAR) regItem = self.getCurrentRegItem() if regItem is None: return if self._importOnSelect and regItem.successfullyImported is None: self.importRegItem(regItem) if regItem.successfullyImported is None: self.editor.setTextColor(QCOLOR_NOT_IMPORTED) self.editor.setPlainText('<plugin not yet imported>') elif regItem.successfullyImported is False: self.editor.setTextColor(QCOLOR_ERROR) self.editor.setPlainText(str(regItem.exception)) elif regItem.descriptionHtml: self.editor.setHtml(regItem.descriptionHtml) else: self.editor.setPlainText(regItem.docString)
python
def currentItemChanged(self, _currentIndex=None, _previousIndex=None): """ Updates the description text widget when the user clicks on a selector in the table. The _currentIndex and _previousIndex parameters are ignored. """ self.editor.clear() self.editor.setTextColor(QCOLOR_REGULAR) regItem = self.getCurrentRegItem() if regItem is None: return if self._importOnSelect and regItem.successfullyImported is None: self.importRegItem(regItem) if regItem.successfullyImported is None: self.editor.setTextColor(QCOLOR_NOT_IMPORTED) self.editor.setPlainText('<plugin not yet imported>') elif regItem.successfullyImported is False: self.editor.setTextColor(QCOLOR_ERROR) self.editor.setPlainText(str(regItem.exception)) elif regItem.descriptionHtml: self.editor.setHtml(regItem.descriptionHtml) else: self.editor.setPlainText(regItem.docString)
Updates the description text widget when the user clicks on a selector in the table. The _currentIndex and _previousIndex parameters are ignored.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/pluginsdialog.py#L170-L194
titusjan/argos
argos/widgets/pluginsdialog.py
PluginsDialog.tryImportAllPlugins
def tryImportAllPlugins(self): """ Refreshes the tables of all tables by importing the underlying classes """ logger.debug("Importing plugins: {}".format(self)) for tabNr in range(self.tabWidget.count()): tab = self.tabWidget.widget(tabNr) tab.tryImportAllPlugins()
python
def tryImportAllPlugins(self): """ Refreshes the tables of all tables by importing the underlying classes """ logger.debug("Importing plugins: {}".format(self)) for tabNr in range(self.tabWidget.count()): tab = self.tabWidget.widget(tabNr) tab.tryImportAllPlugins()
Refreshes the tables of all tables by importing the underlying classes
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/pluginsdialog.py#L243-L249
titusjan/argos
argos/repo/rtiplugins/hdf5.py
dimNamesFromDataset
def dimNamesFromDataset(h5Dataset): """ Constructs the dimension names given a h5py dataset. First looks in the dataset's dimension scales to see if it refers to another dataset. In that case the referred dataset's name is used. If not, the label of the dimension scale is used. Finally, if this is empty, the dimension is numbered. """ dimNames = [] # TODO: cache? for dimNr, dimScales in enumerate(h5Dataset.dims): if len(dimScales) == 0: dimNames.append('Dim{}'.format(dimNr)) elif len(dimScales) == 1: dimScaleLabel, dimScaleDataset = dimScales.items()[0] path = dimScaleDataset.name if path: dimNames.append(os.path.basename(path)) elif dimScaleLabel: # This could potentially be long so it's our second choice dimNames.append(dimScaleLabel) else: dimNames.append('Dim{}'.format(dimNr)) else: # TODO: multiple scales for this dimension. What to do? logger.warn("More than one dimension scale found: {!r}".format(dimScales)) dimNames.append('Dim{}'.format(dimNr)) # For now, just number them return dimNames
python
def dimNamesFromDataset(h5Dataset): """ Constructs the dimension names given a h5py dataset. First looks in the dataset's dimension scales to see if it refers to another dataset. In that case the referred dataset's name is used. If not, the label of the dimension scale is used. Finally, if this is empty, the dimension is numbered. """ dimNames = [] # TODO: cache? for dimNr, dimScales in enumerate(h5Dataset.dims): if len(dimScales) == 0: dimNames.append('Dim{}'.format(dimNr)) elif len(dimScales) == 1: dimScaleLabel, dimScaleDataset = dimScales.items()[0] path = dimScaleDataset.name if path: dimNames.append(os.path.basename(path)) elif dimScaleLabel: # This could potentially be long so it's our second choice dimNames.append(dimScaleLabel) else: dimNames.append('Dim{}'.format(dimNr)) else: # TODO: multiple scales for this dimension. What to do? logger.warn("More than one dimension scale found: {!r}".format(dimScales)) dimNames.append('Dim{}'.format(dimNr)) # For now, just number them return dimNames
Constructs the dimension names given a h5py dataset. First looks in the dataset's dimension scales to see if it refers to another dataset. In that case the referred dataset's name is used. If not, the label of the dimension scale is used. Finally, if this is empty, the dimension is numbered.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/hdf5.py#L39-L64
titusjan/argos
argos/repo/rtiplugins/hdf5.py
dataSetElementType
def dataSetElementType(h5Dataset): """ Returns a string describing the element type of the dataset """ dtype = h5Dataset.dtype if dtype.names: return '<structured>' else: if dtype.metadata and 'vlen' in dtype.metadata: vlen_type = dtype.metadata['vlen'] try: return "<vlen {}>".format(vlen_type.__name__) # when vlen_type is a type except AttributeError: # return "<vlen {}>".format(vlen_type.name) # when vlen_type is a dtype return str(dtype)
python
def dataSetElementType(h5Dataset): """ Returns a string describing the element type of the dataset """ dtype = h5Dataset.dtype if dtype.names: return '<structured>' else: if dtype.metadata and 'vlen' in dtype.metadata: vlen_type = dtype.metadata['vlen'] try: return "<vlen {}>".format(vlen_type.__name__) # when vlen_type is a type except AttributeError: # return "<vlen {}>".format(vlen_type.name) # when vlen_type is a dtype return str(dtype)
Returns a string describing the element type of the dataset
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/hdf5.py#L67-L82
titusjan/argos
argos/repo/rtiplugins/hdf5.py
dataSetUnit
def dataSetUnit(h5Dataset): """ Returns the unit of the h5Dataset by looking in the attributes. It searches in the attributes for one of the following keys: 'unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'. If these are not found, the empty string is returned. Always returns a string """ attributes = h5Dataset.attrs if not attributes: return '' # a premature optimization :-) for key in ('unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'): if key in attributes: # In Python3 the attributes are byte strings so we must decode them # This a bug in h5py, see https://github.com/h5py/h5py/issues/379 return to_string(attributes[key]) # Not found return ''
python
def dataSetUnit(h5Dataset): """ Returns the unit of the h5Dataset by looking in the attributes. It searches in the attributes for one of the following keys: 'unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'. If these are not found, the empty string is returned. Always returns a string """ attributes = h5Dataset.attrs if not attributes: return '' # a premature optimization :-) for key in ('unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'): if key in attributes: # In Python3 the attributes are byte strings so we must decode them # This a bug in h5py, see https://github.com/h5py/h5py/issues/379 return to_string(attributes[key]) # Not found return ''
Returns the unit of the h5Dataset by looking in the attributes. It searches in the attributes for one of the following keys: 'unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'. If these are not found, the empty string is returned. Always returns a string
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/hdf5.py#L85-L104
titusjan/argos
argos/repo/rtiplugins/hdf5.py
dataSetMissingValue
def dataSetMissingValue(h5Dataset): """ Returns the missingData given a HDF-5 dataset Looks for one of the following attributes: _FillValue, missing_value, MissingValue, missingValue. Returns None if these attributes are not found. HDF-EOS and NetCDF files seem to put the attributes in 1-element arrays. So if the attribute contains an array of one element, that first element is returned here. """ attributes = h5Dataset.attrs if not attributes: return None # a premature optimization :-) for key in ('missing_value', 'MissingValue', 'missingValue', 'FillValue', '_FillValue'): if key in attributes: missingDataValue = attributes[key] if is_an_array(missingDataValue) and len(missingDataValue) == 1: return missingDataValue[0] # In case of HDF-EOS and NetCDF files else: return missingDataValue return None
python
def dataSetMissingValue(h5Dataset): """ Returns the missingData given a HDF-5 dataset Looks for one of the following attributes: _FillValue, missing_value, MissingValue, missingValue. Returns None if these attributes are not found. HDF-EOS and NetCDF files seem to put the attributes in 1-element arrays. So if the attribute contains an array of one element, that first element is returned here. """ attributes = h5Dataset.attrs if not attributes: return None # a premature optimization :-) for key in ('missing_value', 'MissingValue', 'missingValue', 'FillValue', '_FillValue'): if key in attributes: missingDataValue = attributes[key] if is_an_array(missingDataValue) and len(missingDataValue) == 1: return missingDataValue[0] # In case of HDF-EOS and NetCDF files else: return missingDataValue return None
Returns the missingData given a HDF-5 dataset Looks for one of the following attributes: _FillValue, missing_value, MissingValue, missingValue. Returns None if these attributes are not found. HDF-EOS and NetCDF files seem to put the attributes in 1-element arrays. So if the attribute contains an array of one element, that first element is returned here.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/hdf5.py#L107-L127
titusjan/argos
argos/repo/rtiplugins/hdf5.py
H5pyFieldRti._subArrayShape
def _subArrayShape(self): """ Returns the shape of the sub-array An empty tuple is returned for regular fields, which have no sub array. """ if self._h5Dataset.dtype.fields is None: return tuple() # regular field else: fieldName = self.nodeName fieldDtype = self._h5Dataset.dtype.fields[fieldName][0] return fieldDtype.shape
python
def _subArrayShape(self): """ Returns the shape of the sub-array An empty tuple is returned for regular fields, which have no sub array. """ if self._h5Dataset.dtype.fields is None: return tuple() # regular field else: fieldName = self.nodeName fieldDtype = self._h5Dataset.dtype.fields[fieldName][0] return fieldDtype.shape
Returns the shape of the sub-array An empty tuple is returned for regular fields, which have no sub array.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/hdf5.py#L268-L277
titusjan/argos
argos/repo/rtiplugins/hdf5.py
H5pyFieldRti.elementTypeName
def elementTypeName(self): """ String representation of the element type. """ fieldName = self.nodeName return str(self._h5Dataset.dtype.fields[fieldName][0])
python
def elementTypeName(self): """ String representation of the element type. """ fieldName = self.nodeName return str(self._h5Dataset.dtype.fields[fieldName][0])
String representation of the element type.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/hdf5.py#L289-L293
titusjan/argos
argos/repo/rtiplugins/hdf5.py
H5pyFieldRti.dimensionNames
def dimensionNames(self): """ Returns a list with the dimension names of the underlying NCDF variable """ nSubDims = len(self._subArrayShape) subArrayDims = ['SubDim{}'.format(dimNr) for dimNr in range(nSubDims)] return dimNamesFromDataset(self._h5Dataset) + subArrayDims
python
def dimensionNames(self): """ Returns a list with the dimension names of the underlying NCDF variable """ nSubDims = len(self._subArrayShape) subArrayDims = ['SubDim{}'.format(dimNr) for dimNr in range(nSubDims)] return dimNamesFromDataset(self._h5Dataset) + subArrayDims
Returns a list with the dimension names of the underlying NCDF variable
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/hdf5.py#L297-L302
titusjan/argos
argos/repo/rtiplugins/hdf5.py
H5pyFieldRti.unit
def unit(self): """ Returns the unit of the RTI by calling dataSetUnit on the underlying dataset """ unit = dataSetUnit(self._h5Dataset) fieldNames = self._h5Dataset.dtype.names # If the missing value attribute is a list with the same length as the number of fields, # return the missing value for field that equals the self.nodeName. if hasattr(unit, '__len__') and len(unit) == len(fieldNames): idx = fieldNames.index(self.nodeName) return unit[idx] else: return unit
python
def unit(self): """ Returns the unit of the RTI by calling dataSetUnit on the underlying dataset """ unit = dataSetUnit(self._h5Dataset) fieldNames = self._h5Dataset.dtype.names # If the missing value attribute is a list with the same length as the number of fields, # return the missing value for field that equals the self.nodeName. if hasattr(unit, '__len__') and len(unit) == len(fieldNames): idx = fieldNames.index(self.nodeName) return unit[idx] else: return unit
Returns the unit of the RTI by calling dataSetUnit on the underlying dataset
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/hdf5.py#L306-L318
titusjan/argos
argos/repo/rtiplugins/hdf5.py
H5pyFieldRti.missingDataValue
def missingDataValue(self): """ Returns the value to indicate missing data. None if no missing-data value is specified. """ value = dataSetMissingValue(self._h5Dataset) fieldNames = self._h5Dataset.dtype.names # If the missing value attribute is a list with the same length as the number of fields, # return the missing value for field that equals the self.nodeName. if hasattr(value, '__len__') and len(value) == len(fieldNames): idx = fieldNames.index(self.nodeName) return value[idx] else: return value
python
def missingDataValue(self): """ Returns the value to indicate missing data. None if no missing-data value is specified. """ value = dataSetMissingValue(self._h5Dataset) fieldNames = self._h5Dataset.dtype.names # If the missing value attribute is a list with the same length as the number of fields, # return the missing value for field that equals the self.nodeName. if hasattr(value, '__len__') and len(value) == len(fieldNames): idx = fieldNames.index(self.nodeName) return value[idx] else: return value
Returns the value to indicate missing data. None if no missing-data value is specified.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/hdf5.py#L322-L334
titusjan/argos
argos/repo/rtiplugins/hdf5.py
H5pyDatasetRti.iconGlyph
def iconGlyph(self): """ Shows an Array icon for regular datasets but a dimension icon for dimension scales """ if self._h5Dataset.attrs.get('CLASS', None) == b'DIMENSION_SCALE': return RtiIconFactory.DIMENSION else: return RtiIconFactory.ARRAY
python
def iconGlyph(self): """ Shows an Array icon for regular datasets but a dimension icon for dimension scales """ if self._h5Dataset.attrs.get('CLASS', None) == b'DIMENSION_SCALE': return RtiIconFactory.DIMENSION else: return RtiIconFactory.ARRAY
Shows an Array icon for regular datasets but a dimension icon for dimension scales
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/hdf5.py#L356-L362
titusjan/argos
argos/repo/rtiplugins/hdf5.py
H5pyDatasetRti._fetchAllChildren
def _fetchAllChildren(self): """ Fetches all fields that this variable contains. Only variables with a structured data type can have fields. """ assert self.canFetchChildren(), "canFetchChildren must be True" childItems = [] # Add fields if self._isStructured: for fieldName in self._h5Dataset.dtype.names: childItems.append(H5pyFieldRti(self._h5Dataset, nodeName=fieldName, fileName=self.fileName)) return childItems
python
def _fetchAllChildren(self): """ Fetches all fields that this variable contains. Only variables with a structured data type can have fields. """ assert self.canFetchChildren(), "canFetchChildren must be True" childItems = [] # Add fields if self._isStructured: for fieldName in self._h5Dataset.dtype.names: childItems.append(H5pyFieldRti(self._h5Dataset, nodeName=fieldName, fileName=self.fileName)) return childItems
Fetches all fields that this variable contains. Only variables with a structured data type can have fields.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/hdf5.py#L428-L442
titusjan/argos
argos/repo/rtiplugins/hdf5.py
H5pyGroupRti._fetchAllChildren
def _fetchAllChildren(self): """ Fetches all sub groups and variables that this group contains. """ assert self._h5Group is not None, "dataset undefined (file not opened?)" assert self.canFetchChildren(), "canFetchChildren must be True" childItems = [] for childName, h5Child in self._h5Group.items(): if isinstance(h5Child, h5py.Group): childItems.append(H5pyGroupRti(h5Child, nodeName=childName, fileName=self.fileName)) elif isinstance(h5Child, h5py.Dataset): if len(h5Child.shape) == 0: childItems.append(H5pyScalarRti(h5Child, nodeName=childName, fileName=self.fileName)) else: childItems.append(H5pyDatasetRti(h5Child, nodeName=childName, fileName=self.fileName)) elif isinstance(h5Child, h5py.Datatype): #logger.debug("Ignored DataType item: {}".format(childName)) pass else: logger.warn("Ignored {}. It has an unexpected HDF-5 type: {}" .format(childName, type(h5Child))) return childItems
python
def _fetchAllChildren(self): """ Fetches all sub groups and variables that this group contains. """ assert self._h5Group is not None, "dataset undefined (file not opened?)" assert self.canFetchChildren(), "canFetchChildren must be True" childItems = [] for childName, h5Child in self._h5Group.items(): if isinstance(h5Child, h5py.Group): childItems.append(H5pyGroupRti(h5Child, nodeName=childName, fileName=self.fileName)) elif isinstance(h5Child, h5py.Dataset): if len(h5Child.shape) == 0: childItems.append(H5pyScalarRti(h5Child, nodeName=childName, fileName=self.fileName)) else: childItems.append(H5pyDatasetRti(h5Child, nodeName=childName, fileName=self.fileName)) elif isinstance(h5Child, h5py.Datatype): #logger.debug("Ignored DataType item: {}".format(childName)) pass else: logger.warn("Ignored {}. It has an unexpected HDF-5 type: {}" .format(childName, type(h5Child))) return childItems
Fetches all sub groups and variables that this group contains.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/hdf5.py#L467-L494
titusjan/argos
argos/repo/rtiplugins/hdf5.py
H5pyFileRti._openResources
def _openResources(self): """ Opens the root Dataset. """ logger.info("Opening: {}".format(self._fileName)) self._h5Group = h5py.File(self._fileName, 'r')
python
def _openResources(self): """ Opens the root Dataset. """ logger.info("Opening: {}".format(self._fileName)) self._h5Group = h5py.File(self._fileName, 'r')
Opens the root Dataset.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/hdf5.py#L512-L516
titusjan/argos
argos/repo/rtiplugins/hdf5.py
H5pyFileRti._closeResources
def _closeResources(self): """ Closes the root Dataset. """ logger.info("Closing: {}".format(self._fileName)) self._h5Group.close() self._h5Group = None
python
def _closeResources(self): """ Closes the root Dataset. """ logger.info("Closing: {}".format(self._fileName)) self._h5Group.close() self._h5Group = None
Closes the root Dataset.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/hdf5.py#L519-L524
titusjan/argos
argos/inspector/pgplugins/imageplot2d.py
calcPgImagePlot2dDataRange
def calcPgImagePlot2dDataRange(pgImagePlot2d, percentage, crossPlot): """ Calculates the range from the inspectors' sliced array. Discards percentage of the minimum and percentage of the maximum values of the inspector.slicedArray :param pgImagePlot2d: the range methods will work on (the sliced array) of this inspector. :param percentage: percentage that will be discarded. :param crossPlot: if None, the range will be calculated from the entire sliced array, if "horizontal" or "vertical" the range will be calculated from the data under the horizontal or vertical cross hairs. If the cursor is outside the image, there is no valid data under the cross-hair and the range will be determined from the sliced array as a fall back. """ check_class(pgImagePlot2d.slicedArray, ArrayWithMask) # sanity check if crossPlot is None: array = pgImagePlot2d.slicedArray # the whole image elif crossPlot == 'horizontal': if pgImagePlot2d.crossPlotRow is not None: array = pgImagePlot2d.slicedArray.asMaskedArray()[pgImagePlot2d.crossPlotRow, :] else: array = pgImagePlot2d.slicedArray # fall back on complete sliced array elif crossPlot == 'vertical': if pgImagePlot2d.crossPlotCol is not None: array = pgImagePlot2d.slicedArray.asMaskedArray()[:, pgImagePlot2d.crossPlotCol] else: array = pgImagePlot2d.slicedArray # fall back on complete sliced array else: raise ValueError("crossPlot must be: None, 'horizontal' or 'vertical', got: {}" .format(crossPlot)) return maskedNanPercentile(array, (percentage, 100-percentage) )
python
def calcPgImagePlot2dDataRange(pgImagePlot2d, percentage, crossPlot): """ Calculates the range from the inspectors' sliced array. Discards percentage of the minimum and percentage of the maximum values of the inspector.slicedArray :param pgImagePlot2d: the range methods will work on (the sliced array) of this inspector. :param percentage: percentage that will be discarded. :param crossPlot: if None, the range will be calculated from the entire sliced array, if "horizontal" or "vertical" the range will be calculated from the data under the horizontal or vertical cross hairs. If the cursor is outside the image, there is no valid data under the cross-hair and the range will be determined from the sliced array as a fall back. """ check_class(pgImagePlot2d.slicedArray, ArrayWithMask) # sanity check if crossPlot is None: array = pgImagePlot2d.slicedArray # the whole image elif crossPlot == 'horizontal': if pgImagePlot2d.crossPlotRow is not None: array = pgImagePlot2d.slicedArray.asMaskedArray()[pgImagePlot2d.crossPlotRow, :] else: array = pgImagePlot2d.slicedArray # fall back on complete sliced array elif crossPlot == 'vertical': if pgImagePlot2d.crossPlotCol is not None: array = pgImagePlot2d.slicedArray.asMaskedArray()[:, pgImagePlot2d.crossPlotCol] else: array = pgImagePlot2d.slicedArray # fall back on complete sliced array else: raise ValueError("crossPlot must be: None, 'horizontal' or 'vertical', got: {}" .format(crossPlot)) return maskedNanPercentile(array, (percentage, 100-percentage) )
Calculates the range from the inspectors' sliced array. Discards percentage of the minimum and percentage of the maximum values of the inspector.slicedArray :param pgImagePlot2d: the range methods will work on (the sliced array) of this inspector. :param percentage: percentage that will be discarded. :param crossPlot: if None, the range will be calculated from the entire sliced array, if "horizontal" or "vertical" the range will be calculated from the data under the horizontal or vertical cross hairs. If the cursor is outside the image, there is no valid data under the cross-hair and the range will be determined from the sliced array as a fall back.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/imageplot2d.py#L56-L88
titusjan/argos
argos/inspector/pgplugins/imageplot2d.py
crossPlotAutoRangeMethods
def crossPlotAutoRangeMethods(pgImagePlot2d, crossPlot, intialItems=None): """ Creates an ordered dict with autorange methods for an PgImagePlot2d inspector. :param pgImagePlot2d: the range methods will work on (the sliced array) of this inspector. :param crossPlot: if None, the range will be calculated from the entire sliced array, if "horizontal" or "vertical" the range will be calculated from the data under the horizontal or vertical cross hairs :param intialItems: will be passed on to the OrderedDict constructor. """ rangeFunctions = OrderedDict({} if intialItems is None else intialItems) # If crossPlot is "horizontal" or "vertical" make functions that determine the range from the # data at the cross hair. if crossPlot: rangeFunctions['cross all data'] = partial(calcPgImagePlot2dDataRange, pgImagePlot2d, 0.0, crossPlot) for percentage in [0.1, 0.2, 0.5, 1, 2, 5, 10, 20]: label = "cross discard {}%".format(percentage) rangeFunctions[label] = partial(calcPgImagePlot2dDataRange, pgImagePlot2d, percentage, crossPlot) # Always add functions that determine the data from the complete sliced array. for percentage in [0.1, 0.2, 0.5, 1, 2, 5, 10, 20]: rangeFunctions['image all data'] = partial(calcPgImagePlot2dDataRange, pgImagePlot2d, 0.0, None) label = "image discard {}%".format(percentage) rangeFunctions[label] = partial(calcPgImagePlot2dDataRange, pgImagePlot2d, percentage, None) return rangeFunctions
python
def crossPlotAutoRangeMethods(pgImagePlot2d, crossPlot, intialItems=None): """ Creates an ordered dict with autorange methods for an PgImagePlot2d inspector. :param pgImagePlot2d: the range methods will work on (the sliced array) of this inspector. :param crossPlot: if None, the range will be calculated from the entire sliced array, if "horizontal" or "vertical" the range will be calculated from the data under the horizontal or vertical cross hairs :param intialItems: will be passed on to the OrderedDict constructor. """ rangeFunctions = OrderedDict({} if intialItems is None else intialItems) # If crossPlot is "horizontal" or "vertical" make functions that determine the range from the # data at the cross hair. if crossPlot: rangeFunctions['cross all data'] = partial(calcPgImagePlot2dDataRange, pgImagePlot2d, 0.0, crossPlot) for percentage in [0.1, 0.2, 0.5, 1, 2, 5, 10, 20]: label = "cross discard {}%".format(percentage) rangeFunctions[label] = partial(calcPgImagePlot2dDataRange, pgImagePlot2d, percentage, crossPlot) # Always add functions that determine the data from the complete sliced array. for percentage in [0.1, 0.2, 0.5, 1, 2, 5, 10, 20]: rangeFunctions['image all data'] = partial(calcPgImagePlot2dDataRange, pgImagePlot2d, 0.0, None) label = "image discard {}%".format(percentage) rangeFunctions[label] = partial(calcPgImagePlot2dDataRange, pgImagePlot2d, percentage, None) return rangeFunctions
Creates an ordered dict with autorange methods for an PgImagePlot2d inspector. :param pgImagePlot2d: the range methods will work on (the sliced array) of this inspector. :param crossPlot: if None, the range will be calculated from the entire sliced array, if "horizontal" or "vertical" the range will be calculated from the data under the horizontal or vertical cross hairs :param intialItems: will be passed on to the OrderedDict constructor.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/imageplot2d.py#L91-L120
titusjan/argos
argos/inspector/pgplugins/imageplot2d.py
PgImagePlot2dCti._closeResources
def _closeResources(self): """ Disconnects signals. Is called by self.finalize when the cti is deleted. """ verCrossViewBox = self.pgImagePlot2d.verCrossPlotItem.getViewBox() verCrossViewBox.sigRangeChangedManually.disconnect(self.yAxisRangeCti.setAutoRangeOff) horCrossViewBox = self.pgImagePlot2d.horCrossPlotItem.getViewBox() horCrossViewBox.sigRangeChangedManually.disconnect(self.xAxisRangeCti.setAutoRangeOff) self.pgImagePlot2d.verCrossPlotItem.sigAxisReset.disconnect(self.setVerCrossPlotAutoRangeOn) self.pgImagePlot2d.horCrossPlotItem.sigAxisReset.disconnect(self.setHorCrossPlotAutoRangeOn) self.pgImagePlot2d.imagePlotItem.sigAxisReset.disconnect(self.setImagePlotAutoRangeOn)
python
def _closeResources(self): """ Disconnects signals. Is called by self.finalize when the cti is deleted. """ verCrossViewBox = self.pgImagePlot2d.verCrossPlotItem.getViewBox() verCrossViewBox.sigRangeChangedManually.disconnect(self.yAxisRangeCti.setAutoRangeOff) horCrossViewBox = self.pgImagePlot2d.horCrossPlotItem.getViewBox() horCrossViewBox.sigRangeChangedManually.disconnect(self.xAxisRangeCti.setAutoRangeOff) self.pgImagePlot2d.verCrossPlotItem.sigAxisReset.disconnect(self.setVerCrossPlotAutoRangeOn) self.pgImagePlot2d.horCrossPlotItem.sigAxisReset.disconnect(self.setHorCrossPlotAutoRangeOn) self.pgImagePlot2d.imagePlotItem.sigAxisReset.disconnect(self.setImagePlotAutoRangeOn)
Disconnects signals. Is called by self.finalize when the cti is deleted.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/imageplot2d.py#L214-L225
titusjan/argos
argos/inspector/pgplugins/imageplot2d.py
PgImagePlot2dCti.setImagePlotAutoRangeOn
def setImagePlotAutoRangeOn(self, axisNumber): """ Sets the image plot's auto-range on for the axis with number axisNumber. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes). """ setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.yAxisRangeCti, axisNumber)
python
def setImagePlotAutoRangeOn(self, axisNumber): """ Sets the image plot's auto-range on for the axis with number axisNumber. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes). """ setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.yAxisRangeCti, axisNumber)
Sets the image plot's auto-range on for the axis with number axisNumber. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes).
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/imageplot2d.py#L228-L233
titusjan/argos
argos/inspector/pgplugins/imageplot2d.py
PgImagePlot2dCti.setHorCrossPlotAutoRangeOn
def setHorCrossPlotAutoRangeOn(self, axisNumber): """ Sets the horizontal cross-hair plot's auto-range on for the axis with number axisNumber. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes). """ setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.horCrossPlotRangeCti, axisNumber)
python
def setHorCrossPlotAutoRangeOn(self, axisNumber): """ Sets the horizontal cross-hair plot's auto-range on for the axis with number axisNumber. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes). """ setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.horCrossPlotRangeCti, axisNumber)
Sets the horizontal cross-hair plot's auto-range on for the axis with number axisNumber. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes).
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/imageplot2d.py#L236-L241
titusjan/argos
argos/inspector/pgplugins/imageplot2d.py
PgImagePlot2dCti.setVerCrossPlotAutoRangeOn
def setVerCrossPlotAutoRangeOn(self, axisNumber): """ Sets the vertical cross-hair plot's auto-range on for the axis with number axisNumber. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes). """ setXYAxesAutoRangeOn(self, self.verCrossPlotRangeCti, self.yAxisRangeCti, axisNumber)
python
def setVerCrossPlotAutoRangeOn(self, axisNumber): """ Sets the vertical cross-hair plot's auto-range on for the axis with number axisNumber. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes). """ setXYAxesAutoRangeOn(self, self.verCrossPlotRangeCti, self.yAxisRangeCti, axisNumber)
Sets the vertical cross-hair plot's auto-range on for the axis with number axisNumber. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes).
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/imageplot2d.py#L244-L249
titusjan/argos
argos/inspector/pgplugins/imageplot2d.py
PgImagePlot2d._clearContents
def _clearContents(self): """ Clears the contents when no valid data is available """ logger.debug("Clearing inspector contents") self.titleLabel.setText('') # Don't clear the imagePlotItem, the imageItem is only added in the constructor. self.imageItem.clear() self.imagePlotItem.setLabel('left', '') self.imagePlotItem.setLabel('bottom', '') # Set the histogram range and levels to finite values to prevent futher errors if this # function was called after an exception in self.drawContents self.histLutItem.setHistogramRange(0, 100) self.histLutItem.setLevels(0, 100) self.crossPlotRow, self.crossPlotCol = None, None self.probeLabel.setText('') self.crossLineHorizontal.setVisible(False) self.crossLineVertical.setVisible(False) self.crossLineHorShadow.setVisible(False) self.crossLineVerShadow.setVisible(False) self.horCrossPlotItem.clear() self.verCrossPlotItem.clear()
python
def _clearContents(self): """ Clears the contents when no valid data is available """ logger.debug("Clearing inspector contents") self.titleLabel.setText('') # Don't clear the imagePlotItem, the imageItem is only added in the constructor. self.imageItem.clear() self.imagePlotItem.setLabel('left', '') self.imagePlotItem.setLabel('bottom', '') # Set the histogram range and levels to finite values to prevent futher errors if this # function was called after an exception in self.drawContents self.histLutItem.setHistogramRange(0, 100) self.histLutItem.setLevels(0, 100) self.crossPlotRow, self.crossPlotCol = None, None self.probeLabel.setText('') self.crossLineHorizontal.setVisible(False) self.crossLineVertical.setVisible(False) self.crossLineHorShadow.setVisible(False) self.crossLineVerShadow.setVisible(False) self.horCrossPlotItem.clear() self.verCrossPlotItem.clear()
Clears the contents when no valid data is available
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/imageplot2d.py#L368-L393
titusjan/argos
argos/inspector/pgplugins/imageplot2d.py
PgImagePlot2d._drawContents
def _drawContents(self, reason=None, initiator=None): """ Draws the plot contents from the sliced array of the collected repo tree item. The reason parameter is used to determine if the axes will be reset (the initiator parameter is ignored). See AbstractInspector.updateContents for their description. """ self.crossPlotRow = None # reset because the sliced array shape may change self.crossPlotCol = None # idem dito gridLayout = self.graphicsLayoutWidget.ci.layout # A QGraphicsGridLayout if self.config.horCrossPlotCti.configValue: gridLayout.setRowStretchFactor(ROW_HOR_LINE, 1) if not self.horPlotAdded: self.graphicsLayoutWidget.addItem(self.horCrossPlotItem, ROW_HOR_LINE, COL_HOR_LINE) self.horPlotAdded = True gridLayout.activate() else: gridLayout.setRowStretchFactor(ROW_HOR_LINE, 0) if self.horPlotAdded: self.graphicsLayoutWidget.removeItem(self.horCrossPlotItem) self.horPlotAdded = False gridLayout.activate() if self.config.verCrossPlotCti.configValue: gridLayout.setColumnStretchFactor(COL_VER_LINE, 1) if not self.verPlotAdded: self.graphicsLayoutWidget.addItem(self.verCrossPlotItem, ROW_VER_LINE, COL_VER_LINE) self.verPlotAdded = True gridLayout.activate() else: gridLayout.setColumnStretchFactor(COL_VER_LINE, 0) if self.verPlotAdded: self.graphicsLayoutWidget.removeItem(self.verCrossPlotItem) self.verPlotAdded = False gridLayout.activate() self.slicedArray = self.collector.getSlicedArray() if not self._hasValidData(): self._clearContents() raise InvalidDataError("No data available or it does not contain real numbers") # -- Valid plot data from here on -- # PyQtGraph doesn't handle masked array so we convert the masked values to Nans. Missing # data values are replaced by NaNs. The PyQtGraph image plot shows this as the color at the # lowest end of the color scale. Unfortunately we cannot choose a missing-value color, but # at least the Nans do not influence for the histogram and color range. # We don't update self.slicedArray here because the data probe should still be able to # print the actual value. imageArray = replaceMaskedValueWithFloat(self.slicedArray.data, self.slicedArray.mask, np.nan, copyOnReplace=True) # Replace infinite value with Nans because PyQtGraph fails on them. WNote that the CTIs of # the cross plots (e.g. horCrossPlotRangeCti) are still connected to self.slicedArray, so # if the cross section consists of only infs, they may not able to update the autorange. # A warning is issued in that case. # We don't update self.slicedArray here because the data probe should still be able to # print the actual value. imageArray = replaceMaskedValueWithFloat(imageArray, np.isinf(self.slicedArray.data), np.nan, copyOnReplace=True) # Reset the axes ranges (via the config) if (reason == UpdateReason.RTI_CHANGED or reason == UpdateReason.COLLECTOR_COMBO_BOX): self.config.xAxisRangeCti.autoRangeCti.data = True self.config.yAxisRangeCti.autoRangeCti.data = True self.config.histColorRangeCti.autoRangeCti.data = True self.config.histRangeCti.autoRangeCti.data = True self.config.horCrossPlotRangeCti.autoRangeCti.data = True self.config.verCrossPlotRangeCti.autoRangeCti.data = True # PyQtGraph uses the following dimension order: T, X, Y, Color. # We need to transpose the slicedArray ourselves because axes = {'x':1, 'y':0} # doesn't seem to do anything. imageArray = imageArray.transpose() self.imageItem.setImage(imageArray, autoLevels=False) self.horCrossPlotItem.invertX(self.config.xFlippedCti.configValue) self.verCrossPlotItem.invertY(self.config.yFlippedCti.configValue) self.probeLabel.setVisible(self.config.probeCti.configValue) self.titleLabel.setText(self.configValue('title').format(**self.collector.rtiInfo)) # Update the config tree from the (possibly) new state of the PgImagePlot2d inspector, # e.g. the axis range or color range may have changed while drawing. self.config.updateTarget()
python
def _drawContents(self, reason=None, initiator=None): """ Draws the plot contents from the sliced array of the collected repo tree item. The reason parameter is used to determine if the axes will be reset (the initiator parameter is ignored). See AbstractInspector.updateContents for their description. """ self.crossPlotRow = None # reset because the sliced array shape may change self.crossPlotCol = None # idem dito gridLayout = self.graphicsLayoutWidget.ci.layout # A QGraphicsGridLayout if self.config.horCrossPlotCti.configValue: gridLayout.setRowStretchFactor(ROW_HOR_LINE, 1) if not self.horPlotAdded: self.graphicsLayoutWidget.addItem(self.horCrossPlotItem, ROW_HOR_LINE, COL_HOR_LINE) self.horPlotAdded = True gridLayout.activate() else: gridLayout.setRowStretchFactor(ROW_HOR_LINE, 0) if self.horPlotAdded: self.graphicsLayoutWidget.removeItem(self.horCrossPlotItem) self.horPlotAdded = False gridLayout.activate() if self.config.verCrossPlotCti.configValue: gridLayout.setColumnStretchFactor(COL_VER_LINE, 1) if not self.verPlotAdded: self.graphicsLayoutWidget.addItem(self.verCrossPlotItem, ROW_VER_LINE, COL_VER_LINE) self.verPlotAdded = True gridLayout.activate() else: gridLayout.setColumnStretchFactor(COL_VER_LINE, 0) if self.verPlotAdded: self.graphicsLayoutWidget.removeItem(self.verCrossPlotItem) self.verPlotAdded = False gridLayout.activate() self.slicedArray = self.collector.getSlicedArray() if not self._hasValidData(): self._clearContents() raise InvalidDataError("No data available or it does not contain real numbers") # -- Valid plot data from here on -- # PyQtGraph doesn't handle masked array so we convert the masked values to Nans. Missing # data values are replaced by NaNs. The PyQtGraph image plot shows this as the color at the # lowest end of the color scale. Unfortunately we cannot choose a missing-value color, but # at least the Nans do not influence for the histogram and color range. # We don't update self.slicedArray here because the data probe should still be able to # print the actual value. imageArray = replaceMaskedValueWithFloat(self.slicedArray.data, self.slicedArray.mask, np.nan, copyOnReplace=True) # Replace infinite value with Nans because PyQtGraph fails on them. WNote that the CTIs of # the cross plots (e.g. horCrossPlotRangeCti) are still connected to self.slicedArray, so # if the cross section consists of only infs, they may not able to update the autorange. # A warning is issued in that case. # We don't update self.slicedArray here because the data probe should still be able to # print the actual value. imageArray = replaceMaskedValueWithFloat(imageArray, np.isinf(self.slicedArray.data), np.nan, copyOnReplace=True) # Reset the axes ranges (via the config) if (reason == UpdateReason.RTI_CHANGED or reason == UpdateReason.COLLECTOR_COMBO_BOX): self.config.xAxisRangeCti.autoRangeCti.data = True self.config.yAxisRangeCti.autoRangeCti.data = True self.config.histColorRangeCti.autoRangeCti.data = True self.config.histRangeCti.autoRangeCti.data = True self.config.horCrossPlotRangeCti.autoRangeCti.data = True self.config.verCrossPlotRangeCti.autoRangeCti.data = True # PyQtGraph uses the following dimension order: T, X, Y, Color. # We need to transpose the slicedArray ourselves because axes = {'x':1, 'y':0} # doesn't seem to do anything. imageArray = imageArray.transpose() self.imageItem.setImage(imageArray, autoLevels=False) self.horCrossPlotItem.invertX(self.config.xFlippedCti.configValue) self.verCrossPlotItem.invertY(self.config.yFlippedCti.configValue) self.probeLabel.setVisible(self.config.probeCti.configValue) self.titleLabel.setText(self.configValue('title').format(**self.collector.rtiInfo)) # Update the config tree from the (possibly) new state of the PgImagePlot2d inspector, # e.g. the axis range or color range may have changed while drawing. self.config.updateTarget()
Draws the plot contents from the sliced array of the collected repo tree item. The reason parameter is used to determine if the axes will be reset (the initiator parameter is ignored). See AbstractInspector.updateContents for their description.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/imageplot2d.py#L396-L484
titusjan/argos
argos/inspector/pgplugins/imageplot2d.py
PgImagePlot2d.mouseMoved
def mouseMoved(self, viewPos): """ Updates the probe text with the values under the cursor. Draws a vertical line and a symbol at the position of the probe. """ try: check_class(viewPos, QtCore.QPointF) show_data_point = False # shows the data point as a circle in the cross hair plots self.crossPlotRow, self.crossPlotCol = None, None self.probeLabel.setText("<span style='color: #808080'>no data at cursor</span>") self.crossLineHorizontal.setVisible(False) self.crossLineVertical.setVisible(False) self.crossLineHorShadow.setVisible(False) self.crossLineVerShadow.setVisible(False) self.horCrossPlotItem.clear() self.verCrossPlotItem.clear() if (self._hasValidData() and self.slicedArray is not None and self.viewBox.sceneBoundingRect().contains(viewPos)): # Calculate the row and column at the cursor. We use math.floor because the pixel # corners of the image lie at integer values (and not the centers of the pixels). scenePos = self.viewBox.mapSceneToView(viewPos) row, col = math.floor(scenePos.y()), math.floor(scenePos.x()) row, col = int(row), int(col) # Needed in Python 2 nRows, nCols = self.slicedArray.shape if (0 <= row < nRows) and (0 <= col < nCols): self.viewBox.setCursor(Qt.CrossCursor) self.crossPlotRow, self.crossPlotCol = row, col index = tuple([row, col]) valueStr = to_string(self.slicedArray[index], masked=self.slicedArray.maskAt(index), maskFormat='&lt;masked&gt;') txt = "pos = ({:d}, {:d}), value = {}".format(row, col, valueStr) self.probeLabel.setText(txt) # Show cross section at the cursor pos in the line plots if self.config.horCrossPlotCti.configValue: self.crossLineHorShadow.setVisible(True) self.crossLineHorizontal.setVisible(True) self.crossLineHorShadow.setPos(row) self.crossLineHorizontal.setPos(row) # Line plot of cross section row. # First determine which points are connected or separated by masks/nans. rowData = self.slicedArray.data[row, :] connected = np.isfinite(rowData) if is_an_array(self.slicedArray.mask): connected = np.logical_and(connected, ~self.slicedArray.mask[row, :]) else: connected = (np.zeros_like(rowData) if self.slicedArray.mask else connected) # Replace infinite value with nans because PyQtGraph can't handle them rowData = replaceMaskedValueWithFloat(rowData, np.isinf(rowData), np.nan, copyOnReplace=True) horPlotDataItem = self.config.crossPenCti.createPlotDataItem() horPlotDataItem.setData(rowData, connect=connected) self.horCrossPlotItem.addItem(horPlotDataItem) # Vertical line in hor-cross plot crossLineShadow90 = pg.InfiniteLine(angle=90, movable=False, pen=self.crossShadowPen) crossLineShadow90.setPos(col) self.horCrossPlotItem.addItem(crossLineShadow90, ignoreBounds=True) crossLine90 = pg.InfiniteLine(angle=90, movable=False, pen=self.crossPen) crossLine90.setPos(col) self.horCrossPlotItem.addItem(crossLine90, ignoreBounds=True) if show_data_point: crossPoint90 = pg.PlotDataItem(symbolPen=self.crossPen) crossPoint90.setSymbolBrush(QtGui.QBrush(self.config.crossPenCti.penColor)) crossPoint90.setSymbolSize(10) crossPoint90.setData((col,), (rowData[col],)) self.horCrossPlotItem.addItem(crossPoint90, ignoreBounds=True) self.config.horCrossPlotRangeCti.updateTarget() # update auto range del rowData # defensive programming if self.config.verCrossPlotCti.configValue: self.crossLineVerShadow.setVisible(True) self.crossLineVertical.setVisible(True) self.crossLineVerShadow.setPos(col) self.crossLineVertical.setPos(col) # Line plot of cross section row. # First determine which points are connected or separated by masks/nans. colData = self.slicedArray.data[:, col] connected = np.isfinite(colData) if is_an_array(self.slicedArray.mask): connected = np.logical_and(connected, ~self.slicedArray.mask[:, col]) else: connected = (np.zeros_like(colData) if self.slicedArray.mask else connected) # Replace infinite value with nans because PyQtGraph can't handle them colData = replaceMaskedValueWithFloat(colData, np.isinf(colData), np.nan, copyOnReplace=True) verPlotDataItem = self.config.crossPenCti.createPlotDataItem() verPlotDataItem.setData(colData, np.arange(nRows), connect=connected) self.verCrossPlotItem.addItem(verPlotDataItem) # Horizontal line in ver-cross plot crossLineShadow0 = pg.InfiniteLine(angle=0, movable=False, pen=self.crossShadowPen) crossLineShadow0.setPos(row) self.verCrossPlotItem.addItem(crossLineShadow0, ignoreBounds=True) crossLine0 = pg.InfiniteLine(angle=0, movable=False, pen=self.crossPen) crossLine0.setPos(row) self.verCrossPlotItem.addItem(crossLine0, ignoreBounds=True) if show_data_point: crossPoint0 = pg.PlotDataItem(symbolPen=self.crossPen) crossPoint0.setSymbolBrush(QtGui.QBrush(self.config.crossPenCti.penColor)) crossPoint0.setSymbolSize(10) crossPoint0.setData((colData[row],), (row,)) self.verCrossPlotItem.addItem(crossPoint0, ignoreBounds=True) self.config.verCrossPlotRangeCti.updateTarget() # update auto range del colData # defensive programming except Exception as ex: # In contrast to _drawContents, this function is a slot and thus must not throw # exceptions. The exception is logged. Perhaps we should clear the cross plots, but # this could, in turn, raise exceptions. if DEBUGGING: raise else: logger.exception(ex)
python
def mouseMoved(self, viewPos): """ Updates the probe text with the values under the cursor. Draws a vertical line and a symbol at the position of the probe. """ try: check_class(viewPos, QtCore.QPointF) show_data_point = False # shows the data point as a circle in the cross hair plots self.crossPlotRow, self.crossPlotCol = None, None self.probeLabel.setText("<span style='color: #808080'>no data at cursor</span>") self.crossLineHorizontal.setVisible(False) self.crossLineVertical.setVisible(False) self.crossLineHorShadow.setVisible(False) self.crossLineVerShadow.setVisible(False) self.horCrossPlotItem.clear() self.verCrossPlotItem.clear() if (self._hasValidData() and self.slicedArray is not None and self.viewBox.sceneBoundingRect().contains(viewPos)): # Calculate the row and column at the cursor. We use math.floor because the pixel # corners of the image lie at integer values (and not the centers of the pixels). scenePos = self.viewBox.mapSceneToView(viewPos) row, col = math.floor(scenePos.y()), math.floor(scenePos.x()) row, col = int(row), int(col) # Needed in Python 2 nRows, nCols = self.slicedArray.shape if (0 <= row < nRows) and (0 <= col < nCols): self.viewBox.setCursor(Qt.CrossCursor) self.crossPlotRow, self.crossPlotCol = row, col index = tuple([row, col]) valueStr = to_string(self.slicedArray[index], masked=self.slicedArray.maskAt(index), maskFormat='&lt;masked&gt;') txt = "pos = ({:d}, {:d}), value = {}".format(row, col, valueStr) self.probeLabel.setText(txt) # Show cross section at the cursor pos in the line plots if self.config.horCrossPlotCti.configValue: self.crossLineHorShadow.setVisible(True) self.crossLineHorizontal.setVisible(True) self.crossLineHorShadow.setPos(row) self.crossLineHorizontal.setPos(row) # Line plot of cross section row. # First determine which points are connected or separated by masks/nans. rowData = self.slicedArray.data[row, :] connected = np.isfinite(rowData) if is_an_array(self.slicedArray.mask): connected = np.logical_and(connected, ~self.slicedArray.mask[row, :]) else: connected = (np.zeros_like(rowData) if self.slicedArray.mask else connected) # Replace infinite value with nans because PyQtGraph can't handle them rowData = replaceMaskedValueWithFloat(rowData, np.isinf(rowData), np.nan, copyOnReplace=True) horPlotDataItem = self.config.crossPenCti.createPlotDataItem() horPlotDataItem.setData(rowData, connect=connected) self.horCrossPlotItem.addItem(horPlotDataItem) # Vertical line in hor-cross plot crossLineShadow90 = pg.InfiniteLine(angle=90, movable=False, pen=self.crossShadowPen) crossLineShadow90.setPos(col) self.horCrossPlotItem.addItem(crossLineShadow90, ignoreBounds=True) crossLine90 = pg.InfiniteLine(angle=90, movable=False, pen=self.crossPen) crossLine90.setPos(col) self.horCrossPlotItem.addItem(crossLine90, ignoreBounds=True) if show_data_point: crossPoint90 = pg.PlotDataItem(symbolPen=self.crossPen) crossPoint90.setSymbolBrush(QtGui.QBrush(self.config.crossPenCti.penColor)) crossPoint90.setSymbolSize(10) crossPoint90.setData((col,), (rowData[col],)) self.horCrossPlotItem.addItem(crossPoint90, ignoreBounds=True) self.config.horCrossPlotRangeCti.updateTarget() # update auto range del rowData # defensive programming if self.config.verCrossPlotCti.configValue: self.crossLineVerShadow.setVisible(True) self.crossLineVertical.setVisible(True) self.crossLineVerShadow.setPos(col) self.crossLineVertical.setPos(col) # Line plot of cross section row. # First determine which points are connected or separated by masks/nans. colData = self.slicedArray.data[:, col] connected = np.isfinite(colData) if is_an_array(self.slicedArray.mask): connected = np.logical_and(connected, ~self.slicedArray.mask[:, col]) else: connected = (np.zeros_like(colData) if self.slicedArray.mask else connected) # Replace infinite value with nans because PyQtGraph can't handle them colData = replaceMaskedValueWithFloat(colData, np.isinf(colData), np.nan, copyOnReplace=True) verPlotDataItem = self.config.crossPenCti.createPlotDataItem() verPlotDataItem.setData(colData, np.arange(nRows), connect=connected) self.verCrossPlotItem.addItem(verPlotDataItem) # Horizontal line in ver-cross plot crossLineShadow0 = pg.InfiniteLine(angle=0, movable=False, pen=self.crossShadowPen) crossLineShadow0.setPos(row) self.verCrossPlotItem.addItem(crossLineShadow0, ignoreBounds=True) crossLine0 = pg.InfiniteLine(angle=0, movable=False, pen=self.crossPen) crossLine0.setPos(row) self.verCrossPlotItem.addItem(crossLine0, ignoreBounds=True) if show_data_point: crossPoint0 = pg.PlotDataItem(symbolPen=self.crossPen) crossPoint0.setSymbolBrush(QtGui.QBrush(self.config.crossPenCti.penColor)) crossPoint0.setSymbolSize(10) crossPoint0.setData((colData[row],), (row,)) self.verCrossPlotItem.addItem(crossPoint0, ignoreBounds=True) self.config.verCrossPlotRangeCti.updateTarget() # update auto range del colData # defensive programming except Exception as ex: # In contrast to _drawContents, this function is a slot and thus must not throw # exceptions. The exception is logged. Perhaps we should clear the cross plots, but # this could, in turn, raise exceptions. if DEBUGGING: raise else: logger.exception(ex)
Updates the probe text with the values under the cursor. Draws a vertical line and a symbol at the position of the probe.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/imageplot2d.py#L488-L621
titusjan/argos
argos/repo/registry.py
RtiRegItem.getFileDialogFilter
def getFileDialogFilter(self): """ Returns a filters that can be used to construct file dialogs filters, for example: 'Text File (*.txt;*.text)' """ extStr = ';'.join(['*' + ext for ext in self.extensions]) return '{} ({})'.format(self.name, extStr)
python
def getFileDialogFilter(self): """ Returns a filters that can be used to construct file dialogs filters, for example: 'Text File (*.txt;*.text)' """ extStr = ';'.join(['*' + ext for ext in self.extensions]) return '{} ({})'.format(self.name, extStr)
Returns a filters that can be used to construct file dialogs filters, for example: 'Text File (*.txt;*.text)'
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/registry.py#L46-L51
titusjan/argos
argos/repo/registry.py
RtiRegItem.asDict
def asDict(self): """ Returns a dictionary for serialization. """ dct = super(RtiRegItem, self).asDict() dct['extensions'] = self.extensions return dct
python
def asDict(self): """ Returns a dictionary for serialization. """ dct = super(RtiRegItem, self).asDict() dct['extensions'] = self.extensions return dct
Returns a dictionary for serialization.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/registry.py#L54-L59
titusjan/argos
argos/repo/registry.py
RtiRegistry._registerExtension
def _registerExtension(self, extension, rtiRegItem): """ Links an file name extension to a repository tree item. """ check_is_a_string(extension) check_class(rtiRegItem, RtiRegItem) logger.debug(" Registering extension {!r} for {}".format(extension, rtiRegItem)) # TODO: type checking if extension in self._extensionMap: logger.info("Overriding extension {!r}: old={}, new={}" .format(extension, self._extensionMap[extension], rtiRegItem)) self._extensionMap[extension] = rtiRegItem
python
def _registerExtension(self, extension, rtiRegItem): """ Links an file name extension to a repository tree item. """ check_is_a_string(extension) check_class(rtiRegItem, RtiRegItem) logger.debug(" Registering extension {!r} for {}".format(extension, rtiRegItem)) # TODO: type checking if extension in self._extensionMap: logger.info("Overriding extension {!r}: old={}, new={}" .format(extension, self._extensionMap[extension], rtiRegItem)) self._extensionMap[extension] = rtiRegItem
Links an file name extension to a repository tree item.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/registry.py#L85-L97
titusjan/argos
argos/repo/registry.py
RtiRegistry.registerItem
def registerItem(self, regItem): """ Adds a ClassRegItem object to the registry. """ super(RtiRegistry, self).registerItem(regItem) for ext in regItem.extensions: self._registerExtension(ext, regItem)
python
def registerItem(self, regItem): """ Adds a ClassRegItem object to the registry. """ super(RtiRegistry, self).registerItem(regItem) for ext in regItem.extensions: self._registerExtension(ext, regItem)
Adds a ClassRegItem object to the registry.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/registry.py#L100-L106
titusjan/argos
argos/repo/registry.py
RtiRegistry.registerRti
def registerRti(self, fullName, fullClassName, extensions=None, pythonPath=''): """ Class that maintains the collection of registered inspector classes. Maintains a lit of file extensions that open the RTI by default. """ check_is_a_sequence(extensions) extensions = extensions if extensions is not None else [] extensions = [prepend_point_to_extension(ext) for ext in extensions] regRti = RtiRegItem(fullName, fullClassName, extensions, pythonPath=pythonPath) self.registerItem(regRti)
python
def registerRti(self, fullName, fullClassName, extensions=None, pythonPath=''): """ Class that maintains the collection of registered inspector classes. Maintains a lit of file extensions that open the RTI by default. """ check_is_a_sequence(extensions) extensions = extensions if extensions is not None else [] extensions = [prepend_point_to_extension(ext) for ext in extensions] regRti = RtiRegItem(fullName, fullClassName, extensions, pythonPath=pythonPath) self.registerItem(regRti)
Class that maintains the collection of registered inspector classes. Maintains a lit of file extensions that open the RTI by default.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/registry.py#L109-L118
titusjan/argos
argos/repo/registry.py
RtiRegistry.getFileDialogFilter
def getFileDialogFilter(self): """ Returns a filter that can be used in open file dialogs, for example: 'All files (*);;Txt (*.txt;*.text);;netCDF(*.nc;*.nc4)' """ filters = [] for regRti in self.items: filters.append(regRti.getFileDialogFilter()) return ';;'.join(filters)
python
def getFileDialogFilter(self): """ Returns a filter that can be used in open file dialogs, for example: 'All files (*);;Txt (*.txt;*.text);;netCDF(*.nc;*.nc4)' """ filters = [] for regRti in self.items: filters.append(regRti.getFileDialogFilter()) return ';;'.join(filters)
Returns a filter that can be used in open file dialogs, for example: 'All files (*);;Txt (*.txt;*.text);;netCDF(*.nc;*.nc4)'
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/registry.py#L129-L136
titusjan/argos
argos/repo/registry.py
RtiRegistry.getDefaultItems
def getDefaultItems(self): """ Returns a list with the default plugins in the repo tree item registry. """ return [ RtiRegItem('HDF-5 file', 'argos.repo.rtiplugins.hdf5.H5pyFileRti', extensions=['hdf5', 'h5', 'h5e', 'he5', 'nc']), # hdf extension is for HDF-4 RtiRegItem('MATLAB file', 'argos.repo.rtiplugins.scipyio.MatlabFileRti', extensions=['mat']), RtiRegItem('NetCDF file', 'argos.repo.rtiplugins.ncdf.NcdfFileRti', #extensions=['nc', 'nc3', 'nc4']), extensions=['nc', 'nc4']), #extensions=[]), RtiRegItem('NumPy binary file', 'argos.repo.rtiplugins.numpyio.NumpyBinaryFileRti', extensions=['npy']), RtiRegItem('NumPy compressed file', 'argos.repo.rtiplugins.numpyio.NumpyCompressedFileRti', extensions=['npz']), RtiRegItem('NumPy text file', 'argos.repo.rtiplugins.numpyio.NumpyTextFileRti', #extensions=['txt', 'text']), extensions=['dat']), RtiRegItem('IDL save file', 'argos.repo.rtiplugins.scipyio.IdlSaveFileRti', extensions=['sav']), RtiRegItem('Pandas CSV file', 'argos.repo.rtiplugins.pandasio.PandasCsvFileRti', extensions=['csv']), RtiRegItem('Pillow image', 'argos.repo.rtiplugins.pillowio.PillowFileRti', extensions=['bmp', 'eps', 'im', 'gif', 'jpg', 'jpeg', 'msp', 'pcx', 'png', 'ppm', 'spi', 'tif', 'tiff', 'xbm', 'xv']), RtiRegItem('Wav file', 'argos.repo.rtiplugins.scipyio.WavFileRti', extensions=['wav'])]
python
def getDefaultItems(self): """ Returns a list with the default plugins in the repo tree item registry. """ return [ RtiRegItem('HDF-5 file', 'argos.repo.rtiplugins.hdf5.H5pyFileRti', extensions=['hdf5', 'h5', 'h5e', 'he5', 'nc']), # hdf extension is for HDF-4 RtiRegItem('MATLAB file', 'argos.repo.rtiplugins.scipyio.MatlabFileRti', extensions=['mat']), RtiRegItem('NetCDF file', 'argos.repo.rtiplugins.ncdf.NcdfFileRti', #extensions=['nc', 'nc3', 'nc4']), extensions=['nc', 'nc4']), #extensions=[]), RtiRegItem('NumPy binary file', 'argos.repo.rtiplugins.numpyio.NumpyBinaryFileRti', extensions=['npy']), RtiRegItem('NumPy compressed file', 'argos.repo.rtiplugins.numpyio.NumpyCompressedFileRti', extensions=['npz']), RtiRegItem('NumPy text file', 'argos.repo.rtiplugins.numpyio.NumpyTextFileRti', #extensions=['txt', 'text']), extensions=['dat']), RtiRegItem('IDL save file', 'argos.repo.rtiplugins.scipyio.IdlSaveFileRti', extensions=['sav']), RtiRegItem('Pandas CSV file', 'argos.repo.rtiplugins.pandasio.PandasCsvFileRti', extensions=['csv']), RtiRegItem('Pillow image', 'argos.repo.rtiplugins.pillowio.PillowFileRti', extensions=['bmp', 'eps', 'im', 'gif', 'jpg', 'jpeg', 'msp', 'pcx', 'png', 'ppm', 'spi', 'tif', 'tiff', 'xbm', 'xv']), RtiRegItem('Wav file', 'argos.repo.rtiplugins.scipyio.WavFileRti', extensions=['wav'])]
Returns a list with the default plugins in the repo tree item registry.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/registry.py#L139-L185
titusjan/argos
argos/widgets/aboutdialog.py
AboutDialog._addModuleInfo
def _addModuleInfo(self, moduleInfo): """ Adds a line with module info to the editor :param moduleInfo: can either be a string or a module info class. In the first case, an object is instantiated as ImportedModuleInfo(moduleInfo). """ if is_a_string(moduleInfo): moduleInfo = mi.ImportedModuleInfo(moduleInfo) line = "{:15s}: {}".format(moduleInfo.name, moduleInfo.verboseVersion) self.editor.appendPlainText(line) QtWidgets.QApplication.instance().processEvents()
python
def _addModuleInfo(self, moduleInfo): """ Adds a line with module info to the editor :param moduleInfo: can either be a string or a module info class. In the first case, an object is instantiated as ImportedModuleInfo(moduleInfo). """ if is_a_string(moduleInfo): moduleInfo = mi.ImportedModuleInfo(moduleInfo) line = "{:15s}: {}".format(moduleInfo.name, moduleInfo.verboseVersion) self.editor.appendPlainText(line) QtWidgets.QApplication.instance().processEvents()
Adds a line with module info to the editor :param moduleInfo: can either be a string or a module info class. In the first case, an object is instantiated as ImportedModuleInfo(moduleInfo).
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/aboutdialog.py#L65-L75
titusjan/argos
argos/widgets/aboutdialog.py
AboutDialog.addDependencyInfo
def addDependencyInfo(self): """ Adds version info about the installed dependencies """ logger.debug("Adding dependency info to the AboutDialog") self.progressLabel.setText("Retrieving package info...") self.editor.clear() self._addModuleInfo(mi.PythonModuleInfo()) self._addModuleInfo(mi.QtModuleInfo()) modules = ['numpy', 'scipy', 'pandas', 'pyqtgraph'] for module in modules: self._addModuleInfo(module) self._addModuleInfo(mi.PillowInfo()) self._addModuleInfo(mi.H5pyModuleInfo()) self._addModuleInfo(mi.NetCDF4ModuleInfo()) self.progressLabel.setText("") logger.debug("Finished adding dependency info to the AboutDialog")
python
def addDependencyInfo(self): """ Adds version info about the installed dependencies """ logger.debug("Adding dependency info to the AboutDialog") self.progressLabel.setText("Retrieving package info...") self.editor.clear() self._addModuleInfo(mi.PythonModuleInfo()) self._addModuleInfo(mi.QtModuleInfo()) modules = ['numpy', 'scipy', 'pandas', 'pyqtgraph'] for module in modules: self._addModuleInfo(module) self._addModuleInfo(mi.PillowInfo()) self._addModuleInfo(mi.H5pyModuleInfo()) self._addModuleInfo(mi.NetCDF4ModuleInfo()) self.progressLabel.setText("") logger.debug("Finished adding dependency info to the AboutDialog")
Adds version info about the installed dependencies
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/aboutdialog.py#L78-L97
titusjan/argos
argos/config/floatcti.py
FloatCti._enforceDataType
def _enforceDataType(self, data): """ Converts to float so that this CTI always stores that type. Replaces infinite with the maximum respresentable float. Raises a ValueError if data is a NaN. """ value = float(data) if math.isnan(value): raise ValueError("FloatCti can't store NaNs") if math.isinf(value): if value > 0: logger.warn("Replacing inf by the largest representable float") value = sys.float_info.max else: logger.warn("Replacing -inf by the smallest representable float") value = -sys.float_info.max return value
python
def _enforceDataType(self, data): """ Converts to float so that this CTI always stores that type. Replaces infinite with the maximum respresentable float. Raises a ValueError if data is a NaN. """ value = float(data) if math.isnan(value): raise ValueError("FloatCti can't store NaNs") if math.isinf(value): if value > 0: logger.warn("Replacing inf by the largest representable float") value = sys.float_info.max else: logger.warn("Replacing -inf by the smallest representable float") value = -sys.float_info.max return value
Converts to float so that this CTI always stores that type. Replaces infinite with the maximum respresentable float. Raises a ValueError if data is a NaN.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/floatcti.py#L60-L78
titusjan/argos
argos/config/floatcti.py
FloatCti._dataToString
def _dataToString(self, data): """ Conversion function used to convert the (default)data to the display value. """ if self.specialValueText is not None and data == self.minValue: return self.specialValueText else: return "{}{:.{}f}{}".format(self.prefix, data, self.decimals, self.suffix)
python
def _dataToString(self, data): """ Conversion function used to convert the (default)data to the display value. """ if self.specialValueText is not None and data == self.minValue: return self.specialValueText else: return "{}{:.{}f}{}".format(self.prefix, data, self.decimals, self.suffix)
Conversion function used to convert the (default)data to the display value.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/floatcti.py#L81-L87
titusjan/argos
argos/config/floatcti.py
FloatCti.debugInfo
def debugInfo(self): """ Returns the string with debugging information """ return ("min = {}, max = {}, step = {}, decimals = {}, specVal = {}" .format(self.minValue, self.maxValue, self.stepSize, self.decimals, self.specialValueText))
python
def debugInfo(self): """ Returns the string with debugging information """ return ("min = {}, max = {}, step = {}, decimals = {}, specVal = {}" .format(self.minValue, self.maxValue, self.stepSize, self.decimals, self.specialValueText))
Returns the string with debugging information
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/floatcti.py#L91-L96
titusjan/argos
argos/config/floatcti.py
FloatCti.createEditor
def createEditor(self, delegate, parent, option): """ Creates a FloatCtiEditor. For the parameters see the AbstractCti constructor documentation. """ return FloatCtiEditor(self, delegate, parent=parent)
python
def createEditor(self, delegate, parent, option): """ Creates a FloatCtiEditor. For the parameters see the AbstractCti constructor documentation. """ return FloatCtiEditor(self, delegate, parent=parent)
Creates a FloatCtiEditor. For the parameters see the AbstractCti constructor documentation.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/floatcti.py#L99-L103
titusjan/argos
argos/config/floatcti.py
FloatCtiEditor.finalize
def finalize(self): """ Called at clean up. Is used to disconnect signals. """ self.spinBox.valueChanged.disconnect(self.commitChangedValue) super(FloatCtiEditor, self).finalize()
python
def finalize(self): """ Called at clean up. Is used to disconnect signals. """ self.spinBox.valueChanged.disconnect(self.commitChangedValue) super(FloatCtiEditor, self).finalize()
Called at clean up. Is used to disconnect signals.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/floatcti.py#L140-L144
titusjan/argos
argos/config/floatcti.py
SnFloatCti.debugInfo
def debugInfo(self): """ Returns the string with debugging information """ return ("enabled = {}, min = {}, max = {}, precision = {}, specVal = {}" .format(self.enabled, self.minValue, self.maxValue, self.precision, self.specialValueText))
python
def debugInfo(self): """ Returns the string with debugging information """ return ("enabled = {}, min = {}, max = {}, precision = {}, specVal = {}" .format(self.enabled, self.minValue, self.maxValue, self.precision, self.specialValueText))
Returns the string with debugging information
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/floatcti.py#L248-L253
titusjan/argos
argos/config/floatcti.py
SnFloatCti.createEditor
def createEditor(self, delegate, parent, option): """ Creates a FloatCtiEditor. For the parameters see the AbstractCti constructor documentation. """ return SnFloatCtiEditor(self, delegate, self.precision, parent=parent)
python
def createEditor(self, delegate, parent, option): """ Creates a FloatCtiEditor. For the parameters see the AbstractCti constructor documentation. """ return SnFloatCtiEditor(self, delegate, self.precision, parent=parent)
Creates a FloatCtiEditor. For the parameters see the AbstractCti constructor documentation.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/floatcti.py#L256-L260
titusjan/argos
argos/config/floatcti.py
SnFloatCtiEditor.finalize
def finalize(self): """ Called at clean up. Is used to disconnect signals. """ self.spinBox.valueChanged.disconnect(self.commitChangedValue) super(SnFloatCtiEditor, self).finalize()
python
def finalize(self): """ Called at clean up. Is used to disconnect signals. """ self.spinBox.valueChanged.disconnect(self.commitChangedValue) super(SnFloatCtiEditor, self).finalize()
Called at clean up. Is used to disconnect signals.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/floatcti.py#L295-L299
titusjan/argos
argos/repo/filesytemrtis.py
detectRtiFromFileName
def detectRtiFromFileName(fileName): """ Determines the type of RepoTreeItem to use given a file name. Uses a DirectoryRti for directories and an UnknownFileRti if the file extension doesn't match one of the registered RTI extensions. Returns (cls, regItem) tuple. Both the cls ond the regItem can be None. If the file is a directory, (DirectoryRti, None) is returned. If the file extension is not in the registry, (UnknownFileRti, None) is returned. If the cls cannot be imported (None, regItem) returned. regItem.exception will be set. Otherwise (cls, regItem) will be returned. """ _, extension = os.path.splitext(fileName) if os.path.isdir(fileName): rtiRegItem = None cls = DirectoryRti else: try: rtiRegItem = globalRtiRegistry().getRtiRegItemByExtension(extension) except (KeyError): logger.debug("No file RTI registered for extension: {}".format(extension)) rtiRegItem = None cls = UnknownFileRti else: cls = rtiRegItem.getClass(tryImport=True) # cls can be None return cls, rtiRegItem
python
def detectRtiFromFileName(fileName): """ Determines the type of RepoTreeItem to use given a file name. Uses a DirectoryRti for directories and an UnknownFileRti if the file extension doesn't match one of the registered RTI extensions. Returns (cls, regItem) tuple. Both the cls ond the regItem can be None. If the file is a directory, (DirectoryRti, None) is returned. If the file extension is not in the registry, (UnknownFileRti, None) is returned. If the cls cannot be imported (None, regItem) returned. regItem.exception will be set. Otherwise (cls, regItem) will be returned. """ _, extension = os.path.splitext(fileName) if os.path.isdir(fileName): rtiRegItem = None cls = DirectoryRti else: try: rtiRegItem = globalRtiRegistry().getRtiRegItemByExtension(extension) except (KeyError): logger.debug("No file RTI registered for extension: {}".format(extension)) rtiRegItem = None cls = UnknownFileRti else: cls = rtiRegItem.getClass(tryImport=True) # cls can be None return cls, rtiRegItem
Determines the type of RepoTreeItem to use given a file name. Uses a DirectoryRti for directories and an UnknownFileRti if the file extension doesn't match one of the registered RTI extensions. Returns (cls, regItem) tuple. Both the cls ond the regItem can be None. If the file is a directory, (DirectoryRti, None) is returned. If the file extension is not in the registry, (UnknownFileRti, None) is returned. If the cls cannot be imported (None, regItem) returned. regItem.exception will be set. Otherwise (cls, regItem) will be returned.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/filesytemrtis.py#L85-L110
titusjan/argos
argos/repo/filesytemrtis.py
createRtiFromFileName
def createRtiFromFileName(fileName): """ Determines the type of RepoTreeItem to use given a file name and creates it. Uses a DirectoryRti for directories and an UnknownFileRti if the file extension doesn't match one of the registered RTI extensions. """ cls, rtiRegItem = detectRtiFromFileName(fileName) if cls is None: logger.warn("Unable to import plugin {}: {}" .format(rtiRegItem.fullName, rtiRegItem.exception)) rti = UnknownFileRti.createFromFileName(fileName) rti.setException(rtiRegItem.exception) else: rti = cls.createFromFileName(fileName) assert rti, "Sanity check failed (createRtiFromFileName). Please report this bug." return rti
python
def createRtiFromFileName(fileName): """ Determines the type of RepoTreeItem to use given a file name and creates it. Uses a DirectoryRti for directories and an UnknownFileRti if the file extension doesn't match one of the registered RTI extensions. """ cls, rtiRegItem = detectRtiFromFileName(fileName) if cls is None: logger.warn("Unable to import plugin {}: {}" .format(rtiRegItem.fullName, rtiRegItem.exception)) rti = UnknownFileRti.createFromFileName(fileName) rti.setException(rtiRegItem.exception) else: rti = cls.createFromFileName(fileName) assert rti, "Sanity check failed (createRtiFromFileName). Please report this bug." return rti
Determines the type of RepoTreeItem to use given a file name and creates it. Uses a DirectoryRti for directories and an UnknownFileRti if the file extension doesn't match one of the registered RTI extensions.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/filesytemrtis.py#L113-L128
titusjan/argos
argos/repo/filesytemrtis.py
DirectoryRti._fetchAllChildren
def _fetchAllChildren(self): """ Gets all sub directories and files within the current directory. Does not fetch hidden files. """ childItems = [] fileNames = os.listdir(self._fileName) absFileNames = [os.path.join(self._fileName, fn) for fn in fileNames] # Add subdirectories for fileName, absFileName in zip(fileNames, absFileNames): if os.path.isdir(absFileName) and not fileName.startswith('.'): childItems.append(DirectoryRti(fileName=absFileName, nodeName=fileName)) # Add regular files for fileName, absFileName in zip(fileNames, absFileNames): if os.path.isfile(absFileName) and not fileName.startswith('.'): childItem = createRtiFromFileName(absFileName) childItems.append(childItem) return childItems
python
def _fetchAllChildren(self): """ Gets all sub directories and files within the current directory. Does not fetch hidden files. """ childItems = [] fileNames = os.listdir(self._fileName) absFileNames = [os.path.join(self._fileName, fn) for fn in fileNames] # Add subdirectories for fileName, absFileName in zip(fileNames, absFileNames): if os.path.isdir(absFileName) and not fileName.startswith('.'): childItems.append(DirectoryRti(fileName=absFileName, nodeName=fileName)) # Add regular files for fileName, absFileName in zip(fileNames, absFileNames): if os.path.isfile(absFileName) and not fileName.startswith('.'): childItem = createRtiFromFileName(absFileName) childItems.append(childItem) return childItems
Gets all sub directories and files within the current directory. Does not fetch hidden files.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/filesytemrtis.py#L63-L82
titusjan/argos
argos/collect/collectortree.py
CollectorTree.resizeColumnsToContents
def resizeColumnsToContents(self, startCol=None, stopCol=None): """ Resizes all columns to the contents """ numCols = self.model().columnCount() startCol = 0 if startCol is None else max(startCol, 0) stopCol = numCols if stopCol is None else min(stopCol, numCols) row = 0 for col in range(startCol, stopCol): indexWidget = self.indexWidget(self.model().index(row, col)) if indexWidget: contentsWidth = indexWidget.sizeHint().width() else: contentsWidth = self.header().sectionSizeHint(col) self.header().resizeSection(col, contentsWidth)
python
def resizeColumnsToContents(self, startCol=None, stopCol=None): """ Resizes all columns to the contents """ numCols = self.model().columnCount() startCol = 0 if startCol is None else max(startCol, 0) stopCol = numCols if stopCol is None else min(stopCol, numCols) row = 0 for col in range(startCol, stopCol): indexWidget = self.indexWidget(self.model().index(row, col)) if indexWidget: contentsWidth = indexWidget.sizeHint().width() else: contentsWidth = self.header().sectionSizeHint(col) self.header().resizeSection(col, contentsWidth)
Resizes all columns to the contents
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collectortree.py#L83-L99
titusjan/argos
argos/collect/collectortree.py
CollectorSpinBox.sizeHint
def sizeHint(self): """ Reimplemented from the C++ Qt source of QAbstractSpinBox.sizeHint, but without truncating to a maximum of 18 characters. """ # The cache is invalid after the prefix, postfix and other properties # have been set. I disabled it because sizeHint isn't called that often. #if self._cachedSizeHint is not None: # return self._cachedSizeHint orgSizeHint = super(CollectorSpinBox, self).sizeHint() self.ensurePolished() d = self fm = QtGui.QFontMetrics(self.fontMetrics()) # This was h = d.edit.sizeHint().height(), but that didn't work. In the end we set the # height to the height calculated from the parent. h = orgSizeHint.height() w = 0 # QLatin1Char seems not to be implemented. # Using regular string literals and hope for the best s = d.prefix() + d.textFromValue(d.minimum()) + d.suffix() + ' ' # We disabled truncating the string here!! #s = s[:18] w = max(w, fm.width(s)) s = d.prefix() + d.textFromValue(d.maximum()) + d.suffix() + ' ' # We disabled truncating the string here!! #s = s[:18] w = max(w, fm.width(s)) if len(d.specialValueText()): s = d.specialValueText() w = max(w, fm.width(s)) w += 2 # cursor blinking space opt = QtWidgets.QStyleOptionSpinBox() self.initStyleOption(opt) hint = QtCore.QSize(w, h) extra = QtCore.QSize(35, 6) opt.rect.setSize(hint + extra) extra += hint - self.style().subControlRect(QtWidgets.QStyle.CC_SpinBox, opt, QtWidgets.QStyle.SC_SpinBoxEditField, self).size() # get closer to final result by repeating the calculation opt.rect.setSize(hint + extra) extra += hint - self.style().subControlRect(QtWidgets.QStyle.CC_SpinBox, opt, QtWidgets.QStyle.SC_SpinBoxEditField, self).size() hint += extra opt.rect = self.rect() result = (self.style().sizeFromContents(QtWidgets.QStyle.CT_SpinBox, opt, hint, self) .expandedTo(QtWidgets.QApplication.globalStrut())) self._cachedSizeHint = result # Use the height ancestor's sizeHint result.setHeight(orgSizeHint.height()) return result
python
def sizeHint(self): """ Reimplemented from the C++ Qt source of QAbstractSpinBox.sizeHint, but without truncating to a maximum of 18 characters. """ # The cache is invalid after the prefix, postfix and other properties # have been set. I disabled it because sizeHint isn't called that often. #if self._cachedSizeHint is not None: # return self._cachedSizeHint orgSizeHint = super(CollectorSpinBox, self).sizeHint() self.ensurePolished() d = self fm = QtGui.QFontMetrics(self.fontMetrics()) # This was h = d.edit.sizeHint().height(), but that didn't work. In the end we set the # height to the height calculated from the parent. h = orgSizeHint.height() w = 0 # QLatin1Char seems not to be implemented. # Using regular string literals and hope for the best s = d.prefix() + d.textFromValue(d.minimum()) + d.suffix() + ' ' # We disabled truncating the string here!! #s = s[:18] w = max(w, fm.width(s)) s = d.prefix() + d.textFromValue(d.maximum()) + d.suffix() + ' ' # We disabled truncating the string here!! #s = s[:18] w = max(w, fm.width(s)) if len(d.specialValueText()): s = d.specialValueText() w = max(w, fm.width(s)) w += 2 # cursor blinking space opt = QtWidgets.QStyleOptionSpinBox() self.initStyleOption(opt) hint = QtCore.QSize(w, h) extra = QtCore.QSize(35, 6) opt.rect.setSize(hint + extra) extra += hint - self.style().subControlRect(QtWidgets.QStyle.CC_SpinBox, opt, QtWidgets.QStyle.SC_SpinBoxEditField, self).size() # get closer to final result by repeating the calculation opt.rect.setSize(hint + extra) extra += hint - self.style().subControlRect(QtWidgets.QStyle.CC_SpinBox, opt, QtWidgets.QStyle.SC_SpinBoxEditField, self).size() hint += extra opt.rect = self.rect() result = (self.style().sizeFromContents(QtWidgets.QStyle.CT_SpinBox, opt, hint, self) .expandedTo(QtWidgets.QApplication.globalStrut())) self._cachedSizeHint = result # Use the height ancestor's sizeHint result.setHeight(orgSizeHint.height()) return result
Reimplemented from the C++ Qt source of QAbstractSpinBox.sizeHint, but without truncating to a maximum of 18 characters.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collectortree.py#L114-L176
titusjan/argos
argos/config/configitemdelegate.py
ConfigItemDelegate.createEditor
def createEditor(self, parent, option, index): """ Returns the widget used to change data from the model and can be reimplemented to customize editing behavior. Reimplemented from QStyledItemDelegate. """ logger.debug("ConfigItemDelegate.createEditor, parent: {!r}".format(parent.objectName())) assert index.isValid(), "sanity check failed: invalid index" cti = index.model().getItem(index) editor = cti.createEditor(self, parent, option) return editor
python
def createEditor(self, parent, option, index): """ Returns the widget used to change data from the model and can be reimplemented to customize editing behavior. Reimplemented from QStyledItemDelegate. """ logger.debug("ConfigItemDelegate.createEditor, parent: {!r}".format(parent.objectName())) assert index.isValid(), "sanity check failed: invalid index" cti = index.model().getItem(index) editor = cti.createEditor(self, parent, option) return editor
Returns the widget used to change data from the model and can be reimplemented to customize editing behavior. Reimplemented from QStyledItemDelegate.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/configitemdelegate.py#L46-L57
titusjan/argos
argos/config/configitemdelegate.py
ConfigItemDelegate.setEditorData
def setEditorData(self, editor, index): """ Provides the widget with data to manipulate. Calls the setEditorValue of the config tree item at the index. :type editor: QWidget :type index: QModelIndex Reimplemented from QStyledItemDelegate. """ # We take the config value via the model to be consistent with setModelData data = index.model().data(index, Qt.EditRole) editor.setData(data)
python
def setEditorData(self, editor, index): """ Provides the widget with data to manipulate. Calls the setEditorValue of the config tree item at the index. :type editor: QWidget :type index: QModelIndex Reimplemented from QStyledItemDelegate. """ # We take the config value via the model to be consistent with setModelData data = index.model().data(index, Qt.EditRole) editor.setData(data)
Provides the widget with data to manipulate. Calls the setEditorValue of the config tree item at the index. :type editor: QWidget :type index: QModelIndex Reimplemented from QStyledItemDelegate.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/configitemdelegate.py#L78-L89
titusjan/argos
argos/config/configitemdelegate.py
ConfigItemDelegate.setModelData
def setModelData(self, editor, model, index): """ Gets data from the editor widget and stores it in the specified model at the item index. Does this by calling getEditorValue of the config tree item at the index. :type editor: QWidget :type model: ConfigTreeModel :type index: QModelIndex Reimplemented from QStyledItemDelegate. """ try: data = editor.getData() except InvalidInputError as ex: logger.warn(ex) else: # The value is set via the model so that signals are emitted logger.debug("ConfigItemDelegate.setModelData: {}".format(data)) model.setData(index, data, Qt.EditRole)
python
def setModelData(self, editor, model, index): """ Gets data from the editor widget and stores it in the specified model at the item index. Does this by calling getEditorValue of the config tree item at the index. :type editor: QWidget :type model: ConfigTreeModel :type index: QModelIndex Reimplemented from QStyledItemDelegate. """ try: data = editor.getData() except InvalidInputError as ex: logger.warn(ex) else: # The value is set via the model so that signals are emitted logger.debug("ConfigItemDelegate.setModelData: {}".format(data)) model.setData(index, data, Qt.EditRole)
Gets data from the editor widget and stores it in the specified model at the item index. Does this by calling getEditorValue of the config tree item at the index. :type editor: QWidget :type model: ConfigTreeModel :type index: QModelIndex Reimplemented from QStyledItemDelegate.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/configitemdelegate.py#L92-L109
titusjan/argos
argos/config/configitemdelegate.py
ConfigItemDelegate.updateEditorGeometry
def updateEditorGeometry(self, editor, option, index): """ Ensures that the editor is displayed correctly with respect to the item view. """ cti = index.model().getItem(index) if cti.checkState is None: displayRect = option.rect else: checkBoxRect = widgetSubCheckBoxRect(editor, option) offset = checkBoxRect.x() + checkBoxRect.width() displayRect = option.rect displayRect.adjust(offset, 0, 0, 0) editor.setGeometry(displayRect)
python
def updateEditorGeometry(self, editor, option, index): """ Ensures that the editor is displayed correctly with respect to the item view. """ cti = index.model().getItem(index) if cti.checkState is None: displayRect = option.rect else: checkBoxRect = widgetSubCheckBoxRect(editor, option) offset = checkBoxRect.x() + checkBoxRect.width() displayRect = option.rect displayRect.adjust(offset, 0, 0, 0) editor.setGeometry(displayRect)
Ensures that the editor is displayed correctly with respect to the item view.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/configitemdelegate.py#L112-L124
titusjan/argos
argos/config/configtreeview.py
ConfigTreeView.closeEditor
def closeEditor(self, editor, hint): """ Finalizes, closes and releases the given editor. """ # It would be nicer if this method was part of ConfigItemDelegate since createEditor also # lives there. However, QAbstractItemView.closeEditor is sometimes called directly, # without the QAbstractItemDelegate.closeEditor signal begin emitted, e.g when the # currentItem changes. Therefore we cannot connect the QAbstractItemDelegate.closeEditor # signal to a slot in the ConfigItemDelegate. configItemDelegate = self.itemDelegate() configItemDelegate.finalizeEditor(editor) super(ConfigTreeView, self).closeEditor(editor, hint)
python
def closeEditor(self, editor, hint): """ Finalizes, closes and releases the given editor. """ # It would be nicer if this method was part of ConfigItemDelegate since createEditor also # lives there. However, QAbstractItemView.closeEditor is sometimes called directly, # without the QAbstractItemDelegate.closeEditor signal begin emitted, e.g when the # currentItem changes. Therefore we cannot connect the QAbstractItemDelegate.closeEditor # signal to a slot in the ConfigItemDelegate. configItemDelegate = self.itemDelegate() configItemDelegate.finalizeEditor(editor) super(ConfigTreeView, self).closeEditor(editor, hint)
Finalizes, closes and releases the given editor.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/configtreeview.py#L93-L104
titusjan/argos
argos/config/configtreeview.py
ConfigTreeView.expandBranch
def expandBranch(self, index=None, expanded=None): """ Expands or collapses the node at the index and all it's descendants. If expanded is True the nodes will be expanded, if False they will be collapsed, and if expanded is None the expanded attribute of each item is used. If parentIndex is None, the invisible root will be used (i.e. the complete forest will be expanded). """ configModel = self.model() if index is None: #index = configTreeModel.createIndex() index = QtCore.QModelIndex() if index.isValid(): if expanded is None: item = configModel.getItem(index) self.setExpanded(index, item.expanded) else: self.setExpanded(index, expanded) for rowNr in range(configModel.rowCount(index)): childIndex = configModel.index(rowNr, configModel.COL_NODE_NAME, parentIndex=index) self.expandBranch(index=childIndex, expanded=expanded)
python
def expandBranch(self, index=None, expanded=None): """ Expands or collapses the node at the index and all it's descendants. If expanded is True the nodes will be expanded, if False they will be collapsed, and if expanded is None the expanded attribute of each item is used. If parentIndex is None, the invisible root will be used (i.e. the complete forest will be expanded). """ configModel = self.model() if index is None: #index = configTreeModel.createIndex() index = QtCore.QModelIndex() if index.isValid(): if expanded is None: item = configModel.getItem(index) self.setExpanded(index, item.expanded) else: self.setExpanded(index, expanded) for rowNr in range(configModel.rowCount(index)): childIndex = configModel.index(rowNr, configModel.COL_NODE_NAME, parentIndex=index) self.expandBranch(index=childIndex, expanded=expanded)
Expands or collapses the node at the index and all it's descendants. If expanded is True the nodes will be expanded, if False they will be collapsed, and if expanded is None the expanded attribute of each item is used. If parentIndex is None, the invisible root will be used (i.e. the complete forest will be expanded).
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/configtreeview.py#L107-L128
titusjan/argos
argos/repo/rtiplugins/ncdf.py
ncVarAttributes
def ncVarAttributes(ncVar): """ Returns the attributes of ncdf variable """ try: return ncVar.__dict__ except Exception as ex: # Due to some internal error netCDF4 may raise an AttributeError or KeyError, # depending on its version. logger.warn("Unable to read the attributes from {}. Reason: {}" .format(ncVar.name, ex)) return {}
python
def ncVarAttributes(ncVar): """ Returns the attributes of ncdf variable """ try: return ncVar.__dict__ except Exception as ex: # Due to some internal error netCDF4 may raise an AttributeError or KeyError, # depending on its version. logger.warn("Unable to read the attributes from {}. Reason: {}" .format(ncVar.name, ex)) return {}
Returns the attributes of ncdf variable
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/ncdf.py#L36-L46
titusjan/argos
argos/repo/rtiplugins/ncdf.py
ncVarUnit
def ncVarUnit(ncVar): """ Returns the unit of the ncVar by looking in the attributes. It searches in the attributes for one of the following keys: 'unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'. If these are not found, the empty string is returned. """ attributes = ncVarAttributes(ncVar) if not attributes: return '' # a premature optimization :-) for key in ('unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'): if key in attributes: # In Python3 the attribures are byte strings so we must decode them # This a bug in h5py, see https://github.com/h5py/h5py/issues/379 return attributes[key] else: return ''
python
def ncVarUnit(ncVar): """ Returns the unit of the ncVar by looking in the attributes. It searches in the attributes for one of the following keys: 'unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'. If these are not found, the empty string is returned. """ attributes = ncVarAttributes(ncVar) if not attributes: return '' # a premature optimization :-) for key in ('unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'): if key in attributes: # In Python3 the attribures are byte strings so we must decode them # This a bug in h5py, see https://github.com/h5py/h5py/issues/379 return attributes[key] else: return ''
Returns the unit of the ncVar by looking in the attributes. It searches in the attributes for one of the following keys: 'unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'. If these are not found, the empty string is returned.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/ncdf.py#L49-L66
titusjan/argos
argos/repo/rtiplugins/ncdf.py
variableMissingValue
def variableMissingValue(ncVar): """ Returns the missingData given a NetCDF variable Looks for one of the following attributes: _FillValue, missing_value, MissingValue, missingValue. Returns None if these attributes are not found. """ attributes = ncVarAttributes(ncVar) if not attributes: return None # a premature optimization :-) for key in ('missing_value', 'MissingValue', 'missingValue', 'FillValue', '_FillValue'): if key in attributes: missingDataValue = attributes[key] return missingDataValue return None
python
def variableMissingValue(ncVar): """ Returns the missingData given a NetCDF variable Looks for one of the following attributes: _FillValue, missing_value, MissingValue, missingValue. Returns None if these attributes are not found. """ attributes = ncVarAttributes(ncVar) if not attributes: return None # a premature optimization :-) for key in ('missing_value', 'MissingValue', 'missingValue', 'FillValue', '_FillValue'): if key in attributes: missingDataValue = attributes[key] return missingDataValue return None
Returns the missingData given a NetCDF variable Looks for one of the following attributes: _FillValue, missing_value, MissingValue, missingValue. Returns None if these attributes are not found.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/ncdf.py#L70-L84
titusjan/argos
argos/repo/rtiplugins/ncdf.py
NcdfFieldRti.elementTypeName
def elementTypeName(self): """ String representation of the element type. """ fieldName = self.nodeName return str(self._ncVar.dtype.fields[fieldName][0])
python
def elementTypeName(self): """ String representation of the element type. """ fieldName = self.nodeName return str(self._ncVar.dtype.fields[fieldName][0])
String representation of the element type.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/ncdf.py#L191-L195
titusjan/argos
argos/repo/rtiplugins/ncdf.py
NcdfFieldRti.unit
def unit(self): """ Returns the unit attribute of the underlying ncdf variable. If the units has a length (e.g is a list) and has precisely one element per field, the unit for this field is returned. """ unit = ncVarUnit(self._ncVar) fieldNames = self._ncVar.dtype.names # If the missing value attribute is a list with the same length as the number of fields, # return the missing value for field that equals the self.nodeName. if hasattr(unit, '__len__') and len(unit) == len(fieldNames): idx = fieldNames.index(self.nodeName) return unit[idx] else: return unit
python
def unit(self): """ Returns the unit attribute of the underlying ncdf variable. If the units has a length (e.g is a list) and has precisely one element per field, the unit for this field is returned. """ unit = ncVarUnit(self._ncVar) fieldNames = self._ncVar.dtype.names # If the missing value attribute is a list with the same length as the number of fields, # return the missing value for field that equals the self.nodeName. if hasattr(unit, '__len__') and len(unit) == len(fieldNames): idx = fieldNames.index(self.nodeName) return unit[idx] else: return unit
Returns the unit attribute of the underlying ncdf variable. If the units has a length (e.g is a list) and has precisely one element per field, the unit for this field is returned.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/ncdf.py#L207-L222
titusjan/argos
argos/repo/rtiplugins/ncdf.py
NcdfFieldRti.dimensionNames
def dimensionNames(self): """ Returns a list with the dimension names of the underlying NCDF variable """ nSubDims = len(self._subArrayShape) subArrayDims = ['SubDim{}'.format(dimNr) for dimNr in range(nSubDims)] return list(self._ncVar.dimensions + tuple(subArrayDims))
python
def dimensionNames(self): """ Returns a list with the dimension names of the underlying NCDF variable """ nSubDims = len(self._subArrayShape) subArrayDims = ['SubDim{}'.format(dimNr) for dimNr in range(nSubDims)] return list(self._ncVar.dimensions + tuple(subArrayDims))
Returns a list with the dimension names of the underlying NCDF variable
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/ncdf.py#L227-L232
titusjan/argos
argos/repo/rtiplugins/ncdf.py
NcdfFieldRti.missingDataValue
def missingDataValue(self): """ Returns the value to indicate missing data. None if no missing-data value is specified. """ value = variableMissingValue(self._ncVar) fieldNames = self._ncVar.dtype.names # If the missing value attibute is a list with the same length as the number of fields, # return the missing value for field that equals the self.nodeName. if hasattr(value, '__len__') and len(value) == len(fieldNames): idx = fieldNames.index(self.nodeName) return value[idx] else: return value
python
def missingDataValue(self): """ Returns the value to indicate missing data. None if no missing-data value is specified. """ value = variableMissingValue(self._ncVar) fieldNames = self._ncVar.dtype.names # If the missing value attibute is a list with the same length as the number of fields, # return the missing value for field that equals the self.nodeName. if hasattr(value, '__len__') and len(value) == len(fieldNames): idx = fieldNames.index(self.nodeName) return value[idx] else: return value
Returns the value to indicate missing data. None if no missing-data value is specified.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/ncdf.py#L236-L248
titusjan/argos
argos/repo/rtiplugins/ncdf.py
NcdfVariableRti.elementTypeName
def elementTypeName(self): """ String representation of the element type. """ dtype = self._ncVar.dtype if type(dtype) == type: # Handle the unexpected case that dtype is a regular Python type # (happens e.g. in the /PROCESSOR/processing_configuration of the Trop LX files) return dtype.__name__ return '<structured>' if dtype.names else str(dtype)
python
def elementTypeName(self): """ String representation of the element type. """ dtype = self._ncVar.dtype if type(dtype) == type: # Handle the unexpected case that dtype is a regular Python type # (happens e.g. in the /PROCESSOR/processing_configuration of the Trop LX files) return dtype.__name__ return '<structured>' if dtype.names else str(dtype)
String representation of the element type.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/ncdf.py#L321-L330
titusjan/argos
argos/repo/rtiplugins/ncdf.py
NcdfVariableRti._fetchAllChildren
def _fetchAllChildren(self): """ Fetches all fields that this variable contains. Only variables with a structured data type can have fields. """ assert self.canFetchChildren(), "canFetchChildren must be True" childItems = [] # Add fields if self._isStructured: for fieldName in self._ncVar.dtype.names: childItems.append(NcdfFieldRti(self._ncVar, nodeName=fieldName, fileName=self.fileName)) return childItems
python
def _fetchAllChildren(self): """ Fetches all fields that this variable contains. Only variables with a structured data type can have fields. """ assert self.canFetchChildren(), "canFetchChildren must be True" childItems = [] # Add fields if self._isStructured: for fieldName in self._ncVar.dtype.names: childItems.append(NcdfFieldRti(self._ncVar, nodeName=fieldName, fileName=self.fileName)) return childItems
Fetches all fields that this variable contains. Only variables with a structured data type can have fields.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/ncdf.py#L354-L367