Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
77
78
79
80
81
82
83
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
154
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
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
275
276
277
278
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
# -*- coding: utf-8 -*-
import os, sys, importlib, re, fnmatch, io, zipfile, pathlib, warnings, collections, copy, shutil
from qgis.core import *
from qgis.core import QgsFeature, QgsPointXY, QgsRectangle
from qgis.gui import *
from qgis.gui import QgisInterface, QgsDockWidget, QgsPluginManagerInterface
from qgis.PyQt.QtCore import *
from qgis.PyQt.QtCore import QMimeData
from qgis.PyQt.QtGui import *
from qgis.PyQt.QtWidgets import *
from qgis.PyQt.QtXml import *
from qgis.PyQt.QtXml import QDomDocument
from qgis.PyQt import uic
from osgeo import gdal
import numpy as np
from qps import resourcemockup
jp = os.path.join
dn = os.path.dirname
def rm(p):
"""
Removes the file or directory `p`
:param p: path of file or directory to be removed.
"""
if os.path.isfile(p):
os.remove(p)
elif os.path.isdir(p):
shutil.rmtree(p)
def cleanDir(d):
"""
Remove content from directory 'd'
:param d: directory to be cleaned.
"""
assert os.path.isdir(d)
for root, dirs, files in os.walk(d):
for p in dirs + files: rm(jp(root, p))
break
def mkDir(d, delete=False):
"""
Make directory.
:param d: path of directory to be created
:param delete: set on True to delete the directory contents, in case the directory already existed.
"""
if delete and os.path.isdir(d):
cleanDir(d)
if not os.path.isdir(d):
os.makedirs(d)
# for python development only. try to find a qgisresources directory
DIR_QGISRESOURCES = None
MAP_LAYER_STORES = [QgsProject.instance()]
def findUpwardPath(basepath, name, isDirectory=True):
"""
:param basepath:
:param name:
:param isDirectory:
:return:
"""
tmp = pathlib.Path(basepath)
while tmp != pathlib.Path(tmp.anchor):
if (isDirectory and os.path.isdir(tmp / name)) or \
os.path.isfile(tmp / name):
return str(tmp / name)
else:
tmp = tmp.parent
return None
DIR_QGISRESOURCES = findUpwardPath(__file__, 'qgisresources')
def file_search(rootdir, pattern, recursive=False, ignoreCase=False):
assert os.path.isdir(rootdir), "Path is not a directory:{}".format(rootdir)
regType = type(re.compile('.*'))
results = []
for root, dirs, files in os.walk(rootdir):
for file in files:
if isinstance(pattern, regType):
if pattern.search(file):
path = os.path.join(root, file)
results.append(path)
elif (ignoreCase and fnmatch.fnmatch(file.lower(), pattern.lower())) \
or fnmatch.fnmatch(file, pattern):
path = os.path.join(root, file)
results.append(path)
if not recursive:
break
pass
return results
UI_DIRECTORIES = []
if os.path.isdir(jp(dn(__file__), 'ui')):
UI_DIRECTORIES.append(jp(dn(__file__), 'ui'))
for f in file_search(os.path.dirname(__file__), '*.ui', recursive=True):
path = os.path.dirname(f)
if path not in UI_DIRECTORIES:
UI_DIRECTORIES.append(path)
def registerMapLayerStore(store):
"""
Registers an QgsMapLayerStore or QgsProject to search QgsMapLayers in
:param store: QgsProject | QgsMapLayerStore
"""
assert isinstance(store, (QgsProject, QgsMapLayerStore))
if store not in MAP_LAYER_STORES:
MAP_LAYER_STORES.append(store)
def registeredMapLayers()->list:
"""
Returns the QgsMapLayers which are stored in known QgsMapLayerStores
:return: [list-of-QgsMapLayers]
"""
layers = []
for store in MAP_LAYER_STORES:
for layer in store.mapLayers().values():
if layer not in layers:
layers.append(layer)
return layers
# Lookup tables
METRIC_EXPONENTS = {
"nm": -9, "um": -6, u"µm": -6, "mm": -3, "cm": -2, "dm": -1, "m": 0, "hm": 2, "km": 3
}
# add synonyms (lower-case)
METRIC_EXPONENTS['nanometers'] = METRIC_EXPONENTS['nm']
METRIC_EXPONENTS['micrometers'] = METRIC_EXPONENTS['μm'] = METRIC_EXPONENTS['um']
METRIC_EXPONENTS['millimeters'] = METRIC_EXPONENTS['mm']
METRIC_EXPONENTS['centimeters'] = METRIC_EXPONENTS['cm']
METRIC_EXPONENTS['decimeters'] = METRIC_EXPONENTS['dm']
METRIC_EXPONENTS['meters'] = METRIC_EXPONENTS['m']
METRIC_EXPONENTS['hectometers'] = METRIC_EXPONENTS['hm']
METRIC_EXPONENTS['kilometers'] = METRIC_EXPONENTS['km']
LUT_WAVELENGTH = dict({'B': 480,
'G': 570,
'R': 660,
'NIR': 850,
'SWIR': 1650,
'SWIR1': 1650,
'SWIR2': 2150
})
def mkdir(path):
if not os.path.isdir(path):
os.mkdir(path)
NEXT_COLOR_HUE_DELTA_CON = 10
NEXT_COLOR_HUE_DELTA_CAT = 100
def nextColor(color, mode='cat')->QColor:
"""
Returns another color.
:param color: QColor
:param mode: str, 'cat' for categorical colors (much difference from 'color')
'con' for continuous colors (similar to 'color')
:return: QColor
"""
assert mode in ['cat', 'con']
assert isinstance(color, QColor)
hue, sat, value, alpha = color.getHsl()
if mode == 'cat':
hue += NEXT_COLOR_HUE_DELTA_CAT
elif mode == 'con':
hue += NEXT_COLOR_HUE_DELTA_CON
if sat == 0:
sat = 255
value = 128
alpha = 255
s = ""
while hue > 360:
hue -= 360
return QColor.fromHsl(hue, sat, value, alpha)
def findMapLayer(layer)->QgsMapLayer:
"""
Returns the first QgsMapLayer out of all layers stored in MAP_LAYER_STORES that matches layer
:param layer: str layer id or layer name or QgsMapLayer
:return: QgsMapLayer
"""
assert isinstance(layer, (QgsMapLayer, str))
if isinstance(layer, QgsMapLayer):
return layer
elif isinstance(layer, str):
#check for IDs
for store in MAP_LAYER_STORES:
l = store.mapLayer(layer)
if isinstance(l, QgsMapLayer):
return l
#check for name
for store in MAP_LAYER_STORES:
l = store.mapLayersByName(layer)
if len(l) > 0:
return l[0]
return None
def qgisLayerTreeLayers() -> list:
"""
Returns the layers shown in the QGIS LayerTree
:return: [list-of-QgsMapLayers]
"""
iface = qgisAppQgisInterface()
if isinstance(iface, QgisInterface):
return [ln.layer() for ln in iface.layerTreeView().model().rootGroup().findLayers()]
else:
return []
def createQgsField(name : str, exampleValue, comment:str=None):
"""
Create a QgsField using a Python-datatype exampleValue
:param name: field name
:param exampleValue: value, can be any type
:param comment: (optional) field comment.
:return: QgsField
"""
t = type(exampleValue)
if t in [str]:
return QgsField(name, QVariant.String, 'varchar', comment=comment)
elif t in [bool]:
return QgsField(name, QVariant.Bool, 'int', len=1, comment=comment)
elif t in [int, np.int32, np.int64]:
return QgsField(name, QVariant.Int, 'int', comment=comment)
elif t in [float, np.double, np.float, np.float64]:
return QgsField(name, QVariant.Double, 'double', comment=comment)
elif isinstance(exampleValue, np.ndarray):
return QgsField(name, QVariant.String, 'varchar', comment=comment)
elif isinstance(exampleValue, list):
assert len(exampleValue)> 0, 'need at least one value in provided list'
v = exampleValue[0]
prototype = createQgsField(name, v)
subType = prototype.type()
typeName = prototype.typeName()
return QgsField(name, QVariant.List, typeName, comment=comment, subType=subType)
else:
raise NotImplemented()
def setQgsFieldValue(feature:QgsFeature, field, value):
"""
Wrties the Python value v into a QgsFeature field, taking care of required conversions
:param feature: QgsFeature
:param field: QgsField | field name (str) | field index (int)
:param value: any python value
"""
if isinstance(field, int):
field = feature.fields().at(field)
elif isinstance(field, str):
field = feature.fields().at(feature.fieldNameIndex(field))
assert isinstance(field, QgsField)
if value is None:
value = QVariant.NULL
if field.type() == QVariant.String:
value = str(value)
elif field.type() in [QVariant.Int, QVariant.Bool]:
value = int(value)
elif field.type() in [QVariant.Double]:
value = float(value)
else:
raise NotImplementedError()
# i = feature.fieldNameIndex(field.name())
feature.setAttribute(field.name(), value)
def showMessage(message:str, title:str, level):
"""
Shows a message using the QgsMessageViewer
:param message: str, message
:param title: str, title of viewer
:param level:
"""
v = QgsMessageViewer()
v.setTitle(title)
isHtml = message.startswith('<html>')
v.setMessage(message, QgsMessageOutput.MessageHtml if isHtml else QgsMessageOutput.MessageText)
v.showMessage(True)
def gdalDataset(pathOrDataset, eAccess=gdal.GA_ReadOnly):
"""
Returns a gdal.Dataset
:param pathOrDataset: path or gdal.Dataset
:return: gdal.Dataset
"""
if not isinstance(pathOrDataset, gdal.Dataset):
pathOrDataset = gdal.Open(pathOrDataset, eAccess)
assert isinstance(pathOrDataset, gdal.Dataset), 'Can not read {} as gdal.Dataset'.format(pathOrDataset)
return pathOrDataset
def loadUI(basename: str):
"""
Loads a UI using the basename ("file.ui") only.
Will search all directories specified in UI_DIRECTORIES
:param basename:
:return:
"""
assert isinstance(basename, str)
for pathDir in UI_DIRECTORIES:
assert isinstance(pathDir, str)
if os.path.isdir(pathDir):
pathUi = jp(pathDir, basename)
if os.path.isfile(pathUi):
return loadUIFormClass(pathUi)
raise Exception('Unable to find full path for "{}". Make its directory known to UI_DIRECTORIES'.format(basename))
# dictionary to store form classes and avoid multiple calls to read <myui>.ui
FORM_CLASSES = dict()
def loadUIFormClass(pathUi:str, from_imports=False, resourceSuffix:str='', fixQGISRessourceFileReferences=True, _modifiedui=None):
"""
Loads Qt UI files (*.ui) while taking care on QgsCustomWidgets.
Uses PyQt4.uic.loadUiType (see http://pyqt.sourceforge.net/Docs/PyQt4/designer.html#the-uic-module)
:param pathUi: *.ui file path
:param from_imports: is optionally set to use import statements that are relative to '.'. At the moment this only applies to the import of resource modules.
:param resourceSuffix: is the suffix appended to the basename of any resource file specified in the .ui file to create the name of the Python module generated from the resource file by pyrcc4. The default is '_rc', i.e. if the .ui file specified a resource file called foo.qrc then the corresponding Python module is foo_rc.
:return: the form class, e.g. to be used in a class definition like MyClassUI(QFrame, loadUi('myclassui.ui'))
"""
RC_SUFFIX = resourceSuffix
assert os.path.isfile(pathUi), '*.ui file does not exist: {}'.format(pathUi)
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
408
409
410
411
412
if pathUi not in FORM_CLASSES.keys():
#parse *.ui xml and replace *.h by qgis.gui
with open(pathUi, 'r') as f:
txt = f.read()
dirUi = os.path.dirname(pathUi)
locations = []
for m in re.findall(r'(<include location="(.*\.qrc)"/>)', txt):
locations.append(m)
missing = []
for t in locations:
line, path = t
if not os.path.isabs(path):
p = os.path.join(dirUi, path)
else:
p = path
if not os.path.isfile(p):
missing.append(t)
match = re.search(r'resource="[^:].*/QGIS[^/"]*/images/images.qrc"',txt)
if match:
txt = txt.replace(match.group(), 'resource=":/images/images.qrc"')
if len(missing) > 0:
missingQrc = []
missingQgs = []
for t in missing:
line, path = t
if re.search(r'.*(?i:qgis)/images/images\.qrc.*', line):
missingQgs.append(m)
else:
missingQrc.append(m)
if len(missingQrc) > 0:
print('{}\nrefers to {} none-existing resource (*.qrc) file(s):'.format(pathUi, len(missingQrc)))
for i, t in enumerate(missingQrc):
line, path = t
print('{}: "{}"'.format(i+1, path), file=sys.stderr)
if len(missingQgs) > 0 and not isinstance(qgisAppQgisInterface(), QgisInterface):
missingFiles = [p[1] for p in missingQrc if p[1] not in QGIS_RESOURCE_WARNINGS]
if len(missingFiles) > 0:
print('{}\nrefers to {} none-existing resource (*.qrc) file(s) '.format(pathUi, len(missingFiles)))
for i, path in enumerate(missingFiles):
print('{}: "{}"'.format(i+1, path))
print('These files are likely available in a QGIS Desktop session. Further warnings will be skipped')
420
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
462
463
464
465
466
467
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
doc = QDomDocument()
doc.setContent(txt)
elem = doc.elementsByTagName('customwidget')
for child in [elem.item(i) for i in range(elem.count())]:
child = child.toElement()
className = str(child.firstChildElement('class').firstChild().nodeValue())
if className.startswith('Qgs'):
cHeader = child.firstChildElement('header').firstChild()
cHeader.setNodeValue('qgis.gui')
# collect resource file locations
elems = doc.elementsByTagName('include')
qrcPaths = []
for i in range(elems.count()):
node = elems.item(i).toElement()
lpath = node.attribute('location')
if len(lpath) > 0 and lpath.endswith('.qrc'):
p = lpath
if not os.path.isabs(lpath):
p = os.path.join(dirUi, lpath)
else:
p = lpath
qrcPaths.append(p)
buffer = io.StringIO() # buffer to store modified XML
if isinstance(_modifiedui, str):
f = open(_modifiedui, 'w', encoding='utf-8')
f.write(doc.toString())
f.flush()
f.close()
buffer.write(doc.toString())
buffer.flush()
buffer.seek(0)
#if existent, make resource file directories available to the python path (sys.path)
baseDir = os.path.dirname(pathUi)
tmpDirs = []
if True:
for qrcPath in qrcPaths:
d = os.path.abspath(os.path.join(baseDir, qrcPath))
d = os.path.dirname(d)
if os.path.isdir(d) and d not in sys.path:
tmpDirs.append(d)
sys.path.extend(tmpDirs)
#create requried mockups
if True:
FORM_CLASS_MOCKUP_MODULES = [os.path.splitext(os.path.basename(p))[0] for p in qrcPaths]
FORM_CLASS_MOCKUP_MODULES = [m for m in FORM_CLASS_MOCKUP_MODULES if m not in sys.modules.keys()]
for mockupModule in FORM_CLASS_MOCKUP_MODULES:
#print('ADD MOCKUP MODULE {}'.format(mockupModule))
sys.modules[mockupModule] = resourcemockup
#load form class
try:
FORM_CLASS, _ = uic.loadUiType(buffer, resource_suffix=RC_SUFFIX)
except Exception as ex1:
print(doc.toString(), file=sys.stderr)
info = 'Unable to load {}'.format(pathUi) + '\n{}'.format(str(ex1))
ex = Exception(info)
raise ex
for mockupModule in FORM_CLASS_MOCKUP_MODULES:
if mockupModule in sys.modules.keys():
sys.modules.pop(mockupModule)
buffer.close()
FORM_CLASSES[pathUi] = FORM_CLASS
#remove temporary added directories from python path
for d in tmpDirs:
sys.path.remove(d)
if pathUi.endswith('spectrallibrarywidget.ui'):
s =""
return FORM_CLASSES[pathUi]
def typecheck(variable, type_):
if isinstance(type_, list):
for i in range(len(type_)):
typecheck(variable[i], type_[i])
else:
assert isinstance(variable, type_)
# thanks to https://gis.stackexchange.com/questions/75533/how-to-apply-band-settings-using-gdal-python-bindings
def read_vsimem(fn):
"""
Reads VSIMEM path as string
:param fn: vsimem path (str)
:return: result of gdal.VSIFReadL(1, vsileng, vsifile)
"""
vsifile = gdal.VSIFOpenL(fn,'r')
gdal.VSIFSeekL(vsifile, 0, 2)
vsileng = gdal.VSIFTellL(vsifile)
gdal.VSIFSeekL(vsifile, 0, 0)
return gdal.VSIFReadL(1, vsileng, vsifile)
def write_vsimem(fn:str,data:str):
"""
Writes data to vsimem path
:param fn: vsimem path (str)
:param data: string to write
:return: result of gdal.VSIFCloseL(vsifile)
"""
'''Write GDAL vsimem files'''
vsifile = gdal.VSIFOpenL(fn,'w')
size = len(data)
gdal.VSIFWriteL(data, 1, size, vsifile)
return gdal.VSIFCloseL(vsifile)
from collections import defaultdict
import weakref
class KeepRefs(object):
__refs__ = defaultdict(list)
def __init__(self):
self.__refs__[self.__class__].append(weakref.ref(self))
@classmethod
def instances(cls):
for inst_ref in cls.__refs__[cls]:
inst = inst_ref()
if inst is not None:
yield inst
def appendItemsToMenu(menu, itemsToAdd):
"""
Appends items to QMenu "menu"
:param menu: the QMenu to be extended
:param itemsToAdd: QMenu or [list-of-QActions-or-QMenus]
:return: menu
"""
assert isinstance(menu, QMenu)
if isinstance(itemsToAdd, QMenu):
itemsToAdd = itemsToAdd.children()[1:]
if not isinstance(itemsToAdd, list):
itemsToAdd = [itemsToAdd]
for item in itemsToAdd:
if isinstance(item, QAction):
item.setParent(menu)
menu.addAction(item)
s = ""
elif isinstance(item, QMenu):
# item.setParent(menu)
sub = menu.addMenu(item.title())
sub.setIcon(item.icon())
appendItemsToMenu(sub, item.children()[1:])
else:
s = ""
return menu
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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
def toVectorLayer(src) -> QgsVectorLayer:
"""
Returns a QgsRasterLayer if it can be extracted from src
:param src: any type of input
:return: QgsRasterLayer or None
"""
lyr = None
try:
if isinstance(src, str):
lyr = QgsVectorLayer(src)
elif isinstance(src, QgsMimeDataUtils.Uri):
lyr, b = src.vectorLayer()
if not b:
lyr = None
if isinstance(src, ogr.DataSource):
path = src.GetDescription()
bn = os.path.basename(path)
lyr = QgsVectorLayer(path, bn, 'ogr')
elif isinstance(src, QgsVectorLayer):
lyr = src
except Exception as ex:
print(ex)
return lyr
def toDataset(src, readonly=True)->gdal.Dataset:
"""
Returns a gdal.Dataset if it can be extracted from src
:param src: input source
:param readonly: bool, true by default, set False to upen the gdal.Dataset in update mode
:return: gdal.Dataset
"""
ga = gdal.GA_ReadOnly if readonly else gdal.GA_Update
if isinstance(src, str):
return gdal.Open(src, ga)
elif isinstance(src, QgsRasterLayer) and src.dataProvider().name() == 'gdal':
return toDataset(src.source(), readonly=readonly)
elif isinstance(src, gdal.Dataset):
return src
else:
return None
def toQgsMimeDataUtilsUri(mapLayer:QgsMapLayer)->QgsMimeDataUtils.Uri:
"""
Creates a QgsMimeDataUtils.Uri that describes the QgsMapLayer `mapLayer`
:param mapLayer: QgsMapLayer
:return: QgsMimeDataUtils.Uri
"""
assert isinstance(mapLayer, QgsMapLayer)
uri = QgsMimeDataUtils.Uri()
uri.uri = mapLayer.source()
uri.name = mapLayer.name()
if uri.name == '':
uri.name = os.path.basename(uri.uri)
uri.providerKey = mapLayer.dataProvider().name()
if isinstance(mapLayer, QgsRasterLayer):
uri.layerType = 'raster'
elif isinstance(mapLayer, QgsVectorLayer):
uri.layerType = 'vector'
elif isinstance(mapLayer, QgsPluginLayer):
uri.layerType = 'plugin'
else:
raise NotImplementedError()
return uri
def toMapLayer(src)->QgsMapLayer:
"""
Return a QgsMapLayer if it can be extracted from src
:param src: any type of input
:return: QgsMapLayer
"""
lyr = toRasterLayer(src)
if isinstance(lyr, QgsMapLayer):
return lyr
lyr = toVectorLayer(src)
if isinstance(lyr, QgsMapLayer):
return lyr
return lyr
def toRasterLayer(src) -> QgsRasterLayer:
"""
Returns a QgsRasterLayer if it can be extracted from src
:param src: any type of input
:return: QgsRasterLayer or None
"""
lyr = None
try:
if isinstance(src, str):
lyr = QgsRasterLayer(src)
elif isinstance(src, QgsMimeDataUtils.Uri):
lyr, b = src.rasterLayer('')
if not b:
lyr = None
elif isinstance(src, gdal.Dataset):
lyr = QgsRasterLayer(src.GetFileList()[0], '', 'gdal')
elif isinstance(src, QgsMapLayer) :
lyr = src
elif isinstance(src, gdal.Band):
return toRasterLayer(src.GetDataset())
except Exception as ex:
print(ex)
if isinstance(lyr, QgsRasterLayer) and lyr.isValid():
return lyr
else:
return None
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
749
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
783
784
785
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
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
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
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
966
967
968
969
970
971
972
973
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
def allSubclasses(cls):
"""
Returns all subclasses of class 'cls'
Thx to: http://stackoverflow.com/questions/3862310/how-can-i-find-all-subclasses-of-a-class-given-its-name
:param cls:
:return:
"""
return cls.__subclasses__() + [g for s in cls.__subclasses__()
for g in allSubclasses(s)]
def check_package(name, package=None, stop_on_error=False):
try:
importlib.import_module(name, package)
except Exception as e:
if stop_on_error:
raise Exception('Unable to import package/module "{}"'.format(name))
return False
return True
def zipdir(pathDir, pathZip):
"""
:param pathDir: directory to compress
:param pathZip: path to new zipfile
"""
# thx to https://stackoverflow.com/questions/1855095/how-to-create-a-zip-archive-of-a-directory
"""
import zipfile
assert os.path.isdir(pathDir)
zipf = zipfile.ZipFile(pathZip, 'w', zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(pathDir):
for file in files:
zipf.write(os.path.join(root, file))
zipf.close()
"""
relroot = os.path.abspath(os.path.join(pathDir, os.pardir))
with zipfile.ZipFile(pathZip, "w", zipfile.ZIP_DEFLATED) as zip:
for root, dirs, files in os.walk(pathDir):
# add directory (needed for empty dirs)
zip.write(root, os.path.relpath(root, relroot))
for file in files:
filename = os.path.join(root, file)
if os.path.isfile(filename): # regular files only
arcname = os.path.join(os.path.relpath(root, relroot), file)
zip.write(filename, arcname)
def convertMetricUnit(value: float, u1: str, u2: str)->float:
"""
Converts value `value` from unit `u1` into unit `u2`
:param value: float | int | might work with numpy.arrays as well
:param u1: str, identifier of unit 1
:param u2: str, identifier of unit 2
:return: float | numpy.array, converted values
or None in case conversion is not possible
"""
assert isinstance(u1, str)
assert isinstance(u2, str)
u1 = u1.lower()
u2 = u2.lower()
e1 = METRIC_EXPONENTS.get(u1)
e2 = METRIC_EXPONENTS.get(u2)
if all([arg is not None for arg in [value, e1, e2]]):
if e1 == e2:
return copy.copy(value)
elif isinstance(value, list):
return [v * 10 ** (e1-e2) for v in value]
else:
return value * 10 ** (e1 - e2)
else:
return None
def displayBandNames(rasterSource, bands=None, leadingBandNumber=True):
"""
Returns a list of readable band names from a raster source.
Will use "Band 1" ff no band name is defined.
:param rasterSource: QgsRasterLayer | gdal.DataSource | str
:param bands:
:return:
"""
if isinstance(rasterSource, str):
return displayBandNames(QgsRasterLayer(rasterSource), bands=bands, leadingBandNumber=leadingBandNumber)
if isinstance(rasterSource, QgsRasterLayer):
if not rasterSource.isValid():
return None
else:
return displayBandNames(rasterSource.dataProvider(), bands=bands, leadingBandNumber=leadingBandNumber)
if isinstance(rasterSource, gdal.Dataset):
#use gdal.Band.GetDescription() for band name
results = []
if bands is None:
bands = range(1, rasterSource.RasterCount + 1)
for band in bands:
b = rasterSource.GetRasterBand(band)
name = b.GetDescription()
if len(name) == 0:
name = 'Band {}'.format(band)
if leadingBandNumber:
name = '{}:{}'.format(band, name)
results.append(name)
return results
if isinstance(rasterSource, QgsRasterDataProvider):
if rasterSource.name() == 'gdal':
ds = gdal.Open(rasterSource.dataSourceUri())
return displayBandNames(ds, bands=bands, leadingBandNumber=leadingBandNumber)
else:
#in case of WMS and other data providers use QgsRasterRendererWidget::displayBandName
results = []
if bands is None:
bands = range(1, rasterSource.bandCount() + 1)
for band in bands:
name = rasterSource.generateBandName(band)
colorInterp ='{}'.format(rasterSource.colorInterpretationName(band))
if colorInterp != 'Undefined':
name += '({})'.format(colorInterp)
if leadingBandNumber:
name = '{}:{}'.format(band, name)
results.append(name)
return results
return None
def defaultBands(dataset):
"""
Returns a list of 3 default bands
:param dataset:
:return:
"""
if isinstance(dataset, str):
return defaultBands(gdal.Open(dataset))
elif isinstance(dataset, QgsRasterDataProvider):
return defaultBands(dataset.dataSourceUri())
elif isinstance(dataset, QgsRasterLayer):
return defaultBands(dataset.source())
elif isinstance(dataset, gdal.Dataset):
db = dataset.GetMetadataItem(str('default_bands'), str('ENVI'))
if db != None:
db = [int(n) for n in re.findall(r'\d+')]
return db
db = [0, 0, 0]
cis = [gdal.GCI_RedBand, gdal.GCI_GreenBand, gdal.GCI_BlueBand]
for b in range(dataset.RasterCount):
band = dataset.GetRasterBand(b + 1)
assert isinstance(band, gdal.Band)
ci = band.GetColorInterpretation()
if ci in cis:
db[cis.index(ci)] = b
if db != [0, 0, 0]:
return db
rl = QgsRasterLayer(dataset.GetFileList()[0])
defaultRenderer = rl.renderer()
if isinstance(defaultRenderer, QgsRasterRenderer):
db = defaultRenderer.usesBands()
if len(db) == 0:
return [0, 1, 2]
if len(db) > 3:
db = db[0:3]
db = [b-1 for b in db]
return db
else:
raise Exception()
def bandClosestToWavelength(dataset, wl, wl_unit='nm'):
"""
Returns the band index of an image dataset closest to wavelength `wl`.
:param dataset: str | gdal.Dataset
:param wl: wavelength to search the closed band for
:param wl_unit: unit of wavelength. Default = nm
:return: band index | 0 of wavelength information is not provided
"""
if isinstance(wl, str):
assert wl.upper() in LUT_WAVELENGTH.keys(), wl
return bandClosestToWavelength(dataset, LUT_WAVELENGTH[wl.upper()], wl_unit='nm')
else:
try:
wl = float(wl)
ds_wl, ds_wlu = parseWavelength(dataset)
if ds_wl is None or ds_wlu is None:
return 0
if ds_wlu != wl_unit:
wl = convertMetricUnit(wl, wl_unit, ds_wlu)
return int(np.argmin(np.abs(ds_wl - wl)))
except:
pass
return 0
def parseWavelength(dataset):
"""
Returns the wavelength + wavelength unit of a dataset
:param dataset:
:return: (wl, wl_u) or (None, None), if not existing
"""
wl = None
wlu = None
if isinstance(dataset, str):
return parseWavelength(gdal.Open(dataset))
elif isinstance(dataset, QgsRasterDataProvider):
return parseWavelength(dataset.dataSourceUri())
elif isinstance(dataset, QgsRasterLayer):
if dataset.dataProvider().name() == 'gdal':
return parseWavelength(gdal.Open(dataset.source()))
else:
return None, None
elif isinstance(dataset, gdal.Dataset):
for domain in dataset.GetMetadataDomainList():
# see http://www.harrisgeospatial.com/docs/ENVIHeaderFiles.html for supported wavelength units
mdDict = dataset.GetMetadata_Dict(domain)
for key, values in mdDict.items():
key = key.lower()
if re.search(r'wavelength$', key, re.I):
tmp = re.findall(r'\d*\.\d+|\d+', values) # find floats
if len(tmp) != dataset.RasterCount:
tmp = re.findall(r'\d+', values) # find integers
if len(tmp) == dataset.RasterCount:
wl = np.asarray([float(w) for w in tmp])
if re.search(r'wavelength.units?', key):
if re.search(r'(Micrometers?|um)', values, re.I):
wlu = 'um' # fix with python 3 UTF
elif re.search(r'(Nanometers?|nm)', values, re.I):
wlu = 'nm'
elif re.search(r'(Millimeters?|mm)', values, re.I):
wlu = 'nm'
elif re.search(r'(Centimeters?|cm)', values, re.I):
wlu = 'nm'
elif re.search(r'(Meters?|m)', values, re.I):
wlu = 'nm'
elif re.search(r'Wavenumber', values, re.I):
wlu = '-'
elif re.search(r'GHz', values, re.I):
wlu = 'GHz'
elif re.search(r'MHz', values, re.I):
wlu = 'MHz'
elif re.search(r'Index', values, re.I):
wlu = '-'
else:
wlu = '-'
if wl is not None and len(wl) > dataset.RasterCount:
wl = wl[0:dataset.RasterCount]
return wl, wlu
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
def qgisAppQgisInterface()->QgisInterface:
"""
Returns the QgisInterface of the QgisApp in case everything was started from within the QGIS Main Application
:return: QgisInterface | None in case the qgis.utils.iface points to another QgisInterface (e.g. the EnMAP-Box itself)
"""
try:
import qgis.utils
if not isinstance(qgis.utils.iface, QgisInterface):
return None
mainWindow = qgis.utils.iface.mainWindow()
if not isinstance(mainWindow, QMainWindow) or mainWindow.objectName() != 'QgisApp':
return None
return qgis.utils.iface
except:
return None