-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdelineation.py.cs
3961 lines (3817 loc) · 209 KB
/
delineation.py.cs
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
using Optional = typing.Optional;
using Tuple = typing.Tuple;
using Dict = typing.Dict;
using Set = typing.Set;
using List = typing.List;
using Any = typing.Any;
using TYPE_CHECKING = typing.TYPE_CHECKING;
using cast = typing.cast;
using Qt = PyQt5.QtCore.Qt;
using pyqtSignal = PyQt5.QtCore.pyqtSignal;
using QFileInfo = PyQt5.QtCore.QFileInfo;
using QObject = PyQt5.QtCore.QObject;
using QSettings = PyQt5.QtCore.QSettings;
using QVariant = PyQt5.QtCore.QVariant;
using QIntValidator = PyQt5.QtGui.QIntValidator;
using QDoubleValidator = PyQt5.QtGui.QDoubleValidator;
using QColor = PyQt5.QtGui.QColor;
using QMessageBox = PyQt5.QtWidgets.QMessageBox;
using os;
using glob;
using shutil;
using math;
using subprocess;
using time;
using gdal = osgeo.gdal;
using ogr = osgeo.ogr;
using traceback;
using DelineationDialog = delineationdialog.DelineationDialog;
using TauDEMUtils = TauDEMUtils.TauDEMUtils;
using Utils = Utils.Utils;
using fileWriter = Utils.fileWriter;
using FileTypes = Utils.FileTypes;
using Topology = topology.Topology;
using OutletsDialog = outletsdialog.OutletsDialog;
using SelectSubbasins = selectsubs.SelectSubbasins;
using Parameters = parameters.Parameters;
using System.Collections.Generic;
using System;
using System.Diagnostics;
using System.Linq;
public static class delineation {
static delineation() {
@"
/***************************************************************************
QSWAT
A QGIS plugin
Create SWAT inputs
-------------------
begin : 2014-07-18
copyright : (C) 2014 by Chris George
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
";
}
public static object QgsLayerTree = Any;
public static object QgsRasterLayer = Any;
public static object QgsMapTool = Any;
public static object QgsPointXY = Any;
public static object QgsVectorLayer = Any;
public static object QgsLayerTreeGroup = Any;
public static object Transform = Dict[@int,float];
// Data about grid cell.
public class GridData {
public object area;
public int downCol;
public int downNum;
public int downRow;
public object drainArea;
public int incount;
public object maxAcc;
public object maxCol;
public object maxRow;
public object num;
public int outlet;
public GridData(
int num,
int area,
double drainArea,
int maxAcc,
int maxRow,
int maxCol) {
//# PolygonId of this grid cell
this.num = num;
//# PolygonId of downstream grid cell
this.downNum = -1;
//# Row in storeGrid of downstream grid cell
this.downRow = -1;
//# Column in storeGrid of downstream grid cell
this.downCol = -1;
//# area of this grid cell in number cells in accumulation grid
this.area = area;
//# area being drained in sq km to start of stream in this grid cell
this.drainArea = drainArea;
//# accumulation at maximum accumulation point
this.maxAcc = maxAcc;
//# Row in accumulation grid of maximum accumulation point
this.maxRow = maxRow;
//# Column in accumulation grid of maximum accumulation point
this.maxCol = maxCol;
//# polygonId of outlet cell
this.outlet = -1;
//# number of cells draining directly to this one (so zero means a leaf cell)
this.incount = 0;
}
}
// Do watershed delineation.
public class Delineation
: QObject {
public object _dlg;
public object _gv;
public object _iface;
public object _odlg;
public double areaOfCell;
public bool changing;
public bool delineationFinishedOK;
public object demHeight;
public object demWidth;
public object drawOutletLayer;
public List<int> dX;
public List<int> dY;
public object extraReservoirBasins;
public bool finishHasRun;
public bool isDelineated;
public object mapTool;
public object sizeX;
public object sizeY;
public bool snapErrors;
public string snapFile;
public bool thresholdChanged;
public Delineation(object gv, bool isDelineated) {
this._gv = gv;
this._iface = gv.iface;
this._dlg = DelineationDialog();
this._dlg.setWindowFlags(this._dlg.windowFlags() & ~Qt.WindowContextHelpButtonHint & Qt.WindowMinimizeButtonHint);
this._dlg.move(this._gv.delineatePos);
//# when a snap file is created this is set to the file path
this.snapFile = "";
//# when not all points are snapped this is set True so snapping can be rerun
this.snapErrors = false;
this._odlg = OutletsDialog();
this._odlg.setWindowFlags(this._odlg.windowFlags() & ~Qt.WindowContextHelpButtonHint);
this._odlg.move(this._gv.outletsPos);
//# Qgs vector layer for drawing inlet/outlet points
this.drawOutletLayer = null;
//# depends on DEM height and width and also on choice of area units
this.areaOfCell = 0.0;
//# Width of DEM as number of cells
this.demWidth = 0;
//# Height of DEM cell as number of cells
this.demHeight = 0;
//# Width of DEM cell in metres
this.sizeX = 0.0;
//# Height of DEM cell in metres
this.sizeY = 0.0;
//# flag to prevent infinite recursion between number of cells and area
this.changing = false;
//# basins selected for reservoirs
this.extraReservoirBasins = new HashSet<object>();
//# flag to show basic delineation is done, so removing subbasins,
//# adding reservoirs and point sources may be done
this.isDelineated = isDelineated;
//# flag to show delineation completed successfully or not
this.delineationFinishedOK = true;
//# flag to show if threshold or outlet file changed since loading form;
//# if not can assume any existing watershed is OK
this.thresholdChanged = false;
//# flag to show finishDelineation has been run
this.finishHasRun = false;
//# mapTool used for drawing outlets etc
this.mapTool = null;
//# x-offsets for TauDEM D8 flow directions, which run 1-8, so we use dir - 1 as index
this.dX = new List<int> {
1,
1,
0,
-1,
-1,
-1,
0,
1
};
//# y-offsets for TauDEM D8 flow directions, which run 1-8, so we use dir - 1 as index
this.dY = new List<int> {
0,
-1,
-1,
-1,
0,
1,
1,
1
};
}
// Set connections to controls; read project delineation data.
public virtual object init() {
var settings = QSettings();
try {
this._dlg.numProcesses.setValue(Convert.ToInt32(settings.value("/QSWAT/NumProcesses")));
} catch (Exception) {
this._dlg.numProcesses.setValue(8);
}
this._dlg.selectDemButton.clicked.connect(this.btnSetDEM);
this._dlg.checkBurn.stateChanged.connect(this.changeBurn);
this._dlg.useGrid.stateChanged.connect(this.changeUseGrid);
this._dlg.burnButton.clicked.connect(this.btnSetBurn);
this._dlg.selectOutletsButton.clicked.connect(this.btnSetOutlets);
this._dlg.selectWshedButton.clicked.connect(this.btnSetWatershed);
this._dlg.selectNetButton.clicked.connect(this.btnSetStreams);
this._dlg.selectExistOutletsButton.clicked.connect(this.btnSetOutlets);
this._dlg.delinRunButton1.clicked.connect(this.runTauDEM1);
this._dlg.delinRunButton2.clicked.connect(this.runTauDEM2);
this._dlg.tabWidget.currentChanged.connect(this.changeExisting);
this._dlg.existRunButton.clicked.connect(this.runExisting);
this._dlg.useOutlets.stateChanged.connect(this.changeUseOutlets);
this._dlg.drawOutletsButton.clicked.connect(this.drawOutlets);
this._dlg.selectOutletsInteractiveButton.clicked.connect(this.selectOutlets);
this._dlg.snapReviewButton.clicked.connect(this.snapReview);
this._dlg.selectSubButton.clicked.connect(this.selectMergeSubbasins);
this._dlg.mergeButton.clicked.connect(this.mergeSubbasins);
this._dlg.selectResButton.clicked.connect(this.selectReservoirs);
this._dlg.addButton.clicked.connect(this.addReservoirs);
this._dlg.taudemHelpButton.clicked.connect(TauDEMUtils.taudemHelp);
this._dlg.OKButton.clicked.connect(this.finishDelineation);
this._dlg.cancelButton.clicked.connect(this.doClose);
this._dlg.numCells.setValidator(QIntValidator());
this._dlg.numCells.textChanged.connect(this.setArea);
this._dlg.area.textChanged.connect(this.setNumCells);
this._dlg.area.setValidator(QDoubleValidator());
this._dlg.areaUnitsBox.addItem(Parameters._SQKM);
this._dlg.areaUnitsBox.addItem(Parameters._HECTARES);
this._dlg.areaUnitsBox.addItem(Parameters._SQMETRES);
this._dlg.areaUnitsBox.addItem(Parameters._SQMILES);
this._dlg.areaUnitsBox.addItem(Parameters._ACRES);
this._dlg.areaUnitsBox.addItem(Parameters._SQFEET);
this._dlg.areaUnitsBox.activated.connect(this.changeAreaOfCell);
this._dlg.horizontalCombo.addItem(Parameters._METRES);
this._dlg.horizontalCombo.addItem(Parameters._FEET);
this._dlg.horizontalCombo.addItem(Parameters._DEGREES);
this._dlg.horizontalCombo.addItem(Parameters._UNKNOWN);
this._dlg.verticalCombo.addItem(Parameters._METRES);
this._dlg.verticalCombo.addItem(Parameters._FEET);
this._dlg.verticalCombo.addItem(Parameters._CM);
this._dlg.verticalCombo.addItem(Parameters._MM);
this._dlg.verticalCombo.addItem(Parameters._INCHES);
this._dlg.verticalCombo.addItem(Parameters._YARDS);
// set vertical unit default to metres
this._dlg.verticalCombo.setCurrentIndex(this._dlg.verticalCombo.findText(Parameters._METRES));
this._dlg.verticalCombo.activated.connect(this.setVerticalUnits);
this._dlg.snapThreshold.setValidator(QIntValidator());
this._odlg.resumeButton.clicked.connect(this.resumeDrawing);
this.readProj();
this.setMergeResGroups();
this.thresholdChanged = false;
this.checkMPI();
// allow for cancellation without being considered an error
this.delineationFinishedOK = true;
// Prevent annoying "error 4 .shp not recognised" messages.
// These should become exceptions but instead just disappear.
// Safer in any case to raise exceptions if something goes wrong.
gdal.UseExceptions();
ogr.UseExceptions();
}
// Allow merging of subbasins and
// adding of reservoirs and point sources if delineation complete.
//
public virtual object setMergeResGroups() {
this._dlg.mergeGroup.setEnabled(this.isDelineated);
this._dlg.addResGroup.setEnabled(this.isDelineated);
}
// Do delineation; check done and save topology data. Return 1 if delineation done and no errors, 2 if not delineated and nothing done, else 0.
public virtual int run() {
this.init();
this._dlg.show();
if (this._gv.useGridModel) {
this._dlg.useGrid.setChecked(true);
this._dlg.GridBox.setChecked(true);
} else {
this._dlg.useGrid.setVisible(false);
this._dlg.GridBox.setVisible(false);
this._dlg.GridSize.setVisible(false);
this._dlg.GridSizeLabel.setVisible(false);
}
var result = this._dlg.exec_();
this._gv.delineatePos = this._dlg.pos();
if (this.delineationFinishedOK) {
if (this.finishHasRun) {
this._gv.writeMasterProgress(1, 0);
return 1;
} else {
// nothing done
return 2;
}
}
this._gv.writeMasterProgress(0, 0);
return 0;
}
//
// Try to make sure there is just one msmpi.dll, either on the path or in the TauDEM directory.
//
// TauDEM executables are built on the assumption that MPI is available.
// But they can run without MPI if msmpi.dll is placed in their directory.
// MPI will fail if there is an msmpi.dll on the path and one in the TauDEM directory
// (unless they happen to be the same version).
// QSWAT supplies msmpi_dll in the TauDEM directory that can be renamed to provide msmpi.dll
// if necessary.
// This function is called every time delineation is started so that if the user installs MPI
// or uninstalls it the appropriate steps are taken.
//
public virtual object checkMPI() {
var dll = "msmpi.dll";
var dummy = "msmpi_dll";
var dllPath = QSWATUtils.join(this._gv.TauDEMDir, dll);
var dummyPath = QSWATUtils.join(this._gv.TauDEMDir, dummy);
// tried various methods here.
//'where msmpi.dll' succeeds if it was there and is moved or renamed - cached perhaps?
// isfile fails similarly
//'where mpiexec' always fails because when run interactively the path does not include the MPI directory
// so just check for existence of mpiexec.exe and assume user will not leave msmpi.dll around
// if MPI is installed and then uninstalled
if (os.path.isfile(this._gv.mpiexecPath)) {
QSWATUtils.loginfo("mpiexec found");
// MPI is on the path; rename the local dll if necessary
if (os.path.exists(dllPath)) {
if (os.path.exists(dummyPath)) {
os.remove(dllPath);
QSWATUtils.loginfo("dll removed");
} else {
os.rename(dllPath, dummyPath);
QSWATUtils.loginfo("dll renamed");
}
}
} else {
QSWATUtils.loginfo("mpiexec not found");
// we don't have MPI on the path; rename the local dummy if necessary
if (os.path.exists(dllPath)) {
return;
} else if (os.path.exists(dummyPath)) {
os.rename(dummyPath, dllPath);
QSWATUtils.loginfo("dummy renamed");
} else {
QSWATUtils.error("Cannot find executable mpiexec in the system or {0} in {1}: TauDEM functions will not run. Install MPI or reinstall QSWAT.".format(dll, this._gv.TauDEMDir), this._gv.isBatch);
}
}
}
//
// Finish delineation.
//
// Checks stream reaches and watersheds defined, sets DEM attributes,
// checks delineation is complete, calculates flow distances,
// runs topology setup. Sets delineationFinishedOK to true if all completed successfully.
//
public virtual object finishDelineation() {
object extraOutletLayer;
object outletLayer;
object wshedLayer;
this.delineationFinishedOK = false;
this.finishHasRun = true;
var root = QgsProject.instance().layerTreeRoot();
var layers = root.findLayers();
object streamLayer = null;
if (!this._gv.existingWshed && this._gv.useGridModel) {
var treeLayer = QSWATUtils.getLayerByLegend(FileTypes.legend(FileTypes._GRIDSTREAMS), layers);
if (treeLayer is not null) {
streamLayer = treeLayer.layer();
}
} else {
streamLayer = QSWATUtils.getLayerByFilename(layers, this._gv.streamFile, FileTypes._STREAMS, null, null, null)[0];
}
if (streamLayer is null) {
if (this._gv.existingWshed) {
QSWATUtils.error("Stream reaches layer not found.", this._gv.isBatch);
} else if (this._gv.useGridModel) {
QSWATUtils.error("Grid stream reaches layer not found.", this._gv.isBatch);
} else {
QSWATUtils.error("Stream reaches layer not found: have you run TauDEM?", this._gv.isBatch);
}
return;
}
if (!this._gv.existingWshed && this._gv.useGridModel) {
var wshedTreeLayer = QSWATUtils.getLayerByLegend(QSWATUtils._GRIDLEGEND, layers);
if (wshedTreeLayer is null) {
QSWATUtils.error("Grid layer not found.", this._gv.isBatch);
return;
}
wshedLayer = wshedTreeLayer.layer();
} else {
var ft = this._gv.existingWshed ? FileTypes._EXISTINGWATERSHED : FileTypes._WATERSHED;
wshedLayer = QSWATUtils.getLayerByFilename(layers, this._gv.wshedFile, ft, null, null, null)[0];
if (wshedLayer is null) {
if (this._gv.existingWshed) {
QSWATUtils.error("Watershed layer not found.", this._gv.isBatch);
} else {
QSWATUtils.error("Watershed layer not found: have you run TauDEM?", this._gv.isBatch);
}
return;
}
}
Debug.Assert(wshedLayer is not null);
// this may be None
if (this._gv.outletFile == "") {
outletLayer = null;
} else {
outletLayer = QSWATUtils.getLayerByFilename(layers, this._gv.outletFile, FileTypes._OUTLETS, null, null, null)[0];
}
var demLayer = QSWATUtils.getLayerByFilename(layers, this._gv.demFile, FileTypes._DEM, null, null, null)[0];
if (demLayer is null) {
QSWATUtils.error("DEM layer not found: have you removed it?", this._gv.isBatch);
return;
}
if (!this.setDimensions(cast(QgsRasterLayer, demLayer))) {
return;
}
if (!this._gv.useGridModel && this._gv.basinFile == "") {
// must have merged some subbasins: recreate the watershed grid
demLayer = QSWATUtils.getLayerByFilename(layers, this._gv.demFile, FileTypes._DEM, null, null, null)[0];
if (!demLayer) {
QSWATUtils.error("Cannot find DEM layer for file {0}".format(this._gv.demFile), this._gv.isBatch);
return;
}
this._gv.basinFile = this.createBasinFile(this._gv.wshedFile, cast(QgsRasterLayer, demLayer), root);
if (this._gv.basinFile == "") {
return;
// QSWATUtils.loginfo('Recreated watershed grid as {0}'.format(self._gv.basinFile))
}
}
this.saveProj();
if (this.checkDEMProcessed()) {
if (this._gv.extraOutletFile != "") {
extraOutletLayer = QSWATUtils.getLayerByFilename(layers, this._gv.extraOutletFile, FileTypes._OUTLETS, null, null, null)[0];
} else {
extraOutletLayer = null;
}
if (!this._gv.existingWshed && !this._gv.useGridModel) {
this.progress("Tributary channel lengths ...");
var threshold = this._gv.topo.makeStreamOutletThresholds(this._gv, root);
if (threshold > 0) {
var demBase = os.path.splitext(this._gv.demFile)[0];
this._gv.distFile = demBase + "dist.tif";
// threshold is already double maximum ad8 value, so values anywhere near it can only occur at subbasin outlets;
// use fraction of it to avoid any rounding problems
var ok = TauDEMUtils.runDistanceToStreams(this._gv.pFile, this._gv.hd8File, this._gv.distFile, Convert.ToInt32(threshold * 0.9).ToString(), this._dlg.numProcesses.value(), this._dlg.taudemOutput, mustRun: this.thresholdChanged);
if (!ok) {
this.cleanUp(3);
return;
}
} else {
// Probably using existing watershed but switched tabs in delineation form
this._gv.existingWshed = true;
}
}
var recalculate = this._gv.existingWshed && this._dlg.recalcButton.isChecked();
this.progress("Constructing topology ...");
this._gv.isBig = this._gv.useGridModel && cast(QgsVectorLayer, wshedLayer).featureCount() > 100000 || this._gv.forTNC;
QSWATUtils.loginfo("isBig is {0}".format(this._gv.isBig));
if (this._gv.topo.setUp(demLayer, streamLayer, wshedLayer, outletLayer, extraOutletLayer, this._gv.db, this._gv.existingWshed, recalculate, this._gv.useGridModel, true)) {
if (!this._gv.topo.inletLinks) {
// no inlets, so no need to expand subbasins layer legend
var treeWshedLayer = root.findLayer(wshedLayer.id());
Debug.Assert(treeWshedLayer is not null);
treeWshedLayer.setExpanded(false);
}
this.progress("Writing Reach table ...");
streamLayer = this._gv.topo.writeReachTable(streamLayer, this._gv);
if (!streamLayer) {
return;
}
this.progress("Writing MonitoringPoint table ...");
this._gv.topo.writeMonitoringPointTable(demLayer, streamLayer);
this.delineationFinishedOK = true;
this.doClose();
return;
} else {
return;
}
}
return;
}
//
// Return true if using grid model or basinFile is newer than wshedFile if using existing watershed,
// or wshed file is newer than slopeFile file if using grid model,
// or wshedFile is newer than DEM.
//
public virtual bool checkDEMProcessed() {
if (this._gv.existingWshed) {
return this._gv.useGridModel || QSWATUtils.isUpToDate(this._gv.wshedFile, this._gv.basinFile);
}
if (this._gv.useGridModel) {
return QSWATUtils.isUpToDate(this._gv.slopeFile, this._gv.wshedFile);
} else {
return QSWATUtils.isUpToDate(this._gv.demFile, this._gv.wshedFile);
}
}
// Open and load DEM; set default threshold.
public virtual object btnSetDEM() {
var root = QgsProject.instance().layerTreeRoot();
(demFile, demMapLayer) = QSWATUtils.openAndLoadFile(root, FileTypes._DEM, this._dlg.selectDem, this._gv.sourceDir, this._gv, null, QSWATUtils._WATERSHED_GROUP_NAME);
if (demFile && demMapLayer) {
this._gv.demFile = demFile;
this.setDefaultNumCells(cast(QgsRasterLayer, demMapLayer));
// warn if large DEM
var numCells = this.demWidth * this.demHeight;
if (numCells > 4000000.0) {
var millions = Convert.ToInt32(numCells / 1000000.0);
this._iface.messageBar().pushMessage("Large DEM", "This DEM has over {0} million cells and could take some time to process. Be patient!".format(millions), level: Qgis.Warning, duration: 20);
}
// hillshade waste of (a lot of) time for TNC DEMs
if (!this._gv.forTNC) {
this.addHillshade(demFile, root, cast(QgsRasterLayer, demMapLayer), this._gv);
}
}
}
// Create hillshade layer and load.
[staticmethod]
public static object addHillshade(string demFile, object root, object demMapLayer, object gv) {
var hillshadeFile = os.path.split(demFile)[0] + "/hillshade.tif";
if (!QSWATUtils.isUpToDate(demFile, hillshadeFile)) {
// run gdaldem to generate hillshade.tif
(ok, path) = QSWATUtils.removeLayerAndFiles(hillshadeFile, root);
if (!ok) {
QSWATUtils.error("Failed to remove old hillshade file {0}: try repeating last click, else remove manually.".format(path), gv.isBatch);
return;
}
var command = "gdaldem.exe hillshade -compute_edges -z 5 \"{0}\" \"{1}\"".format(demFile, hillshadeFile);
var proc = subprocess.run(command, shell: true, stdout: subprocess.PIPE, stderr: subprocess.STDOUT, universal_newlines: true);
QSWATUtils.loginfo("Creating hillshade ...");
QSWATUtils.loginfo(command);
Debug.Assert(proc is not null);
QSWATUtils.loginfo(proc.stdout);
if (!os.path.exists(hillshadeFile)) {
QSWATUtils.information("Failed to create hillshade file {0}".format(hillshadeFile), gv.isBatch);
return;
}
QSWATUtils.copyPrj(demFile, hillshadeFile);
}
// make dem active layer and add hillshade above it
// demLayer allowed to be None for batch running
if (demMapLayer) {
var demLayer = root.findLayer(demMapLayer.id());
var hillMapLayer = QSWATUtils.getLayerByFilename(root.findLayers(), hillshadeFile, FileTypes._HILLSHADE, gv, demLayer, QSWATUtils._WATERSHED_GROUP_NAME)[0];
if (!hillMapLayer) {
QSWATUtils.information("Failed to load hillshade file {0}".format(hillshadeFile), gv.isBatch);
return;
}
Debug.Assert(hillMapLayer is QgsRasterLayer);
// compress legend entry
var hillTreeLayer = root.findLayer(hillMapLayer.id());
Debug.Assert(hillTreeLayer is not null);
hillTreeLayer.setExpanded(false);
hillMapLayer.renderer().setOpacity(0.4);
hillMapLayer.triggerRepaint();
}
}
// Open and load stream network to burn in.
public virtual object btnSetBurn() {
var root = QgsProject.instance().layerTreeRoot();
(burnFile, burnLayer) = QSWATUtils.openAndLoadFile(root, FileTypes._BURN, this._dlg.selectBurn, this._gv.sourceDir, this._gv, null, QSWATUtils._WATERSHED_GROUP_NAME);
if (burnFile && burnLayer) {
Debug.Assert(burnLayer is QgsVectorLayer);
var fileType = QgsWkbTypes.geometryType(burnLayer.dataProvider().wkbType());
if (fileType != QgsWkbTypes.LineGeometry) {
QSWATUtils.error("Burn in file {0} is not a line shapefile".format(burnFile), this._gv.isBatch);
} else {
this._gv.burnFile = burnFile;
}
}
}
// Open and load inlets/outlets shapefile.
public virtual object btnSetOutlets() {
object box;
var root = QgsProject.instance().layerTreeRoot();
if (this._gv.existingWshed) {
Debug.Assert(this._dlg.tabWidget.currentIndex() == 1);
box = this._dlg.selectExistOutlets;
} else {
Debug.Assert(this._dlg.tabWidget.currentIndex() == 0);
box = this._dlg.selectOutlets;
this.thresholdChanged = true;
}
var ft = this._gv.isHUC || this._gv.isHAWQS ? FileTypes._OUTLETSHUC : FileTypes._OUTLETS;
(outletFile, outletLayer) = QSWATUtils.openAndLoadFile(root, ft, box, this._gv.shapesDir, this._gv, null, QSWATUtils._WATERSHED_GROUP_NAME);
if (outletFile && outletLayer) {
Debug.Assert(outletLayer is QgsVectorLayer);
this.snapFile = "";
this._dlg.snappedLabel.setText("");
var fileType = QgsWkbTypes.geometryType(outletLayer.dataProvider().wkbType());
if (fileType != QgsWkbTypes.PointGeometry) {
QSWATUtils.error("Inlets/outlets file {0} is not a point shapefile".format(outletFile), this._gv.isBatch);
} else {
this._gv.outletFile = outletFile;
}
}
}
// Open and load existing watershed shapefile.
public virtual object btnSetWatershed() {
var root = QgsProject.instance().layerTreeRoot();
(wshedFile, wshedLayer) = QSWATUtils.openAndLoadFile(root, FileTypes._EXISTINGWATERSHED, this._dlg.selectWshed, this._gv.sourceDir, this._gv, null, QSWATUtils._WATERSHED_GROUP_NAME);
if (wshedFile && wshedLayer) {
Debug.Assert(wshedLayer is QgsVectorLayer);
var fileType = QgsWkbTypes.geometryType(wshedLayer.dataProvider().wkbType());
if (fileType != QgsWkbTypes.PolygonGeometry) {
QSWATUtils.error("Subbasins file {0} is not a polygon shapefile".format(this._dlg.selectWshed.text()), this._gv.isBatch);
} else {
this._gv.wshedFile = wshedFile;
}
}
}
// Open and load existing stream reach shapefile.
public virtual object btnSetStreams() {
var root = QgsProject.instance().layerTreeRoot();
(streamFile, streamLayer) = QSWATUtils.openAndLoadFile(root, FileTypes._STREAMS, this._dlg.selectNet, this._gv.sourceDir, this._gv, null, QSWATUtils._WATERSHED_GROUP_NAME);
if (streamFile && streamLayer) {
Debug.Assert(streamLayer is QgsVectorLayer);
var fileType = QgsWkbTypes.geometryType(streamLayer.dataProvider().wkbType());
if (fileType != QgsWkbTypes.LineGeometry) {
QSWATUtils.error("Stream reaches file {0} is not a line shapefile".format(this._dlg.selectNet.text()), this._gv.isBatch);
} else {
this._gv.streamFile = streamFile;
}
}
}
// Run Taudem to create stream reach network.
public virtual object runTauDEM1() {
this.runTauDEM(null, false);
}
// Run TauDEM to create watershed shapefile.
public virtual object runTauDEM2() {
// first remove any existing shapesDir inlets/outlets file as will
// probably be inconsistent with new subbasins
var root = QgsProject.instance().layerTreeRoot();
QSWATUtils.removeLayerByLegend(QSWATUtils._EXTRALEGEND, root.findLayers());
this._gv.extraOutletFile = "";
this.extraReservoirBasins.clear();
if (!this._dlg.useOutlets.isChecked()) {
this.runTauDEM(null, true);
} else {
var outletFile = this._dlg.selectOutlets.text();
if (outletFile == "" || !os.path.exists(outletFile)) {
QSWATUtils.error("Please select an inlets/outlets file", this._gv.isBatch);
return;
}
this.runTauDEM(outletFile, true);
}
}
// Change between using existing and delineating watershed.
public virtual object changeExisting() {
var tab = this._dlg.tabWidget.currentIndex();
if (tab > 1) {
// DEM properties or TauDEM output
return;
}
this._gv.existingWshed = tab == 1;
}
// Run TauDEM.
public virtual object runTauDEM(object outletFile, bool makeWshed) {
object subLayer;
object ad8File;
object delineationDem;
this.delineationFinishedOK = false;
var demFile = this._dlg.selectDem.text();
if (demFile == "" || !os.path.exists(demFile)) {
QSWATUtils.error("Please select a DEM file", this._gv.isBatch);
return;
}
this.isDelineated = false;
this._gv.writeMasterProgress(0, 0);
this.setMergeResGroups();
this._gv.demFile = demFile;
// find dem layer (or load it)
var root = QgsProject.instance().layerTreeRoot();
(demLayer, _) = QSWATUtils.getLayerByFilename(root.findLayers(), this._gv.demFile, FileTypes._DEM, this._gv, null, QSWATUtils._WATERSHED_GROUP_NAME);
if (!demLayer) {
QSWATUtils.error("Cannot load DEM {0}".format(this._gv.demFile), this._gv.isBatch);
return;
}
Debug.Assert(demLayer is QgsRasterLayer);
// changing default number of cells
if (!this.setDefaultNumCells(demLayer)) {
return;
}
(@base, suffix) = os.path.splitext(this._gv.demFile);
// burn in if required
if (this._dlg.checkBurn.isChecked()) {
var burnFile = this._dlg.selectBurn.text();
if (burnFile == "") {
QSWATUtils.error("Please select a burn in stream network shapefile", this._gv.isBatch);
return;
}
if (!os.path.exists(burnFile)) {
QSWATUtils.error("Cannot find burn in file {0}".format(burnFile), this._gv.isBatch);
return;
}
var burnedDemFile = os.path.splitext(this._gv.demFile)[0] + "_burned.tif";
if (!QSWATUtils.isUpToDate(demFile, burnFile) || !QSWATUtils.isUpToDate(burnFile, burnedDemFile)) {
// just in case
(ok, path) = QSWATUtils.removeLayerAndFiles(burnedDemFile, root);
if (!ok) {
QSWATUtils.error("Failed to remove old burn file {0}: try repeating last click, else remove manually.".format(path), this._gv.isBatch);
this._dlg.setCursor(Qt.ArrowCursor);
return;
}
this.progress("Burning streams ...");
//burnRasterFile = self.streamToRaster(demLayer, burnFile, root)
//processing.runalg('saga:burnstreamnetworkintodem', demFile, burnRasterFile, burnMethod, burnEpsilon, burnedFile)
var burnDepth = this._gv.fromGRASS ? 25.0 : 50.0;
QSWATTopology.burnStream(burnFile, demFile, burnedDemFile, this._gv.verticalFactor, burnDepth, this._gv.isBatch);
if (!os.path.exists(burnedDemFile)) {
this.cleanUp(-1);
return;
}
}
if (this._gv.fromGRASS) {
// just running to create burned file
this.cleanUp(-1);
return;
}
this._gv.burnedDemFile = burnedDemFile;
delineationDem = burnedDemFile;
} else {
this._gv.burnedDemFile = "";
delineationDem = demFile;
}
if (this._gv.fromGRASS) {
this._gv.pFile = @base + "p.tif";
this._gv.basinFile = @base + "w.tif";
this._gv.slopeFile = @base + "slp.tif";
// slope file should be based on original DEM
if (this._gv.slopeFile.endswith("_burnedslp.tif")) {
var unburnedslp = this._gv.slopeFile.replace("_burnedslp.tif", "slp.tif");
if (os.path.isfile(unburnedslp)) {
this._gv.slopeFile = unburnedslp;
}
}
ad8File = @base + "ad8.tif";
this._gv.outletFile = "";
this._gv.streamFile = @base + "net.shp";
this._gv.wshedFile = @base + "wshed.shp";
this.createGridShapefile(demLayer, this._gv.pFile, ad8File, this._gv.basinFile);
(streamLayer, _) = QSWATUtils.getLayerByFilename(root.findLayers(), this._gv.streamFile, FileTypes._STREAMS, this._gv, null, QSWATUtils._WATERSHED_GROUP_NAME);
if (!this._gv.topo.setUp0(demLayer, streamLayer, this._gv.verticalFactor)) {
this.cleanUp(-1);
return;
}
this.isDelineated = true;
this.setMergeResGroups();
this.saveProj();
this.cleanUp(-1);
return;
}
var numProcesses = this._dlg.numProcesses.value();
var mpiexecPath = this._gv.mpiexecPath;
if (numProcesses > 0 && (mpiexecPath == "" || !os.path.exists(mpiexecPath))) {
QSWATUtils.information("Cannot find MPI program {0} so running TauDEM with just one process".format(mpiexecPath), this._gv.isBatch);
numProcesses = 0;
this._dlg.numProcesses.setValue(0);
}
QSettings().setValue("/QSWAT/NumProcesses", numProcesses.ToString());
if (this._dlg.showTaudem.isChecked()) {
this._dlg.tabWidget.setCurrentIndex(3);
}
this._dlg.setCursor(Qt.WaitCursor);
this._dlg.taudemOutput.clear();
var felFile = @base + "fel" + suffix;
QSWATUtils.removeLayer(felFile, root);
this.progress("PitFill ...");
var ok = TauDEMUtils.runPitFill(delineationDem, felFile, numProcesses, this._dlg.taudemOutput);
if (!ok) {
this.cleanUp(3);
return;
}
var sd8File = @base + "sd8" + suffix;
var pFile = @base + "p" + suffix;
QSWATUtils.removeLayer(sd8File, root);
QSWATUtils.removeLayer(pFile, root);
this.progress("D8FlowDir ...");
ok = TauDEMUtils.runD8FlowDir(felFile, sd8File, pFile, numProcesses, this._dlg.taudemOutput);
if (!ok) {
this.cleanUp(3);
return;
}
var slpFile = @base + "slp" + suffix;
var angFile = @base + "ang" + suffix;
QSWATUtils.removeLayer(slpFile, root);
QSWATUtils.removeLayer(angFile, root);
this.progress("DinfFlowDir ...");
ok = TauDEMUtils.runDinfFlowDir(felFile, slpFile, angFile, numProcesses, this._dlg.taudemOutput);
if (!ok) {
this.cleanUp(3);
return;
}
ad8File = @base + "ad8" + suffix;
QSWATUtils.removeLayer(ad8File, root);
this.progress("AreaD8 ...");
ok = TauDEMUtils.runAreaD8(pFile, ad8File, null, null, numProcesses, this._dlg.taudemOutput, mustRun: this.thresholdChanged);
if (!ok) {
this.cleanUp(3);
return;
}
var scaFile = @base + "sca" + suffix;
QSWATUtils.removeLayer(scaFile, root);
this.progress("AreaDinf ...");
ok = TauDEMUtils.runAreaDinf(angFile, scaFile, null, numProcesses, this._dlg.taudemOutput, mustRun: this.thresholdChanged);
if (!ok) {
this.cleanUp(3);
return;
}
var gordFile = @base + "gord" + suffix;
var plenFile = @base + "plen" + suffix;
var tlenFile = @base + "tlen" + suffix;
QSWATUtils.removeLayer(gordFile, root);
QSWATUtils.removeLayer(plenFile, root);
QSWATUtils.removeLayer(tlenFile, root);
this.progress("GridNet ...");
ok = TauDEMUtils.runGridNet(pFile, plenFile, tlenFile, gordFile, null, numProcesses, this._dlg.taudemOutput, mustRun: this.thresholdChanged);
if (!ok) {
this.cleanUp(3);
return;
}
var srcFile = @base + "src" + suffix;
QSWATUtils.removeLayer(srcFile, root);
this.progress("Threshold ...");
if (this._gv.isBatch) {
QSWATUtils.information("Delineation threshold: {0} cells".format(this._dlg.numCells.text()), true);
}
ok = TauDEMUtils.runThreshold(ad8File, srcFile, this._dlg.numCells.text(), numProcesses, this._dlg.taudemOutput, mustRun: this.thresholdChanged);
if (!ok) {
this.cleanUp(3);
return;
}
var ordFile = @base + "ord" + suffix;
var streamFile = @base + "net.shp";
// if stream shapefile already exists and is a directory, set path to .shp
streamFile = QSWATUtils.dirToShapefile(streamFile);
var treeFile = @base + "tree.dat";
var coordFile = @base + "coord.dat";
var wFile = @base + "w" + suffix;
QSWATUtils.removeLayer(ordFile, root);
QSWATUtils.removeLayer(streamFile, root);
QSWATUtils.removeLayer(wFile, root);
this.progress("StreamNet ...");
ok = TauDEMUtils.runStreamNet(felFile, pFile, ad8File, srcFile, null, ordFile, treeFile, coordFile, streamFile, wFile, numProcesses, this._dlg.taudemOutput, mustRun: this.thresholdChanged);
if (!ok) {
this.cleanUp(3);
return;
}
// if stream shapefile is a directory, set path to .shp, since not done earlier if streamFile did not exist then
streamFile = QSWATUtils.dirToShapefile(streamFile);
// load stream network
QSWATUtils.copyPrj(demFile, wFile);
QSWATUtils.copyPrj(demFile, streamFile);
root = QgsProject.instance().layerTreeRoot();
// make demLayer (or hillshade if exists) active so streamLayer loads above it and below outlets
// (or use Full HRUs layer if there is one)
var fullHRUsLayer = QSWATUtils.getLayerByLegend(QSWATUtils._FULLHRUSLEGEND, root.findLayers());
var hillshadeLayer = QSWATUtils.getLayerByLegend(QSWATUtils._HILLSHADELEGEND, root.findLayers());
if (fullHRUsLayer is not null) {
subLayer = fullHRUsLayer;
} else if (hillshadeLayer is not null) {
subLayer = hillshadeLayer;
} else {
subLayer = root.findLayer(demLayer.id());
}
(streamLayer, loaded) = QSWATUtils.getLayerByFilename(root.findLayers(), streamFile, FileTypes._STREAMS, this._gv, subLayer, QSWATUtils._WATERSHED_GROUP_NAME);
if (!streamLayer || !loaded) {
this.cleanUp(-1);
return;
}
Debug.Assert(streamLayer is QgsVectorLayer);
this._gv.streamFile = streamFile;
if (!makeWshed) {
this.snapFile = "";
this._dlg.snappedLabel.setText("");
// initial run to enable placing of outlets, so finishes with load of stream network
this._dlg.taudemOutput.append("------------------- TauDEM finished -------------------\n");
this.saveProj();
this.cleanUp(-1);
return;
}
if (this._dlg.useOutlets.isChecked()) {
Debug.Assert(outletFile is not null);
var outletBase = os.path.splitext(outletFile)[0];
var snapFile = outletBase + "_snap.shp";
(outletLayer, loaded) = QSWATUtils.getLayerByFilename(root.findLayers(), outletFile, FileTypes._OUTLETS, this._gv, null, QSWATUtils._WATERSHED_GROUP_NAME);
if (!outletLayer) {
this.cleanUp(-1);
return;
}
Debug.Assert(outletLayer is QgsVectorLayer);
this.progress("SnapOutletsToStreams ...");
ok = this.createSnapOutletFile(outletLayer, streamLayer, outletFile, snapFile, root);
if (!ok) {