-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathGroupStatsDialog.py
1099 lines (877 loc) · 50.7 KB
/
GroupStatsDialog.py
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
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
408
409
410
411
412
413
414
415
416
417
418
419
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
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
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
# -*- coding: utf-8 -*-
import csv
import os
import pickle
import sys
import webbrowser
from math import *
from PyQt5 import uic
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QApplication, QFileDialog, QMainWindow, QMessageBox, QTableView, QWidget
from qgis.core import *
from qgis.gui import *
FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'ui_groupstats.ui'))
class GroupStatsDialog(QMainWindow):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.ui = FORM_CLASS()
self.ui.setupUi(self)
self.ui.result = WindowResults(self.ui.centralwidget)
self.ui.horizontalLayout.addWidget(self.ui.result)
self.calculations = Calculations(self)
self.ui.listHalf.setAcceptDrops(True)
self.ui.listHalf.setModelColumn(2)
self.ui.rows.setAcceptDrops(True)
self.ui.columns.setAcceptDrops(True)
self.ui.values.setAcceptDrops(True)
self.ui.calculate.clicked.connect(self.showScore)
self.ui.clear.clicked.connect(self.clearChoice)
self.ui.filterButton.clicked.connect(self.setFilter)
self.ui.layer.currentIndexChanged.connect(self.layerSelection) # Layer selection signal
dictionary = {'attributeTxt':[('Rejon',1), ('Posterunek',2)],
'countAttributes':[('Moc stacji', 3)],
'geometry':[('Length', 1), ('Area', 2)],
'calculations':[('Count', 1), ('Sum', 2), ('Average', 3), ('Standard deviation', 4)]}
self.tm1 = ModelListaPol(self)
self.ui.listHalf.setModel(self.tm1)
self.tm2 = ModelRowsColumns(self)
#tm2.ustawInneModele(tm1)
self.ui.rows.setModel(self.tm2)
self.tm3 = ModelRowsColumns(self)
#tm3.ustawInneModele(tm1)
self.ui.columns.setModel(self.tm3)
self.tm4 = ValueModel(self)
self.ui.values.setModel(self.tm4)
self.tm2.setOtherModels(self.tm3, self.tm4)
self.tm3.setOtherModels(self.tm2, self.tm4)
self.tm4.setOtherModels(self.tm2, self.tm3)
self.tm2.rowsInserted.connect(self.blockCalculations) # Layer selection signal
self.tm3.rowsInserted.connect(self.blockCalculations) # Layer selection signal
self.tm4.rowsInserted.connect(self.blockCalculations) # Layer selection signal
self.tm2.rowsRemoved.connect(self.blockCalculations) # Layer selection signal
self.tm3.rowsRemoved.connect(self.blockCalculations) # Layer selection signal
self.tm4.rowsRemoved.connect(self.blockCalculations) # Layer selection signal
self.ui.actionCopy.triggered.connect(self.duplication) # Layer selection signal
self.ui.actionCopySelected.triggered.connect(self.copyMarked) # Layer selection signal
self.ui.actionSaveCSV.triggered.connect(self.exportToCSV) # Layer selection signal
self.ui.actionSaveCSVSelected.triggered.connect(self.exportMarkedToCSV) # Layer selection signal
self.ui.actionShowPanel.triggered.connect(self.showControlPanel) # Layer selection signal
self.ui.actionShowOnMap.triggered.connect(self.showOnMap) # Layer selection signal
self.ui.actionTutorial.triggered.connect(self.showTutorial) # Layer selection signal
self.ui.result.verticalHeader().sortIndicatorChanged.connect(self.sortRows) # Layer selection signal
def sortRows(self, row, mode):
self.ui.result.model().sortRows(row, mode)
def blockCalculations(self, x, y, z): #finished
values = self.tm4._data
columns = self.tm3._data
rows = self.tm2._data
# If the value field has numbers (attributes or geometry) and some calculate function has been selected
if ('geometry' in [a[0] for a in values] or 'countAttributes' in [a[0] for a in values]) and\
'calculations' in [a[0] for a in values+rows+columns]:
self.ui.calculate.setEnabled(True)
# If the value field has a text attribute and you have selected exactly one function - the counter
elif 'attributeTxt' in [a[0] for a in values] and len([a for a in values+rows+columns if a[0]=='calculations'])>0:
if set([a[2] for a in values+rows+columns if a[0]=='calculations']).issubset(set(self.calculations.textList)): #[a for a in values+rows+columns if a[0]=='calculations'][0][2]==0:
self.ui.calculate.setEnabled(True)
else:
self.ui.calculate.setEnabled(False)
def showScore(self): #finished
"Performs calculations and sends them for display"
chosenRows = tuple(self.tm2._data) # Reading selected rows from the window
chosenColumns = tuple(self.tm3._data) # Reading selected columns from the window
chosenValues = tuple(self.tm4._data) # Reading from the window chosenj values and calculations
value = [x for x in chosenValues if x[0]!='calculations'][0] # reading the field that has been chosen for calculation (can only be one)
if value[0]=='geometry': # Setting the calculate function depending on the chosen value type
if value[2]==1:
valueFunction = lambda _object: _object.geometry().length() # length
elif value[2]==2:
valueFunction = lambda _object: _object.geometry().area() # area
elif value[0]=='attributeTxt':
valueFunction = lambda _object: None if _object.attribute(value[1]) is None else _object.attribute(value[1])#.toString() # text attribute
elif value[0]=='countAttributes':
valueFunction = lambda _object: None if _object.attribute(value[1]) is None or (
isinstance(_object.attribute(value[1]), QVariant) and
_object.attribute(value[1]).isNull()) else (float(_object.attribute(value[1]).value())
if isinstance(_object.attribute(value[1]), QVariant) else float(_object.attribute(value[1])))
index = self.ui.layer.currentIndex() # Download chosen layer
layerId = self.ui.layer.itemData(index)
layer = QgsProject.instance().mapLayer(layerId)#.toString())
provider = layer.dataProvider()
request = QgsFeatureRequest()
_filter = self.ui._filter.toPlainText()
if _filter:
request.setFilterExpression(_filter)
iterator = provider.getFeatures(request)
if self.ui.onlySelected.isChecked(): # Retrieve the IDs of the selected _objects
selectedObjects = layer.selectedFeatureIds()
onlySelected = True
else:
selectedObjects = []
onlySelected = False
result = {} # results translator {((row) (column)): [[values], [indexes]}
f=QgsFeature() # Searching for calculation data
numberOfObjects = provider.featureCount()
if numberOfObjects != 0:
percent = 100.00 / numberOfObjects # Number of _objects
else:
percent = 100
counter = 0.0
NULLcounter = 0
while iterator.nextFeature(f): # for each object ...
if onlySelected==False or (onlySelected and (f.id() in selectedObjects)):
key_column = [] # key column (column1, column2...)
key_row = [] # key row (rows1, rows2...)
key = ()
for k in chosenColumns: # for each chosen column we check the column type
if k[0]=='geometry': # and create the key column
if k[2]==1:
key_column.append(f.geometry().length())
elif k[2]==2:
key_column.append(f.geometry().area())
elif k[0]=='attributeTxt' or k[0]=='countAttributes':
if f.attribute(k[1]) == None:
newKeyColumns = ''
else:
newKeyColumns = f.attribute(k[1])
key_column.append(newKeyColumns)#.toString())
for k in chosenRows: # for each chosen rows we check the rows type
if k[0]=='geometry': # and create key rows
if k[2]==1:
key_row.append(f.geometry().length())
elif k[2]==2:
key_row.append(f.geometry().area())
elif k[0]=='attributeTxt' or k[0]=='countAttributes':
if f.attribute(k[1]) == None:
newRowKey = ''
else:
newRowKey = f.attribute(k[1])
key_row.append(newRowKey)
key = ( tuple(key_row) , tuple(key_column) ) # key to identify object groups
valueToCalculate = valueFunction(f)
if valueToCalculate!=None or self.ui.useNULL.isChecked():
if valueToCalculate==None:
NULLcounter += 1
if value[0]=='countAttributes':
valueToCalculate=0
if key in result:
result[key][0].append(valueToCalculate) # if key exists, a new value is added to the list
else:
result[key] = [[valueToCalculate],[]] # if key does not exist then a new list is created
result[key][1].append(f.id())
else:
NULLcounter += 1
counter = counter + percent
self.statusBar().showMessage(QCoreApplication.translate('GroupStats','Calculate... ') + '%.0f%%' % (counter)) # Displaying progress
self.statusBar().showMessage(self.statusBar().currentMessage() + ' | ' + QCoreApplication.translate('GroupStats','generate view...'))
keys = result.keys() # Finding unique row and column keys (separately)
topmost = set([])
kolu = set([])
for z in keys: # adding keys to collections to reject repetition
topmost.add(z[0])
kolu.add(z[1])
rows = list(topmost) # list of unique row keys
columns = list(kolu) # list of unique column keys
rowDictionary={} # Creating dictionaries for rows and columns (faster search)
for nr, row in enumerate(rows):
rowDictionary[row]=nr
columnDictionary={}
for nr, col in enumerate(columns):
columnDictionary[col]=nr
calculations = [[x[2] for x in chosenValues if x[0]=='calculations'], # list of selected calculations in values, rows and columns
[x[2] for x in chosenRows if x[0]=='calculations'],
[x[2] for x in chosenColumns if x[0]=='calculations']]
if len(calculations[0])!=0: # Take to calculations only the non-empty part of the list above
calculation = calculations[0]
elif len(calculations[1])!=0:
calculation = calculations[1]
else:
calculation = calculations[2]
data = [] # Creating an empty array for the date (l.row x l.column)
for x in range( max( len(rows) , len(rows)*len(calculations[1]))):
data.append(max(len(columns),len(columns)*len(calculations[2]))*[('',())])
for x in keys: # Calculation of values for all keys
nrw = rowDictionary[x[0]] # rows no in the data table for the chosen key
nrk = columnDictionary[x[1]] # column number in the data table for the chosen key
for n,y in enumerate(calculation): # making all calculates for all keys
if len(calculations[1])>0:
data[nrw*len(calculations[1])+n][nrk] = [self.calculations.list[y][1](result[x][0]), result[x][1]] # insert result if calculations with row
elif len(calculations[2])>0:
data[nrw][nrk*len(calculations[2])+n] = [self.calculations.list[y][1](result[x][0]), result[x][1]] # insert result if calculations from columns
else:
data[nrw][nrk] = [self.calculations.list[y][1](result[x][0]), result[x][1]] # insert result if calculations with values
atr = {} # Attributes as dict.
for i in range(provider.fields().count()):
atr[i] = provider.fields().at(i)
rowNames=[] # List with names of rows
for x in chosenRows:
if x[0]=='geometry':
rowNames.append(x[1])
elif x[0]!='calculations':
rowNames.append(atr[x[2]].name())
colNames=[] # List with column names
for x in chosenColumns:
if x[0]=='geometry':
colNames.append(x[1])
elif x[0]!='calculations':
colNames.append(atr[x[2]].name())
nameColumnsCalculations=() # Insert row and column names with calculations
nameRowsCalculation=()
if len(calculations[1])>0:
obl = [self.calculations.list[x][0] for x in calculations[1]]
rows1 = [w+(o,) for w in rows for o in obl]
columns1 = columns
nameRowsCalculation=(QCoreApplication.translate('GroupStats','Function'),)
elif len(calculations[2])>0:
obl = [self.calculations.list[x][0] for x in calculations[2]]
columns1 = [w+(o,) for w in columns for o in obl]
rows1 = rows
nameColumnsCalculations=(QCoreApplication.translate('GroupStats','Function'),)
else:
columns1 = columns
rows1 = rows
if len(rows1)>0 and len(rows1[0])>0:
rows1.insert(0,tuple(rowNames)+nameRowsCalculation)
if len(columns1)>0 and len(columns1[0])>0:
columns1.insert(0,tuple(colNames)+nameColumnsCalculations)
if len(rows1)>0 and len(columns1)>0:
self.ui.result.setUpdatesEnabled(False)
self.tm5 = ResultModel(data, rows1, columns1, layer)
self.ui.result.setModel(self.tm5)
for i in range(len(columns1[0]),0,-1):
self.ui.result.verticalHeader().setSortIndicator( i-1, Qt.AscendingOrder )
for i in range(len(rows1[0]),0,-1):
self.ui.result.horizontalHeader().setSortIndicator( i-1, Qt.AscendingOrder )
statement = self.statusBar().currentMessage()
percent = 100.00 / self.tm5.columnCount()
counter = 0
for i in range(self.tm5.columnCount()):
self.ui.result.resizeColumnToContents(i)
counter = counter + percent
self.statusBar().showMessage(statement + '%.0f%%' % (counter))
self.ui.result.setUpdatesEnabled(True)
if NULLcounter==1:
rekordy='record'
else:
rekordy='records'
if self.ui.useNULL.isChecked() and NULLcounter>0:
textNULL = QCoreApplication.translate('GroupStats',' (used %s %s with null value in "%s" field)' % (NULLcounter, rekordy, value[1]))
elif self.ui.useNULL.isChecked()==False and NULLcounter>0:
textNULL = QCoreApplication.translate('GroupStats',' (not used %s %s with null value in "%s" field)' % (NULLcounter, rekordy, value[1]))
else:
textNULL = ''
self.statusBar().showMessage(self.statusBar().currentMessage() + ' | ' + QCoreApplication.translate('GroupStats','done.')+textNULL, 20000)
else:
try:
del(self.tm5)
except AttributeError:
pass
self.ui.result.setModel(None)
self.statusBar().showMessage(QCoreApplication.translate('GroupStats','No data found.'), 10000)
def setLayers (self, layer): #finished
"Adds available layers to the selection list in the window"
index = self.ui.layer.currentIndex()
if index !=-1:
layerId = self.ui.layer.itemData(index) # id of the previously selected layer
self.ui.layer.blockSignals(True)
self.ui.layer.clear() # fill the comboBox with a new list of layers
layer.sort(key=lambda x: x[0].lower())
for i in layer:
self.ui.layer.addItem(i[0], i[1])
if index !=-1:
index2 = self.ui.layer.findData(layerId) # if the previously selected layer is a list then select it
if index2 !=-1:
self.ui.layer.setCurrentIndex(index2)
else:
self.layerSelection(0) # if it doesn't have the first one
else:
self.layerSelection(0)
self.ui.layer.blockSignals(False)
def layerSelection(self, index): #finished
"Runs after selecting layer from the list. Sets a new list of fields to choose from and deletes windows with already selected fields"
idW = self.ui.layer.itemData(index) # Get the ID of the selected layer
layer = QgsProject.instance().mapLayer(idW)#.toString())
provider = layer.dataProvider()
fields = provider.fields()
dictionary = {}
if layer.geometryType() in (QgsWkbTypes.PointGeometry, QgsWkbTypes.NullGeometry):
dictionary['geometry'] = []
elif layer.geometryType() == QgsWkbTypes.LineGeometry: # line
dictionary['geometry'] = [(QCoreApplication.translate('GroupStats','Length'), 1)]
elif layer.geometryType() == QgsWkbTypes.PolygonGeometry: # polygon
dictionary['geometry'] = [(QCoreApplication.translate('GroupStats','Perimeter'), 1), (QCoreApplication.translate('GroupStats','Area'), 2)]
dictionary['countAttributes'] = []
dictionary['attributeTxt'] = []
for i in range(fields.count()):
field = fields.at(i)
if field.isNumeric():
dictionary['countAttributes'].append((field.name(), i))
else:
dictionary['attributeTxt'].append((field.name(), i))
dictionary['calculations']=[]
obl = self.calculations.list
for c,b in obl.items():
dictionary['calculations'].append((b[0],c))
del(self.tm1)
self.tm1 = ModelListaPol()
self.ui.listHalf.setModel(self.tm1)
keys = ['calculations', 'geometry']
for i in keys:
j = dictionary[i]
j.sort(key=lambda x: x[0].lower())
rows=[]
for k, l in j:
rows.append((i,k,l))
self.tm1.insertRows( 0, len(rows), QModelIndex(), rows)
keys = ['countAttributes', 'attributeTxt']
rows=[]
for i in keys:
j = dictionary[i]
for k, l in j:
rows.append((i,k,l))
rows.sort(key=lambda x: x[1].lower())
self.tm1.insertRows( 0, len(rows), QModelIndex(), rows)
self.clearChoice()
def clearChoice(self): # finished
" Clears windows with selected rows, columns and values"
self.tm2.removeRows(0, self.tm2.rowCount() ,QModelIndex())
self.tm3.removeRows(0, self.tm3.rowCount() ,QModelIndex())
self.tm4.removeRows(0, self.tm4.rowCount() ,QModelIndex())
self.ui._filter.setPlainText('')
def showControlPanel(self): # finished
""
self.ui.controlPanel.setVisible(True)
def showTutorial(self):
url = "http://underdark.wordpress.com/2013/02/02/group-stats-tutorial/"
webbrowser.open (url, 2)
def setFilter(self): # finished 2
index = self.ui.layer.currentIndex() # Download selected layer
layerId = self.ui.layer.itemData(index)
layer = QgsProject.instance().mapLayer(str(layerId))
text = self.ui._filter.toPlainText() # Retrieve the text from the window and display the query window
q = QgsSearchQueryBuilder(layer)
q.setSearchString(text)
q.exec_()
self.ui._filter.setPlainText(q.searchString ()) # Insert a query into the window
# ------------------------ COPYING DATA TO THE CLIPBOARD AND CSV SAVE ----------------------------START
def duplication (self):
"Copy all data to the clipboard"
text, test = self.downloadDataFromTheTable(True, True)
if test==True:
clipboard = QApplication.clipboard()
clipboard.setText(text)
def copyMarked (self):
"Copy selected data to the clipboard"
text, test = self.downloadDataFromTheTable(False, True)
if test==True:
clipboard = QApplication.clipboard()
clipboard.setText(text)
def exportToCSV (self):
"Saves all data to CSV file"
data, test = self.downloadDataFromTheTable(True, False)
if test==True:
self.saveFileData(data)
def exportMarkedToCSV (self):
"Saves selected data to a CSV file"
data, test = self.downloadDataFromTheTable(False, False)
if test==True:
self.saveFileData(data)
def saveFileData (self, data):
"Support for writing data to a file"
fileWindow = QFileDialog() # Select file to write
fileWindow.setAcceptMode(1)
fileWindow.setDefaultSuffix("csv")
fileWindow.setNameFilters(["CSV files (*.csv)", "All files (*)"])
if fileWindow.exec_() == 0: # No file selected - output
return
fileName = fileWindow.selectedFiles()[0]
_file = open(fileName, 'w') # Open file for writing
csvfile = csv.writer( _file, delimiter=';' )
for i in data: # Copying data from the table
#csvfile.writerow([bytes(x, 'utf-8') for x in i])
csvfile.writerow(i)
_file.close()
def downloadDataFromTheTable(self, allData=True, controlCharacters=False):
if self.ui.result.model()==None:
QMessageBox.information(None,QCoreApplication.translate('GroupStats','Information'), \
QCoreApplication.translate('GroupStats','No data to save/copy'))
return None, False
text=''
data = []
numberOfColumns = self.tm5.columnCount()
numberOfRows = self.tm5.rowCount()
rows = []
columns = []
if allData == False: # If the option 'only checked' get indexes of selected fields
indexList = self.ui.result.selectedIndexes()
if len(indexList)==0:
QMessageBox.information(None,QCoreApplication.translate('GroupStats','Information'), \
QCoreApplication.translate('GroupStatsD','No data selected'))
return None, False
for i in indexList:
rows.append(i.row())
columns.append(i.column())
for i in range(numberOfRows): # Copying data from the table
if allData or (i in rows) or (i < self.tm5.offsetY):
row = []
for j in range(numberOfColumns):
if allData or (j in columns) or (j < self.tm5.offsetX):
row.append(str(self.tm5.createIndex(i,j).data()))
data.append(row)
if controlCharacters == True:
for m, i in enumerate(data): # Copying data from the table
if m>0:
text = text + chr(13)
for n, j in enumerate(i):
if n>0:
text = text + chr(9)
text = text + j
return text, True
else:
return data, True
# ------------------------ COPYING DATA TO THE CLIPBOARD AND SAVING CSV ------------------ ---------- END
def showOnMap(self): # change not to duplicate indexes from cells
indexList = self.ui.result.selectedIndexes() # Retrieve the indexes of the selected fields
idList = []
for i in indexList: # Get object indexes to show
lista = i.data(Qt.UserRole)#.toList()
if lista == None: # Reject lines with headers
lista = ()
for j in lista:
idList.append(j) #w 1 było idList.append(j.toInt()[0])
self.tm5.layer.selectByIds(idList) # selecting them on the map
self.iface.mapCanvas().zoomToSelected(self.tm5.layer) # zoom to selected objects
if len(idList)==1 and self.tm5.layer.geometryType()==0: # if the layer is point and there is only one object in the group ..
self.iface.mapCanvas().zoomScale(1000) # set the scale to 1: 1000
class ModelList(QAbstractListModel):
"""
Model for windows with amodeut lists.
Data stored on the list: [(amodeutu type, name, id), ...]
"""
def __init__(self, mainWindow, parent=None):
super(ModelList, self).__init__(parent)
self._data = []
self.mainWindow = mainWindow
self.calculations = Calculations(self)
def rowCount(self, parent=QModelIndex):
return len(self._data)
def data(self, index, role=Qt.DisplayRole):
if not index.isValid() or not 0 <= index.row() < self.rowCount():
return None#QVariant()
row = index.row()
if role == Qt.DisplayRole:
return self._data[row][1]
#elif rola == Qt.ForegroundRole:
# if self.data[row][0] == 'geometry':
# kolor = QColor(0,255,0)
# elif self.data[row][0] == 'calculations':
# kolor = QColor(255,0,0)
# elif self.data[row][0] == 'attributeTxt':
# kolor = QColor(150,150,150)
# else:
# kolor = QColor(0,0,0) # 'countAttributes'
#
# pedzel = QBrush(kolor)
# return pedzel
elif role == Qt.DecorationRole:
if self._data[row][0] == 'geometry':
icon = QIcon(":/plugins/groupstats/icons/geom.png")
elif self._data[row][0] == 'calculations':
icon = QIcon(":/plugins/groupstats/icons/calc.png")
elif self._data[row][0] == 'attributeTxt':
icon = QIcon(":/plugins/groupstats/icons/alpha.png")
else:
icon = QIcon(":/plugins/groupstats/icons/digits.png")
return icon
return None#QVariant()
def mimeTypes(self):
return ['application/x-groupstats-polaL', 'application/x-groupstats-polaWK', 'application/x-groupstats-polaW']
def supportedDragActions(self):
return Qt.MoveAction
def supportedDropActions(self):
return Qt.MoveAction
def insertRows(self, row, number, index, data):
self.beginInsertRows(index, row, row + number - 1)
for n in range(number):
self._data.insert(row + n, data[n])
self.endInsertRows()
return True
def removeRows(self, row, number, index):
self.beginRemoveRows(index, row, row + number - 1)
del self._data[row:row + number]
self.endRemoveRows()
return True
def mimeData(self, indexy, typMime='application/x-groupstats-polaL'):
dataMime = QMimeData()
data = QByteArray()
stream = QDataStream(data, QIODevice.WriteOnly)
for index in indexy:
row = index.row()
stringg = pickle.dumps(self._data[row][2])
#stream << self.data[rows][0][0] << self.data[row][1][0] #----------------------------- ???????[0]correct
# Datatypes below happen to be strings or already bytes! (b'geometry', b'calculations' or b'attributeTxt' - maybe reused?)
stream.writeBytes(bytes(self._data[row][0], 'utf-8') if isinstance(self._data[row][0], str) else bytes(self._data[row][0]))
stream.writeBytes(bytes(self._data[row][1], 'utf-8') if isinstance(self._data[row][1], str) else bytes(self._data[row][1]))
stream.writeInt16(self._data[row][2])
dataMime.setData(typMime, data)
return dataMime
def flags(self, index):
flag = super(ModelList, self).flags(index)
if index.isValid():
return flag | Qt.ItemIsDragEnabled | Qt.ItemIsEnabled | Qt.ItemIsSelectable
else:
return Qt.ItemIsDropEnabled
class ModelRowsColumns(ModelList):
"""
Model for windows with field lists for rows and columns
"""
def __init__(self, parent):
super(ModelRowsColumns, self).__init__(parent)
self._data = []
def setData(self, index, value):
self._data.insert(index, value)
return True
def setOtherModels(self, modelWiK, valueModel):
self.modelWiK = modelWiK._data
self.valueModel = valueModel._data
def mimeData(self, indexy):
return super(ModelRowsColumns, self).mimeData(indexy, 'application/x-groupstats-polaWK')
def dropMimeData(self, dataMime, share, row, column, index):
if dataMime.hasFormat('application/x-groupstats-polaL'):
dataType = 'application/x-groupstats-polaL'
elif dataMime.hasFormat('application/x-groupstats-polaWK'):
dataType = 'application/x-groupstats-polaWK'
elif dataMime.hasFormat('application/x-groupstats-polaW'):
dataType = 'application/x-groupstats-polaW'
else:
return False
data = dataMime.data(dataType)
stream = QDataStream(data, QIODevice.ReadOnly)
outData = []
while not stream.atEnd():
#typ = ''#QString() --------------------------------???????????????????????????????????????
#name = ''#QString() -------------------------------------??????????????????????????????????????????????
#stream >> typ >> name
typ = stream.readBytes().decode('utf-8')
name = stream.readBytes().decode('utf-8')
id = stream.readInt16()
field = (typ, name, id)
dataWKiW = self.modelWiK+self.valueModel
if typ=='calculations' and typ in [x[0] for x in dataWKiW] and dataType == 'application/x-groupstats-polaL':
self.mainWindow.statusBar().showMessage(QCoreApplication.translate('GroupStats','Function can be droped in only one area'),15000)
return False
elif (field in self.modelWiK or field in self._data) and dataType in ['application/x-groupstats-polaL', 'application/x-groupstats-polaW']:
self.mainWindow.statusBar().showMessage(QCoreApplication.translate('GroupStats','This field has already been droped'),15000)
return False
#elif (typ != 'calculations' and 'calculations' in [x[0] for x in self.data]) or (typ=='calculations' and len([x for x in self.data if (x[0] != 'calculations')])>0):
# pprint 'calculated fields cannot be together with other fields'
# return False
elif typ=='calculations' and id not in self.calculations.textList and 'attributeTxt' in [x[0] for x in self.valueModel]: #name != self.calculations.lista[0][0]
self.mainWindow.statusBar().showMessage(QCoreApplication.translate('GroupStats','For the text value function can only be one of (%s)' % self.calculations.textNames), 15000)
return False
outData.append(field)
self.insertRows(row, len(outData), index, outData)
return True
class ValueModel(ModelList):
"""
Model for a window with values for calculations
"""
def __init__(self, parent=None):
super(ValueModel, self).__init__(parent)
self._data = []
def mimeData(self, indexy):
return super(ValueModel, self).mimeData(indexy, 'application/x-groupstats-polaW')
def dropMimeData(self, dataMime, share, row, column, index):
if dataMime.hasFormat('application/x-groupstats-polaL'):
dataType = 'application/x-groupstats-polaL'
elif dataMime.hasFormat('application/x-groupstats-polaWK'):
dataType = 'application/x-groupstats-polaWK'
elif dataMime.hasFormat('application/x-groupstats-polaW'):
dataType = 'application/x-groupstats-polaW'
else:
return False
data = dataMime.data(dataType)
stream = QDataStream(data, QIODevice.ReadOnly)
outData = []
while not stream.atEnd():
#typ = '2'#QString()-------------------------------------????????????????????????????
#name = '2'#QString()-------------------------------------?????????????????????
#stream >> typ >> name
typ = stream.readBytes().decode('utf-8')
name = stream.readBytes().decode('utf-8')
id = stream.readInt16()
field = (typ, name, id)
allData = self.modelRows+self.modelColumns+self._data
dataWiK = self.modelRows+self.modelColumns
if len(self._data)>=2:
self.mainWindow.statusBar().showMessage(QCoreApplication.translate('GroupStats',"Area 'Value' may contain a maximum of two entries"),15000)
return False
elif typ=='calculations' and typ in [x[0] for x in allData] and dataType == 'application/x-groupstats-polaL':
self.mainWindow.statusBar().showMessage(QCoreApplication.translate('GroupStats','Function can be droped in only one area'),15000)
return False
elif len(self._data)==1 and typ != 'calculations' and self._data[0][0] != 'calculations':
self.mainWindow.statusBar().showMessage(QCoreApplication.translate('GroupStats',"In the area 'Value' one of the items must be a function"),15000)
return False
elif len(self._data)==1 and ((typ == 'attributeTxt' and self._data[0][2] not in self.calculations.textList) or (id not in self.calculations.textList and self._data[0][0] == 'attributeTxt')):
self.mainWindow.statusBar().showMessage(QCoreApplication.translate('GroupStats','For the text value function can only be one of (%s)' % self.calculations.textNames), 15000)
return False
elif typ=='attributeTxt' and len([x for x in dataWiK if (x[0]=='calculations' and x[2] not in self.calculations.textList)])>0:
self.mainWindow.statusBar().showMessage(QCoreApplication.translate('GroupStats','For the text value function can only be one of (%s)' % self.calculations.textNames), 15000)
return False
outData.append(field)
self.insertRows(row, len(outData), index, outData)
# check: what if when deleting only the calculated field or the value field is left
return True
def setOtherModels(self, modelRows, modelColumns):
self.modelRows = modelRows._data
self.modelColumns = modelColumns._data
class ModelListaPol(ModelList):
"""
Model for the window with a list of available fields
"""
def __init__(self, parent=None):
super(ModelListaPol, self).__init__(parent)
#self.ustawDane(slownikPol)
self._data = []
def dropMimeData(self, dataMime, share, row, column, index):
return True
def removeRows(self, row, number, index):
return True
class ResultModel(QAbstractTableModel): # finished
"""
Model for the window with calculation results
"""
def __init__(self, data, rows, columns, layer, parent=None):
super(ResultModel, self).__init__(parent)
self._data = data
self.rows = rows
self.columns = columns
self.layer = layer
self.offsetX = max(1,len(rows[0])) # Coordinate shift so that the data starts with 0.0
self.offsetY = max(1, len(columns[0]))
if len(rows[0]) != 0 and len(columns[0]) != 0: # One line offset (empty) to make room for the names of the lines
self.offsetY += 1
def columnCount(self,parent=QModelIndex()):
if len(self.rows[0])>0 and len(self.columns[0])>0:
l = len(self.columns) + len(self.rows[0]) - 1
elif len(self.rows[0])>0 and len(self.columns[0])==0:
l = len(self.rows[0])+1
elif len(self.rows[0])==0 and len(self.columns[0])>0:
l = len(self.columns)
else:
l = 2
return l #max(len(self.rows[0])+1,len(self.column)+len(self.rows[0]))
def rowCount(self, parent=QModelIndex()):
return max(2, len(self.rows) + len(self.columns[0]))
def data(self, index, role=Qt.DisplayRole):
if not index.isValid() or not 0 <= index.row() < self.rowCount():
return None
row = index.row() - self.offsetY
column = index.column() - self.offsetX
if role == Qt.DisplayRole:
if row >=0 and column >=0: # Data
return self._data[row][column][0]
elif column < 0 and row >= 0 and len(self.rows[0])>0: # descriptions of rows
return self.rows[row+1][column]
elif row == -1 and column <0 and len(self.rows[0])>0: # row names
return self.rows[0][column]
elif column >= -1 and row < 0 and len(self.columns[0])>0: # descriptions and column names
if len(self.rows[0])>0:
if row == -1: # break line
return ''
else:
return self.columns[column + 1][row + 1] # descriptions and column names if there is a break line
else:
return self.columns[column + 1][row] # descriptions and column names if there is no gap line
elif role == Qt.UserRole:
if row >=0 and column >=0: # Data
return self._data[row][column][1]
elif role == Qt.UserRole+1:
#print "user role+1"
if row <0 and column >=0: # column, row or data
return "column"
elif row >=0 and column <0:
return "row"
elif row >=0 and column >=0:
return "data"
elif role == Qt.BackgroundRole: # Cell filling
if row<0 or column<0: # gray for cells with descriptions and namesi
colour = QColor(245,235,235)
brush = QBrush(colour)
return brush
elif role == Qt.TextAlignmentRole:
if column < 0 and row < -1 and len(self.rows[0]) != 0:
return Qt.AlignRight | Qt.AlignVCenter
elif column >= 0 and row < 0:
return Qt.AlignHCenter | Qt.AlignVCenter
elif column >= 0 and row >= 0:
return Qt.AlignRight | Qt.AlignVCenter
elif role == Qt.FontRole:
if row<0 and column<0:
font = QFont()
font.setBold(True)
#font.setItalic(True)
return font
return None#QVariant()
def sort(self, column, mode):
"""
Sorts the results table by the selected column
column - column number
mode - 1-descending, other-ascending
"""
if len(self.rows) == 1: # If there is only one line, there is nothing to sort
return
tmp = [] # A temporary list for a sorted column
if column >= self.offsetX: # Selecting data to sort
# n-line number before storting, d-data in line
try:
tmp.extend([(n, float(d[column - self.offsetX][0])) for n, d in enumerate(self._data)])
except (ValueError, TypeError):
tmp.extend([(n, str(d[column - self.offsetX][0])) for n, d in enumerate(self._data)])
else: # or line names
# Either convert all values or none to float for sorting
# n-row number before storting, d-row description
try:
tmp.extend([(n, float(d[column])) for n, d in enumerate(self.rows[1:])])
except (ValueError, TypeError):
tmp.extend([(n, d[column]) for n, d in enumerate(self.rows[1:])])
tmp.sort(key=lambda x: x[1]) # ascending sorting
if mode==1: # descending sorting
tmp.reverse()
data2 = tuple(self._data) # A temporary tuple with all the data
self._data=[]
rows2=tuple(self.rows) # A temporary tuple with descriptions of the rows
self.rows=[]
self.rows.append(rows2[0]) # Adding row names (only names, no row descriptions)
for i in tmp: # Arrange all data and row descriptions according to a temporary sort list
self._data.append(data2[i[0]])
self.rows.append(rows2[i[0]+1])
topLeft = self.createIndex(0,0) # Signal change data
bottomRight = self.createIndex(self.rowCount(), self.columnCount())
self.dataChanged.emit(topLeft, bottomRight)
def sortRows(self, row, mode):
"""
Sorts the results table according to the chosen rows
rows - rows number
mode - 1-descending, other-ascending
"""
if len(self.columns) - self.offsetX <=1: # If there is only one column, there is nothing to sort
return # (self.columns are then the following list [(),])
tmp = [] # A temporary list for a sorted row
if row >= self.offsetY: # Selecting data to sort
# Either convert all values or none to float for sorting
try:
tmp.extend([(n, float(d[0])) for n, d in enumerate(self._data[row - self.offsetY])])
except (ValueError, TypeError):
tmp.extend([(n, str(d[0])) for n, d in enumerate(self._data[row - self.offsetY])]) # n-column number before storting, d-data in the column
else: # or column names
# Either convert all values or none to float for sorting
try:
tmp.extend([(n, float(d[row])) for n, d in enumerate(self.columns[1:])])
except (ValueError, TypeError):
tmp.extend([(n, str(d[row])) for n, d in enumerate(self.columns[1:])])
except IndexError:
# The table can't be sorted using this column. It's probably the row header columnn
return
tmp.sort(key=lambda x: x[1]) # ascending sorting
if mode==1: # descending sorting
tmp.reverse()
data2 = tuple(self._data) # A temporary tuple with all the data
self._data=[]
columns2=tuple(self.columns) # A temporary tuple with column descriptions
self.columns=[]
self.columns.append(columns2[0]) # Adding column names (only names, no column descriptions)
for j in data2: # Arranging all data according to a temporary sort list
row = []
for i in tmp:
row.append(j[i[0]])
self._data.append(tuple(row))
for i in tmp: # Arrangement of column descriptions according to a temporary sort list
self.columns.append(columns2[i[0] + 1])
topLeft = self.createIndex(0,0) # Signal change data
bottomRight = self.createIndex(self.rowCount(), self.columnCount())
self.dataChanged.emit(topLeft, bottomRight)
class WindowResults(QTableView):
"""
Window with calculation results
"""
def __init__(self, parent=None):
super(WindowResults, self).__init__(parent)
self.setSortingEnabled(True)