-
Notifications
You must be signed in to change notification settings - Fork 1
/
DelinForm.cs
4524 lines (4375 loc) · 243 KB
/
DelinForm.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 ArcGIS.Core.Data;
using QueryFilter = ArcGIS.Core.Data.QueryFilter;
using ArcGIS.Core.Data.DDL;
using FieldDescription = ArcGIS.Core.Data.DDL.FieldDescription;
using ArcGIS.Core.Data.UtilityNetwork.Trace;
using ArcGIS.Core.Geometry;
using Envelope = ArcGIS.Core.Geometry.Envelope;
using Polygon = ArcGIS.Core.Geometry.Polygon;
using Unit = ArcGIS.Core.Geometry.Unit;
using AngularUnit = ArcGIS.Core.Geometry.AngularUnit;
using LinearUnit = ArcGIS.Core.Geometry.LinearUnit;
using Polyline = ArcGIS.Core.Geometry.Polyline;
using SpatialReference = ArcGIS.Core.Geometry.SpatialReference;
using ArcGIS.Desktop.Core.Geoprocessing;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using Path = System.IO.Path;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Interop;
using System.Security.Policy;
using ArcGIS.Desktop.Editing;
using ArcGIS.Core.Data.Exceptions;
using ArcGIS.Core.Internal.CIM;
using System.Security.Cryptography;
using System.Windows.Shapes;
using ArcGIS.Core.Data.Raster;
using ArcGIS.Desktop.Internal.GeoProcessing;
using ArcGIS.Core.Data.Realtime;
using ArcGIS.Desktop.Internal.Core;
using ArcGIS.Desktop.Internal.Mapping.Locate.Controls;
using MaxRev.Gdal.Core;
using OSGeo.OGR;
// Disambiguate ArcGIS and GDAL
using Layer = ArcGIS.Desktop.Mapping.Layer;
using Feature = ArcGIS.Core.Data.Feature;
using System.Runtime.InteropServices;
using System.Windows.Diagnostics;
using ArcGIS.Desktop.Core;
using OSGeo.OSR;
using ArcGIS.Desktop.Editing.Attributes;
using System.Windows.Input;
using Microsoft.VisualBasic;
using ArcGIS.Desktop.Internal.Mapping.CommonControls;
namespace ArcSWAT3
{
public partial class DelinForm : Form {
private ArcSWAT _parent;
private GlobalVars _gv;
public double areaOfCell;
public bool changing;
public bool delineationFinishedOK;
public int demHeight;
public int demWidth;
public FeatureLayer drawOutletLayer;
public string drawOutletFile;
public bool drawCurrent;
public FeatureLayer selFromLayer;
public List<int> dX;
public List<int> dY;
public HashSet<int> extraReservoirBasins;
public bool finishHasRun;
public bool isDelineated;
public MapTool mapTool;
public string currentTool;
public bool snapErrors;
public string snapFile;
public bool thresholdChanged;
public string drawFile;
public DelinForm(GlobalVars gv, bool isDelineated, ArcSWAT parent) {
InitializeComponent();
this._parent = parent;
// use GDAL for creating shapefiles
// GdalBase.ConfigureAll();
this._gv = gv;
//# 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;
//# 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;
//# flag to prevent infinite recursion between number of cells and area
this.changing = false;
//# basins selected for reservoirs
this.extraReservoirBasins = new HashSet<int>();
//# 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;
//# path of draw outlets shapefile
this.drawFile = 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
};
}
private async void selectDemButton_Click(object sender, EventArgs e) {
await this.btnSetDEM();
}
private async void burnButton_Click(object sender, EventArgs e) {
await this.btnSetBurn();
}
private void checkBurn_CheckedChanged(object sender, EventArgs e) {
if (this.checkBurn.Checked) {
this.selectBurn.Enabled = true;
this.burnButton.Enabled = true;
if (this.selectBurn.Text != "")
_gv.burnFile = this.selectBurn.Text;
} else {
this.selectBurn.Enabled = false;
this.burnButton.Enabled = false;
this._gv.burnFile = "";
}
}
// Set connections to controls; read project delineation data.
public async Task init() {
//var settings = QSettings();
//try {
// this.numProcesses.setValue(Convert.ToInt32(settings.value("/QSWAT/NumProcesses")));
//}
//catch (Exception) {
// this.numProcesses.setValue(8);
//}
this.numProcesses.Value = 8;
//this.selectDemButton.clicked.connect(this.btnSetDEM);
//this.checkBurn.stateChanged.connect(this.changeBurn);
//this.useGrid.stateChanged.connect(this.changeUseGrid);
//this.burnButton.clicked.connect(this.btnSetBurn);
//this.selectOutletsButton.clicked.connect(this.btnSetOutlets);
//this.selectWshedButton.clicked.connect(this.btnSetWatershed);
//this.selectNetButton.clicked.connect(this.btnSetStreams);
//this.selectExistOutletsButton.clicked.connect(this.btnSetOutlets);
//this.delinRunButton1.clicked.connect(this.runTauDEM1);
//this.delinRunButton2.clicked.connect(this.runTauDEM2);
//this.tabWidget.currentChanged.connect(this.changeExisting);
//this.existRunButton.clicked.connect(this.runExisting);
//this.useOutlets.stateChanged.connect(this.changeUseOutlets);
//this.drawOutletsButton.clicked.connect(this.drawOutlets);
//this.selectOutletsInteractiveButton.clicked.connect(this.selectOutlets);
//this.snapReviewButton.clicked.connect(this.snapReview);
//this.selectSubButton.clicked.connect(this.selectMergeSubbasins);
//this.mergeButton.clicked.connect(this.mergeSubbasins);
//this.selectResButton.clicked.connect(this.selectReservoirs);
//this.addButton.clicked.connect(this.addReservoirs);
//this.taudemHelpButton.clicked.connect(TauDEMUtils.taudemHelp);
//this.OKButton.clicked.connect(this.finishDelineation);
//this.cancelButton.clicked.connect(this.doClose);
//this.numCells.setValidator(QIntValidator());
//this.numCells.textChanged.connect(this.setArea);
//this.area.textChanged.connect(this.setNumCells);
//this.area.setValidator(QDoubleValidator());
this.areaUnitsBox.Items.Add(Parameters._SQKM);
this.areaUnitsBox.Items.Add(Parameters._HECTARES);
this.areaUnitsBox.Items.Add(Parameters._SQMETRES);
this.areaUnitsBox.Items.Add(Parameters._SQMILES);
this.areaUnitsBox.Items.Add(Parameters._ACRES);
this.areaUnitsBox.Items.Add(Parameters._SQFEET);
// set area units initially to hectares
this.areaUnitsBox.SelectedItem = Parameters._HECTARES;
//this.areaUnitsBox.activated.connect(this.changeAreaOfCell);
this.horizontalCombo.Items.Add(Parameters._METRES);
this.horizontalCombo.Items.Add(Parameters._FEET);
this.horizontalCombo.Items.Add(Parameters._DEGREES);
this.horizontalCombo.Items.Add(Parameters._UNKNOWN);
// set horizontal unit default to metres
this.horizontalCombo.SelectedItem = Parameters._METRES;
this.verticalCombo.Items.Add(Parameters._METRES);
this.verticalCombo.Items.Add(Parameters._FEET);
this.verticalCombo.Items.Add(Parameters._CM);
this.verticalCombo.Items.Add(Parameters._MM);
this.verticalCombo.Items.Add(Parameters._INCHES);
this.verticalCombo.Items.Add(Parameters._YARDS);
// set vertical unit default to metres
this.verticalCombo.SelectedIndex = this.verticalCombo.Items.IndexOf(Parameters._METRES);
//this.verticalCombo.activated.connect(this.setVerticalUnits);
//this.snapThreshold.setValidator(QIntValidator());
// initally disable numCells, area and areaUnitsBox (enabled only after loading DEM, when cell-area conversion possible)
this.numCells.Enabled = false;
this.area.Enabled = false;
this.areaUnitsBox.Enabled = false;
// burn not enabled until use burn checked
this.selectBurn.Enabled = false;
this.burnButton.Enabled = false;
await this.readProj();
this.setMergeResGroups();
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 void setMergeResGroups() {
this.mergeGroup.Enabled = this.isDelineated;
this.addResGroup.Enabled = this.isDelineated;
}
// Do delineation; check done and save topology data. Return OK if delineation done and no errors, 2 if not delineated and nothing done, else 0.
public async Task run() {
await this.init();
//if (this._gv.useGridModel) {
// this.useGrid.Checked = true;
// this.GridBox.Checked = true;
//} else {
// this.useGrid.Visible = false);
// this.GridBox.setVisible(false);
// this.GridSize.setVisible(false);
// this.GridSizeLabel.setVisible(false);
//}
//this.Show();
//this.Activate();
//this._gv.delineatePos = this.pos();
}
//
// 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 void checkMPI() {
var dll = "msmpi.dll";
var dummy = "msmpi_dll";
var dllPath = Utils.join(this._gv.TauDEMDir, dll);
var dummyPath = Utils.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 (File.Exists(this._gv.mpiexecPath)) {
Utils.loginfo("mpiexec found");
// MPI is on the path; rename the local dll if necessary
if (File.Exists(dllPath)) {
if (File.Exists(dummyPath)) {
File.Delete(dllPath);
Utils.loginfo("dll removed");
} else {
File.Move(dllPath, dummyPath);
Utils.loginfo("dll renamed");
}
}
} else {
Utils.loginfo("mpiexec not found");
// we don't have MPI on the path; rename the local dummy if necessary
if (File.Exists(dllPath)) {
return;
} else if (File.Exists(dummyPath)) {
File.Move(dummyPath, dllPath);
Utils.loginfo("dummy renamed");
} else {
Utils.error(String.Format("Cannot find executable mpiexec in the system or {0} in {1}: TauDEM functions will not run. Install MPI or reinstall ArcSWAT.", dll, this._gv.TauDEMDir), this._gv.isBatch);
}
}
}
private void numCells_TextChanged(object sender, EventArgs e) {
if (this.numCells.Enabled) { this.setArea(); }
}
//
// 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 async Task finishDelineation() {
FeatureLayer extraOutletLayer;
FeatureLayer outletLayer;
FeatureLayer wshedLayer;
this.delineationFinishedOK = false;
this.finishHasRun = true;
FeatureLayer streamLayer;
if (!this._gv.existingWshed && this._gv.useGridModel) {
streamLayer = (FeatureLayer)Utils.getLayerByLegend(FileTypes.legend(FileTypes._GRIDSTREAMS));
} else {
streamLayer = (FeatureLayer)(await Utils.getLayerByFilename(this._gv.streamFile, FileTypes._STREAMS, null, null, null)).Item1;
}
if (streamLayer is null) {
if (this._gv.existingWshed) {
Utils.error("Stream reaches layer not found.", this._gv.isBatch);
} else if (this._gv.useGridModel) {
Utils.error("Grid stream reaches layer not found.", this._gv.isBatch);
} else {
Utils.error("Stream reaches layer not found: have you run TauDEM?", this._gv.isBatch);
}
return;
}
if (!this._gv.existingWshed && this._gv.useGridModel) {
wshedLayer = (FeatureLayer)Utils.getLayerByLegend(Utils._GRIDLEGEND);
} else {
var ft = this._gv.existingWshed ? FileTypes._EXISTINGWATERSHED : FileTypes._WATERSHED;
wshedLayer = (FeatureLayer)(await Utils.getLayerByFilename(this._gv.wshedFile, ft, null, null, null)).Item1;
if (wshedLayer is null) {
if (this._gv.existingWshed) {
Utils.error("Watershed layer not found.", this._gv.isBatch);
} else {
Utils.error("Watershed layer not found: have you run TauDEM?", this._gv.isBatch);
}
return;
}
}
//Debug.Assert(wshedLayer is not null);
// this may be None
if (string.IsNullOrEmpty(this._gv.outletFile)) {
outletLayer = null;
} else {
outletLayer = (FeatureLayer)(await Utils.getLayerByFilename(this._gv.outletFile, FileTypes._OUTLETS, null, null, null)).Item1;
}
var demLayer = (RasterLayer)(await Utils.getLayerByFilename(this._gv.demFile, FileTypes._DEM, null, null, null)).Item1;
if (demLayer is null) {
Utils.error("DEM layer not found: have you removed it?", this._gv.isBatch);
return;
}
if (!await this.setDimensions(demLayer)) {
return;
}
if (!this._gv.useGridModel && string.IsNullOrEmpty(this._gv.basinFile)) {
// must have merged some subbasins: recreate the watershed grid
demLayer = (RasterLayer)(await Utils.getLayerByFilename(this._gv.demFile, FileTypes._DEM, null, null, null)).Item1;
if (demLayer is null) {
Utils.error(String.Format("Cannot find DEM layer for file {0}", this._gv.demFile), this._gv.isBatch);
return;
}
this._gv.basinFile = await this.createBasinFile(this._gv.wshedFile, demLayer);
if (string.IsNullOrEmpty(this._gv.basinFile)) {
return;
// Utils.loginfo('Recreated watershed grid as {0}', self._gv.basinFile))
}
}
this.saveProj();
if (this.checkDEMProcessed()) {
if (!string.IsNullOrEmpty(this._gv.extraOutletFile)) {
extraOutletLayer = (FeatureLayer)(await Utils.getLayerByFilename(this._gv.extraOutletFile, FileTypes._OUTLETS, null, null, null)).Item1;
} else {
extraOutletLayer = null;
}
if (!this._gv.existingWshed && !this._gv.useGridModel) {
this.progress("Tributary channel lengths ...");
int threshold = await this._gv.topo.makeStreamOutletThresholds(this._gv);
if (threshold > 0) {
var demBase = Path.ChangeExtension(this._gv.demFile, null);
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 = await TauDEMUtils.runDistanceToStreams(this._gv.pFile, this._gv.hd8File, this._gv.distFile, Convert.ToInt32(threshold * 0.9).ToString(), Convert.ToInt32(this.numProcesses.Value), this.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.recalcButton.Checked;
this.progress("Constructing topology ...");
this._gv.isBig = this._gv.useGridModel && wshedLayer.GetFeatureClass().GetCount() > 100000 || this._gv.forTNC;
Utils.loginfo(String.Format("isBig is {0}", this._gv.isBig));
if (await this._gv.topo.setUp(demLayer, this._gv.streamFile, this._gv.wshedFile, this._gv.outletFile, this._gv.extraOutletFile, this._gv, this._gv.existingWshed, recalculate, this._gv.useGridModel, true)) {
if (this._gv.topo.inletLinks.Count == 0) {
// no inlets, so no need to expand subbasins layer legend
//Debug.Assert(wshedLayer is not null);
await QueuedTask.Run(() => wshedLayer.SetExpanded(false));
}
this.progress("Writing Reach table ...");
streamLayer = await this._gv.topo.writeReachTable(streamLayer, this._gv);
if (streamLayer is null) {
return;
}
this.progress("Writing MonitoringPoint table ...");
this._gv.topo.writeMonitoringPointTable(demLayer, streamLayer);
this.delineationFinishedOK = true;
this.doClose(true);
this._parent.postDelineation(true);
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 || Utils.isUpToDate(this._gv.wshedFile, this._gv.basinFile);
}
if (this._gv.useGridModel) {
return Utils.isUpToDate(this._gv.slopeFile, this._gv.wshedFile);
} else {
return Utils.isUpToDate(this._gv.demFile, this._gv.wshedFile);
}
}
// Open and load DEM; set default threshold.
public async Task btnSetDEM() {
var pair = await Utils.openAndLoadFile(FileTypes._DEM, this.selectDem, this._gv.sourceDir, this._gv, null, Utils._WATERSHED_GROUP_NAME);
string demFile = pair.Item1;
RasterLayer demMapLayer = pair.Item2 as RasterLayer;
if (demFile is not null && demMapLayer is not null) {
await QueuedTask.Run(() => {
MapView.Active.ZoomTo(demMapLayer);
// set extent to DEM as otherwise defaults to full globe
var demExtent = demMapLayer.QueryExtent();
var map = MapView.Active.Map;
map.SetCustomFullExtent(demExtent);
});
this._gv.demFile = demFile;
await this.setDefaultNumCells(demMapLayer);
// warn if large DEM
var numCells = this.demWidth * this.demHeight;
if (numCells > 4000000.0) {
var millions = Convert.ToInt32(numCells / 1000000.0);
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(String.Format("Large DEM", "This DEM has over {0} million cells and could take some time to process. Be patient!", millions), Utils._ARCSWATNAME);
}
// hillshade done with relief colorizer for DEM
//// hillshade waste of (a lot of) time for TNC DEMs
//if (!this._gv.forTNC) {
// this.addHillshade(demFile, demMapLayer, this._gv);
}
}
// hillshade in ArcGIS done with relief colorizer for DEM
//// Create hillshade layer and load.
//public async Task addHillshade(string demFile, RasterLayer demMapLayer, object gv) {
// var hillshadeFile = Path.ChangeExtension(demFile) + "/hillshade.tif";
// if (!Utils.isUpToDate(demFile, hillshadeFile)) {
// // run gdaldem to generate hillshade.tif
// await Utils.removeLayerAndFiles(hillshadeFile);
// var command = String.Format("gdaldem.exe hillshade -compute_edges -z 5 \"{0}\" \"{1}\"", demFile, hillshadeFile);
// var proc = subprocess.run(command, shell: true, stdout: subprocess.PIPE, stderr: subprocess.STDOUT, universal_newlines: true);
// Utils.loginfo("Creating hillshade ...");
// Utils.loginfo(command);
// Debug.Assert(proc is not null);
// Utils.loginfo(proc.stdout);
// if (!File.Exists(hillshadeFile)) {
// Utils.information("Failed to create hillshade file {0}", hillshadeFile), gv.isBatch);
// return;
// }
// Utils.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 = Utils.getLayerByFilename(root.findLayers(), hillshadeFile, FileTypes._HILLSHADE, gv, demLayer, Utils._WATERSHED_GROUP_NAME)[0];
// if (!hillMapLayer) {
// Utils.information("Failed to load hillshade file {0}", 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 async Task btnSetBurn() {
var pair = await Utils.openAndLoadFile(FileTypes._BURN, this.selectBurn, this._gv.sourceDir, this._gv, null, Utils._WATERSHED_GROUP_NAME);
string burnFile = pair.Item1;
FeatureLayer burnLayer = pair.Item2 as FeatureLayer;
if (burnFile is not null && burnLayer is not null) {
if (burnLayer.ShapeType != ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolyline) {
Utils.error(string.Format("Burn in file {0} is not a line shapefile", burnFile), this._gv.isBatch);
} else {
this._gv.burnFile = burnFile;
}
}
}
// Open and load inlets/outlets shapefile.
public async Task btnSetOutlets() {
TextBox box;
if (this._gv.existingWshed) {
//Debug.Assert(this.tabWidget.SelectedIndex == 1);
box = this.selectExistOutlets;
} else {
//Debug.Assert(this.tabWidget.SelectedIndex == 0);
box = this.selectOutlets;
this.thresholdChanged = true;
}
var ft = this._gv.isHUC || this._gv.isHAWQS ? FileTypes._OUTLETSHUC : FileTypes._OUTLETS;
var pair = await Utils.openAndLoadFile(ft, box, this._gv.shapesDir, this._gv, null, Utils._WATERSHED_GROUP_NAME);
string outletFile = pair.Item1;
FeatureLayer outletLayer = pair.Item2 as FeatureLayer;
if (outletFile is not null && outletLayer is not null) {
if ((outletLayer.ShapeType != ArcGIS.Core.CIM.esriGeometryType.esriGeometryMultipoint) &&
(outletLayer.ShapeType != ArcGIS.Core.CIM.esriGeometryType.esriGeometryPoint)) {
Utils.error(string.Format("Inlets/outlets file {0} is not a point shapefile", outletFile), this._gv.isBatch);
} else {
this._gv.outletFile = outletFile;
}
}
}
// Open and load existing watershed shapefile.
public async Task btnSetWatershed() {
var pair = await Utils.openAndLoadFile(FileTypes._EXISTINGWATERSHED, this.selectWshed, this._gv.sourceDir, this._gv, null, Utils._WATERSHED_GROUP_NAME);
string wshedFile = pair.Item1;
FeatureLayer wshedLayer = pair.Item2 as FeatureLayer;
if (wshedFile is not null && wshedLayer is not null) {
if (wshedLayer.ShapeType != ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolygon) {
Utils.error(string.Format("Subbasins file {0} is not a polygon shapefile", this.selectWshed.Text), this._gv.isBatch);
} else {
this._gv.wshedFile = wshedFile;
}
}
}
// Open and load existing stream reach shapefile.
public async Task btnSetStreams() {
var pair = await Utils.openAndLoadFile(FileTypes._STREAMS, this.selectNet, this._gv.sourceDir, this._gv, null, Utils._WATERSHED_GROUP_NAME);
string streamFile = pair.Item1;
FeatureLayer streamLayer = pair.Item2 as FeatureLayer;
if (streamFile is not null && streamLayer is not null) {
if (streamLayer.ShapeType != ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolyline) {
Utils.error(string.Format("Streams file {0} is not a line shapefile", this.selectNet.Text), this._gv.isBatch);
} else {
this._gv.streamFile = streamFile;
}
}
}
// Run Taudem to create stream reach network.
public async Task runTauDEM1() {
await this.runTauDEM(null, false);
}
// Run TauDEM to create watershed shapefile.
public async Task runTauDEM2() {
// first remove any existing shapesDir inlets/outlets file as will
// probably be inconsistent with new subbasins
await Utils.removeLayerByLegend(Utils._EXTRALEGEND);
this._gv.extraOutletFile = "";
this.extraReservoirBasins.Clear();
if (!this.useOutlets.Checked) {
await this.runTauDEM(null, true);
} else {
var outletFile = this.selectOutlets.Text;
if (outletFile == "" || !File.Exists(outletFile)) {
Utils.error("Please select an inlets/outlets file", this._gv.isBatch);
return;
}
await this.runTauDEM(outletFile, true);
}
}
// Change between using existing and delineating watershed.
public void changeExisting() {
var tab = this.tabWidget.SelectedIndex;
if (tab > 1) {
// DEM properties or TauDEM output
return;
}
this._gv.existingWshed = tab == 1;
}
// Run TauDEM.
public async Task runTauDEM(string outletFile, bool makeWshed) {
Layer subLayer;
string ad8File;
string delineationDem;
this.delineationFinishedOK = false;
var demFile = this.selectDem.Text;
if (demFile == "" || !File.Exists(demFile)) {
Utils.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)
RasterLayer demLayer;
demLayer = (await Utils.getLayerByFilename(this._gv.demFile, FileTypes._DEM, this._gv, null, Utils._WATERSHED_GROUP_NAME)).Item1 as RasterLayer;
if (demLayer is null) {
Utils.error(string.Format("Cannot load DEM {0}", this._gv.demFile), this._gv.isBatch);
return;
}
// changing default number of cells
if (!await this.setDefaultNumCells(demLayer)) {
return;
}
string @base = Path.ChangeExtension(this._gv.demFile, null);
string suffix = Path.GetExtension(this._gv.demFile);
// burn in if required
if (this.checkBurn.Checked) {
var burnFile = this.selectBurn.Text;
if (burnFile == "") {
Utils.error("Please select a burn in stream network shapefile", this._gv.isBatch);
return;
}
if (!File.Exists(burnFile)) {
Utils.error(string.Format("Cannot find burn in file {0}", burnFile), this._gv.isBatch);
return;
}
var burnedDemFile = Path.ChangeExtension(this._gv.demFile, "_burned.tif");
if (!Utils.isUpToDate(demFile, burnedDemFile) || !Utils.isUpToDate(burnFile, burnedDemFile)) {
// just in case
await Utils.removeLayerAndFiles(burnedDemFile);
this.progress("Burning streams ...");
//burnRasterFile = self.streamToRaster(demLayer, burnFile)
//processing.runalg('saga:burnstreamnetworkintodem', demFile, burnRasterFile, burnMethod, burnEpsilon, burnedFile)
var burnDepth = this._gv.fromGRASS ? 25.0 : 50.0;
Topology.burnStream(burnFile, demFile, burnedDemFile, this._gv.verticalFactor, burnDepth, Convert.ToInt32(this._gv.topo.dx), this._gv);
if (!File.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 (File.Exists(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);
//FeatureLayer streamLayer = (await Utils.getLayerByFilename(this._gv.streamFile, FileTypes._STREAMS, this._gv, null, Utils._WATERSHED_GROUP_NAME)).Item1 as FeatureLayer;
if (!await this._gv.topo.setUp0(demLayer, this._gv.streamFile, this._gv.verticalFactor)) {
this.cleanUp(-1);
return;
}
this.isDelineated = true;
this.setMergeResGroups();
this.saveProj();
this.cleanUp(-1);
return;
}
int numProcesses = Convert.ToInt32(this.numProcesses.Value);
var mpiexecPath = this._gv.mpiexecPath;
if (numProcesses > 0 && (mpiexecPath == "" || !File.Exists(mpiexecPath))) {
Utils.information(string.Format("Cannot find MPI program {0} so running TauDEM with just one process", mpiexecPath), this._gv.isBatch);
numProcesses = 0;
this.numProcesses.Value = 0;
}
if (this.showTaudem.Checked) {
this.tabWidget.SelectedIndex = 3;
}
using (new CursorWait()) {
this.taudemOutput.Clear();
var felFile = @base + "fel" + suffix;
await Utils.removeLayer(felFile);
this.progress("PitFill ...");
var ok = await TauDEMUtils.runPitFill(delineationDem, felFile, numProcesses, this.taudemOutput);
if (!ok) {
this.cleanUp(3);
return;
}
var sd8File = @base + "sd8" + suffix;
var pFile = @base + "p" + suffix;
await Utils.removeLayer(sd8File);
await Utils.removeLayer(pFile);
this.progress("D8FlowDir ...");
ok = await TauDEMUtils.runD8FlowDir(felFile, sd8File, pFile, numProcesses, this.taudemOutput);
if (!ok) {
this.cleanUp(3);
return;
}
var slpFile = @base + "slp" + suffix;
var angFile = @base + "ang" + suffix;
await Utils.removeLayer(slpFile);
await Utils.removeLayer(angFile);
this.progress("DinfFlowDir ...");
ok = await TauDEMUtils.runDinfFlowDir(felFile, slpFile, angFile, numProcesses, this.taudemOutput);
if (!ok) {
this.cleanUp(3);
return;
}
ad8File = @base + "ad8" + suffix;
await Utils.removeLayer(ad8File);
this.progress("AreaD8 ...");
ok = await TauDEMUtils.runAreaD8(pFile, ad8File, null, null, numProcesses, this.taudemOutput, mustRun: this.thresholdChanged);
if (!ok) {
this.cleanUp(3);
return;
}
var scaFile = @base + "sca" + suffix;
await Utils.removeLayer(scaFile);
this.progress("AreaDinf ...");
ok = await TauDEMUtils.runAreaDinf(angFile, scaFile, null, numProcesses, this.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;
await Utils.removeLayer(gordFile);
await Utils.removeLayer(plenFile);
await Utils.removeLayer(tlenFile);
this.progress("GridNet ...");
ok = await TauDEMUtils.runGridNet(pFile, plenFile, tlenFile, gordFile, null, numProcesses, this.taudemOutput, mustRun: this.thresholdChanged);
if (!ok) {
this.cleanUp(3);
return;
}
var srcFile = @base + "src" + suffix;
await Utils.removeLayer(srcFile);
this.progress("Threshold ...");
if (this._gv.isBatch) {
Utils.information(string.Format("Delineation threshold: {0} cells", this.numCells.Text), true);
}
ok = await TauDEMUtils.runThreshold(ad8File, srcFile, this.numCells.Text, numProcesses, this.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 = Utils.dirToShapefile(streamFile);
var treeFile = @base + "tree.dat";
var coordFile = @base + "coord.dat";
var wFile = @base + "w" + suffix;
await Utils.removeLayer(ordFile);
await Utils.removeLayer(streamFile);
await Utils.removeLayer(wFile);
this.progress("StreamNet ...");
ok = await TauDEMUtils.runStreamNet(felFile, pFile, ad8File, srcFile, null, ordFile, treeFile, coordFile, streamFile, wFile, numProcesses, this.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 = Utils.dirToShapefile(streamFile);
// load stream network
Utils.copyPrj(demFile, wFile);
Utils.copyPrj(demFile, streamFile);
// better not to use define projection. Just generates prj and can differ from original, making new file hard to edit.
//var parms = Geoprocessing.MakeValueArray(streamFile, Path.ChangeExtension(demFile, ".prj"));
//Utils.runPython("runDefineProjection.py", parms, this._gv);
// 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 = Utils.getLayerByLegend(Utils._FULLHRUSLEGEND);
var hillshadeLayer = Utils.getLayerByLegend(Utils._HILLSHADELEGEND);
if (fullHRUsLayer is not null) {
subLayer = fullHRUsLayer;
} else if (hillshadeLayer is not null) {
subLayer = hillshadeLayer;
} else {
subLayer = null;
}
var pair = await Utils.getLayerByFilename(streamFile, FileTypes._STREAMS, this._gv, subLayer, Utils._WATERSHED_GROUP_NAME);
FeatureLayer streamLayer = pair.Item1 as FeatureLayer;
bool loaded = pair.Item2;
if (streamLayer is null || !loaded) {
Utils.error("Failed to create stream layer", this._gv.isBatch);
this.cleanUp(-1);
return;
}
this._gv.streamFile = streamFile;
if (!makeWshed) {
this.snapFile = "";
this.snappedLabel.Text = "";
this.selectOutletsInteractiveLabel.Text = "";
// initial run to enable placing of outlets, so finishes with load of stream network
this.taudemOutput.AppendText("------------------- TauDEM finished -------------------\n");
this.saveProj();
this.cleanUp(-1);
return;
}
if (this.useOutlets.Checked) {
//Debug.Assert(outletFile is not null);
var outletBase = Path.ChangeExtension(outletFile, null);
var snapFile = outletBase + "_snap.shp";
pair = await Utils.getLayerByFilename(outletFile, FileTypes._OUTLETS, this._gv, null, Utils._WATERSHED_GROUP_NAME);
FeatureLayer outletLayer = pair.Item1 as FeatureLayer;
loaded = pair.Item2;
if (outletLayer is null) {
this.cleanUp(-1);
return;
}
this.progress("SnapOutletsToStreams ...");
ok = await this.createSnapOutletFile(outletLayer, streamLayer, outletFile, snapFile);
if (!ok) {
this.cleanUp(-1);
return;
}
// replaced by snapping
// outletMovedFile = outletBase + '_moved.shp'
// Utils.removeLayer(outletMovedFile, li)
// self.progress('MoveOutletsToStreams ...')
// ok = await TauDEMUtils.runMoveOutlets(pFile, srcFile, outletFile, outletMovedFile, numProcesses, self.taudemOutput, mustRun=self.thresholdChanged)
// if not ok:
// self.cleanUp(3)
// return
// repeat AreaD8, GridNet, Threshold and StreamNet with snapped outlets
var mustRun = this.thresholdChanged || !string.IsNullOrEmpty(this.snapFile);
await Utils.removeLayer(ad8File);
this.progress("AreaD8 ...");
ok = await TauDEMUtils.runAreaD8(pFile, ad8File, this.snapFile, null, numProcesses, this.taudemOutput, mustRun: mustRun);
if (!ok) {
this.cleanUp(3);
return;
}
await Utils.removeLayer(streamFile);
this.progress("GridNet ...");
ok = await TauDEMUtils.runGridNet(pFile, plenFile, tlenFile, gordFile, this.snapFile, numProcesses, this.taudemOutput, mustRun: mustRun);
if (!ok) {
this.cleanUp(3);
return;
}
await Utils.removeLayer(srcFile);
this.progress("Threshold ...");
ok = await TauDEMUtils.runThreshold(ad8File, srcFile, this.numCells.Text, numProcesses, this.taudemOutput, mustRun: mustRun);
if (!ok) {
this.cleanUp(3);
return;
}
this.progress("StreamNet ...");
ok = await TauDEMUtils.runStreamNet(felFile, pFile, ad8File, srcFile, this.snapFile, ordFile, treeFile, coordFile, streamFile, wFile, numProcesses, this.taudemOutput, mustRun: mustRun);
if (!ok) {
this.cleanUp(3);
return;
}
Utils.copyPrj(demFile, wFile);
Utils.copyPrj(demFile, streamFile);
//var parms = Geoprocessing.MakeValueArray(streamFile, Path.ChangeExtension(demFile, ".prj"));
//try {
// Utils.runPython("runDefineProjection.py", parms, this._gv);
//} catch {; }
// make demLayer (or hillshadelayer if exists) active so streamLayer loads above it and below outlets
// (or use Full HRUs layer if there is one)
if (fullHRUsLayer is not null) {
subLayer = fullHRUsLayer;
} else if (hillshadeLayer is not null) {
subLayer = hillshadeLayer;
} else {
subLayer = null;
}
pair = await Utils.getLayerByFilename(streamFile, FileTypes._STREAMS, this._gv, subLayer, Utils._WATERSHED_GROUP_NAME);
streamLayer = pair.Item1 as FeatureLayer;
loaded = pair.Item2;
if (streamLayer is null || !loaded) {
this.cleanUp(-1);
return;
}
// check if stream network has only one feature
bool hasOneStream = await QueuedTask.Run<bool>(() => {
using (var fc = streamLayer.GetFeatureClass()) {
return (fc.GetCount() == 1);
}
});
if (hasOneStream) {
Utils.error("There is only one stream reach in your watershed, so you will only get one subbasin. You need to reduce the threshold.", this._gv.isBatch);
this.cleanUp(-1);
return;
}
}
this.taudemOutput.AppendText("------------------- TauDEM finished -------------------\n");
this._gv.pFile = pFile;
this._gv.basinFile = wFile;
if (this.checkBurn.Checked) {
// need to make slope file from original dem
var felNoburn = @base + "felnoburn" + suffix;
await Utils.removeLayer(felNoburn);
this.progress("PitFill ...");
ok = await TauDEMUtils.runPitFill(demFile, felNoburn, numProcesses, this.taudemOutput);
if (!ok) {
this.cleanUp(3);
return;
}
// use of slope.tif as name of slope file unaffected by burning in used by demProcessed check in main form
var slopeFile = @base + "slope" + suffix;
var angleFile = @base + "angle" + suffix;
await Utils.removeLayer(slopeFile);
await Utils.removeLayer(angleFile);
this.progress("DinfFlowDir ...");
ok = await TauDEMUtils.runDinfFlowDir(felNoburn, slopeFile, angleFile, numProcesses, this.taudemOutput);
if (!ok) {
this.cleanUp(3);
return;
}
this._gv.slopeFile = slopeFile;
} else {
this._gv.slopeFile = slpFile;
}
this._gv.streamFile = streamFile;
if (this.useOutlets.Checked) {
//Debug.Assert(outletFile is not null);
this._gv.outletFile = outletFile;
} else {
this._gv.outletFile = "";
}