forked from seanlinmt/DelimitationToolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredistricting_dock.py
1346 lines (1098 loc) · 56.6 KB
/
redistricting_dock.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 -*-
"""
/***************************************************************************
Redistricting
Electorate Rebalancing and Redistricting
-------------------
begin : 2014-07-06
git sha : $Format:%H$
copyright : (C) 2014 by Sean Lin
email : seanlinmt at gmail dot com
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
"""
from builtins import map
from builtins import str
from qgis.core import Qgis, QgsRectangle, QgsCoordinateTransform, QgsVectorLayer, \
QgsPalLayerSettings, QgsSymbol, QgsRendererCategory, QgsPointXY, \
QgsCategorizedSymbolRenderer, QgsFeatureRequest, QgsGeometry, QgsExpression, QgsProject, QgsWkbTypes, \
QgsTextFormat, QgsRuleBasedLabeling, QgsVectorLayerSimpleLabeling
from qgis.gui import QgsMapToolEmitPoint, QgsRubberBand
from qgis.PyQt import uic, QtCore, QtGui, QtWidgets
from qgis.PyQt.QtCore import Qt, QObject, QVariant, pyqtSignal
import json
import os
import math
import codecs
from .balancer import Balancer
from . import configuration as config
from helper.qgis_util import extend_qgis_interface
from helper.string_util import parse_float
from .configuration import KEY_AREA, KEY_CIRCULARITY, KEY_COMPACTNESS, KEY_VOTERS
from .layer_type import LayerType
import statistics
FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'ui_redistricting_dock.ui'))
CONFIG_FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'ui_configuration.ui'))
CONSTITUENCIES_FORM_CLASS, _ = uic.loadUiType(
os.path.join(os.path.dirname(__file__), 'ui_redistricting_constituencies.ui'))
STATS_WIDGET, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'ui_widget_statistics.ui'))
class RedistrictingDock(QtWidgets.QDockWidget, FORM_CLASS):
closingPlugin = pyqtSignal()
def __init__(self, iface, parent=None):
"""Constructor."""
super(RedistrictingDock, self).__init__(parent)
self.setupUi(self)
# get project instance
self.project = QgsProject.instance()
# load configuration
config.Configuration().load()
# coordinate transform
self.coordinateTransform = None
# threads
self.thread = None
self.worker = None
self.progressBar = None
# init the sub dialogs
self.configuration = DelimitationToolboxConfigDialog(self)
self.configuration.saved.connect(self.populate_state_selector)
self.constituencies = RedistrictingConstituenciesDialog(self)
# init widgets
self.stats_old = QStatsWidget()
self.layout_stats_old.addWidget(self.stats_old)
self.stats_new = QStatsWidget()
self.layout_stats_new.addWidget(self.stats_new)
self.topology = None
self.id_graph = None
self.balancer_new = None
self.balancer_old = None
self.layer_id = None
# extensions
self.iface = extend_qgis_interface(iface)
self.clickTool_prev = None
self.clickTool = DelimitationMapTool(self.iface.mapCanvas())
self.clickTool.canvasDoubleClicked.connect(self.canvas_doubleclicked)
self.clickTool.canvasSingleClicked.connect(self.canvas_clicked)
# manual rebalancer
self.balancer_started = False
self.clicked_feature_id = None
self.layer = None
self.context_fieldname = None
self.polling_old_fieldname = None
self.state_old_fieldname = None
self.par_old_fieldname = None
self.state_new_fieldname = None
self.par_new_fieldname = None
self.polling_new_fieldname = None
self.par_new_prefix = None
self.btLoadLayer.clicked.connect(self.layer_select)
self.btShowTopology.clicked.connect(self.constituencies.show)
self.tab_rebalance.currentChanged.connect(self.tab_change_handler)
# todo : dropping layers and files
self.btRenumber.clicked.connect(self.layer_renumber)
self.btRebalance.clicked.connect(self.balancer_start)
self.btRebalanceStop.clicked.connect(self.balancer_stop)
self.btEditConfig.clicked.connect(self.configuration.show)
self.btDuplicate.clicked.connect(self.layer_copy_old)
self.btRedrawLayer.clicked.connect(self.layer_redraw)
self.selector_state.currentIndexChanged.connect(self.live_show)
self.selector_par.currentIndexChanged.connect(self.live_show)
# http://qgis.org/api/classQgsMapCanvas.html
self.cb_label.stateChanged.connect(self.label_update)
self.cb_feature_id.stateChanged.connect(self.label_update)
self.cb_old_id.stateChanged.connect(self.label_update)
# monitor layer selection change
self.btClearSelected.clicked.connect(self.selection_clear)
self.btReset.clicked.connect(self.layer_reset)
self.btUpdateAttributes.clicked.connect(self.selection_update)
self.iface.mapCanvas().layersChanged.connect(self.layer_changed)
self.selector_layers.currentIndexChanged.connect(self.layer_preload)
# populate state
self.populate_state_selector()
self.selector_par_old.currentIndexChanged[int].connect(self.load_par_field)
self.selector_state_old.currentIndexChanged[int].connect(self.load_state_field)
def closeEvent(self, event):
self.closingPlugin.emit()
event.accept()
self.balancer_stop()
self.constituencies.close()
self.iface.mapCanvas().layersChanged.disconnect(self.layer_changed)
self.clickTool.canvasDoubleClicked.disconnect(self.canvas_doubleclicked)
self.clickTool.canvasSingleClicked.disconnect(self.canvas_clicked)
self.layer = None
@staticmethod
def extract_stats(dic, key):
itemlist = []
for v in dic.values():
itemlist.append(v[key])
min_value = min(itemlist)
max_value = max(itemlist)
median = statistics.median(itemlist)
return min_value, median, max_value
def statistics_update(self):
total_area = math.fsum([v[config.KEY_GEOMETRY].area()
for v in list(self.balancer_old.topology_par.values())]) / 1000 / 1000
self.label_total_area.setText("{:.0f} sqr kms".format(total_area))
self.label_context_total.setText(str(self.balancer_old.total_voters))
self.label_context_label.setText("{}".format(self.context_fieldname))
self.label_stats_eq.setText(parse_float("{}%".format(self.tbDelta.text()) * 100))
# old stats
self.balancer_old.statistics_calculate(self.coordinateTransform)
old_areas_state = self.extract_stats(self.balancer_old.state_statistics, KEY_AREA)
old_circularity_state = self.extract_stats(self.balancer_old.state_statistics, KEY_CIRCULARITY)
old_areas_par = self.extract_stats(self.balancer_old.par_statistics, KEY_AREA)
old_circularity_par = self.extract_stats(self.balancer_old.par_statistics, KEY_CIRCULARITY)
old_unused = self.balancer_old.get_unused()
if old_areas_par.__len__():
self.stats_old.setParValues(old_unused[0].__len__(),
self.balancer_old.par_count_limit,
self.balancer_old.parmin_actual_percentage,
self.balancer_old.parmax_actual_percentage,
self.balancer_old.par_average,
old_areas_par,
old_circularity_par)
if old_areas_state.__len__():
self.stats_old.setStateValues(old_unused[1].__len__(),
self.balancer_old.state_count_limit,
self.balancer_old.statemin_actual_percentage,
self.balancer_old.statemax_actual_percentage,
self.balancer_old.state_average,
old_areas_state,
old_circularity_state)
# new stats
self.balancer_new.statistics_calculate(self.coordinateTransform)
new_areas_state = self.extract_stats(self.balancer_new.state_statistics, KEY_AREA)
new_circularity_state = self.extract_stats(self.balancer_new.state_statistics, KEY_CIRCULARITY)
new_areas_par = self.extract_stats(self.balancer_new.par_statistics, KEY_AREA)
new_circularity_par = self.extract_stats(self.balancer_new.par_statistics, KEY_CIRCULARITY)
new_unused = self.balancer_new.get_unused()
if new_areas_par.__len__():
self.stats_new.setParValues(new_unused[0].__len__(),
self.balancer_new.par_count_limit,
self.balancer_new.parmin_actual_percentage,
self.balancer_new.parmax_actual_percentage,
self.balancer_new.par_average,
new_areas_par,
new_circularity_par)
if new_areas_state.__len__():
self.stats_new.setStateValues(new_unused[1].__len__(),
self.balancer_new.state_count_limit,
self.balancer_new.statemin_actual_percentage,
self.balancer_new.statemax_actual_percentage,
self.balancer_new.state_average,
new_areas_state,
new_circularity_state)
def load_par_field(self, index):
if not self.layer or index < 1:
return
par_fieldname = self.selector_par_old.currentText()
pars = set()
for f in self.layer.getFeatures():
if par_fieldname:
pars.add(f[par_fieldname])
self.tb_old_par_count.setText(str(pars.__len__()))
if not self.tb_new_par_count.text():
self.tb_new_par_count.setText(str(pars.__len__()))
def load_state_field(self, index):
if not self.layer or index < 1:
return
state_fieldname = self.selector_state_old.currentText()
states = set()
for f in self.layer.getFeatures():
if state_fieldname:
states.add(f[state_fieldname])
self.tb_old_state_count.setText(str(states.__len__()))
if not self.tb_new_state_count.text():
self.tb_new_state_count.setText(str(states.__len__()))
def live_show(self):
"""update totals and statistics"""
if not self.layer:
return
if self.selector_state.currentIndex() == -1 or self.selector_par.currentIndex() == -1:
return
selectedfeatureids = self.layer.selectedFeatureIds()
self.label_selected.setText("Selected ({})".format(len(selectedfeatureids)))
current_state = self.selector_state.itemData(self.selector_state.currentIndex())
current_par = self.selector_par.itemData(self.selector_par.currentIndex())
balancer = self.get_balancer()
totals = balancer.calculate_live_totals(current_par, current_state, selectedfeatureids)
voters_par = totals[0]
voters_state = totals[1]
voters_selected = totals[2]
# number of state seats in current parliament seat
if str(current_par) in balancer.map_par_state:
states_per_par = balancer.map_par_state[str(current_par)]['states'].__len__()
else:
states_per_par = "-"
self.label_state_voters.setText(str(voters_state))
self.label_par_voters.setText("{} ({})".format(voters_par, states_per_par))
self.lb_recommendation.setText(balancer.recommendation_by_par(str(current_par)))
if balancer.state_average:
delta_state = voters_state - balancer.state_average
delta_state_percentage = 100 * delta_state / balancer.state_average
self.label_delta_state.setText("{:.2f}%".format(delta_state_percentage))
self.label_delta_state.setToolTip("{:.0f}".format(delta_state))
self.label_selected_state.setText("{:.2f}%".format(100 * voters_selected / balancer.state_average))
self.label_selected_state.setToolTip("{}".format(voters_selected))
if balancer.par_average:
delta_par = voters_par - balancer.par_average
delta_par_percentage = 100 * delta_par / balancer.par_average
self.label_delta_par.setText("{:.2f}%".format(delta_par_percentage))
self.label_delta_par.setToolTip("{:.0f}".format(delta_par))
self.label_selected_par.setText("{:.2f}%".format(100 * voters_selected / balancer.par_average))
self.label_selected_par.setToolTip("{}".format(voters_selected))
def layer_copy_old(self):
import re
confirmation = QtWidgets.QMessageBox.question(self,
"Overwrite values",
"Are you sure? Any newly allocated IDs will be overwritten.",
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
if confirmation == QtWidgets.QMessageBox.No:
return
delta = self.get_delta()
if not delta:
return
# get all values then sort by PAR and then by STATE which returns a tuple
attributes_old = sorted(list(self.balancer_old.topology_polling.items()),
key=lambda x: (x[1][self.par_old_fieldname],
x[1][self.state_old_fieldname],
x[1][self.polling_old_fieldname]))
par_format = self.balancer_new.par_prefix_format
state_format = self.balancer_new.state_prefix_format
poll_format = self.balancer_new.polling_prefix_format
regexp = r"(\d+)"
base_par = int(re.match(regexp, attributes_old[0][1][self.par_old_fieldname], re.I).group(1))
# http://gis.stackexchange.com/questions/58296/speed-of-editing-attributes-in-qgis-from-a-python-plugin
self.layer.startEditing()
for row in attributes_old:
old_par = int(re.match(regexp, row[1][self.par_old_fieldname], re.I).group(1))
old_state = int(re.match(regexp, row[1][self.state_old_fieldname], re.I).group(1))
old_polling = int(re.match(regexp, row[1][self.polling_old_fieldname], re.I).group(1))
new_par = par_format % (old_par - base_par + 1)
new_state = state_format % old_state
new_polling = poll_format % old_polling
self.balancer_new.topology_update(
{row[0]: {
self.state_new_fieldname: new_state,
self.par_new_fieldname: new_par,
self.polling_new_fieldname: new_polling}})
self.layer.commitChanges()
self.balancer_new.topology_dirty = True
self.layer_redraw(True)
self.iface.info("Done")
def layer_reset(self):
confirmation = QtWidgets.QMessageBox.question(self,
"Reset values",
"Are you sure? This operation will permanently remove all new "
"allocated IDs. You will need to start all over again from the "
"beginning.",
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
if confirmation == QtWidgets.QMessageBox.No:
return
self.layer.startEditing()
for k, v in list(self.balancer_new.topology_polling.items()):
self.layer.changeAttributeValue(k, self.layer.fields().indexFromName(self.polling_new_fieldname), None)
self.layer.changeAttributeValue(k, self.layer.fields().indexFromName(self.state_new_fieldname), None)
self.layer.changeAttributeValue(k, self.layer.fields().indexFromName(self.par_new_fieldname), None)
self.layer.commitChanges()
self.balancer_new.topology_dirty = True
self.layer_redraw(True)
self.iface.info("Attribute fields reset")
def label_update(self):
label = QgsPalLayerSettings()
if self.cb_label.isChecked() or self.cb_feature_id.isChecked():
label.enabled = True
self.layer.setLabelsEnabled(True)
else:
label.enabled = False
self.layer.setLabelsEnabled(False)
expr = []
balancer = self.get_balancer()
if self.cb_feature_id.isChecked():
if self.cb_old_id.isChecked():
# force display of old ID
expr.append(self.balancer_old.get_feature_label())
else:
expr.append(balancer.get_feature_label())
if self.cb_label.isChecked():
if self.selector_seat_type.currentIndex() == 1:
divisor = balancer.par_average
elif self.selector_seat_type.currentIndex() == 0:
divisor = balancer.state_average
else:
raise Exception("Unknown seat type")
if expr.__len__():
expr.append("'\\n'")
expr.append("round({}*100.0/{}, 2)".format(self.context_fieldname, divisor))
label.fieldName = "concat({})".format(",".join(expr))
label.isExpression = True
label.placement = QgsPalLayerSettings.OverPoint
text_format = QgsTextFormat()
text_format.setSize(8)
label.setFormat(text_format)
labeler = QgsVectorLayerSimpleLabeling(label)
self.layer.setLabeling(labeler)
self.layer.triggerRepaint()
def tab_change_handler(self, index):
if index == 3:
self.statistics_update()
def ui_state_save(self):
saved_state = {}
for widget in self.findChildren(QtWidgets.QComboBox):
saved_state.update({widget.objectName(): widget.currentIndex()})
for widget in self.findChildren(QtWidgets.QLineEdit):
saved_state.update({widget.objectName(): widget.text()})
config.Configuration().store_qt(config.Configuration.UI_STATE, json.dumps(saved_state))
def ui_state_load(self, excludes=None):
if not excludes:
excludes = []
try:
saved_state = json.loads(config.Configuration().read_qt(config.Configuration.UI_STATE))
except:
return
for widget in self.findChildren(QtWidgets.QComboBox):
if widget.objectName() in saved_state and widget.objectName() not in excludes:
widget.setCurrentIndex(saved_state[widget.objectName()])
for widget in self.findChildren(QtWidgets.QLineEdit):
if widget.objectName() in saved_state and widget.objectName() not in excludes:
widget.setText(saved_state[widget.objectName()])
def layer_select(self):
# startdir = Configuration().read_qt(Configuration.SRC_DIR)
startdir = os.path.join(os.path.split(__file__)[0], "data")
filepath, __ = QtWidgets.QFileDialog.getOpenFileName(parent=self,
caption='Select file',
filter="*.shp;*.gpkg",
directory=startdir)
if filepath:
path, filename = os.path.split(filepath)
# remember selected path
config.Configuration().store_qt(config.Configuration.SRC_DIR, path)
name, ext = os.path.splitext(filename)
# don't assign layer to self yet. only after balancer has started
layer = QgsVectorLayer(filepath, name, "ogr")
# layer = self.iface.addVectorLayer(filepath, name, "ogr")
if not layer.isValid():
self.iface.error("Layer failed to load!")
return
self.project.addMapLayer(layer)
self.layer_add_to_selector(layer)
def layer_preload(self, index):
layer_id = self.selector_layers.itemData(index)
if layer_id in self.project.mapLayers():
self.layer = self.project.mapLayers()[layer_id]
self.layer_load()
def layer_add_to_selector(self, layer):
self.selector_layers.addItem(layer.name(), layer.id())
def layer_changed(self):
layer_found = False
selected_index = self.selector_layers.currentIndex()
layer_id = self.selector_layers.itemData(selected_index)
if layer_id in self.project.mapLayers():
layer = self.project.mapLayers()[layer_id]
layer_found = True
if self.selector_layers.findData(layer.id()) == -1 and \
layer.type() == layer.VectorLayer and \
layer.geometryType() == QgsWkbTypes.PolygonGeometry:
self.layer_add_to_selector(layer)
if not layer_found:
# handle just started
if selected_index != -1:
self.selector_layers.removeItem(selected_index)
else:
if self.selector_layers.count() != 0:
selected_index = 0
self.selector_layers.setCurrentIndex(selected_index)
layer_found = True
if layer_found:
self.layer_preload(selected_index)
else:
if self.balancer_started:
self.balancer_stop()
else:
self.layer = None
return layer_found
def layer_selectors_clear(self):
self.selector_context.clear()
self.selector_polling_old.clear()
self.selector_state_old.clear()
self.selector_par_old.clear()
self.selector_state_new.clear()
self.selector_par_new.clear()
self.selector_polling_new.clear()
self.selector_context.addItem("Select field ...", "")
self.selector_polling_old.addItem("Select poll district ...", "")
self.selector_state_old.addItem("Select state ...", "")
self.selector_par_old.addItem("Select par ...", "")
self.selector_state_new.addItem("Select state ...", "")
self.selector_par_new.addItem("Select par ...", "")
self.selector_polling_new.addItem("Select poll district ...", "")
def layer_load(self):
self.layer_selectors_clear()
if self.layer is None:
return
self.iface.info("Reading layer definition {}".format(self.layer.id()))
provider = self.layer.dataProvider()
fields = provider.fields()
try:
for field in fields:
field_name = field.name()
self.selector_context.addItem(field_name, field_name)
self.selector_polling_old.addItem(field_name, field_name)
self.selector_state_old.addItem(field_name, field_name)
self.selector_par_old.addItem(field_name, field_name)
self.selector_state_new.addItem(field_name, field_name)
self.selector_par_new.addItem(field_name, field_name)
self.selector_polling_new.addItem(field_name, field_name)
except Exception as e:
self.iface.error(e.message)
finally:
del provider
# load save state
self.ui_state_load(["selector_layers", "selector_map_type"])
def layer_redraw(self, zoom_to_layer=False):
if not self.balancer_started:
self.iface.warning("balancer_not_started")
return
delta = self.get_delta()
if not delta:
return
# update info
self.label_map_type.setText(self.selector_map_type.currentText())
balancer = self.get_balancer()
balancer.topology_load()
balancer.init_colouring()
# init selectors
self.feature_selector_init()
# update label parameters
self.label_update()
seat_type = self.selector_seat_type.currentIndex()
if seat_type == 0:
# state
get_colour_method = balancer.get_colour_by_state
attr_prefix = balancer.state_prefix_format
attr_name = balancer.state_field
colouring = balancer.colouring_state
self.label_context_type.setText("State")
else:
# par
get_colour_method = balancer.get_colour_by_parliament
attr_prefix = balancer.par_prefix_format
attr_name = balancer.par_field
colouring = balancer.colouring_par
self.label_context_type.setText("Parliament")
geomtype = self.layer.geometryType()
if self.selector_overlay_type.currentIndex() == 2:
# load adjacency layers
name = self.selector_target_state.currentText()
state_alayer = balancer.adjlayer_make(name, LayerType.State)
par_alayer = balancer.adjlayer_make(name, LayerType.Parliament)
existing_layerids = []
for lyr in [state_alayer, par_alayer]:
existing_layerids.extend(
[x.id() for x in self.project.mapLayersByName(lyr.name()) if x is not None])
self.project.removeMapLayers(existing_layerids)
self.project.addMapLayer(state_alayer)
self.project.addMapLayer(par_alayer)
return
# balancer
categories = []
# add blank category for unallocated features
empty_symbol = QgsSymbol.defaultSymbol(geomtype)
empty_symbol.setColor(QtGui.QColor('white'))
empty_category = QgsRendererCategory("", empty_symbol, "")
categories.append(empty_category)
for k, v in colouring.gColouring.items():
if self.selector_overlay_type.currentIndex() == 1:
colour = get_colour_method(k, v)
elif self.selector_overlay_type.currentIndex() == 0:
colour = colouring.get_colour(v)
else:
self.iface.warning("That analysis option is not available yet")
return
if not colour:
continue
symbol = QgsSymbol.defaultSymbol(geomtype)
symbol.setColor(QtGui.QColor(colour.hex))
val = attr_prefix % int(k)
category = QgsRendererCategory(val, symbol, val)
categories.append(category)
# create the renderer and assign it to a layer
renderer = QgsCategorizedSymbolRenderer(attr_name, categories)
self.layer.setRenderer(renderer)
# self.iface.mapCanvas().setDirty(True)
self.iface.mapCanvas().clearCache()
"""
if zoom_to_layer:
extent = self.iface.mapCanvas().mapSettings().layerToMapCoordinates(self.layer, self.layer.extent())
self.iface.mapCanvas().setExtent(extent)
self.iface.mapCanvas().zoomToNextExtent()
"""
self.iface.mapCanvas().refresh()
def layer_renumber(self):
balancer = self.get_balancer()
if balancer.readonly:
self.iface.warning("You cannot edit the old map. Please select the new map.")
return
confirmation = QtWidgets.QMessageBox.question(self,
"Reorder allocation",
"Are you sure? This will renumber and " +
"reorganise all the parliament, state and polling district IDs.",
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
if confirmation == QtWidgets.QMessageBox.No:
return
self.layer.startEditing()
if not self.balancer_new.resequence():
self.iface.error("Renumber failed! There are geometry errors. Please run geometry and topology checker.")
self.layer.rollBack()
self.layer.endEditCommand()
return
par_used = [v[self.par_new_fieldname] for v in list(self.balancer_new.topology_polling.values())]
state_used = [v[self.state_new_fieldname] for v in list(self.balancer_new.topology_polling.values())]
if set(par_used).__len__() > self.balancer_new.par_count_limit or \
set(state_used).__len__() > self.balancer_new.state_count_limit:
self.iface.error("Allocation limit exceeded")
self.layer.rollBack()
self.layer.endEditCommand()
return
self.layer.commitChanges()
self.iface.info("Renumbering completed.")
self.layer_redraw(True)
def canvas_doubleclicked(self, point, button):
current_state = self.selector_state.itemData(self.selector_state.currentIndex())
current_par = self.selector_par.itemData(self.selector_par.currentIndex())
balancer = self.get_balancer()
par_field = balancer.par_field
state_field = balancer.state_field
ids = []
if button == Qt.LeftButton:
if current_state and current_par:
ids = [int(k) for k, v in list(balancer.topology_polling.items())
if v[par_field] == str(current_par) and v[state_field] == str(current_state)]
elif button == Qt.RightButton:
if current_par:
ids = [int(k) for k, v in list(balancer.topology_polling.items())
if v[par_field] == str(current_par)]
else:
self.iface.warning("What button did you just click??")
return
if set(ids) \
.difference(self.layer.selectedFeatureIds()) \
.difference([self.clicked_feature_id]) \
.__len__() == 0:
self.layer.modifySelection([], ids)
else:
self.layer.modifySelection(ids, [])
def canvas_rectangle(self, p):
# setup the provider select to filter results based on a rectangle
point = QgsGeometry().fromPointXY(p)
# scale-dependent buffer of 2 pixels-worth of map units
buff = point.buffer((self.iface.mapCanvas().mapUnitsPerPixel() * 2), 0)
rect_pseudo = buff.boundingBox()
rect = self.iface.mapCanvas().mapSettings().mapToLayerCoordinates(self.layer, rect_pseudo)
return rect
def canvas_clicked(self, geom, button):
import re
if not self.balancer_started:
self.iface.warning("balancer_not_started")
return
if self.layer is None:
self.iface.warning("Active layer not found")
return
rect = None
if type(geom) is QgsPointXY:
rect = self.canvas_rectangle(geom)
elif type(geom) is QgsRectangle:
rect = geom
feats = []
balancer = self.get_balancer()
for f in balancer.topology_polling.items():
if f[1][config.KEY_GEOMETRY].intersects(rect):
feats.append(f)
if feats.__len__() == 0:
self.layer.removeSelection()
return
# changed_feature = (feature id, values)
changed_feature = feats[0]
self.clicked_feature_id = changed_feature[0]
if button == Qt.RightButton:
# update selectors & recalculate
balancer = self.get_balancer()
self.tab_rebalance.setCurrentIndex(1)
# changed_feature = (feature id, values)
raw_par = changed_feature[1][balancer.par_field]
if raw_par:
par_val = int(re.search(r'\d+', str(raw_par)).group())
selector_par_index = self.selector_par.findData(par_val)
if selector_par_index != -1:
self.selector_par.setCurrentIndex(selector_par_index)
raw_state = changed_feature[1][balancer.state_field]
if raw_state:
state_val = int(re.search(r'\d+', str(raw_state)).group())
selector_state_index = self.selector_state.findData(state_val)
if selector_state_index != -1:
self.selector_state.setCurrentIndex(selector_state_index)
self.live_show()
else:
# toggle selection & recalculate
self.layer.invertSelectionInRectangle(rect)
def populate_state_selector(self):
self.selector_target_state.clear()
self.selector_target_state.addItem("Select state ...", "")
list(
map(lambda x: self.selector_target_state.addItem(x[0], x[1] if x.__len__() == 2 else ""),
[entry.split(':')
for entry in config.Configuration().read("Settings", "state_prefixes")]))
def selection_update(self):
if not self.balancer_started:
self.iface.warning("balancer_not_started")
return
balancer = self.get_balancer()
# don't allow write to old layer
if balancer.readonly:
self.iface.warning("Old map is read only. Please switch to the new map for rebalancing.")
return
if len(self.layer.selectedFeatures()) == 0:
self.iface.warning("Nothing selected. Click on a feature to select it.")
return
current_state = balancer.state_prefix_format % self.selector_state.itemData(
self.selector_state.currentIndex())
current_par = balancer.par_prefix_format % self.selector_par.itemData(self.selector_par.currentIndex())
confirmation = QtWidgets.QMessageBox.question(self,
"Confirm action",
"Move selected features to the following constituencies?\n\n" +
"Parliament:{}\nState:{}".format(current_par, current_state),
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
if confirmation == QtWidgets.QMessageBox.Yes:
self.layer.startEditing()
updates = [(current_par, current_state)]
for f in self.layer.selectedFeatures():
updates.append((f[self.par_new_fieldname], f[self.state_new_fieldname]))
balancer.topology_update(
{f.id(): {self.state_new_fieldname: current_state,
self.par_new_fieldname: current_par}})
# renumber POLLs in the changed
for entry in updates:
filter_expression = "'{}' = '{}' AND '{}' = '{}'" \
.format(self.par_new_fieldname,
entry[0],
self.state_new_fieldname,
entry[1])
req = QgsFeatureRequest(QgsExpression(filter_expression))
for i, f in enumerate(self.layer.getFeatures(req)):
balancer.topology_update(
{f.id(): {self.polling_new_fieldname: balancer.polling_prefix_format % (i + 1)}})
self.layer.commitChanges()
self.selection_clear()
self.layer_redraw(False)
self.iface.info("Selected features updated")
def selection_clear(self):
if self.layer is None:
return
self.layer.removeSelection()
def get_balancer(self):
"""0=old map, 1=new map"""
if self.label_map_type.text() == self.selector_map_type.itemData(1, Qt.DisplayRole):
return self.balancer_new
return self.balancer_old
def get_delta(self):
delta = parse_float(self.tbDelta.text())
if not delta or delta < 0:
self.iface.info("Please specify a value greater than 0")
return delta
def balancer_destroy(self):
self.balancer_old = None
self.balancer_new = None
def balancer_start(self):
if not self.layer:
self.iface.error(
"Redistricting plugin not started. Layer is missing, invalid or changed externally. Please reload "
"layer.")
return
# save state
self.ui_state_save()
self.iface.mapCanvas().setCurrentLayer(self.layer)
if not self.tb_new_par_count.text().isdigit() or \
not self.tb_new_state_count.text().isdigit():
self.iface.error("Total parliamentary and state seats must be integer values")
return
delta = self.get_delta()
if (self.selector_context.currentIndex() <= 0 or
self.selector_polling_old.currentIndex() <= 0 or
self.selector_state_old.currentIndex() <= 0 or
self.selector_par_old.currentIndex() <= 0 or
self.selector_state_new.currentIndex() <= 0 or
self.selector_par_new.currentIndex() <= 0 or
self.selector_polling_new.currentIndex() <= 0 or
self.selector_target_state.currentIndex() <= 0 or
not delta or
not self.tb_new_par_count.text() or
not self.tb_new_state_count.text()):
self.iface.error("Some fields are unspecified")
return
layer_crs = self.layer.dataProvider().crs()
if layer_crs.projectionAcronym() != 'merc' or \
self.iface.mapCanvas().mapSettings().destinationCrs().projectionAcronym() != 'merc':
self.iface.warning(
"The current working layer is not using a mercator projection like EPSG:3857. Area calculations will not work.")
provider = self.layer.dataProvider()
self.coordinateTransform = QgsCoordinateTransform(layer_crs,
self.iface.mapCanvas().mapSettings().destinationCrs(),
self.project)
err_fields = []
self.context_fieldname = self.selector_context.itemData(self.selector_context.currentIndex())
if not provider.fields().at(provider.fieldNameIndex(self.context_fieldname)).isNumeric():
self.iface.error("The {} (voters field) must be an integer number field.".format(self.context_fieldname))
del provider
return
self.polling_old_fieldname = self.selector_polling_old.itemData(self.selector_polling_old.currentIndex())
self.par_new_prefix = self.selector_target_state.itemData(self.selector_target_state.currentIndex())
# the following needs to be text fields
self.state_old_fieldname = self.selector_state_old.itemData(self.selector_state_old.currentIndex())
if provider.fields().at(provider.fieldNameIndex(self.state_old_fieldname)).type() != QVariant.String:
err_fields.append(self.state_old_fieldname)
self.par_old_fieldname = self.selector_par_old.itemData(self.selector_par_old.currentIndex())
if provider.fields().at(provider.fieldNameIndex(self.par_old_fieldname)).type() != QVariant.String:
err_fields.append(self.par_old_fieldname)
self.state_new_fieldname = self.selector_state_new.itemData(self.selector_state_new.currentIndex())
if provider.fields().at(provider.fieldNameIndex(self.state_new_fieldname)).type() != QVariant.String:
err_fields.append(self.state_new_fieldname)
self.par_new_fieldname = self.selector_par_new.itemData(self.selector_par_new.currentIndex())
if provider.fields().at(provider.fieldNameIndex(self.par_new_fieldname)).type() != QVariant.String:
err_fields.append(self.par_new_fieldname)
self.polling_new_fieldname = self.selector_polling_new.itemData(self.selector_polling_new.currentIndex())
del provider
if err_fields.__len__() != 0:
self.iface.error("The following fields must be text fields: {}".format(", ".join(err_fields)))
return
if self.layer_id != self.layer.id():
self.balancer_destroy()
self.layer_id = self.layer.id()
try:
# just need to do this once as this layer doesn't ever get changed
if self.balancer_old is None:
self.balancer_old = Balancer("old", self.layer,
self.context_fieldname,
self.polling_old_fieldname,
self.state_old_fieldname,
self.par_old_fieldname,
delta)
self.balancer_new = Balancer("new", self.layer,
self.context_fieldname,
self.polling_new_fieldname,
self.state_new_fieldname,
self.par_new_fieldname,
delta,
par_count_limit=int(self.tb_new_par_count.text()),
state_count_limit=int(self.tb_new_state_count.text()),
state_prefix_format="N%03d",
par_prefix_format="{}%02d".format(self.par_new_prefix),
polling_prefix_format="%02d",
readonly=False)
except AttributeError as attr_e:
self.iface.error("Specified fields must be part of a sequence of numbers")
self.balancer_destroy()
return
self.layer.selectionChanged.connect(self.live_show)
# init click tool
self.clickTool_prev = self.iface.mapCanvas().mapTool()
self.iface.mapCanvas().setMapTool(self.clickTool)
self.balancer_started = True
self.panel_active.setCurrentIndex(1)
self.iface.info("{} features found. Redistricting plugin started ({})."
.format(list(self.balancer_old.topology_polling.keys()).__len__(),
self.layer.id()), 4)
self.layer_redraw(True)
def feature_selector_init(self):
selected_state = self.selector_state.currentIndex()
selected_par = self.selector_par.currentIndex()
self.selector_state.clear()
self.selector_par.clear()
balancer = self.get_balancer()
unused = balancer.get_unused()
unused_colour = QtGui.QColor(Qt.green)
for i, s in enumerate(balancer.get_state_code_sequence()):
self.selector_state.insertItem(i, balancer.state_prefix_format % s, s)
if str(s) in unused[1]:
self.selector_state.setItemData(i, unused_colour, Qt.BackgroundRole)