forked from apryet/Qgridder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
qgridder_utils_base.py
1245 lines (1011 loc) · 36.7 KB
/
qgridder_utils_base.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 -*-
"""
/***************************************************************************
qgridder_utils_base.py
Qgridder - A QGIS plugin
This file gathers main plugin functions.
Qgridder Builds 2D regular and unstructured grids and comes together with
pre- and post-processing capabilities for spatially distributed modeling.
-------------------
begin : 2013-04-08
copyright : (C) 2013 by Pryet
email : alexandre.pryet@ensegid.fr
***************************************************************************/
This plugin uses functions from fTools
Copyright (C) 2008-2011 Carson Farmer
EMAIL: carson.farmer (at) gmail.com
WEB : http://www.ftools.ca/fTools.html
/***************************************************************************
* *
* 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 PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
import numpy as np
import multiprocessing as mp
import ftools_utils
import time
# ======================================================================================
# Global constants
TOLERANCE = 1e-6 # expressed relative to a value
MAX_DECIMALS = 2 # used to limit the effects of numerical noise
# ======================================================================================
def make_rgrid(inputFeat, n, m, vprovider, progressBar = QProgressDialog("Building grid...", "Abort",0,100) ):
"""
Description
----------
Builds regular grid of n lines and m columns, from QgsRectangle bbox.
Resulting features are appended to vprovider
Parameters
----------
inputFeat : Qgis feature whose bounding box will be used to define the extents of the grid.
It can be generated by QgsRectangle()
n, m : number of rows and columns of output grid, respectively
vprovider : Qgis vector provider to which the output grid will be appended
Returns
-------
List of feature ids in the grid
Examples
--------
>>>
"""
# Retrieve bbox and attributes from input feature
bbox = inputFeat.geometry().boundingBox()
#attr = inputFeat.attributeMap()
attr = inputFeat.attributes()
# Compute grid coordinates
x = np.linspace(bbox.xMinimum(), bbox.xMaximum(), m+1)
y = np.linspace(bbox.yMinimum(), bbox.yMaximum(), n+1)
xx, yy = np.meshgrid(x, y)
# Initialize progress bar
progressBar.setRange(0,100)
progressBar.setValue(0)
count = 0
countMax = n*m
countUpdate = countMax * 0.05 # update each 5%
# Initialize feature output list
outFeatList = []
# iterate over grid lines
for i in range(len(y)-1):
# iterate over grid columns
for j in range(len(x)-1):
# compute feature coordinate
# clock-wise point numbering (top-left, top-right, bottom-right, bottom-left)
# i for lines (top to bottom), j for columns (left to right)
x1, x2, x3, x4 = xx[i+1,j], xx[i+1,j+1], xx[i,j+1], xx[i,j]
y1, y2, y3, y4 = yy[i+1,j], yy[i+1,j+1], yy[i,j+1], yy[i,j]
# define feature points
pt1, pt2, pt3, pt4 = QgsPoint(x1, y1), QgsPoint(x2, y2), QgsPoint(x3, y3), QgsPoint(x4, y4)
pt5 = pt1
# define polygon from points
polygon = [[pt1, pt2, pt3, pt4, pt5]]
# initialize new feature
outFeat = QgsFeature()
#outFeat.setAttributeMap(attr)
outFeat.setAttributes(attr)
outGeom = QgsGeometry()
outFeat.setGeometry(outGeom.fromPolygon(polygon))
# save features
outFeatList.append(outFeat)
# update counter
count += 1
# update ID (TO DO : check numbering)
#idvar = count
# each 5%, update progress bar
if int( np.fmod( count, countUpdate ) ) == 0:
prog = int( count / countMax * 100 )
progressBar.setValue(prog)
QCoreApplication.processEvents()
progressBar.setValue(100)
# Check type of vector provider
# If vprovider is a layer provider
if repr(QgsVectorDataProvider) == str(type(vprovider)):
isFeatureAddSuccessful, newFeatures = vprovider.addFeatures(outFeatList)
return([feat.id() for feat in newFeatures])
# Else, if provider is a writer
else :
for outFeat in outFeatList:
vprovider.addFeature(outFeat)
return([])
# ======================================================================================
# Format of topoRules dictionary
# -- for Modflow
#topoRules = {'model':'modflow','nmax':1}
# -- for Nested
# topoRules = {'model':'nested', 'nmax':2}
# -- no check
# topoRules = {'model':None, 'nmax':None}
# ======================================================================================
def rect_size(inputFeature):
"""
Description
Parameters
----------
inputFeature : Qgis vector feature
Returns
-------
Dictionary {'dx':dx,'dy':dy} where dx and dy are the extents of inputFeature.
Examples
--------
>>>
"""
# Extract the four corners of inputFeature
# Note : rectangle points are numbered from top-left to bottom-left, clockwise
p0, p1, p2, p3 = ftools_utils.extractPoints(inputFeature.geometry())[:4]
# Compute size
dx = abs(p1.x() - p0.x())
dy = abs(p3.y() - p0.y())
return( {'dx':dx,'dy':dy} )
# ======================================================================================
def build_vect(p1, p2):
"""
Description
----------
Return vector coordinates as { 'x' : x, 'y': y } from two QgisPoint()
Parameters
----------
p1 : parameter 1
Returns
-------
out1 : output1
Examples
--------
>>>
"""
return { 'x' : p2.x()-p1.x(), 'y': p2.y()-p1.y() }
# ======================================================================================
# Check if two vectors are colinear
def is_colinear(v1, v2):
"""
Description
Parameters
----------
p1 : parameter 1
Returns
-------
out1 : output1
Examples
--------
>>>
"""
if( is_equal( v1['y']*v2['x'] - v1['x']*v2['y'] , 0 ) ):
return True
else :
return False
# ======================================================================================
def update_fixDict(fixDict, thisFixDict):
"""
Description
----------
Appends records of thisFixDict to fixDict
thisFixDict and fixDict should have the same structure : fixDict = { 'id':[] , 'n':[], 'm':[] }
n and m correponds to the number split to perform along rows and columns, respectively.
If a record of thisFixDict is already in fixDict, updates the corresponding record
If not, simply appends the record to fixDict
Parameters
----------
fixDict : The feature dictionary to be extended, { 'id':[] , 'n':[], 'm':[] }
thisFixDict : The feature dictionary to append to fixDict
Returns
-------
fixDict with features from thisFixDict appended.
Examples
--------
>>>
"""
for fId, n, m in zip( thisFixDict['id'], thisFixDict['n'], thisFixDict['m'] ):
# if the feature is already in fixDict, update this record
if fId in fixDict['id']:
i = fixDict['id'].index(fId)
fixDict['n'][i] = max( n, fixDict['n'][i] )
fixDict['m'][i] = max( m, fixDict['m'][i] )
# if the feature is not in fixDict, append it
else :
fixDict['id'].append(fId)
fixDict['n'].append(n)
fixDict['m'].append(m)
return fixDict
# ======================================================================================
def is_equal(a,b,relativeError=TOLERANCE):
"""
Description
----------
From Ftools, voronoi.py
Check whether two values are identical for a given a tolerance interval
Parameters
----------
a, b : float values to compare
relativeError : float value representative of the tolerance
Returns
-------
True if a equals b, False otherwise.
Examples
--------
>>>
"""
# is nearly equal to within the allowed relative error
norm = max(abs(a),abs(b))
return (norm < relativeError) or (abs(a - b) < (relativeError * norm))
# ======================================================================================
def is_over(geomA,geomB,relativeError=TOLERANCE):
"""
Description
----------
Checks wheter two QgsPoints are identical for a given tolerance interval.
Parameters
----------
geomA, geomB : Qgis vector feature geometry.
Returns
-------
relativeError : float value representative of the tolerance
Examples
--------
>>>
"""
return ( is_equal( geomA.x(), geomB.x() ) and
is_equal( geomA.y(), geomB.y() )
)
# ======================================================================================
def refine_by_split(featIds, n, m, topoRules, gridLayer, progressBar = QProgressDialog("Building grid...", "Abort",0,100), labelIter = QLabel() ) :
"""
Description
----------
Split inputFeatures in gridLayer and check their topology
Parameters
----------
featIds : ids of features from gridLayer to be refined
n : number of split for selected cells in the horizontal direction
m : number of split for selected cells in the vertical direction
topoRules : topological rules for the propagation of refinement
gridLayer : grid layer to be refined
progressBar : progress bar in dialog
labelIter : iteration label in dialog
Returns
-------
Nothing, just gridLayer is updated
Examples
--------
>>>
"""
start_time = time.time()
# -- Procedure for regular structured grids (MODFLOW , n_max = 1)
if topoRules['nmax'] == 1 :
# build feature dictionary
allFeatures = {feature.id(): feature for feature in gridLayer.getFeatures()}
# init fix dictionary
rowFixDict = { 'id': [] , 'n':[], 'm':[] }
colFixDict = { 'id': [] , 'n':[], 'm':[] }
# Initialize spatial index
gridLayerIndex = QgsSpatialIndex()
# Fill spatial Index
for feat in allFeatures.values():
gridLayerIndex.insertFeature(feat)
# get bbox of grid layer
grid_bbox = gridLayer.extent()
# iterate over initial feature set
# -- cells that have to be split horizontally
if n > 1 :
for featId in featIds :
# only consider featId if current row has not been considered before
if featId not in rowFixDict['id'] :
# build bounding box over row
bbox = allFeatures[featId].geometry().boundingBox()
bbox.setXMinimum( grid_bbox.xMinimum() )
bbox.setXMaximum( grid_bbox.xMaximum() )
bbox.setYMinimum( bbox.yMinimum() + TOLERANCE )
bbox.setYMaximum( bbox.yMaximum() - TOLERANCE )
# get features in current row
rowFeatIds = gridLayerIndex.intersects( bbox )
# update fixDict with features in current row
thisFixDict = { 'id':rowFeatIds , 'n':[n]*len(rowFeatIds), 'm':[1]*len(rowFeatIds) }
rowFixtDict = update_fixDict(rowFixDict,thisFixDict)
# -- cells that have to be split along columns
if m > 1 :
for featId in featIds :
# only consider featId if current row has not been considered before
if featId not in colFixDict['id'] :
# build bounding box over column
bbox = allFeatures[featId].geometry().boundingBox()
bbox.setXMinimum( bbox.xMinimum() + TOLERANCE )
bbox.setXMaximum( bbox.xMaximum() - TOLERANCE )
bbox.setYMinimum( grid_bbox.yMinimum() )
bbox.setYMaximum( grid_bbox.yMaximum() )
# get features in current column
colFeatIds = gridLayerIndex.intersects( bbox )
# update fixDict with features in current column
thisFixDict = { 'id':colFeatIds , 'n':[1]*len(colFeatIds), 'm':[m]*len(colFeatIds) }
colFixtDict = update_fixDict(colFixDict,thisFixDict)
fixDict = rowFixDict.copy()
fixDict = update_fixDict(fixDict,colFixDict)
newFeatIds = split_cells(fixDict, gridLayer)
print("OPTIM OVER %s sec" % (time.time() - start_time))
return()
# -- Refinement procedure for nested grids
# init iteration counter
itCount = 0
# init fix dict
fixDict = { 'id': featIds , 'n':[n]*len(featIds), 'm':[m]*len(featIds) }
# Continue until inputFeatures is empty
while len(fixDict['id']) > 0:
# Split inputFeatures
newFeatIds = split_cells(fixDict, gridLayer)
# Get all the features
allFeatures = {feature.id(): feature for feature in gridLayer.getFeatures()}
# Initialize spatial index
gridLayerIndex = QgsSpatialIndex()
# Fill spatial Index
for feat in allFeatures.values():
gridLayerIndex.insertFeature(feat)
# re-initialize the list of features to be fixed
fixDict = { 'id':[] , 'n':[], 'm':[] }
# Initialize progress bar
progressBar.setRange(0,100)
progressBar.setValue(0)
count = 0
countMax = len(newFeatIds)
countUpdate = countMax * 0.05 # update each 5%
# Iterate over newFeatures to check topology
for newFeatId in newFeatIds:
# Get the neighbors of newFeatId that must be fixed
thisFixDict = check_topo( newFeatId, n, m, topoRules, allFeatures, gridLayer, gridLayerIndex)
# Update fixDict with thisFixDict
fixDict = update_fixDict(fixDict,thisFixDict)
# update counter
count += 1
# update progressBar
if int( np.fmod( count, countUpdate ) ) == 0:
prog = int( count / countMax * 100 )
progressBar.setValue(prog)
QCoreApplication.processEvents()
progressBar.setValue(100)
# Update iteration counter
itCount+=1
labelIter.setText(unicode(itCount))
print("BASE OVER %s sec" % (time.time() - start_time))
# ======================================================================================
def split_cells(fixDict, vLayer = QgsVectorLayer()):
"""
Description
----------
Split features in fixDict into n and m identical parts along rows and columns, respectively
Parameters
----------
fixDict : { 'id':[] , 'n':[], 'm':[] }
n, m : number of parts to split feature
Returns
-------
List of IDs of new features
Examples
--------
>>>
"""
# note that n and m parameters are obsolete.
# Get all the features from vLayer
allFeatures = {feature.id(): feature for (feature) in vLayer.getFeatures()}
# remove features that must be split from vLayer
# this operation must be done before any feature add
# since ids() are updated
vLayer.dataProvider().deleteFeatures(fixDict['id'])
# Initialize the list of new features
newFeatIds = []
# Split each element of fixDict
for featId, n, m in zip( fixDict['id'], fixDict['n'], fixDict['m'] ):
feat = allFeatures[featId]
newFeatIds.extend( make_rgrid(feat, n, m, vLayer.dataProvider() ) )
# Return new features
return(newFeatIds)
# --------------------------------------------------------------------------------------------------------------
# Check the coherence of a boundary between 2 grid elements
def is_valid_boundary( feat1, feat2, direction, topoRules ):
"""
Description
Parameters
----------
p1 : parameter 1
Returns
-------
out1 : output1
Examples
--------
>>>
"""
# feat1, feat2 (QgsFeature) : the features considered
# direction (Int)
# Numbering rule for neighbors of feature 0 :
# | 8 | 1 | 5 |
# | 4 | 0 | 2 |
# | 7 | 3 | 6 |
# topo Rules (Dict) :
# -- for Modflow
#topoRules = {'model':'modflow','nmax':1}
# -- for Nested
# topoRules = {'model':'nested', 'nmax':2}
# get feat1 geometry
dx1, dy1 = rect_size(feat1)['dx'], rect_size(feat1)['dy']
# get feat2 geometry
dx2, dy2 = rect_size(feat2)['dx'], rect_size(feat2)['dy']
# Check if the boundary satisfies topoRules
# Note: in the logic of this program, we only consider the case
# when the neighbor is bigger than the given cell (dy2/dy1 >=1)
# Indeed, we
# start with a regular grid. The topology is checked at each
# feature split.
if direction == 2 or direction == 4 : # horizontal directions
if dy2 / dy1 < 1 or is_equal(dy2 / dy1, 1 ) or \
dy2 / dy1 < topoRules['nmax'] or is_equal(dy2 / dy1, topoRules['nmax']) :
return(True)
if direction == 1 or direction == 3 : # vertical directions
if ( dx2 / dx1 < 1 or is_equal(dx2 / dx1, 1 ) ) or \
(dx2 / dx1 < topoRules['nmax'] or is_equal(dx2 / dx1, topoRules['nmax']) ) :
return(True)
# If the boundary doesn't satisfy topoRules, or
# if the direction is not valid
return(False)
# --------------------------------------------------------------------------------------------------------------
# Check topology of feat's neighbors and
# return the neighbors that don't satisfy topoRules
def check_topo(featId, n, m, topoRules, allFeatures, vLayer, vLayerIndex):
"""
Description
Parameters
----------
p1 : parameter 1
Returns
-------
out1 : output1
Examples
--------
>>>
"""
# Get the feature
feat = allFeatures[featId]
# Initialize list of features to be fixed
fixDict = { 'id':[] , 'n':[], 'm':[] }
# Find neighbors
neighbors = find_neighbors(feat, allFeatures, vLayerIndex)
# Check the compatibility of inputFeature and neighbors with topoRules
for direction, neighbor in zip(neighbors['direction'], neighbors['feature']):
if direction in [1, 2, 3, 4]:
# Special case for nested grid
if topoRules['model']=='nested':
N = M = 2
else :
N = n
M = m
# Set refinement to 1 for orthogonal directions
if direction in [2,4] : # horizontally
M = 1
elif direction in [1,3] : # vertically
N = 1
# check feat, neighbor boundary
if not is_valid_boundary( feat, neighbor, direction, topoRules ) :
# update fixDict : add neighbor
fixDict = update_fixDict( fixDict, { 'id':[neighbor.id()] , 'n':[N], 'm':[M] } )
# check neighbor, feat boundary
if not is_valid_boundary( neighbor, feat, direction, topoRules ) :
# update fixDict : add feat
fixDict = update_fixDict( fixDict, { 'id':[feat.id()] , 'n':[N], 'm':[M] } )
# return features that do not satisfy topoRules
return fixDict
# --------------------------------------------------------------------------------------------------------------
# Find the neighbors of inputFeature neighbor and identify the direction
def find_neighbors(inputFeature, allFeatures, vLayerIndex):
"""
Description
Parameters
----------
p1 : parameter 1
Returns
-------
out1 : output1
Examples
--------
>>>
"""
# Get neighbors Ids.
neighborsId = vLayerIndex.intersects( inputFeature.geometry().boundingBox() )
# Get neighbors
featNeighbors = [ allFeatures[featId] for featId in neighborsId ]
# Initialize dictionary
neighbors = { 'direction':[], 'feature':[] }
# Extract the four corners of inputFeature
# Note : rectangle points are numbered from top-left to bottom-left, clockwise
p0, p1, p2, p3 = ftools_utils.extractPoints(inputFeature.geometry())[:4]
# Iterate over neighbors
for featNeighbor in featNeighbors:
# Extract the four corners of neighbor
# Note : rectangle points are numbered from top-left to bottom-left, clockwise
q0, q1, q2, q3 = ftools_utils.extractPoints(featNeighbor.geometry())[:4]
# Numbering rule for neighbors of feature 0 :
# | 8 | 1 | 5 |
# | 4 | 0 | 2 |
# | 7 | 3 | 6 |
# Identify type of neighborhood
if is_over(p0, q0) and is_over(p1, q1) and is_over(p2, q2) and is_over(p3, q3):
cell_dir = 0 # features overlap
elif is_over(p0, q3) and is_over(p1, q2):
cell_dir = 1 # feature B is above A
elif is_over(p1, q0) and is_over(p2, q3):
cell_dir = 2 # feature B is to the right of A
elif is_over(p2, q1) and is_over(p3, q0):
cell_dir = 3 # feature B is below A
elif is_over(p3, q2) and is_over(p0, q1):
cell_dir = 4 # feature B is to the left of A
elif is_over(p1, q3):
cell_dir = 5 # feature B is to the top-right corner of A
elif is_over(p2, q0):
cell_dir = 6 # feature B is to the bottom-right corner of A
elif is_over(p3, q1):
cell_dir = 7 # feature B is to the bottom-left corner of A
elif is_over(p0, q2):
cell_dir = 8 # feature B is to the top-left corner of A
elif is_colinear( build_vect(q3, p0), build_vect(p1, q2) ) and \
is_colinear(build_vect(q3, p0), {'x':1, 'y':0} ) and \
is_colinear(build_vect(p1, q2), {'x':1, 'y':0} ) :
cell_dir = 1 # feature B is above A
elif is_colinear( build_vect(q3, p2), build_vect(p1, q0) ) and \
is_colinear(build_vect(q3, p2), {'x':0, 'y':1} ) and \
is_colinear(build_vect(p1, q0), {'x':0, 'y':1} ) :
cell_dir = 2 # feature B is to the right of A
elif is_colinear( build_vect(q0, p3), build_vect(p2, q1) ) and \
is_colinear(build_vect(q0, p3), {'x':1, 'y':0} ) and \
is_colinear(build_vect(p2, q1), {'x':1, 'y':0} ) :
cell_dir = 3 # feature B is below A
elif is_colinear( build_vect(q2, p3), build_vect(p0, q1) ) and \
is_colinear(build_vect(q2, p3), {'x':0, 'y':1} ) and \
is_colinear(build_vect(p0, q1), {'x':0, 'y':1} ) :
cell_dir = 4 # feature B is to the left of A
else :
cell_dir = -1 # feature B is not a neighbor in a valid grid
# If the feature is an "actual" neighbor, save it to the dictionary
# "actual" = neither the feature itself, neither neighbors from corners
#if cell_dir > 0 :
neighbors['direction'].append(cell_dir)
neighbors['feature'].append(featNeighbor)
# Return dictionary with neighbors
return neighbors
# -----------------------------------------------------
# get centroids of a grid layer
def get_centroid_layer(gridLayer) :
"""
Description
-----------
return layer of centroids (cLayer) from layer of polygons (gridLayer)
Parameters
----------
gridLayer : polygon layer (grid)
Returns
-------
cLayer : centroid layer (pointset)
Examples
--------
>>> cLayer = get_grid_centroids(gridLayer)
"""
# build memory layer of centroids
cLayer = QgsVectorLayer("Point?crs=" + gridLayer.crs().authid(), 'cLayer', providerLib = 'memory')
# list of centroid features
feat_centroids = []
# build centroids features
for feat in gridLayer.getFeatures() :
feat_centroid = QgsFeature()
feat_centroid.setGeometry(QgsGeometry(feat.geometry().centroid()))
feat_centroids.append(feat_centroid)
# populate layer
success, feature = cLayer.dataProvider().addFeatures( feat_centroids )
if success :
return(cLayer)
else :
return(None)
# -----------------------------------------------------
# get nrow and ncol or a regular (modflow) grid layer
def get_rgrid_nrow_ncol(gridLayer):
"""
Description
Parameters
----------
p1 : parameter 1
Returns
-------
out1 : output1
Examples
--------
>>>
"""
# TODO : check if the grid is actually regular
# Load layer
#allAttrs = gridLayer.pendingAllAttributesList()
#gridLayer.select(allAttrs)
# Init variables
allFeatures = {feat.id():feat for feat in gridLayer.getFeatures()}
allCentroids = [feat.geometry().centroid().asPoint() \
for feat in allFeatures.values()]
centroids_ids = allFeatures.keys()
centroids_x = [centroid.x() for centroid in allCentroids]
centroids_y = [centroid.y() for centroid in allCentroids]
centroids = np.array( [centroids_ids , centroids_x, centroids_y] )
centroids = centroids.T
# get ncol :
# sort by decreasing y and increasing x
idx_row = np.lexsort([centroids[:,1],-centroids[:,2]])
yy = centroids[idx_row,2]
# iterate along first row and count number of items with same y
i=0
#return yy
while is_equal(yy[i],yy[i+1]):
i+=1
if i >= (yy.size - 1):
break # for one-row grids
ncol = i+1
# get nrow :
# sort by increasing x and decreasing y
idx_col = np.lexsort([-centroids[:,2],centroids[:,1]])
xx=centroids[idx_col,1]
# iterate over first col and count number of items with same x
i=0
while is_equal(xx[i],xx[i+1]) :
i+=1
if i >= (xx.size-1):
break # for one-column grids
nrow = i+1
# return nrow, ncol
return(nrow, ncol)
# ======================================================================================
def get_rgrid_delr_delc(gridLayer):
"""
Description
----------
get delr delc of a structured (modflow-like) grid layer
Parameters
----------
p1 : parameter 1
Returns
-------
out1 : output1
Examples
--------
>>>
"""
# TODO : check if the grid is actually regular
# Load layer
#allAttrs = gridLayer.pendingAllAttributesList()
#gridLayer.select(allAttrs)
#gridLayer.dataProvider().select(allAttrs)
# Init variables
allFeatures = {feat.id():feat for feat in gridLayer.getFeatures()}
allCentroids = [feat.geometry().centroid().asPoint() \
for feat in allFeatures.values()]
centroids_ids = allFeatures.keys()
centroids_x = [centroid.x() for centroid in allCentroids]
centroids_y = [centroid.y() for centroid in allCentroids]
centroids = np.array( [centroids_ids , centroids_x, centroids_y] )
centroids = centroids.T
# get nrow, ncol
nrow, ncol = get_rgrid_nrow_ncol(gridLayer)
# init list
delr = []
delc = []
# sort by decreasing y and increasing x
idx_row = np.lexsort([centroids[:,1],-centroids[:,2]])
# iterate along first row
for featId in centroids[idx_row,0][:ncol]:
# Extract the four corners of feat
# Note : rectangle points are numbered from top-left to bottom-left, clockwise
p0, p1, p2, p3 = ftools_utils.extractPoints(allFeatures[featId].geometry())[:4]
delr.append( p1.x() - p0.x() )
# sort by increasing x and decreasing y
idx_col = np.lexsort([-centroids[:,2],centroids[:,1]])
# iterate along first col
for featId in centroids[idx_col,0][:nrow]:
# Extract the four corners of feat
# Note : rectangle points are numbered from top-left to bottom-left, clockwise
p0, p1, p2, p3 = ftools_utils.extractPoints(allFeatures[featId].geometry())[:4]
delc.append( p0.y() - p3.y() )
# round
delr = [round(val, MAX_DECIMALS) for val in delr]
delc = [round(val, MAX_DECIMALS) for val in delc]
# If all values are identical, return scalar
if delr.count(delr[0]) == len(delr):
delr = delr[0]
if delc.count(delc[0]) == len(delc):
delc = delc[0]
return(delr, delc)
# ======================================================================================
def rgrid_numbering(gridLayer):
"""
Description
----------
Adds attributes NROW, NCOL to a regular (modflow) grid layer
Parameters
----------
p1 : parameter 1
Returns
-------
out1 : output1
Examples
--------
>>>
"""
# TODO : check if the grid is actually regular
caps = gridLayer.dataProvider().capabilities()
# Init variables
res = 1
allFeatures = {feat.id():feat for feat in gridLayer.getFeatures()}
allCentroids = [feat.geometry().centroid().asPoint() \
for feat in allFeatures.values()]
centroids_ids = allFeatures.keys()
centroids_x = np.around(np.array([centroid.x() for centroid in allCentroids]), MAX_DECIMALS)
centroids_y = np.around(np.array([centroid.y() for centroid in allCentroids]), MAX_DECIMALS)
centroids = np.array( [centroids_ids , centroids_x, centroids_y] )
centroids = centroids.T
# Fetch field name index of ROW and COL
# If columns don't exist, add them
row_field_idx = gridLayer.dataProvider().fieldNameIndex('ROW')
col_field_idx = gridLayer.dataProvider().fieldNameIndex('COL')
cx_field_idx = gridLayer.dataProvider().fieldNameIndex('CX')
cy_field_idx = gridLayer.dataProvider().fieldNameIndex('CY')
if row_field_idx == -1:
if caps & QgsVectorDataProvider.AddAttributes:
res = gridLayer.dataProvider().addAttributes( [QgsField("ROW", QVariant.Int)] )
if col_field_idx == -1:
if caps & QgsVectorDataProvider.AddAttributes:
res = res*gridLayer.dataProvider().addAttributes( [QgsField("COL", QVariant.Int)] )
if cx_field_idx == -1:
if caps & QgsVectorDataProvider.AddAttributes:
res = gridLayer.dataProvider().addAttributes( [QgsField("CX", QVariant.Double)] )
if cy_field_idx == -1:
if caps & QgsVectorDataProvider.AddAttributes:
res = res*gridLayer.dataProvider().addAttributes( [QgsField("CY", QVariant.Double)] )
row_field_idx = gridLayer.dataProvider().fieldNameIndex('ROW')
col_field_idx = gridLayer.dataProvider().fieldNameIndex('COL')
cx_field_idx = gridLayer.dataProvider().fieldNameIndex('CX')
cy_field_idx = gridLayer.dataProvider().fieldNameIndex('CY')
# update fields
gridLayer.updateFields()
# get nrow, ncol
nrow, ncol = get_rgrid_nrow_ncol(gridLayer)
# Iterate over grid row-wise and column wise
# sort by decreasing y and increasing x
idx = np.lexsort( [centroids_x,-1*centroids_y] )
centroids = centroids[idx,:]
row = 0 # 0-based
col = 0 # 0-based
# start editing
gridLayer.startEditing()
attrValues = {}
for i in range(centroids.shape[0]):
if col > ncol:
col = 1
row = row + 1
featId = centroids[i, 0]
cx = centroids[i, 1]
cy = centroids[i, 2]
attr = { row_field_idx : int(row), col_field_idx : int(col),\
cx_field_idx : float(cx), cy_field_idx : float(cy)}
attrValues[featId] = attr
col+=1
# write attributes to shapefile
res = gridLayer.dataProvider().changeAttributeValues(attrValues)
# commit
gridLayer.commitChanges()
# res should be True if the operation is successful
return(res)
# ======================================================================================
def get_overlapping_features_areas(feat, spatialIndex, gridLayerFeatures) :
"""
Description
Parameters