Newer
Older
i = np.argmin(dt)
self.sigMoveToTSD.emit(self.TS[i])
def onPixelLoaded(self, nDone, nMax, d):
self.ui.progressBar.setValue(nDone)
self.ui.progressBar.setMaximum(nMax)
if d.success():
t = 'Last loaded from {}.'.format(bn)
else:
t = 'Failed loading from {}.'.format(bn)
if d.info and d.info != '':
t += '({})'.format(d.info)
def requestUpdate(self, *args):
self.updateRequested = True
#next time
def updatePersistentWidgets(self):
model = self.tableView2DProfiles.model()
if isinstance(model, PlotSettingsModel):
colExpression = model.columnIndex(model.cnExpression)
colStyle = model.columnIndex(model.cnStyle)

benjamin.jakimow@geo.hu-berlin.de
committed
for row in range(model.rowCount()):
idxExpr = model.createIndex(row, colExpression)
idxStyle = model.createIndex(row, colStyle)
#self.TV.openPersistentEditor(idxExpr)
#self.TV.openPersistentEditor(idxStyle)

benjamin.jakimow@geo.hu-berlin.de
committed
#self.TV.openPersistentEditor(model.createIndex(start, colStyle))
s = ""
def onRowsInserted(self, parent, start, end):
model = self.tableView2DProfiles.model()
if isinstance(model, PlotSettingsModel):
colExpression = model.columnIndex(model.cnExpression)
colStyle = model.columnIndex(model.cnStyle)
while start <= end:
idxExpr = model.createIndex(start, colExpression)
idxStyle = model.createIndex(start, colStyle)
self.tableView2DProfiles.openPersistentEditor(idxExpr)
self.tableView2DProfiles.openPersistentEditor(idxStyle)
start += 1
#self.TV.openPersistentEditor(model.createIndex(start, colStyle))
s = ""
def onObservationClicked(self, plotDataItem, points):
for p in points:
tsd = p.data()
def clear(self):
#first remove from pixelCollection
self.plotData2D.clear()
self.plotData3D.clear()
pi = self.plot2D.getPlotItem()
plotItems = pi.listDataItems()
for p in plotItems:
p.clear()
p.update()
if len(self.TS) > 0:
rng = [self.TS[0].date, self.TS[-1].date]
rng = [date2num(d) for d in rng]
self.plot2D.getPlotItem().setRange(xRange=rng)
if self.plot3D:
pass
def loadCoordinate(self, spatialPoints=None, LUT_bandIndices=None):
"""
Loads a temporal profile for a single or multiple geometries.
:param spatialPoints: SpatialPoint | [list-of-SpatialPoints]
"""
if not isinstance(self.plotSettingsModel, PlotSettingsModel):
return False
if not self.pixelLoader.isReadyToLoad():
return False
assert isinstance(self.TS, TimeSeries)
#Get or create the TimeSeriesProfiles which will store the loaded values
tasks = []
TPs = []
theGeometries = []
# Define a which (new) bands need to be loaded for each sensor
if LUT_bandIndices is None:
LUT_bandIndices = dict()
for sensor in self.TS.Sensors:
LUT_bandIndices[sensor] = self.plotSettingsModel.requiredBandsIndices(sensor)
assert isinstance(LUT_bandIndices, dict)
for sensor in self.TS.Sensors:
assert sensor in LUT_bandIndices.keys()
#update new / existing points
if isinstance(spatialPoints, SpatialPoint):
spatialPoints = [spatialPoints]
for spatialPoint in spatialPoints:
assert isinstance(spatialPoint, SpatialPoint)
TP = self.tpCollection.fromSpatialPoint(spatialPoint)
if not isinstance(TP, TemporalProfile):
TP = TemporalProfile(self.TS, spatialPoint)
self.tpCollection.insertTemporalProfiles(TP, i=0)
TPs.append(TP)
theGeometries.append(TP.mCoordinate)
TP_ids = [TP.mID for TP in TPs]
#each TSD is a Task
#a Task defines which bands are to be loaded
for tsd in self.TS:
#do not load from invisible TSDs
if not tsd.isVisible():
continue
#which bands do we need to load?
requiredIndices = set(LUT_bandIndices[tsd.sensor])
if len(requiredIndices) == 0:
continue
else:
s = ""
missingIndices = set()
for TP in TPs:
assert isinstance(TP, TemporalProfile)
existingBandKeys = [k for k in TP.data(tsd).keys() if PlotSettingsModel.regBandKeyExact.search(k)]
existingBandIndices = set([bandKey2bandIndex(k) for k in existingBandKeys])
need2load = requiredIndices.difference(existingBandIndices)
missingIndices = missingIndices.union(need2load)
if len(missingIndices) > 0:
task = PixelLoaderTask(tsd.pathImg, theGeometries,
bandIndices=missingIndices,
temporalProfileIDs=TP_ids)
tasks.append(task)
if len(tasks) > 0:
aGoodDefault = 2 if len(self.TS) > 25 else 1
self.pixelLoader.setNumberOfProcesses(SETTINGS.value('profileloader_threads', aGoodDefault))
if DEBUG:
print('Start loading for {} geometries from {} sources...'.format(
len(theGeometries), len(tasks)
))
self.pixelLoader.startLoading(tasks)
else:
if DEBUG:
print('Data for geometries already loaded')
def setVisibility(self, sensorPlotStyle):
assert isinstance(sensorPlotStyle, TemporalProfilePlotStyle)
self.setVisibility2D(sensorPlotStyle)
def setVisibility2D(self, sensorPlotStyle):
self.plot2D.update()
if sensorView is None:
for sv in self.plotSettingsModel.items:
self.setData(sv)
else:
assert isinstance(sensorView, TemporalProfilePlotStyle)
self.setData2D(sensorView)
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
def onDataUpdate(self):
for plotSetting in self.plotSettingsModel:
assert isinstance(plotSetting, TemporalProfilePlotStyle)
if plotSetting.temporalProfile().updated():
for pdi in plotSetting.mPlotItems:
assert isinstance(pdi, TemporalProfilePlotDataItem)
pdi.updateDataAndStyle()
plotSetting.temporalProfile().resetUpdated()
for i in self.plot2D.getPlotItem().dataItems:
i.updateItems()
if not self.plot2D.xAxisInitialized:
x0 = x1 = None
for plotSetting in self.plotSettingsModel:
assert isinstance(plotSetting, TemporalProfilePlotStyle)
for pdi in plotSetting.mPlotItems:
assert isinstance(pdi, TemporalProfilePlotDataItem)
if x0 is None:
x0 = pdi.xData.min()
x1 = pdi.xData.max()
else:
x0 = min(pdi.xData.min(), x0)
x1 = max(pdi.xData.max(), x1)
if x0 is not None:
self.plot2D.getPlotItem().setXRange(x0, x1)
self.plot2D.xAxisInitialized = True
@QtCore.pyqtSlot()
def updatePlot3D(self):
if OPENGL_AVAILABLE:
from pyqtgraph.opengl import GLViewWidget
import pyqtgraph.opengl as gl
assert isinstance(self.plot3D, GLViewWidget)
w = self.plot3D
#we need the data from all bands
del self.glPlotDataItems[:]
for i in w.items:
w.removeItem(i)
idx = self.ui.cbTemporalProfile3D.currentIndex()
if idx >= 0:
tp = self.ui.cbTemporalProfile3D.itemData(idx, role=Qt.UserRole)
assert isinstance(tp, TemporalProfile)
#1. ensure that data from all bands will be loaded
LUT_bandIndices = dict()
for sensor in self.TS.sensors():
assert isinstance(sensor, SensorInstrument)
LUT_bandIndices[sensor] = list(range(sensor.nb))
self.loadCoordinate(tp.mCoordinate, LUT_bandIndices=LUT_bandIndices)
#2. visualize already loaded data
profileData = {}
#x =
#y =
for sensor in tp.mTimeSeries.sensors():
profileData[sensor] = {'x':[],'y':[],'z':[]}
dataPos = []
x0 = x1 = y0 = y1 = z0 = z1 = 0
for iDate, tsd in enumerate(tp.mTimeSeries):
data = tp.data(tsd)
bandKeys = sorted([k for k in data.keys() if k.startswith('b') and data[k] != None], key=lambda k: bandKey2bandIndex(k))
if len(bandKeys) < 2:
continue
t = date2num(tsd.date)
x = []
y = []
z = []
for i, k in enumerate(bandKeys):
x.append(i)
y.append(t)
z.append(data[k])
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
x = np.asarray(x)
y = np.asarray(y)
z = np.asarray(z)
if iDate == 0:
x0, x1 = (x.min(), x.max())
y0, y1 = (y.min(), y.max())
z0, z1 = (z.min(), z.max())
else:
x0, x1 = (min(x.min(), x0), max(x.max(), x1))
y0, y1 = (min(y.min(), y0), max(y.max(), y1))
z0, z1 = (min(z.min(), z0), max(z.max(), z1))
dataPos.append((x,y,z))
xyz = [(x0,x1),(y0,y1),(z0,z1)]
l = len(dataPos)
for iPos, pos in enumerate(dataPos):
x,y,z = pos
arr = np.asarray(pos, dtype=np.float64).transpose()
for i, m in enumerate(xyz):
m0,m1 = m
arr[:, i] = (arr[:,i] - m0)/(m1-m0)
plt = gl.GLLinePlotItem(pos=arr,
#color=pg.glColor((i, n * 1.3)),
#color=pg.glColor(255,123,123,125),
color=pg.glColor((iPos, l * 1.3)),
width=1.0,
self.glPlotDataItems.append(plt)
for i, item in enumerate(self.glPlotDataItems):
w.addItem(item)
self.glGridItem.scale(0.1,0.1,0.1, local=False)
#w.setBackgroundColor(QColor('black'))
w.setCameraPosition(pos=(0.0, 0.0, 0.0), distance=1.)
w.addItem(self.glGridItem)
w.update()
"""
for sensor, values in data.items():
if len(values['z']) > 0:
x = values['x']
y = values['y']
z = values['z']
p2 = gl.GLSurfacePlotItem(x=x, y=y, z=z, shader='normalColor')
p2.translate(-10, -10, 0)
w.addItem(p2)
"""
@QtCore.pyqtSlot()
def updatePlot2D(self):
if isinstance(self.plotSettingsModel, PlotSettingsModel):
if DEBUG:
pi = self.plot2D.getPlotItem()
piDataItems = pi.listDataItems()
locations = set()
for plotSetting in self.plotSettingsModel:
assert isinstance(plotSetting, TemporalProfilePlotStyle)
locations.add(plotSetting.temporalProfile().mCoordinate)
for pdi in plotSetting.mPlotItems:
assert isinstance(pdi, TemporalProfilePlotDataItem)
#for i in pi.dataItems:
# i.updateItems()
#self.plot2D.update()
#2. load pixel data
self.loadCoordinate(list(locations))
# https://github.com/pyqtgraph/pyqtgraph/blob/5195d9dd6308caee87e043e859e7e553b9887453/examples/customPlot.py
return
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
# prepare QGIS environment
if sys.platform == 'darwin':
PATH_QGS = r'/Applications/QGIS.app/Contents/MacOS'
os.environ['GDAL_DATA'] = r'/usr/local/Cellar/gdal/1.11.3_1/share'
else:
# assume OSGeo4W startup
PATH_QGS = os.environ['QGIS_PREFIX_PATH']
assert os.path.exists(PATH_QGS)
qgsApp = QgsApplication([], True)
QApplication.addLibraryPath(r'/Applications/QGIS.app/Contents/PlugIns')
QApplication.addLibraryPath(r'/Applications/QGIS.app/Contents/PlugIns/qgis')
qgsApp.setPrefixPath(PATH_QGS, True)
qgsApp.initQgis()
gb = QGroupBox()
gb.setTitle('Sandbox')
PL = PixelLoader()
if False:
files = ['observationcloud/testdata/2014-07-26_LC82270652014207LGN00_BOA.bsq',
'observationcloud/testdata/2014-08-03_LE72270652014215CUB00_BOA.bsq'
]
else:
from timeseriesviewer.utils import file_search
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
searchDir = r'H:\LandsatData\Landsat_NovoProgresso'
files = file_search(searchDir, '*227065*band4.img', recursive=True)
#files = files[0:3]
lyr = QgsRasterLayer(files[0])
coord = lyr.extent().center()
crs = lyr.crs()
l = QVBoxLayout()
btnStart = QPushButton()
btnStop = QPushButton()
prog = QProgressBar()
tboxResults = QPlainTextEdit()
tboxResults.setMaximumHeight(300)
tboxThreads = QPlainTextEdit()
tboxThreads.setMaximumHeight(200)
label = QLabel()
label.setText('Progress')
def showProgress(n,m,md):
prog.setMinimum(0)
prog.setMaximum(m)
prog.setValue(n)
info = []
for k, v in md.items():
info.append('{} = {}'.format(k,str(v)))
tboxResults.setPlainText('\n'.join(info))
#tboxThreads.setPlainText(PL.threadInfo())
qgsApp.processEvents()
PL.sigPixelLoaded.connect(showProgress)
btnStart.setText('Start loading')
btnStart.clicked.connect(lambda : PL.startLoading(files, coord, crs))
btnStop.setText('Cancel')
btnStop.clicked.connect(lambda: PL.cancelLoading())
lh = QHBoxLayout()
lh.addWidget(btnStart)
lh.addWidget(btnStop)
l.addLayout(lh)
l.addWidget(prog)
l.addWidget(tboxThreads)
l.addWidget(tboxResults)
gb.setLayout(l)
gb.show()
#rs.setBackgroundStyle('background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #222, stop:1 #333);')
#rs.handle.setStyleSheet('background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #282, stop:1 #393);')
qgsApp.exec_()
qgsApp.exitQgis()
if __name__ == '__main__':
import site, sys
from timeseriesviewer import utils
qgsApp = utils.initQgisApplication()
if False: #the ultimative test for floating point division correctness, at least on a DOY-level
date1 = np.datetime64('1960-12-31','D')
assert date1 == num2date(date2num(date1))
#1960 - 12 - 31
for year in range(1960, 2057):
for doy in range(1, daysPerYear(year)+1):
dt = datetime.timedelta(days=doy - 1)
date1 = np.datetime64('{}-01-01'.format(year)) + np.timedelta64(doy-1,'D')
date2 = datetime.date(year=year, month=1, day=1) + datetime.timedelta(days=doy-1)
assert date1 == num2date(date2num(date1), dt64=True), 'date1: {}'.format(date1)
assert date2 == num2date(date2num(date2), dt64=False), 'date2: {}'.format(date1)
STVis = SpectralTemporalVisualization(ui)
STVis.setTimeSeries(TS)
import example.Images
from timeseriesviewer import file_search
files = file_search(os.path.dirname(example.Images.__file__), '*.tif')
TS.addFiles(files)
cpND = SpatialPoint(ext.crs(), 681151.214,-752388.476)
cp2 = SpatialPoint(ext.crs(), ext.center())
cp3 = SpatialPoint(ext.crs(), ext.center().x()+500, ext.center().y()+250)
STVis.loadCoordinate(cpND)
STVis.loadCoordinate(cp2)
STVis.loadCoordinate(cp3)
if False:
for tp in STVis.tpCollection:
assert isinstance(tp, TemporalProfile)
tp.plot()