spectrallibraries.py 66.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# -*- coding: utf-8 -*-
# noinspection PyPep8Naming
"""
***************************************************************************
    spectrallibraries.py

    Spectral Profiles and Libraries for a GUI context.
    ---------------------
    Date                 : Juli 2017
    Copyright            : (C) 2017 by Benjamin Jakimow
    Email                : benjamin.jakimow@geo.hu-berlin.de
***************************************************************************
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
***************************************************************************
"""
21

22
23
#see http://python-future.org/str_literals.html for str issue discussion
import os, re, tempfile, pickle, copy, shutil
24
25
26
27
28
from collections import OrderedDict
from qgis.core import *
from qgis.gui import *
import pyqtgraph as pg
from pyqtgraph import functions as fn
Benjamin Jakimow's avatar
Benjamin Jakimow committed
29
30
31
from qgis.PyQt.QtCore import *
from qgis.PyQt.QtGui import *
from qgis.PyQt.QtWidgets import *
32
33
34
import numpy as np
from osgeo import gdal, gdal_array

Benjamin Jakimow's avatar
Benjamin Jakimow committed
35
36
37
38
from timeseriesviewer.utils import *
from timeseriesviewer.virtualrasters import *
from timeseriesviewer.models import *
import timeseriesviewer.mimedata as mimedata
39

40
FILTERS = 'ENVI Spectral Library (*.esl *.sli);;CSV Table (*.csv)'
41

Benjamin Jakimow's avatar
Benjamin Jakimow committed
42
43


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def gdalDataset(pathOrDataset, eAccess=gdal.GA_ReadOnly):
    """

    :param pathOrDataset: path or gdal.Dataset
    :return: gdal.Dataset
    """

    if isinstance(pathOrDataset, QgsRasterLayer):
        return gdalDataset(pathOrDataset.source())

    if not isinstance(pathOrDataset, gdal.Dataset):
        pathOrDataset = gdal.Open(pathOrDataset, eAccess)

    assert isinstance(pathOrDataset, gdal.Dataset)

    return pathOrDataset


#Lookup table for ENVI IDL DataTypes to GDAL Data Types
LUT_IDL2GDAL = {1:gdal.GDT_Byte,
                12:gdal.GDT_UInt16,
                2:gdal.GDT_Int16,
                13:gdal.GDT_UInt32,
                3:gdal.GDT_Int32,
                4:gdal.GDT_Float32,
                5:gdal.GDT_Float64,
                #:gdal.GDT_CInt16,
                #8:gdal.GDT_CInt32,
                6:gdal.GDT_CFloat32,
                9:gdal.GDT_CFloat64}

def value2str(value, sep=' '):
    if isinstance(value, list):
77
        value = sep.join([str(v) for v in value])
78
79
80
    elif isinstance(value, np.array):
        value = value2str(value.astype(list), sep=sep)
    elif value is None:
81
        value = str('')
82
    else:
83
        value = str(value)
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
    return value

class SpectralLibraryTableView(QTableView):

    def __init__(self, parent=None):
        super(SpectralLibraryTableView, self).__init__(parent)
        s = ""

    def contextMenuEvent(self, event):

        menu = QMenu(self)

        m = menu.addMenu('Copy...')
        a = m.addAction("Cell Values")
        a.triggered.connect(lambda :self.onCopy2Clipboard('CELLVALUES', separator=';'))
        a = m.addAction("Spectral Values")
        a.triggered.connect(lambda: self.onCopy2Clipboard('YVALUES', separator=';'))
        a = m.addAction("Spectral Values + Metadata")
        a.triggered.connect(lambda: self.onCopy2Clipboard('ALL', separator=';'))

        a = m.addAction("Spectral Values (Excel)")
        a.triggered.connect(lambda: self.onCopy2Clipboard('YVALUES', separator='\t'))
        a = m.addAction("Spectral Values + Metadata (Excel)")
        a.triggered.connect(lambda: self.onCopy2Clipboard('ALL', separator='\t'))

        a = menu.addAction('Save to file')
        a.triggered.connect(self.onSaveToFile)

        a = menu.addAction('Set color')
        a.triggered.connect(self.onSetColor)

        m.addSeparator()

        a = menu.addAction('Check')
        a.triggered.connect(lambda : self.setCheckState(Qt.Checked))
        a = menu.addAction('Uncheck')
        a.triggered.connect(lambda: self.setCheckState(Qt.Unchecked))

        menu.addSeparator()
        a = menu.addAction('Remove')
        a.triggered.connect(lambda : self.model().removeProfiles(self.selectedSpectra()))
        menu.popup(QCursor.pos())

    def onCopy2Clipboard(self, key, separator='\t'):
        assert key in ['CELLVALUES', 'ALL', 'YVALUES']
        txt = None
        if key == 'CELLVALUES':
            lines = []
            line = []
            row = None
            for idx in self.selectionModel().selectedIndexes():
                if row is None:
                    row = idx.row()
                elif row != idx.row():
                    lines.append(line)
                    line = []
                line.append(self.model().data(idx, role=Qt.DisplayRole))
            lines.append(line)
            lines = [value2str(l, sep=separator) for l in lines]
            QApplication.clipboard().setText('\n'.join(lines))
        else:
            sl = SpectralLibrary(profiles=self.selectedSpectra())
            txt = None
            if key == 'ALL':
                lines = CSVSpectralLibraryIO.asTextLines(sl, separator=separator)
                txt = '\n'.join(lines)
            elif key == 'YVALUES':
                lines = []
                for p in sl:
                    assert isinstance(p, SpectralProfile)
154
                    lines.append(separator.join([str(v) for v in p.yValues()]))
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
                txt = '\n'.join(lines)
            if txt:
                QApplication.clipboard().setText(txt)

    def onSaveToFile(self, *args):
        sl = SpectralLibrary(profiles=self.selectedSpectra())
        sl.exportProfiles()




    def selectedSpectra(self):
        rows = self.selectedRowsIndexes()
        m = self.model()
        return [m.idx2profile(m.createIndex(r, 0)) for r in rows]

    def onSetColor(self):
        c = QColorDialog.getColor()
        if isinstance(c, QColor):
            model = self.model()
            for idx in self.selectedRowsIndexes():
                model.setData(model.createIndex(idx, 1), c, Qt.BackgroundRole)

    def setCheckState(self, checkState):
        model = self.model()

        for idx in self.selectedRowsIndexes():
            model.setData(model.createIndex(idx, 0), checkState, Qt.CheckStateRole)

        selectionModel = self.selectionModel()
        assert isinstance(selectionModel, QItemSelectionModel)
        selectionModel.clearSelection()

    def selectedRowsIndexes(self):
        selectionModel = self.selectionModel()
        assert isinstance(selectionModel, QItemSelectionModel)
        return sorted(list(set([i.row() for i in self.selectionModel().selectedIndexes()])))

    def dropEvent(self, event):
        assert isinstance(event, QDropEvent)
        mimeData = event.mimeData()

        if self.model().rowCount() == 0:
            index = self.model().createIndex(0,0)
        else:
            index = self.indexAt(event.pos())

Benjamin Jakimow's avatar
Benjamin Jakimow committed
202
        if mimeData.hasFormat(mimedata.MDF_SPECTRALLIBRARY):
203
204
205
206
207
208
209
210
211
            self.model().dropMimeData(mimeData, event.dropAction(), index.row(), index.column(), index.parent())
            event.accept()





    def dragEnterEvent(self, event):
        assert isinstance(event, QDragEnterEvent)
Benjamin Jakimow's avatar
Benjamin Jakimow committed
212
        if event.mimeData().hasFormat(mimedata.MDF_SPECTRALLIBRARY):
213
214
215
216
            event.accept()

    def dragMoveEvent(self, event):
        assert isinstance(event, QDragMoveEvent)
Benjamin Jakimow's avatar
Benjamin Jakimow committed
217
        if event.mimeData().hasFormat(mimedata.MDF_SPECTRALLIBRARY):
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
            event.accept()
        s = ""


    def mimeTypes(self):
        pass

"""
class SpectralProfileMapTool(QgsMapToolEmitPoint):

    sigProfileRequest = pyqtSignal(SpatialPoint, QgsMapCanvas)

    def __init__(self, canvas, showCrosshair=True):
        self.mShowCrosshair = showCrosshair
        self.mCanvas = canvas
        QgsMapToolEmitPoint.__init__(self, self.mCanvas)
        self.marker = QgsVertexMarker(self.mCanvas)
235
        self.rubberband = QgsRubberBand(self.mCanvas, QgsWkbTypes.PolygonGeometry)
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274

        color = QColor('red')

        self.rubberband.setLineStyle(Qt.SolidLine)
        self.rubberband.setColor(color)
        self.rubberband.setWidth(2)

        self.marker.setColor(color)
        self.marker.setPenWidth(3)
        self.marker.setIconSize(5)
        self.marker.setIconType(QgsVertexMarker.ICON_CROSS)  # or ICON_CROSS, ICON_X

    def canvasPressEvent(self, e):
        geoPoint = self.toMapCoordinates(e.pos())
        self.marker.setCenter(geoPoint)
        #self.marker.show()

    def setStyle(self, color=None, brushStyle=None, fillColor=None, lineStyle=None):
        if color:
            self.rubberband.setColor(color)
        if brushStyle:
            self.rubberband.setBrushStyle(brushStyle)
        if fillColor:
            self.rubberband.setFillColor(fillColor)
        if lineStyle:
            self.rubberband.setLineStyle(lineStyle)

    def canvasReleaseEvent(self, e):

        pixelPoint = e.pixelPoint()

        crs = self.mCanvas.mapSettings().destinationCrs()
        self.marker.hide()
        geoPoint = self.toMapCoordinates(pixelPoint)
        if self.mShowCrosshair:
            #show a temporary crosshair
            ext = SpatialExtent.fromMapCanvas(self.mCanvas)
            cen = geoPoint
            geom = QgsGeometry()
275
            geom.addPart([QgsPointXY(ext.upperLeftPt().x(),cen.y()), QgsPointXY(ext.lowerRightPt().x(), cen.y())],
276
                          Qgis.Line)
277
            geom.addPart([QgsPointXY(cen.x(), ext.upperLeftPt().y()), QgsPointXY(cen.x(), ext.lowerRightPt().y())],
278
                          Qgis.Line)
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
            self.rubberband.addGeometry(geom, None)
            self.rubberband.show()
            #remove crosshair after 0.1 sec
            QTimer.singleShot(100, self.hideRubberband)

        self.sigProfileRequest.emit(SpatialPoint(crs, geoPoint), self.mCanvas)

    def hideRubberband(self):
        self.rubberband.reset()

"""

class SpectralProfilePlotDataItem(pg.PlotDataItem):

    def __init__(self, spectralProfle):
        assert isinstance(spectralProfle, SpectralProfile)
        super(SpectralProfilePlotDataItem, self).__init__(spectralProfle.xValues(), spectralProfle.yValues())
        self.mProfile = spectralProfle

    def setClickable(self, b, width=None):
        assert isinstance(b, bool)
        self.curve.setClickable(b, width=width)

    def setColor(self, color):
        if not isinstance(color, QColor):

            color = QColor(color)
        self.setPen(color)

    def pen(self):

        return fn.mkPen(self.opts['pen'])

    def color(self):
        return self.pen().color()

    def setLineWidth(self, width):
        pen = pg.mkPen(self.opts['pen'])
        assert isinstance(pen, QPen)
        pen.setWidth(width)
        self.setPen(pen)


class SpectralProfile(QObject):

    @staticmethod
    def fromMapCanvas(mapCanvas, position):
        """
        Returns a list of Spectral Profiles the raster layers in QgsMapCanvas mapCanvas.
        :param mapCanvas:
        :param position:
        """
        assert isinstance(mapCanvas, QgsMapCanvas)

        layers = [l for l in mapCanvas.layers() if isinstance(l, QgsRasterLayer)]
        sources = [l.source() for l in layers]
        return SpectralProfile.fromRasterSources(sources, position)

    @staticmethod
    def fromRasterSources(sources, position):
        """
        Returns a list of Spectral Profiles
        :param sources: list-of-raster-sources, e.g. file paths, gdal.Datasets, QgsRasterLayers
        :param position:
        :return:
        """
        profiles = [SpectralProfile.fromRasterSource(s, position) for s in sources]
        return [p for p in profiles if isinstance(p, SpectralProfile)]


    @staticmethod
    def fromRasterSource(source, position):
        """
        Returns the Spectral Profiles from source at position `position`
        :param source: path or gdal.Dataset
        :param position:
        :return: SpectralProfile
        """

        ds = gdalDataset(source)
        crs = QgsCoordinateReferenceSystem(ds.GetProjection())
        gt = ds.GetGeoTransform()

        if isinstance(position, QPoint):
            px = position
        elif isinstance(position, SpatialPoint):
            px = geo2px(position.toCrs(crs), gt)
        elif isinstance(position, QgsPoint):
            px = geo2px(position, ds.GetGeoTransform())
        else:
            raise Exception('Unsupported type of argument "position" {}'.format('{}'.format(position)))
        #check out-of-raster
        if px.x() < 0 or px.y() < 0: return None
        if px.x() > ds.RasterXSize - 1 or px.y() > ds.RasterYSize - 1: return None


        values = ds.ReadAsArray(px.x(), px.y(), 1, 1)

        values = values.flatten()
        for b in range(ds.RasterCount):
            band = ds.GetRasterBand(b+1)
            nodata = band.GetNoDataValue()
            if nodata and values[b] == nodata:
                return None

        wl = ds.GetMetadataItem(str('wavelength'),str('ENVI'))
        wlu = ds.GetMetadataItem(str('wavelength_units'),str('ENVI'))
        if wl is not None and len(wl) > 0:
            wl = re.sub(r'[ {}]','', wl).split(',')
            wl = [float(w) for w in wl]

        profile = SpectralProfile()
        profile.setValues(values, valuePositions=wl, valuePositionUnit=wlu)
        profile.setCoordinates(px=px, spatialPoint=SpatialPoint(crs,px2geo(px, gt)))
        profile.setSource('{}'.format(ds.GetFileList()[0]))
        return profile

    def __init__(self, parent=None):
        super(SpectralProfile, self).__init__(parent)
        self.mName = ''
        self.mValues = []
        self.mValueUnit = None
        self.mValuePositions = []
        self.mValuePositionUnit = None
        self.mMetadata = dict()
        self.mSource = None
        self.mPxCoordinate = None
        self.mGeoCoordinate = None

408
    sigNameChanged = pyqtSignal(str)
409
    def setName(self, name):
410
        assert isinstance(name, str)
411
412
413
414
415
416
417
418
419

        if name != self.mName:
            self.mName = name
            self.sigNameChanged.emit(name)

    def name(self):
        return self.mName

    def setSource(self, uri):
420
        assert isinstance(uri, str)
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
        self.mSource = uri

    def source(self):
        return self.mSource

    def setCoordinates(self, px=None, spatialPoint=None):
        if isinstance(px, QPoint):
            self.mPxCoordinate = px
        if isinstance(spatialPoint, SpatialPoint):
            self.mGeoCoordinate = spatialPoint

    def pxCoordinate(self):
        return self.mPxCoordinate

    def geoCoordinate(self):
        return self.mGeoCoordinate

    def isValid(self):
        return len(self.mValues) > 0 and self.mValueUnit is not None

    def setValues(self, values, valueUnit=None,
                  valuePositions=None, valuePositionUnit=None):
        n = len(values)
        self.mValues = values[:]

        if valuePositions is None:
            valuePositions = list(range(n))
            valuePositionUnit = 'Index'
        self.setValuePositions(valuePositions, unit=valuePositionUnit)

    def setValuePositions(self, positions, unit=None):
        assert len(positions) == len(self.mValues)
        self.mValuePositions = positions[:]
        self.mValuePositionUnit = unit

    def updateMetadata(self, metaData):
        assert isinstance(metaData, dict)
        self.mMetadata.update(metaData)

    def setMetadata(self, key, value):

462
        assert isinstance(key, str)
463
464
465
466

        self.mMetadata[key] = value

    def metadata(self, key, default=None):
467
        assert isinstance(key, str)
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
        v = self.mMetadata.get(key)
        return default if v is None else v

    def yValues(self):
        return self.mValues[:]

    def yUnit(self):
        return self.mValueUnit

    def xValues(self):
        return self.mValuePositions[:]

    def xUnit(self):
        return self.mValuePositionUnit

    def valueIndexes(self):
        return np.arange(len(self.yValues()))

    def clone(self):
        return copy.copy(self)

    def plot(self):
        """
        Plots this profile to an new PyQtGraph window
        :return:
        """
        import pyqtgraph as pg

        pi = SpectralProfilePlotDataItem(self)
        pi.setClickable(True)
        pw = pg.plot( title=self.name())
        pw.getPlotItem().addItem(pi)

        pi.setColor('green')
        pg.QAPP.exec_()


    def __reduce_ex__(self, protocol):

        return self.__class__, (), self.__getstate__()

    def __getstate__(self):
        return self.__dict__.copy()

    def __setstate__(self, state):
        self.__dict__.update(state)

    def __copy__(self):
        return copy.deepcopy(self)

    def isEqual(self, other):
        if not isinstance(other, SpectralProfile):
            return False
        if len(self.mValues) != len(other.mValues):
            return False
        return all(a == b for a, b in zip(self.mValues, other.mValues)) \
               and self.mValuePositions == other.mValuePositions \
               and self.mValueUnit == other.mValueUnit \
               and self.mValuePositionUnit == other.mValuePositionUnit \
               and self.mGeoCoordinate == other.mGeoCoordinate \
               and self.mPxCoordinate == other.mPxCoordinate

    """
    def __eq__(self, other):
        if not isinstance(other, SpectralProfile):
            return False
        if len(self.mValues) != len(other.mValues):
            return False
        return all(a == b for a,b in zip(self.mValues, other.mValues)) \
            and self.mValuePositions == other.mValuePositions \
            and self.mValueUnit == other.mValueUnit \
            and self.mValuePositionUnit == other.mValuePositionUnit \
            and self.mGeoCoordinate == other.mGeoCoordinate \
            and self.mPxCoordinate == other.mPxCoordinate

    def __ne__(self, other):
        return not self.__eq__(other)
    """
    def __len__(self):
        return len(self.mValues)

class SpectralLibraryWriter(object):

    @staticmethod
    def writeSpeclib(speclib):
        assert isinstance(speclib, SpectralLibrary)



class SpectralLibraryIO(object):
    """
    Abstract Class to define I/O operations for spectral libraries
    Overwrite the canRead and read From routines.
    """
    @staticmethod
    def canRead(path):
        """
        Returns true if it can reath the source definded by path
        :param path: source uri
        :return: True, if source is readibly
        """
        return False

    @staticmethod
    def readFrom(path):
        """
        Returns the SpectralLibrary read from "path"
        :param path: source of SpectralLibrary
        :return: SpectralLibrary
        """
        return None

    @staticmethod
    def write(speclib, path):
        """Writes the SpectralLibrary speclib to path, returns a list of written files"""
        assert isinstance(speclib, SpectralLibrary)
        return None


class CSVSpectralLibraryIO(SpectralLibraryIO):

    @staticmethod
    def write(speclib, path, separator='\t'):

        assert isinstance(speclib, SpectralLibrary)
        lines = ['Spectral Library {}'.format(speclib.name())]

        lines.extend(
            CSVSpectralLibraryIO.asTextLines(speclib, separator=separator)
        )

        file = open(path, 'w')
        for line in lines:
            file.write(line+'\n')
        file.flush()
        file.close()

    @staticmethod
    def asTextLines(speclib, separator='\t'):
        lines = []
        attributes = speclib.metadataAttributes()
        grouping = speclib.groupBySpectralProperties()
        for profiles in grouping.values():
            wlU = profiles[0].xUnit()
            wavelength = profiles[0].xValues()

            columns = ['n', 'name', 'geo', 'px', 'src']+attributes
            if wlU in [None, 'Index']:
                columns.extend(['b{}'.format(i + 1) for i in range(len(wavelength))])
            else:
                for i, wl in enumerate(wavelength):
                    columns.append('b{}_{}'.format(i + 1, wl))
            lines.append(value2str(columns, sep=separator))

            for i, p in enumerate(profiles):
                line = [i + 1, p.name(), p.geoCoordinate(), p.pxCoordinate(), p.source()]
                line.extend([p.metadata(a) for a in attributes])
                line.extend(p.yValues())
                lines.append(value2str(line, sep=separator))
            lines.append('')
        return lines


class EnviSpectralLibraryIO(SpectralLibraryIO):

    @staticmethod
    def canRead(pathESL):
        """
        Checks if a file can be read as SpectraLibrary
        :param pathESL: path to ENVI Spectral Library (ESL)
        :return: True, if pathESL can be read as Spectral Library.
        """
640
        assert isinstance(pathESL, str)
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
        if not os.path.isfile(pathESL):
            return False
        hdr = EnviSpectralLibraryIO.readENVIHeader(pathESL, typeConversion=False)
        if hdr is None or hdr[u'file type'] != u'ENVI Spectral Library':
            return False
        return True

    @staticmethod
    def readFrom(pathESL, tmpVrt=None):
        """
        Reads an ENVI Spectral Library (ESL).
        :param pathESL: path ENVI Spectral Library
        :param tmpVrt: (optional) path of GDAL VRt that is used to read the ESL
        :return: SpectralLibrary
        """
656
        assert isinstance(pathESL, str)
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
        md = EnviSpectralLibraryIO.readENVIHeader(pathESL, typeConversion=True)
        data = None
        try:
            to_delete = []
            if tmpVrt is None:
                tmpVrt = tempfile.mktemp(prefix='tmpESLVrt', suffix='.esl.vrt')
                to_delete.append(tmpVrt)
            ds = EnviSpectralLibraryIO.esl2vrt(pathESL, tmpVrt)
            data = ds.ReadAsArray()
            ds = None

            #remove the temporary VRT, as it was created internally only
            for file in to_delete:
                os.remove(file)

        except Exception as ex:
        #if False:
            pathHdr = EnviSpectralLibraryIO.findENVIHeader(pathESL)

            pathTmpBin = tempfile.mktemp(prefix='tmpESL', suffix='.esl.bsq')
            pathTmpHdr = re.sub('bsq$','hdr',pathTmpBin)
            shutil.copyfile(pathESL, pathTmpBin)
            shutil.copyfile(pathHdr, pathTmpHdr)
            assert os.path.isfile(pathTmpBin)
            assert os.path.isfile(pathTmpHdr)

            import codecs
684
685
686
687
            file = codecs.open(pathTmpHdr, encoding='utf-8')
            hdr = file.readlines()
            file.close()

688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
            for iLine in range(len(hdr)):
                if re.search('file type =', hdr[iLine]):
                    hdr[iLine] = 'file type = ENVI Standard\n'
                    break
            file = codecs.open(pathTmpHdr, 'w', encoding='utf-8')
            file.writelines(hdr)
            file.flush()
            file.close()
            assert os.path.isfile(pathTmpHdr)
            hdr = EnviSpectralLibraryIO.readENVIHeader(pathTmpBin)
            ds = gdal.Open(pathTmpBin)
            data = ds.ReadAsArray()
            ds = None

            try:
                os.remove(pathTmpBin)
            except:
                pass
            try:
                os.remove(pathTmpHdr)
            except:
                pass
        assert data is not None




        nSpectra, nbands = data.shape
        valueUnit = ''
        valuePositionUnit = md.get('wavelength units')
        valuePositions = md.get('wavelength')
        if valuePositions is None:
            valuePositions = list(range(1, nbands+1))
            valuePositionUnit = 'Band'

        spectraNames = md.get('spectra names', ['Spectrum {}'.format(i+1) for i in range(nSpectra)])
        listAttributes = [(k, v) for k,v in md.items() \
                          if k not in ['spectra names','wavelength'] and \
                          isinstance(v, list) and len(v) == nSpectra]


        profiles = []
        for i, name in enumerate(spectraNames):
            p = SpectralProfile()
            p.setValues(data[i,:],
                        valueUnit=valueUnit,
                        valuePositions=valuePositions,
                        valuePositionUnit=valuePositionUnit)
            p.setName(name.strip())
            for listAttribute in listAttributes:
                p.setMetadata(listAttribute[0], listAttribute[1][i])
            p.setSource(pathESL)
            profiles.append(p)


        SLIB = SpectralLibrary()
        SLIB.addProfiles(profiles)
        return SLIB

    @staticmethod
    def write(speclib, path, ext='sli'):
749
        assert isinstance(path, str)
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
        dn = os.path.dirname(path)
        bn = os.path.basename(path)

        writtenFiles = []

        if bn.lower().endswith(ext.lower()):
            bn = os.path.splitext(bn)[0]

        if not os.path.isdir(dn):
            os.makedirs(dn)

        def value2hdrString(values):
            s = None
            maxwidth = 75

            if isinstance(values, list):
                lines = ['{']
                values = ['{}'.format(v).replace(',','-') for v in values]
                line = ' '
                l = len(values)
                for i, v in enumerate(values):
                    line += v
                    if i < l-1: line += ', '
                    if len(line) > maxwidth:
                        lines.append(line)
                        line = ' '
                line += '}'
                lines.append(line)
                s = '\n'.join(lines)

            else:
                s = '{}'.format(values)

783
            #strdata.normalize('NFKD', title).encode('ascii','ignore')
784
            #return s
785
            return s
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826


        for iGrp, grp in enumerate(speclib.groupBySpectralProperties().values()):

            wl = grp[0].xValues()
            wlu = grp[0].xUnit()


            # stack profiles
            pData = [np.asarray(p.yValues()) for p in grp]
            pData = np.vstack(pData)
            pNames = [p.name() for p in grp]

            if iGrp == 0:
                pathDst = os.path.join(dn, '{}.{}'.format(bn, ext))
            else:
                pathDst = os.path.join(dn, '{}.{}.{}'.format(bn, iGrp, ext))

            drv = gdal.GetDriverByName(str('ENVI'))
            assert isinstance(drv, gdal.Driver)


            eType = gdal_array.NumericTypeCodeToGDALTypeCode(pData.dtype)
            """Create(utf8_path, int xsize, int ysize, int bands=1, GDALDataType eType, char ** options=None) -> Dataset"""
            ds = drv.Create(pathDst, pData.shape[1], pData.shape[0], 1, eType)
            band = ds.GetRasterBand(1)
            assert isinstance(band, gdal.Band)
            band.WriteArray(pData)

            #ds = gdal_array.SaveArray(pData, pathDst, format='ENVI')

            assert isinstance(ds, gdal.Dataset)
            ds.SetDescription(str(speclib.name()))
            ds.SetMetadataItem(str('band names'), str('Spectral Library'), str('ENVI'))
            ds.SetMetadataItem(str('spectra names'),value2hdrString(pNames), str('ENVI'))
            ds.SetMetadataItem(str('wavelength'), value2hdrString(wl), str('ENVI'))
            ds.SetMetadataItem(str('wavelength units'), str(wlu), str('ENVI'))


            for a in speclib.metadataAttributes():
                v = value2hdrString([p.metadata(a) for p in grp])
827
                ds.SetMetadataItem(a, v, str('ENVI'))
828
829
830
831
832

            pathHdr = ds.GetFileList()[1]
            ds = None

            # last step: change ENVI Hdr
833
834
835
836
            file = open(pathHdr)
            hdr = file.readlines()
            file.close()

837
838
839
840
            for iLine in range(len(hdr)):
                if re.search('file type =', hdr[iLine]):
                    hdr[iLine] = 'file type = ENVI Spectral Library\n'
                    break
841

842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
            file = open(pathHdr, 'w')
            file.writelines(hdr)
            file.flush()
            file.close()
            writtenFiles.append(pathDst)

        return writtenFiles


    @staticmethod
    def esl2vrt(pathESL, pathVrt=None):
        """
        Creates a GDAL Virtual Raster (VRT) that allows to read an ENVI Spectral Library file
        :param pathESL: path ENVI Spectral Library file (binary part)
        :param pathVrt: (optional) path of created GDAL VRT.
        :return: GDAL VRT
        """

        hdr = EnviSpectralLibraryIO.readENVIHeader(pathESL, typeConversion=False)
        assert hdr is not None and hdr['file type'] == 'ENVI Spectral Library'

        if hdr.get('file compression') == '1':
            raise Exception('Can not read compressed spectral libraries')

        eType = LUT_IDL2GDAL[int(hdr['data type'])]
        xSize = int(hdr['samples'])
        ySize = int(hdr['lines'])
        bands = int(hdr['bands'])
        byteOrder = 'MSB' if hdr['byte order'] == 0 else 'LSB'

        if pathVrt is None:
            pathVrt = tempfile.mktemp(prefix='tmpESLVrt', suffix='.esl.vrt')

875

876
877
878
879
        ds = describeRawFile(pathESL, pathVrt, xSize, ySize, bands=bands, eType=eType, byteOrder=byteOrder)
        for key, value in hdr.items():
            if isinstance(value, list):
                value = u','.join(v for v in value)
Benjamin Jakimow's avatar
Benjamin Jakimow committed
880
            ds.SetMetadataItem(key, value, 'ENVI')
881
882
883
884
885
886
887
888
889
890
891
892
893
        ds.FlushCache()
        return ds


    @staticmethod
    def readENVIHeader(pathESL, typeConversion=False):
        """
        Reads an ENVI Header File (*.hdr) and returns its values in a dictionary
        :param pathESL: path to ENVI Header
        :param typeConversion: Set on True to convert header keys with numeric
        values into numeric data types (int / float)
        :return: dict
        """
894
        assert isinstance(pathESL, str)
895
896
897
898
899
900
901
902
903
        if not os.path.isfile(pathESL):
            return None

        pathHdr = EnviSpectralLibraryIO.findENVIHeader(pathESL)
        if pathHdr is None:
            return None

        import codecs
        #hdr = open(pathHdr).readlines()
904
905
906
907
        file = codecs.open(pathHdr, encoding='utf-8')
        hdr = file.readlines()
        file.close()

908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
        i = 0
        while i < len(hdr):
            if '{' in hdr[i]:
                while not '}' in hdr[i]:
                    hdr[i] = hdr[i] + hdr.pop(i + 1)
            i += 1

        hdr = [''.join(re.split('\n[ ]*', line)).strip() for line in hdr]
        # keep lines with <tag>=<value> structure only
        hdr = [line for line in hdr if re.search('^[^=]+=', line)]

        # restructure into dictionary of type
        # md[key] = single value or
        # md[key] = [list-of-values]
        md = dict()
        for line in hdr:
            tmp = line.split('=')
            key, value = tmp[0].strip(), '='.join(tmp[1:]).strip()
            if value.startswith('{') and value.endswith('}'):
                value = [v.strip() for v in value.strip('{}').split(',')]
            md[key] = value

        # check required metadata tegs
        for k in ['byte order', 'data type', 'header offset', 'lines', 'samples', 'bands']:
            if not k in md.keys():
                return None

        #todo: transform known strings into int/floats?
        def toType(t, arg):
            if isinstance(arg, list):
                return [toType(t, a) for a  in arg]
            else:
                return t(arg)

        if typeConversion:
            to_int = ['bands','lines','samples','data type','header offset','byte order']
            to_float = ['fwhm','wavelength', 'reflectance scale factor']
            for k in to_int:
                if k in md.keys():
                    md[k] = toType(int, md[k])
            for k in to_float:
                if k in md.keys():
                    md[k] = toType(float, md[k])


        return md

    @staticmethod
    def findENVIHeader(pathESL):
        paths = [os.path.splitext(pathESL)[0] + '.hdr', pathESL + '.hdr']
        pathHdr = None
        for p in paths:
            if os.path.exists(p):
                pathHdr = p
        return pathHdr


class SpectralLibraryPanel(QgsDockWidget):
Benjamin Jakimow's avatar
Benjamin Jakimow committed
966
    sigLoadFromMapRequest = None
967
968
    def __init__(self, parent=None):
        super(SpectralLibraryPanel, self).__init__(parent)
Benjamin Jakimow's avatar
Benjamin Jakimow committed
969
        self.setObjectName('spectralLibraryPanel')
970
971
972
973
        self.setWindowTitle('Spectral Library')
        self.SLW = SpectralLibraryWidget(self)
        self.setWidget(self.SLW)

974

975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
class SpectralLibraryVectorLayer(QgsVectorLayer):

    def __init__(self, speclib, crs=None):
        assert isinstance(speclib, SpectralLibrary)
        if crs is None:
            crs = QgsCoordinateReferenceSystem('EPSG:4326')

        uri = 'Point?crs={}'.format(crs.authid())
        super(SpectralLibraryVectorLayer, self).__init__(uri, speclib.name(), 'memory', False)
        self.mCrs = crs
        self.mSpeclib = speclib
        self.mSpeclib.sigNameChanged.connect(self.setName)
        self.nameChanged.connect(self.mSpeclib.setName)

        #todo QGIS3: use QgsFieldContraint instead self.mOIDs
        self.mOIDs = dict()


        #initialize fields
        assert self.startEditing()
        # standard field names, types, etc.
        fieldDefs = [('oid', QVariant.Int, 'integer'),
                     ('name', QVariant.String, 'string'),
                     ('geo_x', QVariant.Double, 'decimal'),
                     ('geo_y', QVariant.Double, 'decimal'),
                     ('px_x', QVariant.Int, 'integer'),
                     ('px_y', QVariant.Int, 'integer'),
                     ('source', QVariant.String, 'string'),
                     ]
        # initialize fields
        for fieldDef in fieldDefs:
            field = QgsField(fieldDef[0], fieldDef[1], fieldDef[2])
            self.addAttribute(field)
        self.commitChanges()

Benjamin Jakimow's avatar
Benjamin Jakimow committed
1010
1011
        self.mSpeclib.sigProfilesAdded[list].connect(self.onProfilesAdded)
        self.mSpeclib.sigProfilesRemoved[list].connect(self.onProfilesRemoved)
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
        self.onProfilesAdded(self.mSpeclib[:])

    def onProfilesAdded(self, profiles):
        for p in [p for p in profiles if p.geoCoordinate() is not None]:
            assert isinstance(p, SpectralProfile)
            oid = str(id(p))
            if oid in self.mOIDs.keys():
                continue
            geo = p.geoCoordinate().toCrs(self.mCrs)
            if isinstance(geo, SpatialPoint):
1022
                geometry = QgsPointXY(geo.x(), geo.y())
1023
1024
1025
                feature = QgsFeature(self.fields())
                feature.setGeometry(QgsGeometry(geometry))
                feature.setAttribute('oid', oid)
1026
                feature.setAttribute('name', str(p.name()))
1027
1028
                feature.setAttribute('geo_x', p.geoCoordinate().x())
                feature.setAttribute('geo_y', p.geoCoordinate().y())
1029
                feature.setAttribute('source', str(p.source()))
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044

                px = p.pxCoordinate()
                if isinstance(px, QPoint):
                    feature.setAttribute('px_x', px.x())
                    feature.setAttribute('px_y', px.y())

            self.startEditing()
            assert self.addFeature(feature)

            assert self.commitChanges()
            self.mOIDs[oid] = feature.id()
            self.updateExtents()

    def onProfilesRemoved(self, profiles):

1045
        oids = [str(id(p)) for p in profiles]
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
        oids = [o for o in oids if o in self.mOIDs.keys()]
        #fids = [self.mOIDs[o] for o in  oids]
        self.selectByExpression('"oid" in ({})'.format(','.join(oids)))
        self.deleteSelectedFeatures()


    def spectralLibrary(self):
        return self.mSpeclib

    def nSpectra(self):
        return len(self.mSpeclib)


class SpectralLibrary(QObject):
    _pickle_protocol = pickle.HIGHEST_PROTOCOL
    @staticmethod
    def readFromPickleDump(data):
        return pickle.loads(data)

    @staticmethod
    def readFromSourceDialog(parent=None):
        """
        Opens a FileOpen dialog to select
        :param parent:
        :return:
        """

1073
1074
        SETTINGS = settings()
        lastDataSourceDir = SETTINGS.value('_lastSpecLibSourceDir', '')
1075

1076
        if not QFileInfo(lastDataSourceDir).isDir():
1077
1078
            lastDataSourceDir = None

1079
        uris = QFileDialog.getOpenFileNames(parent, "Open spectral library", lastDataSourceDir, filter=FILTERS + ';;All files (*.*)', )
1080
1081
1082
        if isinstance(uris, tuple):
            uris = uris[0]

1083
1084
1085
        if len(uris) > 0:
            SETTINGS.setValue('_lastSpecLibSourceDir', os.path.dirname(uris[-1]))

1086
        uris = [u for u in uris if QFileInfo(u).isFile()]
1087
1088
        speclib = SpectralLibrary()
        for u in uris:
1089
            sl = SpectralLibrary.readFrom(str(u))
1090
1091
            if isinstance(sl, SpectralLibrary):
                speclib.addSpeclib(sl)
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
        return speclib

    @staticmethod
    def readFrom(uri):
        """
        Reads a Spectral Library from the source specified in "uri" (path, url, ...)
        :param uri: path or uri of the source from which to read SpectralProfiles and return them in a SpectralLibrary
        :return: SpectralLibrary
        """
        for cls in SpectralLibraryIO.__subclasses__():
            if cls.canRead(uri):
                return cls.readFrom(uri)
        return None


Benjamin Jakimow's avatar
Benjamin Jakimow committed
1107
1108
1109
1110
    sigProfilesAdded = pyqtSignal([list], [list, list])
    sigProfilesRemoved = pyqtSignal([list], [list, list])
    sigNameChanged = pyqtSignal(str)

1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
    def __init__(self, parent=None, profiles=None):
        super(SpectralLibrary, self).__init__(parent)

        self.mProfiles = []
        self.mName = ''
        if profiles is not None:
            self.mProfiles.extend(profiles[:])

    def setName(self, name):
        if name != self.mName:
            self.mName = name
            self.sigNameChanged.emit(name)

    def name(self):
        return self.mName

    def addSpeclib(self, speclib):
        assert isinstance(speclib, SpectralLibrary)
        self.addProfiles([p for p in speclib])


    def addProfile(self, profile):
        self.addProfiles([profile])

    def addProfiles(self, profiles, index=None):
        to_add = self.extractProfileList(profiles)
        to_add = [p for p in to_add if p not in self.mProfiles]
        if len(to_add) > 0:
            if index is None:
                index = len(self.mProfiles)
            self.mProfiles[index:index] = to_add
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1142
1143
1144
1145
1146

            indices = [self.mProfiles.index(p) for p in to_add]
            self.sigProfilesAdded[list].emit(to_add)
            self.sigProfilesAdded[list, list].emit(to_add, indices)

1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184

    def extractProfileList(self, profiles):
        if isinstance(profiles, SpectralProfile):
            profiles = [profiles]
        if isinstance(profiles, list):
            profiles = [p for p in profiles if isinstance(p, SpectralProfile)]
        elif isinstance(profiles, SpectralLibrary):
            profiles = profiles.mProfiles[:]
        else:
            raise Exception('Unknown type {}'.format(type(profiles)))
        return profiles


    def groupBySpectralProperties(self):
        """
        Groups the SpectralProfiles by:
            wavelength (xValues), wavelengthUnit (xUnit) and yUnit
        :return: {(xValues, wlU, yUnit):[list-of-profiles]}
        """

        d = dict()
        for p in self.mProfiles:
            #assert isinstance(p, SpectralProfile)
            id = (str(p.xValues()), str(p.xUnit()), str(p.yUnit()))
            if id not in d.keys():
                d[id] = list()
            d[id].append(p)
        return d

    def metadataAttributes(self):
        attributes = set()
        for p in self:
            for k in p.mMetadata.keys():
                attributes.add(k)
        return sorted(list(attributes))

    def renameMetadataAttribute(self,oldName, newName):
        assert oldName in self.metadataAttributes()
1185
1186
        assert isinstance(oldName, str)
        assert isinstance(newName, str)
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200

        for p in self:
            if oldName in p.mMetadata.keys:
                p.mMetadata[newName] = p.mMetadata.pop(oldName)

    def asTextLines(self, separator='\t'):
        return CSVSpectralLibraryIO.asTextLines(self, separator=separator)

    def asPickleDump(self):
        return pickle.dumps(self, SpectralLibrary._pickle_protocol)

    def exportProfiles(self, path=None):

        if path is None:
1201
1202

            path = QFileDialog.getSaveFileName(parent=None, caption="Save Spectral Library", filter=FILTERS)
1203
1204
            if isinstance(path, tuple):
                path = path[0]
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215

        if len(path) > 0:
            ext = os.path.splitext(path)[-1].lower()
            if ext in ['.sli','.esl']:
                EnviSpectralLibraryIO.write(self, path)

            if ext in ['.csv']:
                CSVSpectralLibraryIO.write(self, path, separator='\t')

            s = ""

Benjamin Jakimow's avatar
Benjamin Jakimow committed
1216

1217
1218
1219
1220
1221
1222
1223
    def removeProfiles(self, profiles):
        """
        Removes profiles from this ProfileSet
        :param profiles: Profile or [list-of-profiles] to be removed
        :return: [list-of-remove profiles] (only profiles that existed in this set before)
        """
        to_remove = self.extractProfileList(profiles)
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1224
1225
1226
1227

        indices_to_remove = sorted([self.mProfiles.index(p) for p in to_remove if p in self.mProfiles], reverse=True)
        to_remove = [self.mProfiles[i] for i in indices_to_remove]

1228
1229
1230
        if len(to_remove) > 0:
            for p in to_remove:
                self.mProfiles.remove(p)
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1231
1232
1233
1234
1235
1236
            self.sigProfilesRemoved[list].emit(to_remove)
            self.sigProfilesRemoved[list, list].emit(to_remove, indices_to_remove)

        s = ""


1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298

    def yRange(self):
        minY = min([min(p.yValues()) for p in self.mProfiles])
        maxY = max([max(p.yValues()) for p in self.mProfiles])
        return  minY, maxY

    def plot(self):
        import pyqtgraph as pg
        pg.mkQApp()

        win = pg.GraphicsWindow(title="Spectral Library")
        win.resize(1000, 600)

        # Enable antialiasing for prettier plots
        pg.setConfigOptions(antialias=True)

        # Create a plot with some random data
        p1 = win.addPlot(title="Spectral Library {}".format(self.name()), pen=0.5)
        yMin, yMax = self.yRange()
        p1.setYRange(yMin, yMax)

        # Add three infinite lines with labels
        for p in self:
            pi = pg.PlotDataItem(p.xValues(), p.yValues())
            p1.addItem(pi)

        pg.QAPP.exec_()

    def index(self, obj):
        return self.mProfiles.index(obj)

    def __reduce_ex__(self, protocol):
        return self.__class__, (), self.__getstate__()

    def __getstate__(self):
        return self.__dict__.copy()

    def __setstate__(self, state):
        self.__dict__.update(state)


    def __len__(self):
        return len(self.mProfiles)

    def __iter__(self):
        return iter(self.mProfiles)

    def __getitem__(self, slice):
        return self.mProfiles[slice]

    def __delitem__(self, slice):
        profiles = self[slice]
        self.removeProfiles(profiles)

    def __eq__(self, other):
        if not isinstance(other, SpectralLibrary):
            return False

        if len(self) != len(other):
            return False

        for p1, p2 in zip(self.__iter__(), other.__iter__()):
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1299
            if not p1.isEqual(p2):
1300
1301
1302
1303
1304
1305
                return False
        return True


class SpectralLibraryTableViewModel(QAbstractTableModel):

1306
1307
1308
    #sigPlotStyleChanged = pyqtSignal(SpectralProfile)
    #sigAttributeRemoved = pyqtSignal(str)
    #sigAttributeAdded = pyqtSignal(str)
1309
1310
1311
1312
1313
1314
1315
1316

    class ProfileWrapper(object):
        def __init__(self, profile):
            assert isinstance(profile, SpectralProfile)
            self.profile = profile
            self.style = QColor('white')
            self.checkState = Qt.Unchecked

Benjamin Jakimow's avatar
Benjamin Jakimow committed
1317
    def __init__(self, speclib=None, parent=None):
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
        super(SpectralLibraryTableViewModel, self).__init__(parent)

        self.cIndex = '#'
        self.cStyle = 'Style'
        self.cName = 'Name'
        self.cPxX = 'px x'
        self.cPxY = 'px y'
        self.cCRS = 'CRS'
        self.cGeoX = 'x'
        self.cGeoY = 'y'
        self.cSrc = 'Source'


        self.mAttributeColumns = []
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
        if speclib is None:
            speclib = SpectralLibrary()
        assert isinstance(speclib, SpectralLibrary)
        self.mSpecLib = speclib
        self.mSpecLib.sigProfilesAdded[list, list].connect(self.onProfilesAdded)
        self.mSpecLib.sigProfilesRemoved[list,list].connect(self.onProfilesRemoved)
        self.mProfileWrappers = list() #contains a wrapper for each SpectralProfile
        self.mProfileWrapperLUT = {}

        #add existing spectral profiles
        l = len(self.mSpecLib)
        if  l > 0:
            self.onProfilesAdded(self.mSpecLib[:], range(l))

    def onProfilesAdded(self, profiles, indices):


        for p, i in zip(profiles, indices):
            assert self.mSpecLib[i] == p
            self.beginInsertRows(QModelIndex(), i, i)
            w = SpectralLibraryTableViewModel.ProfileWrapper(p)
            self.mProfileWrappers.insert(i, w)
            self.mProfileWrapperLUT[p]=w
            self.endInsertRows()
        s = ""

    def onProfilesRemoved(self, profiles, indices):
        for i, p in zip(indices, profiles):
            idx = self.profile2idx(p)
            assert idx.row() == i
            self.beginRemoveRows(QModelIndex(), i, i)
            w = self.mProfileWrapperLUT[p]
            self.mProfileWrappers.remove(w)
            self.mProfileWrapperLUT.pop(p)
            self.endRemoveRows()

1368

1369
1370
    def addAttribute(self, name, i = None):
        assert isinstance(name, str)
1371
        if name != self.cName and name not in self.mAttributeColumns:
1372
1373
1374
1375
1376
            if i is None:
                i = len(self.mAttributeColumns)
            self.beginInsertColumns(QModelIndex(), i, i)
            self.mAttributeColumns.insert(i, name)
            self.endInsertColumns()
1377
1378

    def removeAttribute(self, name):
1379
        assert isinstance(name, str)
1380
1381

        if name in self.mAttributeColumns:
1382
1383
            i = self.mAttributeColumns
            self.beginRemoveColumns(QModelIndex(), i,i)
1384
1385
1386
1387
1388
            self.mAttributeColumns.remove(name)
            for s in self.mSpecLib:
                assert isinstance(s, SpectralProfile)
                if name in s.mMetadata.keys():
                    s.mMetadata.pop(name)
1389
            self.endRemoveColumns()
1390
1391
1392

    def columnNames(self):

1393
        return [self.cIndex, self.cStyle, self.cName] + self.mAttributeColumns + \
1394
1395
1396
               [self.cPxX, self.cPxY, self.cGeoX, self.cGeoY, self.cCRS, self.cSrc]


1397
    def insertProfiles(self, profiles, i=None):
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1398

1399
1400
1401
1402
1403
1404
        if isinstance(profiles, SpectralLibrary):
            profiles = profiles[:]

        if not isinstance(profiles, list):
            profiles =  [profiles]

Benjamin Jakimow's avatar
Benjamin Jakimow committed
1405
1406
        self.mSpecLib.addProfiles(profiles, index=i)

1407
1408


1409
    def removeProfiles(self, profiles):
1410
1411
        if isinstance(profiles, SpectralLibrary):
            profiles = profiles[:]
1412

1413
        profiles = [p for p in profiles if isinstance(p, SpectralProfile) and p in self.mSpecLib]
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1414
        self.mSpecLib.removeProfiles(profiles)
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424

    def headerData(self, col, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return self.columnNames()[col]
        elif orientation == Qt.Vertical and role == Qt.DisplayRole:
            return col
        return None

    def setHeaderData(self, col, orientation, newName, role=None):
        oldName = self.columnNames()[col]
1425
        assert isinstance(newName, str)
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
        if orientation == Qt.Horizontal:
            if role == Qt.EditRole and oldName in self.mAttributeColumns:
                self.mSpecLib.renameMetadataAttribute(oldName, newName)
                self.headerDataChanged.emit()
                return True
        return False


    def sort(self, col, order):
        """Sort table by given column number.
        """
1437
        return
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
        self.layoutAboutToBeChanged.emit()
        columnName = self.columnNames()[col]
        rev = order == Qt.DescendingOrder
        sortedProfiles = None
        profiles = self.mProfileWrappers.keys()
        if columnName == self.cName:
            sortedProfiles = sorted(profiles, key= lambda p: p.name(), reverse=rev)
        elif columnName == self.cSrc:
            sortedProfiles = sorted(profiles, key=lambda p: p.source(), reverse=rev)
        elif columnName == self.cIndex:
            sortedProfiles = sorted(profiles, key=lambda p: self.mSpecLib.index(p), reverse=rev)
        elif columnName in self.mAttributeColumns:
            sortedProfiles = sorted(profiles, key=lambda p: p.metadata(columnName), reverse=rev)
        if sortedProfiles is not None:
            tmp = OrderedDict([(p, self.mProfileWrappers[p]) for p in sortedProfiles])
            self.mProfileWrappers.clear()
            self.mProfileWrappers.update(tmp)
1455
        self.layoutChanged.emit()
1456
1457

    def rowCount(self, parentIdx=None, *args, **kwargs):
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1458
        return len(self.mProfileWrappers)
1459
1460
1461
1462
1463
1464

    def columnCount(self, QModelIndex_parent=None, *args, **kwargs):
        return len(self.columnNames())

    def profile2idx(self, profile):
        assert isinstance(profile, SpectralProfile)
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1465
1466
        w = self.mProfileWrapperLUT.get(profile)
        if not isinstance(w, SpectralLibraryTableViewModel.ProfileWrapper):
1467
            return None
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1468
1469
        else:
            return self.createIndex(self.mProfileWrappers.index(w), 0, profile)
1470

Benjamin Jakimow's avatar
Benjamin Jakimow committed
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
    def profiles2indices(self, profiles):
        """
        Returns a list of model-indices related to a list of profiles
        :param profiles: [list-of-SpectraProfiles]
        :return: [list-of-QModelIndices]
        """
        for p in profiles:
            assert isinstance(p, SpectralProfile)
        indices = [self.profile2idx(p) for p in profiles]
        indices = [i for i in indices if isinstance(i, QModelIndex)]
        return  indices
1482
1483

    def idx2profileWrapper(self, index):
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1484
1485
1486
1487
1488
        """
        Returns the profile-wrapper related to a model index
        :param index: QModelIndex
        :return: ProfileWrapper
        """
1489
1490
1491
1492
        assert isinstance(index, QModelIndex)
        if not index.isValid():
            return None

Benjamin Jakimow's avatar
Benjamin Jakimow committed
1493
1494
        return self.mProfileWrappers[index.row()]

1495
1496

    def indices2profiles(self, indices):
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1497
1498
1499
1500
1501
1502
1503
        """
        Returns a list of SpectralProfiles related to a list of QModelIndices
        :param indices: [list-of-QModelIndeices]
        :return: [list-of-SpectraProfiles]
        """
        profiles = [self.idx2profile(idx) for idx in indices]
        profiles = [p for p in profiles if isinstance(p, SpectralProfile)]
1504
1505
1506
1507
        return profiles


    def idx2profile(self, index):
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1508
1509
1510

        assert isinstance(index, QModelIndex)
        if not index.isValid():
1511
            return None
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1512
1513
        else:
            return self.mProfileWrappers[index.row()].profile
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553

    def data(self, index, role=Qt.DisplayRole):
        if role is None or not index.isValid():
            return None

        columnName = self.columnNames()[index.column()]
        profileWrapper = self.idx2profileWrapper(index)
        profile = profileWrapper.profile
        assert isinstance(profile, SpectralProfile)
        px = profile.pxCoordinate()
        geo = profile.geoCoordinate()
        value = None

        if role == Qt.DisplayRole:
            if columnName == self.cIndex:
                value = self.mSpecLib.index(profile)+1
            elif columnName == self.cName:
                value = profile.name()
            elif columnName == self.cSrc:
                value = profile.source()
            elif columnName in self.mAttributeColumns:
                value = profile.metadata(columnName)
                value = '' if value is None else value
            if px is not None:
                if columnName == self.cPxX:
                    value = profile.pxCoordinate().x()
                elif columnName == self.cPxY:
                    value = profile.pxCoordinate().y()

            if geo is not None:
                if columnName == self.cGeoX:
                    value = '{:0.10f}'.format(profile.geoCoordinate().x())
                elif columnName == self.cGeoY:
                    value = '{:0.10f}'.format(profile.geoCoordinate().y())
                elif columnName == self.cCRS:
                    value = profile.geoCoordinate().crs().authid()


        if role == Qt.BackgroundRole:
            if columnName == self.cStyle:
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1554
                return self.mProfileWrapperLUT[profile].style
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612

        if role == Qt.EditRole:
            if columnName == self.cName:
                value = profile.name()
            elif columnName in self.mAttributeColumns:
                value = profile.metadata(columnName)

        if role == Qt.UserRole:
            value = profile
        if role == Qt.CheckStateRole:
            if columnName == self.cIndex:
                value = profileWrapper.checkState
        return value


    def supportedDragActions(self):
        return Qt.CopyAction | Qt.MoveAction

    def supportedDropActions(self):
        return Qt.CopyAction | Qt.MoveAction


    def setData(self, index, value, role=None):
        if role is None or not index.isValid():
            return False
        assert isinstance(index, QModelIndex)
        cName = self.columnNames()[index.column()]
        profileWrapper = self.idx2profileWrapper(index)
        profile = profileWrapper.profile

        if role  == Qt.EditRole:
            if cName == self.cName:
                profile.setName(value)
                return True
            if cName in self.mAttributeColumns:
                profile.setMetadata(cName, value)

        if role == Qt.CheckStateRole:
            if cName == self.cIndex:
                profileWrapper.checkState = value
                return True
        if role == Qt.BackgroundRole:
            if cName == self.cStyle:
                profileWrapper.style = value
                return True

        return False

    def supportedDragActions(self):
        return Qt.CopyAction

    def supportedDropActions(self):
        return Qt.CopyAction

    def dropMimeData(self, mimeData, action, row, column, parent):
        assert isinstance(mimeData, QMimeData)
        assert isinstance(parent, QModelIndex)

Benjamin Jakimow's avatar
Benjamin Jakimow committed
1613
        if mimeData.hasFormat(mimedata.MDF_SPECTRALLIBRARY):
1614

Benjamin Jakimow's avatar
Benjamin Jakimow committed
1615
            dump = mimeData.data(mimedata.MDF_SPECTRALLIBRARY)
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
            speclib = SpectralLibrary.readFromPickleDump(dump)
            self.mSpecLib.addSpeclib(speclib)
            return True
        return False

    def mimeData(self, indexes):

        if len(indexes) == 0:
            return None

        profiles = self.indices2profiles(indexes)
        speclib = SpectralLibrary(profiles=profiles)
        mimeData = QMimeData()
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1629
        mimeData.setData(mimedata.MDF_SPECTRALLIBRARY, speclib.asPickleDump())
1630
1631
1632
1633
1634
1635
1636
1637
1638

        #as text
        mimeData.setText('\n'.join(speclib.asTextLines()))

        return mimeData

    def mimeTypes(self):
        # specifies the mime types handled by this model
        types = []
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1639
1640
1641
        types.append(mimedata.MDF_DATASOURCETREEMODELDATA)
        #types.append(mimedata.MDF_LAYERTREEMODELDATA)
        types.append(mimedata.MDF_URILIST)
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
        return types

    def flags(self, index):
        if index.isValid():
            columnName = self.columnNames()[index.column()]
            flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled | Qt.ItemIsDropEnabled
            if columnName in [self.cName] + self.mAttributeColumns:  # allow check state
                flags = flags | Qt.ItemIsEditable | Qt.ItemIsUserCheckable
            if columnName == self.cIndex:
                flags = flags | Qt.ItemIsUserCheckable
            return flags
        return None


1656
class UnitComboBoxItemModel(OptionListModel):
1657
1658
1659
1660
1661
    def __init__(self, parent=None):
        super(UnitComboBoxItemModel, self).__init__(parent)

    def addUnit(self, unit):

1662
1663
        o = Option(unit, unit)
        self.addOption(o)
1664
1665
1666


    def getUnitFromIndex(self, index):
1667
1668
1669
        o = self.idx2option(index)
        assert isinstance(o, Option)
        return o.mValue
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

    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid():
            return None

        if (index.row() >= len(self.mUnits)) or (index.row() < 0):
            return None
        unit = self.getUnitFromIndex(index)
        value = None
        if role == Qt.DisplayRole:
            value = '{}'.format(unit)
        return value



class SpectralLibraryWidget(QFrame, loadUI('spectrallibrarywidget.ui')):
    sigLoadFromMapRequest = pyqtSignal()

    def __init__(self, parent=None):
        super(SpectralLibraryWidget, self).__init__(parent)
        self.setupUi(self)

        self.mColorCurrentSpectra = QColor('green')
        self.mColorSelectedSpectra = QColor('yellow')

        self.m_plot_max = 500
1696
        self.mPlotXUnitModel = UnitComboBoxItemModel()
1697
1698
        self.mPlotXUnitModel.addUnit('Index')

1699
1700
1701
1702

        self.mPlotXUnitModel = OptionListModel()
        self.mPlotXUnitModel.addOption(Option('Index'))

1703
1704
1705
1706
1707
1708
        self.cbXUnit.setModel(self.mPlotXUnitModel)
        self.cbXUnit.currentIndexChanged.connect(lambda: self.setPlotXUnit(self.cbXUnit.currentText()))
        self.cbXUnit.setCurrentIndex(0)
        self.mSelectionModel = None

        self.mCurrentSpectra = []
1709
#        self.tableViewSpeclib.verticalHeader().setMovable(True)
1710
1711
1712
1713
1714
1715
        self.tableViewSpeclib.verticalHeader().setDragEnabled(True)
        self.tableViewSpeclib.verticalHeader().setDragDropMode(QAbstractItemView.InternalMove)
        self.tableViewSpeclib.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents)
        self.tableViewSpeclib.setAcceptDrops(True)
        self.tableViewSpeclib.setDropIndicatorShown(True)

1716
1717
        self.mModel = SpectralLibraryTableViewModel()
        self.mSpeclib = self.mModel.mSpecLib
1718
1719
1720

        self.mSpeclib.sigProfilesAdded.connect(self.onProfilesAdded)
        self.mSpeclib.sigProfilesRemoved.connect(self.onProfilesRemoved)
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1721
        self.mPlotDataItems = dict() #stores plotDataItems
1722

1723
1724
1725

        #self.mModel.sigAttributeAdded.connect(self.onAttributesChanged)
        #self.mModel.sigAttributeRemoved.connect(self.onAttributesChanged)
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738

        self.tableViewSpeclib.setModel(self.mModel)
        self.mSelectionModel = QItemSelectionModel(self.mModel)
        self.mSelectionModel.selectionChanged.connect(self.onSelectionChanged)
        #self.mSelectionModel.currentChanged.connect(self.onCurrentSelectionChanged)
        self.tableViewSpeclib.setSelectionModel(self.mSelectionModel)


        self.plotWidget.setAntialiasing(True)
        self.plotWidget.setAcceptDrops(True)

        self.plotWidget.dragEnterEvent = self.dragEnterEvent
        self.plotWidget.dragMoveEvent = self.dragMoveEvent
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1739
        self.plotWidget.dropEvent = self.dropEvent
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
        pi = self.plotWidget.getPlotItem()
        pi.setAcceptDrops(True)

        pi.dropEvent = self.dropEvent

        self.btnLoadFromFile.clicked.connect(lambda : self.addSpeclib(SpectralLibrary.readFromSourceDialog(self)))
        self.btnExportSpeclib.clicked.connect(self.onExportSpectra)

        self.btnAddCurrentToSpeclib.clicked.connect(self.addCurrentSpectraToSpeclib)

        self.btnLoadfromMap.clicked.connect(self.sigLoadFromMapRequest.emit)

        self.btnAddAttribute.clicked.connect(
            lambda :self.mModel.addAttribute(
                QInputDialog.getText(self, 'Add Attribute', 'Attribute', text='New Attribute')[0])
        )

        self.btnRemoveAttribute.setEnabled(len(self.mSpeclib) > 0)
        self.btnRemoveAttribute.clicked.connect(
            lambda : self.mModel.removeAttribute(
                QInputDialog.getItem(self, 'Delete Attribute', 'Attributes',
                                     self.mModel.mAttributeColumns, editable=False)[0]
            )
        )

    def setMapInteraction(self, b):
        assert isinstance(b, bool)
        if b is None or b is False:
            self.setCurrentSpectra(None)
        self.btnBoxMapInteraction.setEnabled(b)

    def mapInteraction(self):
        return self.btnBoxMapInteraction.isEnabled()

    def dragEnterEvent(self, event):
        assert isinstance(event, QDragEnterEvent)
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1776
        if event.mimeData().hasFormat(mimedata.MDF_SPECTRALLIBRARY):
1777
1778
1779
1780
            event.accept()

    def dragMoveEvent(self, event):
        assert isinstance(event, QDragMoveEvent)
Benjamin Jakimow's avatar
Benjamin Jakimow committed
1781
        if event.mimeData().hasFormat(mimedata.MDF_SPECTRALLIBRARY):
1782
1783
1784
1785
1786
1787
1788
            event.accept()


    def dropEvent(self, event):
        assert isinstance(event, QDropEvent)
        mimeData = event.mimeData()

Benjamin Jakimow's avatar
Benjamin Jakimow committed
1789
1790
        if mimeData.hasFormat(mimedata.MDF_SPECTRALLIBRARY):
            speclib = SpectralLibrary.readFromPickleDump(mimeData.data(mimedata.MDF_SPECTRALLIBRARY))
1791
1792
1793
1794
1795
1796
1797
            self.mSpeclib.addSpeclib(speclib)
            event.accept()

    def onAttributesChanged(self):
        self.btnRemoveAttribute.setEnabled(len(self.mSpeclib.metadataAttributes()) > 0)

    def addAttribute(self, name):
1798
        name = str(name)
1799
1800
1801
1802
        if len(name) > 0 and name not in self.mSpeclib.metadataAttributes():
            self.mModel.addAttribute(name)

    def setPlotXUnit(self, unit):
1803
        unit = str(unit)
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841

        pi = self.getPlotItem()
        if unit == 'Index':
            for pdi in pi.dataItems:

                assert isinstance(pdi, SpectralProfilePlotDataItem)
                p = pdi.mProfile
                pdi.setData(y=pdi.yData, x= p.valueIndexes())
                pdi.setVisible(True)
        else:
            #hide items that can not be presented in unit "unit"
            for pdi in pi.dataItems[:]:
                p = pdi.mProfile
                if pdi.mProfile.xUnit() != unit:
                    pdi.setVisible(False)
                else:
                    pdi.setData(y=pdi.yData, x=pdi.mProfile.xValues())
                    pdi.setVisible(True)
        pi.replot()
    def getPlotItem(self):
        pi = self.plotWidget.getPlotItem()
        assert isinstance(pi, pg.PlotItem)
        return pi

    def onExportSpectra(self, *args):
        self.mSpeclib.exportProfiles()


    def onProfilesAdded(self, profiles):
        # todo: remove some PDIs from plot if there are too many
        pi = self.getPlotItem()
        if True:
            to_remove = max(0</