code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if role == Qt.DecorationRole: if column == self.COL_DECORATION: return item.decoration elif role == Qt.FontRole: return item.font elif role == Qt.ForegroundRole: return item.foregroundBrush elif role == Qt.BackgroundRole: return item.backgroundBrush elif role == Qt.SizeHintRole: return self.cellSizeHint if item.sizeHint is None else item.sizeHint return None
def itemData(self, item, column, role=Qt.DisplayRole)
Returns the data stored under the given role for the item. O The column parameter may be used to differentiate behavior per column. The default implementation does nothing. Descendants should typically override this function instead of data() Note: If you do not have a value to return, return an invalid QVariant instead of returning 0. (This means returning None in Python)
2.511098
2.720106
0.923162
# logger.debug(" called index({}, {}, {}) {}" # .format(parentIndex.row(), parentIndex.column(), parentIndex.isValid(), # parentIndex.isValid() and parentIndex.column() != 0)) parentItem = self.getItem(parentIndex, altItem=self.invisibleRootItem) #logger.debug(" Getting row {} from parentItem: {}".format(row, parentItem)) if not (0 <= row < parentItem.nChildren()): # Can happen when deleting the last child. #logger.warn("Index row {} invalid for parent item: {}".format(row, parentItem)) return QtCore.QModelIndex() if not (0 <= column < self.columnCount()): #logger.warn("Index column {} invalid for parent item: {}".format(column, parentItem)) return QtCore.QModelIndex() childItem = parentItem.child(row) if childItem: return self.createIndex(row, column, childItem) else: logger.warn("No child item found at row {} for parent item: {}".format(row, parentItem)) return QtCore.QModelIndex()
def index(self, row, column, parentIndex=QtCore.QModelIndex())
Returns the index of the item in the model specified by the given row, column and parent index. Since each item contains information for an entire row of data, we create a model index to uniquely identify it by calling createIndex() it with the row and column numbers and a pointer to the item. (In the data() function, we will use the item pointer and column number to access the data associated with the model index; in this model, the row number is not needed to identify data.) When reimplementing this function in a subclass, call createIndex() to generate model indexes that other components can use to refer to items in your model.
2.817537
2.860361
0.985029
if not index.isValid(): return QtCore.QModelIndex() childItem = self.getItem(index, altItem=self.invisibleRootItem) parentItem = childItem.parentItem if parentItem == self.invisibleRootItem: return QtCore.QModelIndex() return self.createIndex(parentItem.childNumber(), 0, parentItem)
def parent(self, index)
Returns the parent of the model item with the given index. If the item has no parent, an invalid QModelIndex is returned. A common convention used in models that expose tree data structures is that only items in the first column have children. For that case, when reimplementing this function in a subclass the column of the returned QModelIndex would be 0. (This is done here.) When reimplementing this function in a subclass, be careful to avoid calling QModelIndex member functions, such as QModelIndex.parent(), since indexes belonging to your model will simply call your implementation, leading to infinite recursion.
2.965716
3.359691
0.882735
parentItem = self.getItem(parentIndex, altItem=self.invisibleRootItem) return parentItem.nChildren()
def rowCount(self, parentIndex=QtCore.QModelIndex())
Returns the number of rows under the given parent. When the parent is valid it means that rowCount is returning the number of children of parent. Note: When implementing a table based model, rowCount() should return 0 when the parent is valid.
12.717434
14.89942
0.853552
parentItem = self.getItem(parentIndex, altItem=self.invisibleRootItem) return parentItem.hasChildren()
def hasChildren(self, parentIndex=QtCore.QModelIndex())
Returns true if parent has any children; otherwise returns false. Use rowCount() on the parent to find out the number of children.
7.954561
7.040884
1.129767
if role != Qt.CheckStateRole and role != Qt.EditRole: return False treeItem = self.getItem(index, altItem=self.invisibleRootItem) try: result = self.setItemData(treeItem, index.column(), value, role=role) if result: # Emit dataChanged to update the tree view # TODO, update the entire tree? # A check box can have a tristate checkbox as parent which state depends # on the state of this child check box. Therefore we update the parentIndex # and the descendants. self.emitDataChanged(treeItem) # Emit sigItemChanged to update other widgets. self.sigItemChanged.emit(treeItem) return result except Exception as ex: # When does this still happen? Can we remove it? logger.warn("Unable to set data: {}".format(ex)) if DEBUGGING: raise return False
def setData(self, index, value, role=Qt.EditRole)
Sets the role data for the item at index to value. Returns true if successful; otherwise returns false. The dataChanged and sigItemChanged signals will be emitted if the data was successfully set. Descendants should typically override setItemData function instead of setData()
7.784906
7.460179
1.043528
if index.isValid(): item = index.internalPointer() if item: return item #return altItem if altItem is not None else self.invisibleRootItem # TODO: remove return altItem
def getItem(self, index, altItem=None)
Returns the TreeItem for the given index. Returns the altItem if the index is invalid.
5.161546
5.134117
1.005343
if parentIndex is None: parentIndex=QtCore.QModelIndex() parentItem = self.getItem(parentIndex, altItem=self.invisibleRootItem) nChildren = parentItem.nChildren() if position is None: position = nChildren assert 0 <= position <= nChildren, \ "position should be 0 < {} <= {}".format(position, nChildren) self.beginInsertRows(parentIndex, position, position) try: parentItem.insertChild(childItem, position) finally: self.endInsertRows() childIndex = self.index(position, 0, parentIndex) assert childIndex.isValid(), "Sanity check failed: childIndex not valid" return childIndex
def insertItem(self, childItem, position=None, parentIndex=None)
Inserts a childItem before row 'position' under the parent index. If position is None the child will be appended as the last child of the parent. Returns the index of the new inserted child.
2.805249
2.765741
1.014285
if not parentIndex.isValid(): logger.debug("No valid item selected for deletion (ignored).") return parentItem = self.getItem(parentIndex, None) logger.debug("Removing children of {!r}".format(parentItem)) assert parentItem, "parentItem not found" #firstChildRow = self.index(0, 0, parentIndex).row() #lastChildRow = self.index(parentItem.nChildren()-1, 0, parentIndex).row() #logger.debug("Removing rows: {} to {}".format(firstChildRow, lastChildRow)) #self.beginRemoveRows(parentIndex, firstChildRow, lastChildRow) self.beginRemoveRows(parentIndex, 0, parentItem.nChildren()-1) try: parentItem.removeAllChildren() finally: self.endRemoveRows() logger.debug("removeAllChildrenAtIndex completed")
def removeAllChildrenAtIndex(self, parentIndex)
Removes all children of the item at the parentIndex. The children's finalize method is called before removing them to give them a chance to close their resources
2.923654
2.990467
0.977658
if not itemIndex.isValid(): logger.debug("No valid item selected for deletion (ignored).") return item = self.getItem(itemIndex, "<no item>") logger.debug("deleteItemAtIndex: removing {}".format(item)) parentIndex = itemIndex.parent() parentItem = self.getItem(parentIndex, altItem=self.invisibleRootItem) row = itemIndex.row() self.beginRemoveRows(parentIndex, row, row) try: parentItem.removeChild(row) finally: self.endRemoveRows() logger.debug("deleteItemAtIndex completed")
def deleteItemAtIndex(self, itemIndex)
Removes the item at the itemIndex. The item's finalize method is called before removing so it can close its resources.
3.876057
3.962885
0.97809
oldItem = self.getItem(oldItemIndex) childNumber = oldItem.childNumber() parentIndex = oldItemIndex.parent() self.deleteItemAtIndex(oldItemIndex) insertedIndex = self.insertItem(newItem, position=childNumber, parentIndex=parentIndex) return insertedIndex
def replaceItemAtIndex(self, newItem, oldItemIndex)
Removes the item at the itemIndex and insert a new item instead.
3.44065
3.360048
1.023988
if self.isTopLevelIndex(childIndex): return childIndex else: return self.findTopLevelItemIndex(childIndex.parent())
def findTopLevelItemIndex(self, childIndex)
Traverses the tree upwards from childItem until its top level ancestor item is found. Top level items are items that are direct children of the (invisible) root item. This function therefore raises an exception when called with the root item.
3.001402
2.917476
1.028767
def _getIndexAndItemByName(nodeName, parentItem, parentIndex): if self.canFetchMore(parentIndex): self.fetchMore(parentIndex) for rowNr, childItem in enumerate(parentItem.childItems): if childItem.nodeName == nodeName: childIndex = self.index(rowNr, 0, parentIndex=parentIndex) return (childItem, childIndex) raise IndexError("Item not found: {!r}".format(path)) def _auxGetByPath(parts, item, index): "Aux function that does the actual recursive search" #logger.debug("_auxGetByPath item={}, parts={}".format(item, parts)) if len(parts) == 0: return [(item, index)] head, tail = parts[0], parts[1:] if head == '': # Two consecutive slashes. Just go one level deeper. return _auxGetByPath(tail, item, index) else: childItem, childIndex = _getIndexAndItemByName(head, item, index) return [(item, index)] + _auxGetByPath(tail, childItem, childIndex) # The actual body of findItemAndIndexPath starts here check_is_a_string(path) if not path: raise IndexError("Item not found: {!r}".format(path)) if startIndex is None or path.startswith('/'): startIndex = QtCore.QModelIndex() startItem = self.invisibleRootItem else: startItem = self.getItem(startIndex, None) if not startItem: raise IndexError("Item not found: {!r}. No start item!".format(path)) return _auxGetByPath(path.split('/'), startItem, startIndex)
def findItemAndIndexPath(self, path, startIndex=None)
Searches all the model recursively (starting at startIndex) for an item where item.nodePath == path. Returns list of (item, itemIndex) tuples from the start index to that node. Raises IndexError if the item cannot be found. If startIndex is None, or path starts with a slash, searching begins at the (invisible) root item.
3.620155
3.493704
1.036194
rootItem = self.rootItem() if rootItem is None: logger.debug("No items in: {}".format(self)) else: rootItem.logBranch(level=level)
def logItems(self, level=logging.DEBUG)
rootItem
5.056633
4.090078
1.236317
checked = checked if checked is not None else {} checkable = checkable if checkable is not None else {} enabled = enabled if enabled is not None else {} horizontal_header = self.horizontalHeader() horizontal_header.setContextMenuPolicy(Qt.ActionsContextMenu) self.toggle_column_actions_group = QtWidgets.QActionGroup(self) self.toggle_column_actions_group.setExclusive(False) self.__toggle_functions = [] # for keeping references for col in range(horizontal_header.count()): column_label = self.model().headerData(col, Qt.Horizontal, Qt.DisplayRole) #logger.debug("Adding: col {}: {}".format(col, column_label)) action = QtWidgets.QAction(str(column_label), self.toggle_column_actions_group, checkable = checkable.get(column_label, True), enabled = enabled.get(column_label, True), toolTip = "Shows or hides the {} column".format(column_label)) func = self.__makeShowColumnFunction(col) self.__toggle_functions.append(func) # keep reference horizontal_header.addAction(action) is_checked = checked.get(column_label, not horizontal_header.isSectionHidden(col)) horizontal_header.setSectionHidden(col, not is_checked) action.setChecked(is_checked) action.toggled.connect(func)
def addHeaderContextMenu(self, checked = None, checkable = None, enabled = None)
Adds the context menu from using header information checked can be a header_name -> boolean dictionary. If given, headers with the key name will get the checked value from the dictionary. The corresponding column will be hidden if checked is False. checkable can be a header_name -> boolean dictionary. If given, header actions with the key name will get the checkable value from the dictionary. (Default True) enabled can be a header_name -> boolean dictionary. If given, header actions with the key name will get the enabled value from the dictionary. (Default True)
2.660144
2.697576
0.986124
show_column = lambda checked: self.setColumnHidden(column_idx, not checked) return show_column
def __makeShowColumnFunction(self, column_idx)
Creates a function that shows or hides a column.
5.423166
3.848691
1.409094
#logger.debug("Reading view settings for: {}".format(key)) if settings is None: settings = QtCore.QSettings() horizontal_header = self.horizontalHeader() header_restored = horizontal_header.restoreState(settings.value(key)) # update actions for col, action in enumerate(horizontal_header.actions()): is_checked = not horizontal_header.isSectionHidden(col) action.setChecked(is_checked) return header_restored
def readViewSettings(self, key, settings=None)
Reads the persistent program settings :param key: key where the setting will be read from :param settings: optional QSettings object which can have a group already opened. :returns: True if the header state was restored, otherwise returns False
4.027204
3.652349
1.102634
#logger.debug("Writing view settings for: {}".format(key)) if settings is None: settings = QtCore.QSettings() settings.setValue(key, self.horizontalHeader().saveState())
def saveProfile(self, key, settings=None)
Writes the view settings to the persistent store :param key: key where the setting will be read from :param settings: optional QSettings object which can have a group already opened.
5.974761
5.45373
1.095537
if self.cls is None: return None elif hasattr(self.cls, 'descriptionHtml'): return self.cls.descriptionHtml() else: return ''
def descriptionHtml(self)
HTML help describing the class. For use in the detail editor.
3.518836
2.810668
1.251957
logger.info("Importing: {}".format(self.fullClassName)) self._triedImport = True self._exception = None self._cls = None try: for pyPath in self.pythonPath.split(':'): if pyPath and pyPath not in sys.path: logger.debug("Appending {!r} to the PythonPath.".format(pyPath)) sys.path.append(pyPath) self._cls = import_symbol(self.fullClassName) # TODO: check class? except Exception as ex: self._exception = ex logger.warn("Unable to import {!r}: {}".format(self.fullClassName, ex)) if DEBUGGING: raise
def tryImportClass(self)
Tries to import the registered class. Will set the exception property if and error occurred.
3.610557
3.554694
1.015715
if not self.triedImport and tryImport: self.tryImportClass() return self._cls
def getClass(self, tryImport=True)
Gets the underlying class. Tries to import if tryImport is True (the default). Returns None if the import has failed (the exception property will contain the reason)
7.702322
7.269413
1.059552
check_class(regItem, ClassRegItem) if regItem.identifier in self._index: oldRegItem = self._index[regItem.identifier] logger.warn("Class key {!r} already registered as {}. Removing old regItem." .format(regItem.identifier, oldRegItem.fullClassName)) self.removeItem(oldRegItem) logger.info("Registering {!r} with {}".format(regItem.identifier, regItem.fullClassName)) self._items.append(regItem) self._index[regItem.identifier] = regItem
def registerItem(self, regItem)
Adds a ClassRegItem object to the registry.
3.349125
2.997733
1.11722
check_class(regItem, ClassRegItem) logger.info("Removing {!r} containing {}".format(regItem.identifier, regItem.fullClassName)) del self._index[regItem.identifier] idx = self._items.index(regItem) del self._items[idx]
def removeItem(self, regItem)
Removes a ClassRegItem object to the registry. Will raise a KeyError if the regItem is not registered.
6.42804
5.202466
1.235576
groupName = groupName if groupName else self.settingsGroupName settings = QtCore.QSettings() #for key in sorted(settings.allKeys()): # print(key) if containsSettingsGroup(groupName, settings): self.loadSettings(groupName) else: logger.info("Group {!r} not found, falling back on default settings".format(groupName)) for item in self.getDefaultItems(): self.registerItem(item) self.saveSettings(groupName) assert containsSettingsGroup(groupName, settings), \ "Sanity check failed. {} not found".format(groupName)
def loadOrInitSettings(self, groupName=None)
Reads the registry items from the persistent settings store, falls back on the default plugins if there are no settings in the store for this registry.
4.163124
4.019248
1.035797
groupName = groupName if groupName else self.settingsGroupName settings = QtCore.QSettings() logger.info("Reading {!r} from: {}".format(groupName, settings.fileName())) settings.beginGroup(groupName) self.clear() try: for key in settings.childKeys(): if key.startswith('item'): dct = ast.literal_eval(settings.value(key)) regItem = self._itemClass.createFromDict(dct) self.registerItem(regItem) finally: settings.endGroup()
def loadSettings(self, groupName=None)
Reads the registry items from the persistent settings store.
3.613612
3.432771
1.052681
groupName = groupName if groupName else self.settingsGroupName settings = QtCore.QSettings() logger.info("Saving {} to: {}".format(groupName, settings.fileName())) settings.remove(groupName) # start with a clean slate settings.beginGroup(groupName) try: for itemNr, item in enumerate(self.items): key = "item-{:03d}".format(itemNr) value = repr(item.asDict()) settings.setValue(key, value) finally: settings.endGroup()
def saveSettings(self, groupName=None)
Writes the registry items into the persistent settings store.
3.543471
3.448186
1.027633
groupName = groupName if groupName else self.settingsGroupName settings = QtCore.QSettings() logger.info("Deleting {} from: {}".format(groupName, settings.fileName())) removeSettingsGroup(groupName)
def deleteSettings(self, groupName=None)
Deletes registry items from the persistent store.
5.980699
6.03043
0.991753
logger.debug("dockVisibilityChanged of {!r}: visible={}".format(self, visible)) if visible: self._repoTreeView.sigRepoItemChanged.connect(self.repoItemChanged) self._isConnected = True currentRepoItem, _currentIndex = self._repoTreeView.getCurrentItem() self.repoItemChanged(currentRepoItem) else: # At start-up the pane be be hidden but the signals are not connected. # A disconnect would fail in that case so we test for isConnected == True. if self.isConnected: self._repoTreeView.sigRepoItemChanged.disconnect(self.repoItemChanged) self._isConnected = False self.errorWidget.setError(msg="Contents disabled", title="Error") self.setCurrentIndex(self.ERROR_PAGE_IDX)
def dockVisibilityChanged(self, visible)
Slot to be called when the dock widget that this pane contains become (in)visible. Is used to (dis)connect the pane from its repo tree view and so prevent unnecessary and potentially costly updates when the pane is hidden.
7.471495
6.669228
1.120294
check_class(rti, (BaseRti, int), allow_none=True) assert type(rti) != int, "rti: {}".format(rti) try: self._drawContents(rti) self.setCurrentIndex(self.CONTENTS_PAGE_IDX) except Exception as ex: if DEBUGGING: raise logger.exception(ex) self.errorWidget.setError(msg=str(ex), title=get_class_name(ex)) self.setCurrentIndex(self.ERROR_PAGE_IDX)
def repoItemChanged(self, rti)
Updates the content when the current repo tree item changes. The rti parameter can be None when no RTI is selected in the repository tree.
5.721618
5.7327
0.998067
inspectorMenu.addAction(execInspectorDialogAction) inspectorMenu.addSeparator() for action in inspectorActionGroup.actions(): inspectorMenu.addAction(action) return inspectorMenu
def addInspectorActionsToMenu(inspectorMenu, execInspectorDialogAction, inspectorActionGroup)
Adds menu items to the inpsectorMenu for the given set-inspector actions. :param inspectorMenu: inspector menu that will be modified :param execInspectorDialogAction: the "Browse Inspectors..." actions :param inspectorActionGroup: action group with actions for selecting a new inspector :return: the inspectorMenu, which has been modified.
2.046117
3.022561
0.676948
library, name = inspectorRegItem.splitName() label = "{} ({})".format(name, library) if library else name #self.label.setText(label) self.menuButton.setText(label)
def updateFromInspectorRegItem(self, inspectorRegItem)
Updates the label from the full name of the InspectorRegItem
6.271308
5.303674
1.182446
return StringCtiEditor(self, delegate, parent=parent)
def createEditor(self, delegate, parent, option)
Creates a StringCtiEditor. For the parameters see the AbstractCti constructor documentation.
37.705864
5.298931
7.11575
self.vb.enableAutoRange(self.vb.YAxis, False) self.vb.setYRange(mn, mx, padding)
def setHistogramRange(self, mn, mx, padding=0.1)
Set the Y range on the histogram plot. This disables auto-scaling.
3.786216
3.514025
1.077459
self.imageItem = weakref.ref(img) img.sigImageChanged.connect(self.imageChanged) img.setLookupTable(self.getLookupTable) ## send function pointer, not the result #self.gradientChanged() self.regionChanged() self.imageChanged(autoLevel=True)
def setImageItem(self, img)
Set an ImageItem to have its levels and LUT automatically controlled by this HistogramLUTItem.
7.004917
6.360859
1.101253
if n is None: if img.dtype == np.uint8: n = 256 else: n = 512 if self.lut is None: self.lut = self.gradient.getLookupTable(n, alpha=alpha) return self.lut
def getLookupTable(self, img=None, n=None, alpha=None)
Return a lookup table from the color gradient defined by this HistogramLUTItem.
2.773376
2.542894
1.090637
setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.yAxisRangeCti, axisNumber)
def setAutoRangeOn(self, axisNumber)
Sets the auto-range of the axis on. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes).
14.707132
21.944294
0.670203
logger.debug("Finalizing: {}".format(self)) self.plotItem.scene().sigMouseMoved.disconnect(self.mouseMoved) self.plotItem.close() self.graphicsLayoutWidget.close()
def finalize(self)
Is called before destruction. Can be used to clean-up resources
5.122831
5.095607
1.005343
self.titleLabel.setText('') self.plotItem.clear() self.plotItem.setLabel('left', '') self.plotItem.setLabel('bottom', '')
def _clearContents(self)
Clears the the inspector widget when no valid input is available.
3.564312
3.266274
1.091247
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 arrays so we convert the masked values to Nans (missing # data values are replaced by NaNs). The PyQtGraph line plot omits the Nans, which is great. self.slicedArray.replaceMaskedValueWithNan() # will convert data to float if int self.plotItem.clear() # Reset the axes ranges (via the config) if (reason == UpdateReason.RTI_CHANGED or reason == UpdateReason.COLLECTOR_COMBO_BOX): # self.config.yAxisRangeCti.setAutoRangeOn() doesn't work as refreshBlocked is True # TODO: can refreshBlocked maybe only block the signals to prevent loops? self.config.xAxisRangeCti.autoRangeCti.data = True self.config.yAxisRangeCti.autoRangeCti.data = True self.titleLabel.setText(self.configValue('title').format(**self.collector.rtiInfo)) connected = np.isfinite(self.slicedArray.data) if is_an_array(self.slicedArray.mask): connected = np.logical_and(connected, ~self.slicedArray.mask) else: connected = np.zeros_like(self.slicedArray.data) if self.slicedArray.mask else connected plotDataItem = self.config.plotDataItemCti.createPlotDataItem() plotDataItem.setData(self.slicedArray.data, connect=connected) self.plotItem.addItem(plotDataItem) if self.config.probeCti.configValue: self.probeLabel.setVisible(True) self.plotItem.addItem(self.crossLineVerShadow, ignoreBounds=True) self.plotItem.addItem(self.crossLineVertical, ignoreBounds=True) self.plotItem.addItem(self.probeDataItem, ignoreBounds=True) self.probeDataItem.setSymbolBrush(QtGui.QBrush(self.config.plotDataItemCti.penColor)) self.probeDataItem.setSymbolSize(10) else: self.probeLabel.setVisible(False) # Update the config tree from the (possibly) new state of the PgLinePlot1d inspector, # e.g. the axis range may have changed while drawing. self.config.updateTarget()
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.
7.157082
6.798152
1.052798
try: check_class(viewPos, QtCore.QPointF) self.crossLineVerShadow.setVisible(False) self.crossLineVertical.setVisible(False) self.probeLabel.setText("") self.probeDataItem.clear() if (self._hasValidData() and self.config.probeCti.configValue and self.viewBox.sceneBoundingRect().contains(viewPos)): scenePos = self.viewBox.mapSceneToView(viewPos) index = int(scenePos.x()) data = self.slicedArray.data if not 0 <= index < len(data): txt = "<span style='color: grey'>no data at cursor</span>" self.probeLabel.setText(txt) else: valueStr = to_string(data[index], masked=self.slicedArray.maskAt(index), maskFormat='&lt;masked&gt;') self.probeLabel.setText("pos = {!r}, value = {}".format(index, valueStr)) if np.isfinite(data[index]): self.crossLineVerShadow.setVisible(True) self.crossLineVerShadow.setPos(index) self.crossLineVertical.setVisible(True) self.crossLineVertical.setPos(index) if data[index] > 0 or self.config.yLogCti.configValue == False: self.probeDataItem.setData((index,), (data[index],)) 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)
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.
5.588543
5.389173
1.036995
# Try to see if env_var can be converted to an int try: env_var = int(env_var) except ValueError: pass if isinstance(env_var, numbers.Number): return bool(env_var) elif is_a_string(env_var): env_var = env_var.lower().strip() if env_var in "false": return False else: return True else: return bool(env_var)
def environment_var_to_bool(env_var)
Converts an environment variable to a boolean Returns False if the environment variable is False, 0 or a case-insenstive string "false" or "0".
2.579432
2.662944
0.968639
if masked_array is not None and masked_array.dtype.kind == 'f': check_class(masked_array, ma.masked_array) logger.debug("Replacing fill_values by NaNs") masked_array[:] = ma.filled(masked_array, np.nan) masked_array.set_fill_value(np.nan) else: return masked_array
def fill_values_to_nan(masked_array)
Replaces the fill_values of the masked array by NaNs If the array is None or it does not contain floating point values, it cannot contain NaNs. In that case the original array is returned.
3.408305
3.121326
1.091941
if isinstance(s, six.string_types): s = s.lower() if s == 'true': return True elif s == 'false': return False else: return ValueError('Invalid boolean representation: {!r}'.format(s)) else: return s
def setting_str_to_bool(s)
Converts 'true' to True and 'false' to False if s is a string
2.204857
2.089981
1.054965
#logger.debug("to_string: {!r} ({})".format(var, type(var))) # Decode and select correct format specifier. if is_binary(var): fmt = strFormat try: decodedVar = var.decode(decode_bytes, 'replace') except LookupError as ex: # Add URL to exception message. raise LookupError("{}\n\nFor a list of encodings in Python see: {}" .format(ex, URL_PYTHON_ENCODINGS_DOC)) elif is_text(var): fmt = strFormat decodedVar = six.text_type(var) elif is_a_string(var): fmt = strFormat decodedVar = str(var) elif isinstance(var, numbers.Integral): fmt = intFormat decodedVar = var elif isinstance(var, numbers.Number): fmt = numFormat decodedVar = var elif var is None: fmt = noneFormat decodedVar = var else: fmt = otherFormat decodedVar = var if maskFormat != '{}': try: allMasked = all(masked) except TypeError as ex: allMasked = bool(masked) if allMasked: fmt = maskFormat try: result = fmt.format(decodedVar) except Exception: result = "Invalid format {!r} for: {!r}".format(fmt, decodedVar) #if masked: # logger.debug("to_string (fmt={}): {!r} ({}) -> result = {!r}".format(maskFormat, var, type(var), result)) return result
def to_string(var, masked=None, decode_bytes='utf-8', maskFormat='', strFormat='{}', intFormat='{}', numFormat=DEFAULT_NUM_FORMAT, noneFormat='{!r}', otherFormat='{}')
Converts var to a python string or unicode string so Qt widgets can display them. If var consists of bytes, the decode_bytes is used to decode the bytes. If var consists of a numpy.str_, the result will be converted to a regular Python string. This is necessary to display the string in Qt widgets. For the possible format string (replacement fields) see: https://docs.python.org/3/library/string.html#format-string-syntax :param masked: if True, the element is masked. The maskFormat is used. :param decode_bytes': string containing the expected encoding when var is of type bytes :param strFormat' : new style format string used to format strings :param intFormat' : new style format string used to format integers :param numFormat' : new style format string used to format all numbers except integers. :param noneFormat': new style format string used to format Nones. :param maskFormat': override with this format used if masked is True. If the maskFormat is empty, the format is never overriden. :param otherFormat': new style format string used to format all other types
3.071623
3.167717
0.969665
return isinstance(var, six.string_types) or (var is None and allow_none)
def is_a_string(var, allow_none=False)
Returns True if var is a string (ascii or unicode) Result py-2 py-3 ----------------- ----- ----- b'bytes literal' True False 'string literal' True True u'unicode literal' True True Also returns True if the var is a numpy string (numpy.string_, numpy.unicode_).
2.947053
5.632115
0.523259
if not is_a_string(var, allow_none=allow_none): raise TypeError("var must be a string, however type(var) is {}" .format(type(var)))
def check_is_a_string(var, allow_none=False)
Calls is_a_string and raises a type error if the check fails.
3.078089
2.820019
1.091513
return isinstance(var, six.text_type) or (var is None and allow_none)
def is_text(var, allow_none=False)
Returns True if var is a unicode text Result py-2 py-3 ----------------- ----- ----- b'bytes literal' False False 'string literal' False True u'unicode literal' True True Also works with the corresponding numpy types.
3.256083
5.835526
0.557976
return isinstance(var, six.binary_type) or (var is None and allow_none)
def is_binary(var, allow_none=False)
Returns True if var is a binary (bytes) objects Result py-2 py-3 ----------------- ----- ----- b'bytes literal' True True 'string literal' True False u'unicode literal' False False Also works with the corresponding numpy types.
3.252952
5.708185
0.569875
return isinstance(var, (list, tuple)) or (var is None and allow_none)
def is_a_sequence(var, allow_none=False)
Returns True if var is a list or a tuple (but not a string!)
3.286296
2.876901
1.142304
if not is_a_sequence(var, allow_none=allow_none): raise TypeError("var must be a list or tuple, however type(var) is {}" .format(type(var)))
def check_is_a_sequence(var, allow_none=False)
Calls is_a_sequence and raises a type error if the check fails.
3.335137
3.027427
1.101641
if not is_a_mapping(var, allow_none=allow_none): raise TypeError("var must be a dict, however type(var) is {}" .format(type(var)))
def check_is_a_mapping(var, allow_none=False)
Calls is_a_mapping and raises a type error if the check fails.
3.387676
3.044033
1.112891
return isinstance(var, np.ndarray) or (var is None and allow_none)
def is_an_array(var, allow_none=False)
Returns True if var is a numpy array.
3.261157
2.820828
1.156099
if not is_an_array(var, allow_none=allow_none): raise TypeError("var must be a NumPy array, however type(var) is {}" .format(type(var)))
def check_is_an_array(var, allow_none=False)
Calls is_an_array and raises a type error if the check fails.
3.37706
3.067599
1.100881
kind = array.dtype.kind assert kind in 'biufcmMOSUV', "Unexpected array kind: {}".format(kind) return kind in 'iuf'
def array_has_real_numbers(array)
Uses the dtype kind of the numpy array to determine if it represents real numbers. That is, the array kind should be one of: i u f Possible dtype.kind values. b boolean i signed integer u unsigned integer f floating-point c complex floating-point m timedelta M datetime O object S (byte-)string U Unicode V void
6.654174
6.114135
1.088326
if not isinstance(obj, target_class): if not (allow_none and obj is None): raise TypeError("obj must be a of type {}, got: {}" .format(target_class, type(obj)))
def check_class(obj, target_class, allow_none = False)
Checks that the obj is a (sub)type of target_class. Raises a TypeError if this is not the case. :param obj: object whos type is to be checked :type obj: any type :param target_class: target type/class :type target_class: any class or type :param allow_none: if true obj may be None :type allow_none: boolean
2.786773
3.403183
0.818873
parts = full_symbol_name.rsplit('.', 1) if len(parts) == 2: module_name, symbol_name = parts module_name = str(module_name) # convert from possible unicode symbol_name = str(symbol_name) #logger.debug("From module {} importing {!r}".format(module_name, symbol_name)) module = __import__(module_name, fromlist=[symbol_name]) cls = getattr(module, symbol_name) return cls elif len(parts) == 1: # No module part, only a class name. If you want to create a class # by using name without module, you should use globals()[symbol_name] # We cannot do this here because globals is of the module that defines # this function, not of the modules where this function is called. raise ImportError("full_symbol_name should contain a module") else: assert False, "Bug: parts should have 1 or elements: {}".format(parts)
def import_symbol(full_symbol_name)
Imports a symbol (e.g. class, variable, etc) from a dot separated name. Can be used to create a class whose type is only known at run-time. The full_symbol_name must contain packages and module, e.g.: 'argos.plugins.rti.ncdf.NcdfFileRti' If the module doesn't exist an ImportError is raised. If the class doesn't exist an AttributeError is raised.
4.321577
4.393521
0.983625
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)
def createPenStyleCti(nodeName, defaultData=0, includeNone=False)
Creates a ChoiceCti with Qt PenStyles. If includeEmtpy is True, the first option will be None.
3.751249
3.548013
1.057282
# 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)
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
7.88968
7.635982
1.033224
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())
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.
3.903739
3.824787
1.020642
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)
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.
4.245953
4.480841
0.947579
qColor = QtGui.QColor(data) # TODO: store a RGB string? if not qColor.isValid(): raise ValueError("Invalid color specification: {!r}".format(data)) return qColor
def _enforceDataType(self, data)
Converts to str so that this CTI always stores that type.
8.068489
7.914668
1.019435
dct = {} if self.data != self.defaultData: dct['data'] = self.data.name() return dct
def _nodeGetNonDefaultsDict(self)
Retrieves this nodes` values as a dictionary to be used for persistence. Non-recursive auxiliary function for getNonDefaultsDict
6.144742
6.245707
0.983834
return ColorCtiEditor(self, delegate, parent=parent)
def createEditor(self, delegate, parent, option)
Creates a ColorCtiEditor. For the parameters see the AbstractCti constructor documentation.
36.284454
5.30126
6.844496
self.pickButton.clicked.disconnect(self.openColorDialog) super(ColorCtiEditor, self).finalize()
def finalize(self)
Is called when the editor is closed. Disconnect signals.
21.342043
11.395965
1.872772
try: currentColor = self.getData() except InvalidInputError: currentColor = self.cti.data qColor = QtWidgets.QColorDialog.getColor(currentColor, self) if qColor.isValid(): self.setData(qColor) self.commitAndClose()
def openColorDialog(self)
Opens a QColorDialog for the user
5.947894
5.718358
1.04014
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)
def getData(self)
Gets data from the editor widget.
4.348245
4.042727
1.075572
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()
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.
5.726327
4.950804
1.156646
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()
def defaultData(self, defaultData)
Sets the data of this item. Does type conversion to ensure default data is always of the correct type.
5.961202
6.070306
0.982027
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)
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.
3.317698
2.903242
1.142756
dct = {} if self.data != self.defaultData: dct['data'] = self.data.toString() # calls QFont.toString() return dct
def _nodeGetNonDefaultsDict(self)
Retrieves this nodes` values as a dictionary to be used for persistence. Non-recursive auxiliary function for getNonDefaultsDict
9.658505
10.091542
0.957089
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
def _nodeSetValuesFromDict(self, dct)
Sets values from a dictionary in the current node. Non-recursive auxiliary function for setValuesFromDict
4.201223
4.41452
0.951683
return FontCtiEditor(self, delegate, parent=parent)
def createEditor(self, delegate, parent, option)
Creates a FontCtiEditor. For the parameters see the AbstractCti documentation.
35.270145
5.617267
6.27888
self.pickButton.clicked.disconnect(self.execFontDialog) super(FontCtiEditor, self).finalize()
def finalize(self)
Is called when the editor is closed. Disconnect signals.
27.507439
16.642723
1.652821
currentFont = self.getData() newFont, ok = QtGui.QFontDialog.getFont(currentFont, self) if ok: self.setData(newFont) else: self.setData(currentFont) self.commitAndClose()
def execFontDialog(self)
Opens a QColorDialog for the user
3.476422
3.798289
0.91526
return FontChoiceCtiEditor(self, delegate, parent=parent)
def createEditor(self, delegate, parent, option)
Creates a ChoiceCtiEditor. For the parameters see the AbstractCti constructor documentation.
53.275536
9.560465
5.572484
self.comboBox.activated.disconnect(self.comboBoxActivated) super(FontChoiceCtiEditor, self).finalize()
def finalize(self)
Is called when the editor is closed. Disconnect signals.
20.519896
11.804565
1.738302
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
def configValue(self)
Creates a QPen made of the children's config values.
3.803986
2.896864
1.31314
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
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.
4.716495
4.386421
1.075249
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
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.
3.14631
3.43187
0.916792
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)
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.
3.661333
3.998104
0.915767
#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
def maskedNanPercentile(maskedArray, percentiles, *args, **kwargs)
Calculates np.nanpercentile on the non-masked values
4.374926
4.349178
1.00592
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
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.
3.454457
3.268187
1.056995
check_class(mask, (np.ndarray, bool, np.bool_)) if isinstance(mask, (bool, np.bool_)): self._mask = bool(mask) else: self._mask = mask
def mask(self, mask)
The mask values. Must be an array or a boolean scalar.
3.576523
2.975596
1.201952
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))
def checkIsConsistent(self)
Raises a ConsistencyError if the mask has an incorrect shape.
6.300773
4.19382
1.502395
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)
def createFromMaskedArray(cls, masked_arr)
Creates an ArrayWithMak :param masked_arr: a numpy MaskedArray or numpy array :return: ArrayWithMask
3.727051
3.595301
1.036645
return ma.masked_array(data=self.data, mask=self.mask, fill_value=self.fill_value)
def asMaskedArray(self)
Creates converts to a masked array
2.946459
3.127187
0.942208
if isinstance(self.mask, bool): return self.mask else: return self.mask[index]
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.
3.834957
3.978611
0.963894
if isinstance(self.mask, bool): return np.full(self.data.shape, self.mask, dtype=np.bool) else: return self.mask
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.
3.234486
2.98564
1.083348
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)
def transpose(self, *args, **kwargs)
Transposes the array and mask separately :param awm: ArrayWithMask :return: copy/view with transposed
3.233379
3.219656
1.004262
if self.mask is False: pass elif self.mask is True: self.data[:] = replacementValue else: self.data[self.mask] = replacementValue
def replaceMaskedValue(self, replacementValue)
Replaces values where the mask is True with the replacement value.
3.191117
2.678072
1.191572
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
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.
3.223175
3.294281
0.978415
self.statusLabel.setText("Importing {}...".format(regItem.fullName)) QtWidgets.qApp.processEvents() regItem.tryImportClass() self.tableView.model().emitDataChanged(regItem) self.statusLabel.setText("") QtWidgets.qApp.processEvents()
def importRegItem(self, regItem)
Imports the regItem Writes this in the statusLabel while the import is in progress.
4.413406
3.743109
1.179075
for regItem in self.registeredItems: if not regItem.triedImport: self.importRegItem(regItem) logger.debug("Importing finished.")
def tryImportAllPlugins(self)
Tries to import all underlying plugin classes
8.29627
8.050774
1.030494
check_class(regItem, ClassRegItem, allow_none=True) self.tableView.setCurrentRegItem(regItem)
def setCurrentRegItem(self, regItem)
Sets the current item to the regItem
9.20616
10.398013
0.885377
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)
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.
3.654158
3.678726
0.993321
logger.debug("Importing plugins: {}".format(self)) for tabNr in range(self.tabWidget.count()): tab = self.tabWidget.widget(tabNr) tab.tryImportAllPlugins()
def tryImportAllPlugins(self)
Refreshes the tables of all tables by importing the underlying classes
4.345952
5.086007
0.854492
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
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.
3.875279
3.484589
1.11212
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)
def dataSetElementType(h5Dataset)
Returns a string describing the element type of the dataset
4.125027
4.103672
1.005204
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 ''
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
5.451123
4.4644
1.22102
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
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.
4.889225
3.635069
1.345015