Newer
Older
self.cnNS = 'ns'
self.cnNL = 'nl'
self.cnNB = 'nb'
self.cnCRS = 'CRS'
self.cnImages = 'Source Image(s)'
self.mColumnNames = [self.cnDate, self.cnSensor,
self.cnNS, self.cnNL, self.cnNB,
self.cnCRS, self.cnImages]
self.mRootIndex = QModelIndex()
self.mTasks = dict()
def setCurrentSpatialExtent(self, spatialExtent:SpatialExtent):
"""
Sets the spatial extent currently shown
:param spatialExtent:
"""
if isinstance(spatialExtent, SpatialExtent) and self.mCurrentSpatialExtent != spatialExtent:
self.mCurrentSpatialExtent = spatialExtent
def focusVisibilityToExtent(self):
ext = self.currentSpatialExtent()
if isinstance(ext, SpatialExtent):
changed = False
assert isinstance(tsd, TimeSeriesDate)
if b != tsd.isVisible():
changed = True
if changed:
ul = self.index(0, 0)
lr = self.index(self.rowCount()-1, 0)
self.dataChanged.emit(ul, lr, roles=[Qt.CheckStateRole])
self.sigVisibilityChanged.emit()
def currentSpatialExtent(self)->SpatialExtent:
"""
Returns the current spatial extent
:return: SpatialExtent
"""
return self.mCurrentSpatialExtent
def setVisibleDates(self, tsds:list):
:param tsds: [list-of-TimeSeriesDate]
self.mVisibleDate.clear()
self.mVisibleDate.extend(tsds)
for tsd in tsds:
assert isinstance(tsd, TimeSeriesDate)
if tsd in self:
idx = self.tsdToIdx(tsd)
# force reset of background color
idx2 = self.index(idx.row(), self.columnCount()-1)
self.dataChanged.emit(idx, idx2, [Qt.BackgroundColorRole])
def sensor(self, sensorID:str)->SensorInstrument:
for sensor in self.mSensors:
assert isinstance(sensor, SensorInstrument)
return sensor
return None
def sensors(self)->list:
"""
Returns the list of sensors derived from the TimeSeries data sources
:return: [list-of-SensorInstruments]
"""
def loadFromFile(self, path, n_max=None, progressDialog:QProgressDialog=None):
"""
Loads a CSV file with source images of a TimeSeries
:param path: str, Path of CSV file
:param n_max: optional, maximum number of files to load
"""
images = []
masks = []
with open(path, 'r') as f:
lines = f.readlines()
for l in lines:
if re.match('^[ ]*[;#&]', l):
continue
parts = re.split('[\n'+TimeSeries._sep+']', l)
parts = [p for p in parts if p != '']
images.append(parts[0])
if len(parts) > 1:
masks.append(parts[1])
images = images[0:n_max]
if isinstance(progressDialog, QProgressDialog):
progressDialog.setMaximum(len(images))
progressDialog.setMinimum(0)
progressDialog.setValue(0)
progressDialog.setLabelText('Start loading {} images....'.format(len(images)))
self.addSourcesAsync(images, progressDialog=progressDialog)
"""
Saves the TimeSeries sources into a CSV file
:param path: str, path of CSV file
:return: path of CSV file
"""
lines = []
lines.append('#Time series definition file: {}'.format(np.datetime64('now').astype(str)))
assert isinstance(TSD, TimeSeriesDate)
for pathImg in TSD.sourceUris():
lines.append(pathImg)
messageLog('Time series source images written to {}'.format(path))
"""
Returns the pixel sizes of all SensorInstruments
:return: [list-of-QgsRectangles]
"""

benjamin.jakimow@geo.hu-berlin.de
committed
r = []

benjamin.jakimow@geo.hu-berlin.de
committed
r.append((QgsRectangle(sensor.px_size_x, sensor.px_size_y)))
return r
"""
Returns the maximum SpatialExtent of all images of the TimeSeries
:param crs: QgsCoordinateSystem to express the SpatialExtent coordinates.
:return:
"""
assert isinstance(tsd, TimeSeriesDate)
ext = tsd.spatialExtent()
if isinstance(extent, SpatialExtent):
extent = extent.combineExtentWith(ext)
else:
extent = ext

benjamin.jakimow@geo.hu-berlin.de
committed
def getTSD(self, pathOfInterest):
Returns the TimeSeriesDate related to an image source
:param pathOfInterest: str, image source uri
assert isinstance(tsd, TimeSeriesDate)

benjamin.jakimow@geo.hu-berlin.de
committed
return tsd
return None
def tsd(self, date: np.datetime64, sensor)->TimeSeriesDate:
Returns the TimeSeriesDate identified by date and sensorID

Benjamin Jakimow
committed
:param date: numpy.datetime64
:param sensor: SensorInstrument | str with sensor id
:return:
"""
assert isinstance(date, np.datetime64)
if isinstance(sensor, str):
sensor = self.sensor(sensor)
if isinstance(sensor, SensorInstrument):
for tsd in self.mTSDs:
if tsd.date() == date and tsd.sensor() == sensor:
return tsd

Benjamin Jakimow
committed
else:
for tsd in self.mTSDs:
if tsd.date() == date:
return tsd
def insertTSD(self, tsd: TimeSeriesDate)->TimeSeriesDate:
Inserts a TimeSeriesDate
:param tsd: TimeSeriesDate
"""
#insert sorted by time & sensor
assert tsd not in self.mTSDs
assert tsd.sensor() in self.mSensors
tsd.sigRemoveMe.connect(lambda tsd=tsd: self.removeTSDs([tsd]))
tsd.rowsAboutToBeRemoved.connect(lambda p, first, last, tsd=tsd: self.beginRemoveRows(self.tsdToIdx(tsd), first, last))
tsd.rowsRemoved.connect(self.endRemoveRows)
tsd.rowsAboutToBeInserted.connect(lambda p, first, last, tsd=tsd: self.beginInsertRows(self.tsdToIdx(tsd), first, last))
tsd.rowsInserted.connect(self.endInsertRows)
tsd.sigSourcesAdded.connect(self.sigSourcesAdded)
tsd.sigSourcesRemoved.connect(self.sigSourcesRemoved)
row = bisect.bisect(self.mTSDs, tsd)
self.beginInsertRows(self.mRootIndex, row, row)
self.mTSDs.insert(row, tsd)
self.endInsertRows()
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
def showTSDs(self, tsds:list, b:bool=True):
tsds = [t for t in tsds if t in self]
minRow = None
maxRow = None
for t in tsds:
idx = self.tsdToIdx(t)
if minRow is None:
minRow = idx.row()
maxRow = idx.row()
else:
minRow = min(minRow, idx.row())
maxRow = min(maxRow, idx.row())
assert isinstance(t, TimeSeriesDate)
t.setVisibility(b)
if minRow:
ul = self.index(minRow, 0)
lr = self.index(maxRow, 0)
self.dataChanged.emit(ul, lr, roles=[Qt.CheckStateRole])
self.sigVisibilityChanged.emit()
def hideTSDs(self, tsds):
self.showTSDs(tsds, False)
Removes a list of TimeSeriesDate
:param tsds: [list-of-TimeSeriesDate]
toRemove = set()
for t in tsds:
if isinstance(t, TimeSeriesDate):
toRemove.add(t)
if isinstance(t, TimeSeriesSource):
toRemove.add(t.timeSeriesDate())
for tsd in list(toRemove):
assert isinstance(tsd, TimeSeriesDate)
tsd.sigSourcesRemoved.disconnect()
tsd.sigSourcesAdded.disconnect()
tsd.sigRemoveMe.disconnect()
row = self.mTSDs.index(tsd)
self.beginRemoveRows(self.mRootIndex, row, row)
self.mTSDs.remove(tsd)
tsd.mTimeSeries = None
removed.append(tsd)
self.endRemoveRows()

Benjamin Jakimow
committed
if len(removed) > 0:
self.sigTimeSeriesDatesRemoved.emit(removed)
def tsds(self, date:np.datetime64=None, sensor:SensorInstrument=None)->list:
Returns a list of TimeSeriesDate of the TimeSeries. By default all TimeSeriesDate will be returned.
:param date: numpy.datetime64 to return the TimeSeriesDate for
:param sensor: SensorInstrument of interest to return the [list-of-TimeSeriesDate] for.
:return: [list-of-TimeSeriesDate]
tsds = self.mTSDs[:]
if date:
tsds = [tsd for tsd in tsds if tsd.date() == date]
if sensor:

Benjamin Jakimow
committed
tsds = [tsd for tsd in tsds if tsd.sensor() == sensor]
"""
Removes all data sources from the TimeSeries (which will be empty after calling this routine).
"""
self.removeTSDs(self[:])
def addSensor(self, sensor:SensorInstrument):
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
if not sensor in self.mSensors:
self.mSensors.append(sensor)
self.sigSensorAdded.emit(sensor)
return sensor
else:
return None
def checkSensorList(self):
"""
Removes sensors without linked TSD / no data
"""
to_remove = []
for sensor in self.sensors():
tsds = [tsd for tsd in self.mTSDs if tsd.sensor() == sensor]
if len(tsds) == 0:
to_remove.append(sensor)
for sensor in to_remove:
self.removeSensor(sensor)
def removeSensor(self, sensor:SensorInstrument)->SensorInstrument:
"""
Removes a sensor and all linked images
:param sensor: SensorInstrument
:return: SensorInstrument or none, if sensor was not defined in the TimeSeries
"""
assert isinstance(sensor, SensorInstrument)
if sensor in self.mSensors:
tsds = [tsd for tsd in self.mTSDs if tsd.sensor() == sensor]
self.removeTSDs(tsds)
self.mSensors.remove(sensor)
self.sigSensorRemoved.emit(sensor)
return sensor
return None
def addSourcesAsync(self, sources:list, nWorkers:int = 1, progressDialog:QProgressDialog=None):
tm = QgsApplication.taskManager()
assert isinstance(tm, QgsTaskManager)
assert isinstance(nWorkers, int) and nWorkers >= 1
self.mLoadingProgressDialog = progressDialog
if True:
n = len(sources)
taskDescription = 'Load {} images'.format(n)
dump = pickle.dumps(sources)
qgsTask = QgsTask.fromFunction(taskDescription, doLoadTimeSeriesSourcesTask, dump,
on_finished = self.onAddSourcesAsyncFinished)
tid = id(qgsTask)
qgsTask.taskCompleted.connect(lambda *args, tid=tid: self.onRemoveTask(tid))
qgsTask.taskTerminated.connect(lambda *args, tid=tid: self.onRemoveTask(tid))
self.mTasks[tid] = qgsTask
if False: # for debugging only
resultDump = doLoadTimeSeriesSourcesTask(qgsTask, dump)
self.onAddSourcesAsyncFinished(None, resultDump)
else:
tm.addTask(qgsTask)
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
else:
# see https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
n = int(len(sources) / nWorkers)
for subset in chunks(sources, 50):
dump = pickle.dumps(subset)
taskDescription = 'Load {} images'.format(len(subset))
qgsTask = QgsTask.fromFunction(taskDescription, doLoadTimeSeriesSourcesTask, dump, on_finished=self.onAddSourcesAsyncFinished)
tid = id(qgsTask)
self.mTasks[tid] = qgsTask
qgsTask.taskCompleted.connect(lambda *args, tid=tid: self.onRemoveTask(tid))
qgsTask.taskTerminated.connect(lambda *args, tid=tid: self.onRemoveTask(tid))
if False: # for debugging only
resultDump = doLoadTimeSeriesSourcesTask(qgsTask, dump)
self.onAddSourcesAsyncFinished(None, resultDump)
else:
tm.addTask(qgsTask)
s = ""
def onRemoveTask(self, key):
self.mTasks.pop(key)
def onAddSourcesAsyncFinished(self, *args):
error = args[0]
if error is None:
try:
addedDates = []
dump = args[1]
sources = pickle.loads(dump)
for source in sources:
if isinstance(self.mLoadingProgressDialog, QProgressDialog):
self.increaseProgressBar()
if isinstance(newTSD, TimeSeriesDate):
addedDates.append(newTSD)
if len(addedDates) > 0:
self.sigTimeSeriesDatesAdded.emit(addedDates)
except Exception as ex:

Benjamin Jakimow
committed
import traceback
traceback.print_exc()
if isinstance(self.mLoadingProgressDialog, QProgressDialog):
if self.mLoadingProgressDialog.wasCanceled() or self.mLoadingProgressDialog.value() == -1:
self.mLoadingProgressDialog = None
def increaseProgressBar(self):
if isinstance(self.mLoadingProgressDialog, QProgressDialog):
v = self.mLoadingProgressDialog.value() + 1
self.mLoadingProgressDialog.setValue(v)
self.mLoadingProgressDialog.setLabelText('{}/{}'.format(v, self.mLoadingProgressDialog.maximum()))
if v == 1 or v % 25 == 0:
QApplication.processEvents()
def addSources(self, sources:list, progressDialog:QProgressDialog=None):
Adds new data sources to the TimeSeries
:param sources: [list-of-TimeSeriesSources]
self.mLoadingProgressDialog = progressDialog
nMax = len(sources)
# 1. read sources
# this could be excluded into a parallel process
addedDates = []
for i, source in enumerate(sources):
newTSD = None
if False: #debug
newTSD = self._addSource(source)
else:
try:
newTSD = self._addSource(source)
except Exception as ex:
msg = 'Unable to add: {}\n{}'.format(str(source), str(ex))
print(msg, file=sys.stderr)
if isinstance(self.mLoadingProgressDialog, QProgressDialog):
if self.mLoadingProgressDialog.wasCanceled():
break
self.increaseProgressBar()
if isinstance(newTSD, TimeSeriesDate):
addedDates.append(newTSD)
#if len(addedDates) > 0:
if isinstance(progressDialog, QProgressDialog):
progressDialog.setLabelText('Create map widgets...')
if len(addedDates) > 0:
self.sigTimeSeriesDatesAdded.emit(addedDates)
self.mLoadingProgressDialog = None
def _addSource(self, source:TimeSeriesSource)->TimeSeriesDate:
"""
:param source:
:return: TimeSeriesDate (if new created)
"""
if isinstance(source, TimeSeriesSource):
tss = source
else:
tss = TimeSeriesSource.create(source)
assert isinstance(tss, TimeSeriesSource)
newTSD = None
tsdDate = self.date2date(tss.date())
tssDate = tss.date()
sid = tss.sid()
sensor = self.sensor(sid)
# if necessary, add a new sensor instance
if not isinstance(sensor, SensorInstrument):
sensor = self.addSensor(SensorInstrument(sid))
assert isinstance(sensor, SensorInstrument)
# if necessary, add a new TimeSeriesDate instance
if not isinstance(tsd, TimeSeriesDate):
tsd = self.insertTSD(TimeSeriesDate(self, tsdDate, sensor))
newTSD = tsd
# addedDates.append(tsd)
assert isinstance(tsd, TimeSeriesDate)
# add the source
tsd.addSource(tss)
return newTSD

Benjamin Jakimow
committed
def setDateTimePrecision(self, mode:DateTimePrecision):
"""
Sets the precision with which the parsed DateTime information will be handled.
:param mode: TimeSeriesViewer:DateTimePrecision
:return:
"""
self.mDateTimePrecision = mode
#do we like to update existing sources?
def date2date(self, date:np.datetime64)->np.datetime64:
"""

Benjamin Jakimow
committed
Converts a date of arbitrary precision into the date with precision according to the EOTSV settions.
:param date: numpy.datetime64
:return: numpy.datetime64
"""

Benjamin Jakimow
committed
assert isinstance(date, np.datetime64)
if self.mDateTimePrecision == DateTimePrecision.Original:
return date
else:
date = np.datetime64(date, self.mDateTimePrecision.value)
return date
def sources(self) -> list:
"""
Returns the input sources
:return: iterator over [list-of-TimeSeriesSources]
"""
for tsd in self:
for source in tsd:
yield source

Benjamin Jakimow
committed
def sourceUris(self)->list:
"""
Returns the uris of all sources
:return: [list-of-str]
"""
uris = []
for tsd in self:
assert isinstance(tsd, TimeSeriesDate)
def __len__(self):
def __iter__(self):
def __getitem__(self, slice):
def __delitem__(self, slice):
def __contains__(self, item):
def __repr__(self):
info = []
info.append('TimeSeries:')
l = len(self)
info.append(' Scenes: {}'.format(l))
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
def headerData(self, section, orientation, role):
assert isinstance(section, int)
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
if len(self.mColumnNames) > section:
return self.mColumnNames[section]
else:
return ''
else:
return None
def parent(self, index: QModelIndex) -> QModelIndex:
"""
Returns the parent index of a QModelIndex `index`
:param index: QModelIndex
:return: QModelIndex
"""
if not index.isValid():
return QModelIndex()
node = index.internalPointer()
tsd = None
tss = None
if isinstance(node, TimeSeriesDate):
return self.mRootIndex
elif isinstance(node, TimeSeriesSource):
tss = node
return self.createIndex(self.mTSDs.index(tsd), 0, tsd)
def rowCount(self, index: QModelIndex=None) -> int:
"""
Return the row-count, i.e. number of child node for a TreeNode as index `index`.
:param index: QModelIndex
:return: int
"""
if index is None:
index = QModelIndex()
if not index.isValid():
return len(self)
node = index.internalPointer()
if isinstance(node, TimeSeriesDate):
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
return len(node)
if isinstance(node, TimeSeriesSource):
return 0
def columnNames(self) -> list:
"""
Returns the column names
:return: [list-of-string]
"""
return self.mColumnNames[:]
def columnCount(self, index:QModelIndex = None) -> int:
"""
Returns the number of columns
:param index: QModelIndex
:return:
"""
return len(self.mColumnNames)
def connectTreeView(self, treeView):
self.mTreeView = treeView
def index(self, row: int, column: int, parent: QModelIndex = None) -> QModelIndex:
"""
Returns the QModelIndex
:param row: int
:param column: int
:param parent: QModelIndex
:return: QModelIndex
"""
if parent is None:
parent = self.mRootIndex
else:
assert isinstance(parent, QModelIndex)
if row < 0 or row >= len(self):
return QModelIndex()
if column < 0 or column >= len(self.mColumnNames):
return QModelIndex()
if parent == self.mRootIndex:
# TSD node
if row < 0 or row >= len(self):
return QModelIndex()
return self.createIndex(row, column, self[row])
elif parent.parent() == self.mRootIndex:
# TSS node
tsd = self.tsdFromIdx(parent)
if row < 0 or row >= len(tsd):
return QModelIndex()
return self.createIndex(row, column, tsd[row])
return QModelIndex()
def tsdToIdx(self, tsd:TimeSeriesDate)->QModelIndex:
"""
Returns an QModelIndex pointing on a TimeSeriesDate of interest
:param tsd: TimeSeriesDate
:return: QModelIndex
"""
row = self.mTSDs.index(tsd)
return self.index(row, 0)
def tsdFromIdx(self, index: QModelIndex) -> TimeSeriesDate:
"""
Returns the TimeSeriesDate related to an QModelIndex `index`.
:param index: QModelIndex
:return: TreeNode
"""
if index.row() == -1 and index.column() == -1:
return None
elif not index.isValid():
return None
else:
node = index.internalPointer()
if isinstance(node, TimeSeriesDate):
return node
elif isinstance(node, TimeSeriesSource):
return None
def data(self, index, role):
"""
:param index: QModelIndex
:param role: Qt.ItemRole
:return: object
"""
assert isinstance(index, QModelIndex)
if not index.isValid():
return None
node = index.internalPointer()
tsd = None
tss = None
if isinstance(node, TimeSeriesSource):
tss = node
elif isinstance(node, TimeSeriesDate):
tsd = node
if role == Qt.UserRole:
return node
cName = self.mColumnNames[index.column()]
if role in [Qt.DisplayRole]:
if cName == self.cnDate:
if cName == self.cnImages:
return tss.uri()
if cName == self.cnNB:
return tss.nb
if cName == self.cnNL:
return tss.nl
if cName == self.cnNS:
return tss.ns
if cName == self.cnCRS:
return tss.crs().description()
if cName == self.cnSensor:
return tsd.sensor().name()
if role == Qt.DecorationRole and index.column() == 0:
return None
ext = tss.spatialExtent()
if isinstance(self.mCurrentSpatialExtent, SpatialExtent) and isinstance(ext, SpatialExtent):
ext = ext.toCrs(self.mCurrentSpatialExtent.crs())
b = isinstance(ext, SpatialExtent) and ext.intersects(self.mCurrentSpatialExtent)
if b:
return QIcon(r':/timeseriesviewer/icons/mapview.svg')
else:
return QIcon(r':/timeseriesviewer/icons/mapviewHidden.svg')
else:
print(ext)
return None
if role == Qt.BackgroundColorRole and tsd in self.mVisibleDate:
if isinstance(node, TimeSeriesDate):
if role in [Qt.DisplayRole]:
if cName == self.cnSensor:
return tsd.sensor().name()
if cName == self.cnImages:
return len(tsd)
if cName == self.cnDate:
return str(tsd.date())
return Qt.Checked if tsd.isVisible() else Qt.Unchecked
if role == Qt.BackgroundColorRole and tsd in self.mVisibleDate:
return None
def setData(self, index: QModelIndex, value: typing.Any, role: int):
if not index.isValid():
return False
result = False
bVisibilityChanged = False
node = index.internalPointer()
if isinstance(node, TimeSeriesDate):
if role == Qt.CheckStateRole and index.column() == 0:
node.setVisibility(value == Qt.Checked)
result = True
bVisibilityChanged = True
if result == True:
self.dataChanged.emit(index, index, [role])
if bVisibilityChanged:
self.sigVisibilityChanged.emit()
return result

Benjamin Jakimow
committed
def findDate(self, date)->TimeSeriesDate:
"""
Returns a TimeSeriesDate closes to that in date
:param date: numpy.datetime64 | str | TimeSeriesDate
:return: TimeSeriesDate
"""
if isinstance(date, str):
date = np.datetime64(date)
if isinstance(date, TimeSeriesDate):
date = date.date()
assert isinstance(date, np.datetime64)
if len(self) == 0:
return None
dtAbs = np.abs(date - np.asarray([tsd.date() for tsd in self.mTSDs]))
i = np.argmin(dtAbs)
return self.mTSDs[i]
def flags(self, index):
assert isinstance(index, QModelIndex)
if not index.isValid():
return Qt.NoItemFlags
#cName = self.mColumnNames.index(index.column())
flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable
if isinstance(index.internalPointer(), TimeSeriesDate) and index.column() == 0:
flags = flags | Qt.ItemIsUserCheckable
return flags
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
def getSpatialPropertiesFromDataset(ds):
assert isinstance(ds, gdal.Dataset)
nb = ds.RasterCount
nl = ds.RasterYSize
ns = ds.RasterXSize
proj = ds.GetGeoTransform()
px_x = float(abs(proj[1]))
px_y = float(abs(proj[5]))
crs = QgsCoordinateReferenceSystem(ds.GetProjection())
return nb, nl, ns, crs, px_x, px_y
wl = None
wlu = None
# see http://www.harrisgeospatial.com/docs/ENVIHeaderFiles.html for supported wavelength units
regWLkey = re.compile('.*wavelength[_ ]*$', re.I)
regWLUkey = re.compile('.*wavelength[_ ]*units?$', re.I)
regNumeric = re.compile(r"([-+]?\d*\.\d+|[-+]?\d+)", re.I)
regWLU = re.compile('((micro|nano|centi)meters)|(um|nm|mm|cm|m|GHz|MHz)', re.I)
if isinstance(ds, QgsRasterLayer):
lyr = ds
md = [l.split('=') for l in str(lyr.metadata()).splitlines() if 'wavelength' in l.lower()]
#see http://www.harrisgeospatial.com/docs/ENVIHeaderFiles.html for supported wavelength units
for kv in md:
key, value = kv
key = key.lower()
if key == 'center wavelength':
tmp = re.findall(r'\d*\.\d+|\d+', value) #find floats
if len(tmp) == 0:
tmp = re.findall(r'\d+', value) #find integers
if len(tmp) == lyr.bandCount():
wl = [float(w) for w in tmp]
if key == 'wavelength units':
match = regWLU.search(value)
if match:
wlu = match.group()
names = ['nanometers','micrometers','millimeters','centimeters','decimenters']
si = ['nm','um','mm','cm','dm']
if wlu in names:
wlu = si[names.index(wlu)]
elif isinstance(ds, gdal.Dataset):
for domain in ds.GetMetadataDomainList():
md = ds.GetMetadata_Dict(domain)
for key, value in md.items():
if wl is None and regWLkey.search(key):
numbers = regNumeric.findall(value)
if len(numbers) == ds.RasterCount:
wl = [float(n) for n in numbers]
if wlu is None and regWLUkey.search(key):
match = regWLU.search(value)
if match:
wlu = match.group().lower()
names = ['nanometers', 'micrometers', 'millimeters', 'centimeters', 'decimeters']
si = ['nm', 'um', 'mm', 'cm', 'dm']
if wlu in names:
wlu = si[names.index(wlu)]
return wl, wlu
class TimeSeriesDock(QgsDockWidget, loadUI('timeseriesdock.ui')):
"""
QgsDockWidget that shows the TimeSeries
"""
def __init__(self, parent=None):
super(TimeSeriesDock, self).__init__(parent)
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
self.setupUi(self)
#self.progressBar.setMinimum(0)
#self.setProgressInfo(0, 100, 'Add images to fill time series')
#self.progressBar.setValue(0)
#self.progressInfo.setText(None)
self.frameFilters.setVisible(False)
self.mTimeSeries = None
self.mSelectionModel = None
def initActions(self, parent):
from eotimeseriesviewer.main import TimeSeriesViewerUI
assert isinstance(parent, TimeSeriesViewerUI)
self.btnAddTSD.setDefaultAction(parent.actionAddTSD)
self.btnRemoveTSD.setDefaultAction(parent.actionRemoveTSD)
self.btnLoadTS.setDefaultAction(parent.actionLoadTS)
self.btnSaveTS.setDefaultAction(parent.actionSaveTS)
self.btnClearTS.setDefaultAction(parent.actionClearTS)
def showTSD(self, tsd:TimeSeriesDate):
assert isinstance(self.timeSeriesTreeView, TimeSeriesTreeView)
assert isinstance(self.mTSProxyModel, QSortFilterProxyModel)
tsd.setVisibility(True)
assert isinstance(self.mTimeSeries, TimeSeries)
idxSrc = self.mTimeSeries.tsdToIdx(tsd)
if isinstance(idxSrc, QModelIndex):
idx2 = self.mTSProxyModel.mapFromSource(idxSrc)
if isinstance(idx2, QModelIndex):
self.timeSeriesTreeView.setCurrentIndex(idx2)
self.timeSeriesTreeView.scrollTo(idx2, QAbstractItemView.PositionAtCenter)
def updateSummary(self):
if isinstance(self.mTimeSeries, TimeSeries):
if len(self.mTimeSeries) == 0:
info = 'Empty TimeSeries. Please add source images.'
else:
nDates = self.mTimeSeries.rowCount()
nSensors = len(self.mTimeSeries.sensors())
nImages = len(list(self.mTimeSeries.sources()))
info = '{} dates, {} sensors, {} source images'.format(nDates, nSensors, nImages)
else:
info = ''
self.summary.setText(info)
def onSelectionChanged(self, *args):
"""