-
Notifications
You must be signed in to change notification settings - Fork 36
/
KsnProfiler.m
3814 lines (3330 loc) · 121 KB
/
KsnProfiler.m
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
function [knl,ksn_master,bnd_list,kn_list,Sc]=KsnProfiler(DEM,FD,A,S,varargin)
%
% Usage:
% [knl,ksn_master,bnd_list,kn_list,Sc]=KsnProfiler(DEM,FD,A,S);
% [knl,ksn_master,bnd_list,kn_list,Sc]=KsnProfiler(DEM,FD,A,S,'name',value,...);
%
% Description:
% Function to interactively select channel heads and define segements over which to calculate channel steepness values.
% This function is designed to be similar to the operation of Profiler_51, with some improvements. Function will display map
% with the stream network and expects the user to select a location near a channel head of interest. The user will be then
% prompted to confirm that the defined stream is the desired choice. Finally, displays of the chi-z and longitudinal profile
% of the selected river will appear and the user is expected to define (with mouse clicks) any obvious segments with different
% channel steepness (or concavity) on either the chi-z plot, the stream profile, or a slope-area plot (see 'pick_method' option).
% When done selecting press enter/return. The user will be prompted whether they wish to continue picking streams or if they are done.
% When done picking streams, the function will output five different products (see below) and produce a shapefile of the selected streams
% with ksn, concavity, area, and gradient.
%
% Picking Bounds:
% The function expects that you will select bounds for defining different ksn segments on the appropriate plot (the one with red
% axes, based on what you provide to 'pick_method') with LEFT MOUSE CLICKS. If you click any other mouse button or press any key
% (other than the return/enter key) the code will recognize this as selecting a knickpoint location. This is distinguished from a
% bound in that it's positions will be logged and recorded in the 'kn_list' output, but it will NOT be used to define different
% ksn segments. This is to provide the user the ability to 'mark' locations on the profile that you do not wish to use as bounds.
% Both bounds and these marked locations are provided to inputs to the companion 'ClassifyKnicks' function (where the bounds and
% these knickpoints / marked locations are distinguished from each other).
%
% Required Inputs:
% DEM - Digital Elevation as a GRIDobj, assumes unconditioned DEM (e.g. DEMoc from ProcessRiverBasins or output from MakeStreams)
% FD - Flow direction as FLOWobj
% S - Stream network as STREAMobj
% A - Flow accumulation GRIDobj
%
%%%%%%%%%%%%%%%%%%
% Optional Inputs:
%
%%% Restart Picking
% restart [] - providing an entry to this parameter allows the user to restart a run, either a run that you succesfully completed
% but want to restart or a run that failed part way through either because of an error or because you aborted out. While
% the code is running, it will save data necessary to restart in a mat file called '*_restart.mat'. If the code succesfully
% completes, this '*_restart.mat' file will be deleted. DO NOT DELETE THIS FILE WHILE THE CODE IS RUNNING OR IF THE CODE FAILS
% AND YOU WISH TO SALVAGE THE RUN. You can also call use restart if you just wish to restart picking streams from a previously
% completed run. If you run the code with an 'input_method' other than 'interactive' and the code succesfully completes (i.e
% you fit all the streams selected via the input method you choose and you did not stop the code early) then running with restart
% will not do anything. If you wish to restart, you do not need to define any of the original parameters, these are saved in the
% output files and will be loaded in, you only need to provide the four required inputs (see example) along with the restart parameter.
% Valid inputs to restart are:
% 'continue' - will restart the run. If used with a completed or failed 'interactive' run will repopulate the map with already picked
% streams and you can continue picking. If using with a non interactive input method that either failed or you aborted, will start
% on the next stream in the sequence.
% 'skip' - only a meaningful input for a non interactive run. This will skip the next stream segment in the sequence. This would be useful
% if a particular stream segment causes the code to error, this way you can skip that stream in a restart without having to modifying
% the stream network.
%
%%% Main Options
% input_method ['interactive'] - parameter which controls how streams of interest are supplied:
% 'interactive' - user picks streams of interest by selecting channelheads on a map, this option will also iteratively build a
% channel steepness map as the user picks more streams.
% 'all_streams' - will use the supplied STREAMobj and iterate through all channel heads. There is an internal parameter to avoid
% selecting streams that are too short to properly fit (mostly relevant if 'junction method' is set to 'check'). The default
% value is ~4 * the DEM cellisze, the user can change this value by providing an input for the optional parameter 'min_channel_length',
% input should be in map units and greater than the default. You can use a code like 'SegmentPicker' to select portions of a STREAMobj
% 'stream_length' - will use supplied STREAMobj and entry to 'min_length_to_extract' to iterate through all streams that are longer than
% the length provided to 'min_length_to_extract'. There is an internal parameter to avoid selecting streams that are too short to fit
% (mostly relevant if 'junction method' is set to 'check'). The default value is ~4 * the DEM cellsize, the user can change this value
% by providing an input for the optional parameter 'min_channel_length', input should be in map units and greater than the default.
% 'channel_heads' - will use a supplied list of coordinates of channel heads to select and iterate through streams of interest. If this
% option is used, the user must provide an input for the optional 'channel_head_list' parameter.
% pick_method ['chi'] - choice of how you want to pick stream segments. The diagram within which to pick based on your selection will be
% outline in red. Valid inputs are:
% 'chi' - select segments on a chi - z plot (recommended and default)
% 'stream' - select segments on a longitudinal profile
% 'slope_area' - select segments on a slope area plot
% junction_method ['check'] - choice of how to deal with stream junctions:
% 'check' - after each choice, will check whether downstream portions of the selected stream have already been fit, and if it has,
% the already fit portion of the stream will not be displayed or refit
% 'ignore' - each stream will be displayed from its head to mouth independent of whether portions of the same stream network have
% been fit
% concavity_method ['ref']- options for concavity:
% 'ref' - uses a reference concavity, the user can specify this value with the reference concavity option (see below)
% 'auto' - function finds a best fit concavity for each selected stream, if used in conjunction with 'junction_method','check'
% this means that short sections of streams picked will auto fit concavity that may differ from downstream portions of the same
% streams
%
%%% Input Method Options
% min_channel_length [] - minimum channel length for consideration when using the 'all_streams' method of input, provide in map units.
% channel_head_list [] - m x 2 array of x and y coordinates of channel heads OR the name / location of a point shapefile of channel heads,
% one of these is required when using 'channel_heads' method of input, must be in the same coordinate system as the input DEM etc.
% The code will attempt to find the nearest channel head to the coordinates you provided, so the closer the provided user coordinates
% are to channel heads, the more accurate this selection method will be.
% min_length_to_extract [] - minimum stream length (in map units) to extract streams if 'input_method' is set to 'stream_length'.
%
%%% Redefine Threshold Area Options
% redefine_threshold [false] - logical flag to initiate an extra step for each stream where you manually define the hillslope-fluvial
% transition (this will result in overriding the threshold area you used to generate the supplied STREAMobj, and it will also produce
% a STREAMobj with a variable threshold area for channel definition). See additional optional input 'rd_pick_method'.
% rd_pick_method ['slope_area'] - plot to use to choose new threshold area if 'redefine_threshold' is set to true. Valid inputs are
% 'slopearea' and 'chi'.
%
%%% Stream Network Modification Options
% complete_networks_only [false] - if true, the code will filter out portions of the stream network that are incomplete prior to choosing
% streams
% min_elev [] - minimum elevation below which the code stops extracting channel information (no action if left empty)
% max_area [] - maximum drainage area above which the code stops extracting channel information (in square map units, no action if left empty)
%
%%% Hydrological Conditioning Options
% conditioned_DEM [] - option to provide a hydrologically conditioned DEM for use in this function (do not provide a conditoned DEM
% for the main required DEM input!) which will be used for extracting elevations. See 'ConditionDEM' function for options
% for making a hydrological conditioned DEM. If no input is provided the code defaults to using the mincosthydrocon function.
% interp_value [0.1] - value (between 0 and 1) used for interpolation parameter in mincosthydrocon (not used if user provides a
% conditioned DEM). Values closer to 0 tend to 'carve' more, whereas values closer to 1 tend to fill. See info for
% 'mincosthydrocon'
%
%%% Display Options
% display_slope_area [false] - logical flag to display slope area plots. Some people love slope area plots (like one of the authors of
% the supporting paper), some people hate slope area plots (like the other author of the supporting paper), so you can either
% not draw them at all (false - default) or include them (true). This will automatically be set to true if you select 'slope_area'
% as the 'pick_method'.
% plot_type ['vector'] - expects either 'vector' or 'grid', default is 'vector'. Controls whether all streams are drawn as individual
% lines ('vector') or if the stream network is plotted as a grid and downsampled ('grid'). The 'grid' option is much faster on
% large datasets, but can result in inaccurate channel head selection. The 'vector' option is easier to see, but can be very
% slow to load and interact with on large datasets.
%
%%% Constants
% ref_concavity [0.50] - refrence concavity used if 'theta_method' is set to 'ref'
% smooth_distance [1000] - distance in map units over which to smooth ksn measures when converting to shapefile
% max_ksn [250] - maximum ksn used for the color scale, will not effect actual results, for display purposes only
% threshold_area [1e6] - used to redraw downsampled stream network if 'plot_type' is set to 'grid'
%
%%% Output Options
% stack_method ['stack'] - if 'junction_method' is set to 'ignore', this parameter will control how the function deals with overlapping sections
% of stream networks when generating the shapefile. Valid inputs are 'stack' (default) and 'average'. If set to 'stack', the output shapefile
% will have multiple stacked polylines in overlapping portions of networks. This is similar to how Profiler51 worked. If set to 'average', the
% function will average overlapping portions of networks on a node by node basis. Note that if 'junction_method' is set to 'check', then this
% parameter is ignored.
% shape_name ['ksn'] - name for the shapefile to be export, must have no spaces to be a valid name for ArcGIS and should NOT include the '.shp'
% save_figures [false] - logical flag to either save figures showing ksn fits (true) or to not (false - default)
%
%%%%%%%%%%
% Outputs:
% knl - n x 12 matrix of node list for selected stream segments, columns are x coordinate, y coordinate, drainage area, ksn, negative ksn error,
% positive ksn error, reference concavity, best fit concavity, mininum threshold area, gradient, fit residual, and an identifying number. Note
% that if using the code in 'concavity_method','auto' mode then the reference concavity and best fit concavity columns will be the same.
% ksn_master - identical to knl but as a cell array where individual cells are individual selected channels
% bnd_list - n x 4 matrix of selected bounds for fitting ksn, columns are x coordinate, y coordinate, elevation, and the stream identifying number,
% also output as a seperate shapefile ('_bounds.shp'). If x y and z values appear as NaN, this indicates that bounds for this stream were not selected.
%
% kn_list - n x 4 matrix of extra identified knickpoints (not bounds),columns are x coordinate, y coordinate, elevation, and the stream identifying number,
% also output as a seperate shapefile ('_knicks.shp'. If x y and z values appear as NaN, this indicates that knicks for this stream were not selected.
% Sc - STREAMobj of selected streams
%
% Examples:
% [knl,ksn_master,bnd_list,kn_list,Sc]=KSN_Profiler(DEM,FD,A,S);
% [knl,ksn_master,bnd_list,kn_list,Sc]=KSN_Profiler(DEM,FD,A,S,'junction_method','ignore','ref_concavity',0.65,'max_ksn',500);
% [knl,ksn_master,bnd_list,kn_list,Sc]=KSN_Profiler(DEM,FD,A,S,'input_method','channel_heads','channel_head_list',channel_head_array);
% [knl,ksn_master,bnd_list,kn_list,Sc]=KSN_Profiler(DEM,FD,A,S,'input_method','channel_heads','channel_head_list','channel_heads.shp');
% Restart Examples:
% [knl,ksn_master,bnd_list,kn_list,Sc]=KSN_Profiler(DEM,FD,A,S,'restart','continue'); % Continues where you left off
% [knl,ksn_master,bnd_list,kn_list,Sc]=KSN_Profiler(DEM,FD,A,S,'restart','skip'); % Skips next stream in non interactive sequence
%
%
% Note:
% -If no boundaries/knickpoints are selected for any of the streams selected, then a '_bounds.shp'/'_knicks.shp' shapefile will not be produced.
% -The '*_profiler.mat' that is saved out contains additional files besides the formal outputs of the code. These additional variables
% are necessary to be able to restart a run using the 'restart' option.
% -If you have set 'save_figures' to true, DO NOT close figures manually as this will cause the code to error.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Function Written by Adam M. Forte - Updated : 01/09/20 %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Parse Inputs
p = inputParser;
p.FunctionName = 'KsnProfiler';
addRequired(p,'DEM',@(x) isa(x,'GRIDobj'));
addRequired(p,'FD',@(x) isa(x,'FLOWobj'));
addRequired(p,'A',@(x) isa(x,'GRIDobj'));
addRequired(p,'S',@(x) isa(x,'STREAMobj'));
addParameter(p,'shape_name','ksn',@(x) ischar(x));
addParameter(p,'smooth_distance',1000,@(x) isscalar(x) && isnumeric(x));
addParameter(p,'concavity_method','ref',@(x) ischar(validatestring(x,{'ref','auto'})));
addParameter(p,'complete_networks_only',false,@(x) isscalar(x) && islogical(x));
addParameter(p,'pick_method','chi',@(x) ischar(validatestring(x,{'chi','stream','slope_area'})));
addParameter(p,'junction_method','check',@(x) ischar(validatestring(x,{'check','ignore'})));
addParameter(p,'ref_concavity',0.50,@(x) isscalar(x) && isnumeric(x));
addParameter(p,'redefine_threshold',false,@(x) isscalar(x) && islogical(x));
addParameter(p,'rd_pick_method','slope_area',@(x) ischar(validatestring(x,{'chi','slope_area'})));
addParameter(p,'display_slope_area',false,@(x) isscalar(x) && islogical(x));
addParameter(p,'max_ksn',250,@(x) isscalar(x) && isnumeric(x));
addParameter(p,'min_elev',[],@(x) isscalar(x) && isnumeric(x) || isempty(x));
addParameter(p,'max_area',[],@(x) isscalar(x) && isnumeric(x) || isempty(x));
addParameter(p,'plot_type','vector',@(x) ischar(validatestring(x,{'vector','grid'})));
addParameter(p,'threshold_area',1e6,@(x) isnumeric(x));
addParameter(p,'input_method','interactive',@(x) ischar(validatestring(x,{'interactive','channel_heads','all_streams','stream_length'})));
addParameter(p,'channel_head_list',[],@(x) isnumeric(x) && size(x,2)==2 || regexp(x,regexptranslate('wildcard','*.shp')) || isempty(x));
addParameter(p,'min_length_to_extract',[],@(x) isnumeric(x) && isscalar(x) || isempty(x));
addParameter(p,'min_channel_length',[],@(x) isnumeric(x) && isscalar(x) || isempty(x));
addParameter(p,'conditioned_DEM',[],@(x) isa(x,'GRIDobj') || isempty(x));
addParameter(p,'interp_value',0.1,@(x) isnumeric(x) && x>=0 && x<=1);
addParameter(p,'save_figures',false,@(x) isscalar(x) && islogical(x));
addParameter(p,'restart',[],@(x) ischar(validatestring(x,{'continue','skip'})) || isempty(x));
addParameter(p,'stack_method','stack',@(x) ischar(validatestring(x,{'average','stack'})));
addParameter(p,'restart_loc',[],@(x) ischar(x) || isempty(x));
parse(p,DEM,FD,A,S,varargin{:});
DEM=p.Results.DEM;
FD=p.Results.FD;
S=p.Results.S;
A=p.Results.A;
shape_name=p.Results.shape_name;
smooth_distance=p.Results.smooth_distance;
theta_method=p.Results.concavity_method;
cno=p.Results.complete_networks_only;
pick_method=p.Results.pick_method;
junction_method=p.Results.junction_method;
ref_theta=p.Results.ref_concavity;
display_slope_area=p.Results.display_slope_area;
plot_type=p.Results.plot_type;
threshold_area=p.Results.threshold_area;
input_method=p.Results.input_method;
chl=p.Results.channel_head_list;
mlte=p.Results.min_length_to_extract;
min_channel_length=p.Results.min_channel_length;
iv=p.Results.interp_value;
DEMc=p.Results.conditioned_DEM;
min_elev=p.Results.min_elev;
max_area=p.Results.max_area;
save_figures=p.Results.save_figures;
redefine_thresh=p.Results.redefine_threshold;
rd_pick_method=p.Results.rd_pick_method;
mksn=p.Results.max_ksn;
restart=p.Results.restart;
stack_method=p.Results.stack_method;
restart_loc=p.Results.restart_loc; % Hidden parameter for GUI deployed versions
wtb=waitbar(0,'Preparing inputs...');
% Set restart flag
if ~isempty(restart)
rf=true;
else
rf=false;
end
% Check to see if restart if invoked and replace parameters if necessary
if rf
if ~isempty(restart_loc)
restart_file=dir('*_restart.mat');
out_file=dir('*_profiler.mat');
else
restart_file=dir(fullfile(restart_loc,'*_restart.mat'));
out_file=dir(fullfile(restart_loc,'*_profiler.mat'));
end
if numel(restart_file)>1
if isdeployed
errordlg('Multiple restart files were found, please remove non-target restart files from active directory or search path')
end
error('Multiple restart files were found, please remove non-target restart files from active directory or search path');
elseif isempty(restart_file) & ~isempty(out_file)
if numel(out_file)>1
if isdeployed
errordlg('Multiple profiler output mat files were found, please remove non-target restart files from active directory or search path')
end
error('Multiple profiler output mat files were found, please remove non-target restart files from active directory or search path');
end
load(out_file(1,1).name,'input_params');
r_type='c';
elseif isempty(restart_file) & isempty(out_file)
if isdeployed
errordlg('No previous run files were found, do not provide an entry to "restart" if this is your first time running KsnProfiler for these data')
end
error('No previous run files were found, do not provide an entry to "restart" if this is your first time running KsnProfiler for these data')
else
load(restart_file(1,1).name,'input_params');
r_type='r';
end
% Load in parameters from previous run
shape_name=input_params.shape_name;
smooth_distance=input_params.smooth_distance;
theta_method=input_params.concavity_method;
cno=input_params.complete_networks_only;
pick_method=input_params.pick_method;
junction_method=input_params.junction_method;
ref_theta=input_params.ref_concavity;
display_slope_area=input_params.display_slope_area;
plot_type=input_params.plot_type;
threshold_area=input_params.threshold_area;
input_method=input_params.input_method;
chl=input_params.channel_head_list;
mlte=input_params.min_length_to_extract;
min_channel_length=input_params.min_channel_length;
iv=input_params.interp_value;
DEMc=input_params.conditioned_DEM;
min_elev=input_params.min_elev;
max_area=input_params.max_area;
save_figures=input_params.save_figures;
redefine_thresh=input_params.redefine_threshold;
rd_pick_method=input_params.rd_pick_method;
mksn=input_params.max_ksn;
end
waitbar(1/4,wtb);
% Store out parameters in both final file and restart file
out_mat_name=[shape_name '_profiler.mat'];
out_restart_name=[shape_name '_restart.mat'];
if rf
save(out_mat_name,'input_params','-append');
if exist(out_restart_name)==2
save(out_restart_name,'input_params','-append');
else
save(out_restart_name,'input_params','-v7.3');
end
else
input_params=p.Results;
save(out_mat_name,'input_params','-v7.3');
save(out_restart_name,'input_params','-v7.3');
end
% Remove edges if flag is thrown
if cno
S=removeedgeeffects(S,FD,DEM);
end
% Find channel heads
[ch]=streampoi(S,'channelheads','xy');
% Create master KSN colormap
KSN_col=ksncolor(100);
waitbar(2/4,wtb);
% Perform some checks and reassign values as needed
if strcmp(input_method,'channel_heads')
if isempty(chl)
if isdeployed
errordlg('Selection method is "channel_heads", must provide an input for the "channel_head_list" parameter')
end
error('Selection method is "channel_heads", must provide an input for the "channel_head_list" parameter');
end
if ischar(chl)
% Load in shapefile if provided
if logical(regexp(chl,regexptranslate('wildcard','*.shp')))
ch_ms=shaperead(chl);
ch_t=struct2table(ch_ms);
if ~strcmp(ch_t.Geometry(1),'Point')
if isdeployed
errordlg('Shapefile provided as "channel_heads" does not appear to be a point shapefile')
end
error('Shapefile provided as "channel_heads" does not appear to be a point shapefile');
end
xi=ch_t.X;
yi=ch_t.Y;
chl=[xi yi];
end
end
% Snap to nearest channel heads
dists=pdist2(chl,ch);
[~,s_ch_ix]=min(dists,[],2);
s_ch=ch(s_ch_ix,:);
num_ch=size(s_ch,1);
plot_type='none';
input_method='preselected';
elseif strcmp(input_method,'all_streams')
s_ch=ch;
num_ch=size(s_ch,1);
if isempty(min_channel_length);
min_channel_length=sqrt((4*DEM.cellsize)^2 + (4*DEM.cellsize)^2);
end
plot_type='none';
input_method='preselected';
elseif strcmp(input_method,'stream_length')
if isempty(mlte)
if isdeployed
errordlg('Selection method is "stream_length", must provide an input for "mean_length_to_extract" parameter')
end
error('Selection method is "stream_length", must provide an input for "mean_length_to_extract" parameter');
end
FlowD=flowdistance(FD);
ix=coord2ind(DEM,ch(:,1),ch(:,2));
idx=FlowD.Z(ix)>=mlte;
s_ch=ch(idx,:);
if isempty(s_ch)
if isdeployed
errordlg('Input to "mean_length_to_extract" resulted in no streams being selected, reduce the length and retry')
end
error('Input to "mean_length_to_extract" resulted in no streams being selected, reduce the length and retry')
end
num_ch=size(s_ch,1);
if isempty(min_channel_length);
min_channel_length=sqrt((4*DEM.cellsize)^2 + (4*DEM.cellsize)^2);
end
plot_type='none';
input_method='preselected';
end
if strcmp(pick_method,'slope_area')
display_slope_area=true;
end
if ~isempty(min_elev) && ~isempty(max_area)
if isdeployed
errordlg('Providing values to both "min_elev" and "max_area" is not permitted, please only provide values for one of these parameters')
end
error('Providing values to both "min_elev" and "max_area" is not permitted, please only provide values for one of these parameters')
end
% Hydrologically condition dem
if isempty(DEMc)
zc=mincosthydrocon(S,DEM,'interp',iv);
DEMc=GRIDobj(DEM);
DEMc.Z(DEMc.Z==0)=NaN;
DEMc.Z(S.IXgrid)=zc;
elseif ~isempty(DEMc) & redefine_thresh
if isdeployed
warndlg(['Supplying a Conditioned DEM and redefining the drainage area threshold may produce unexpected results as it may be necessary ' ...
'to recondition portions of the DEM using a different method. To avoid this, make sure that a very low threshold area was used to ' ...
'produce the supplied Conditioned DEM.'])
else
warning(['Supplying a Conditioned DEM and redefining the drainage area threshold may produce unexpected results as it may be necessary ' ...
'to recondition portions of the DEM using a different method. To avoid this, make sure that a very low threshold area was used to ' ...
'produce the supplied Conditioned DEM.'])
end
end
% Make gradient
G=gradient8(DEMc);
% Make drainage area
DA=A.*A.cellsize^2;
waitbar(3/4,wtb);
% Modify provided stream network if minimum elevation or maximum drainage area options are included
if ~isempty(min_elev)
zel=getnal(S,DEMc);
idx=zel>min_elev;
new_ix=S.IXgrid(idx);
W=GRIDobj(DEMc,'logical');
W.Z(new_ix)=true;
S=STREAMobj(FD,W);
elseif ~isempty(max_area)
DA=A.*(A.cellsize^2);
zda=getnal(S,DA);
idx=zda<max_area;
new_ix=S.IXgrid(idx);
W=GRIDobj(DEMc,'logical');
W.Z(new_ix)=true;
S=STREAMobj(FD,W);
end
% Generate flow distance grid if redefining threshold
if redefine_thresh
FLUS=flowdistance(FD);
end
% Generate Map Figures for interactive picking
switch plot_type
case 'grid'
disp('Downsampling datasets for display purposes')
% Redo flow direction
DEMr=resample(DEM,DEM.cellsize*4);
FDr=FLOWobj(DEMr,'preprocess','carve');
% True outlets
out_T_xy=streampoi(S,'outlets','xy');
% Downsampled total stream network
Sr_temp=STREAMobj(FDr,'minarea',threshold_area,'unit','mapunits');
out_D_xy=streampoi(Sr_temp,'outlets','xy');
out_D_ix=streampoi(Sr_temp,'outlets','ix');
% Find if outlet list is different
dists=pdist2(out_T_xy,out_D_xy);
[~,s_out_ix]=min(dists,[],2);
out_D_ix=out_D_ix(s_out_ix);
% Rebuild downsampled network
Sr=STREAMobj(FDr,'minarea',threshold_area,'unit','mapunits','outlets',out_D_ix);
% Turn it into a grid
SG=STREAMobj2GRIDobj(Sr);
% Initiate Map Figure
f1=figure(1);
set(f1,'Visible','off');
hold on
[RGB]=imageschs(DEMr,SG,'colormap','gray');
[~,R]=GRIDobj2im(DEMr);
imshow(flipud(RGB),R);
axis xy
colormap(KSN_col);
caxis([0 mksn])
c1=colorbar;
ylabel(c1,'Channel Steepness')
if ~verLessThan('matlab','9.5')
disableDefaultInteractivity(gca);
end
hold off
set(f1,'Visible','on','Units','normalized','Position',[0.05 0.1 0.5 0.5],'renderer','painters');
case 'vector'
% Initiate Map Figure;
f1=figure(1);
set(f1,'Visible','off');
[RGB]=imageschs(DEM,DEM,'colormap','gray');
[~,R]=GRIDobj2im(DEM);
imshow(flipud(RGB),R);
axis xy
hold on
colormap(KSN_col);
plot(S,'-w');
caxis([0 mksn])
c1=colorbar;
ylabel(c1,'Channel Steepness')
if ~verLessThan('matlab','9.5')
disableDefaultInteractivity(gca);
end
hold off
set(f1,'Visible','on','Units','normalized','Position',[0.05 0.1 0.5 0.5],'renderer','painters');
end
waitbar(1,wtb);
close(wtb);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Main switch for graphical selection vs list of channel heads %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch input_method
case 'interactive'
% Initiate counters and while loop values
str1='N';
str2='Y';
if rf & strcmp(r_type,'c')
% Load in data from previous run
load(out_mat_name,'count','ksn_master','bnd_master','kn_master','res_master','Sc');
ii=count+1;
% Regenerate plotted streams
km=vertcat(ksn_master{:});
kix=coord2ind(DEM,km(:,1),km(:,2));
K=GRIDobj(DEM);
K.Z(kix)=km(:,4);
figure(1)
hold on
plotc(Sc,K);
hold off
clear km kix K;
elseif rf & strcmp(r_type,'r')
% Load in data from failed or aborted run
load(out_restart_name,'count','ksn_master','bnd_master','kn_master','res_master','Sc');
ii=count+1;
% Regenerate plotted streams
km=vertcat(ksn_master{:});
kix=coord2ind(DEM,km(:,1),km(:,2));
K=GRIDobj(DEM);
K.Z(kix)=km(:,4);
figure(1)
hold on
plotc(Sc,K);
hold off
clear km kix K;
else
ii=1;
end
if strcmp(theta_method,'ref')
% Autocalculate ksn for comparison purposes
[auto_ksn]=KSN_Quick(DEM,A,S,ref_theta);
end
% Begin picking streams
while strcmpi(str2,'Y');
% Select channel to fit
while strcmpi(str1,'N');
str3='R'; %Reset redo flag
figure(1)
hold on
title('Zoom or pan to area of interest and then press enter');
hold off
pause()
figure(1)
hold on
title('Choose point near channel head of interest');
hold off
[x,y]=ginput(1);
pOI=[x y];
% Find nearest channel head
distance=sqrt(sum(bsxfun(@minus, ch, pOI).^2,2));
chOI=ch(distance==min(distance),:);
% Build logical raster
ix=coord2ind(DEM,chOI(:,1),chOI(:,2));
IX=GRIDobj(DEM,'logical');
IX.Z(ix)=true;
if redefine_thresh
% Extract stream of interest
Sn=modify(S,'downstreamto',IX);
figure(f1)
hold on
p1=plot(Sn,'-b','LineWidth',2);
hold off
qa1=questdlg('Is this the stream segment you wanted?','Stream Selection','Yes','No','Yes');
switch qa1
case 'Yes'
delete(p1);
[Sn]=RedefineThreshold(DEM,FD,A,Sn,FLUS,ref_theta,rd_pick_method,smooth_distance,ii,save_figures,shape_name);
% Update DEMc
if any(isnan(getnal(Sn,DEMc)));
zc=mincosthydrocon(Sn,DEM,'interp',iv);
DEMc.Z(Sn.IXgrid)=zc;
end
% Recalculate auto_ksn
if strcmp(theta_method,'ref')
[auto_ksn]=KSN_Quick(DEM,A,Sn,ref_theta);
end
str1='Y';
if strcmp(junction_method,'check')
if ii>1
[IIXX,~,~,Si]=intersectlocs(Sc,Sn);
if isempty(IIXX)
Sn=Sn;
Sct=union(Sn,Sc,FD);
else
Sn=Si;
Sct=union(Sn,Sc,FD);
end
else
Sct=Sn;
end
elseif strcmp(junction_method,'ignore')
if ii>1
Sct=union(Sn,Sc,FD);
else
Sct=Sn;
end
end
% Plot updated stream
figure(f1)
hold on
p1=plot(Sn,'-b','LineWidth',2);
hold off
Sc=Sct;
case 'No'
str1='N';
delete(p1);
end
else
% Extract stream of interest
Sn=modify(S,'downstreamto',IX);
% Build composite stream network of picked streams
if strcmp(junction_method,'check')
if ii>1
[IIXX,~,~,Si]=intersectlocs(Sc,Sn);
if isempty(IIXX)
Sn=Sn;
Sct=union(Sn,Sc,FD);
else
Sn=Si;
Sct=union(Sn,Sc,FD);
end
else
Sct=Sn;
end
elseif strcmp(junction_method,'ignore')
if ii>1
Sct=union(Sn,Sc,FD);
else
Sct=Sn;
end
end
figure(f1)
hold on
p1=plot(Sn,'-b','LineWidth',2);
hold off
qa1=questdlg('Is this the stream segment you wanted?','Stream Selection','Yes','No','Yes');
switch qa1
case 'Yes'
str1='Y';
Sc=Sct;
case 'No'
str1='N';
delete(p1);
end
end
end % End single channel select
%% Extract threshold drainage area
snchix=streampoi(Sn,'channelheads','ix');
snda=DA.Z(snchix);
%% Calculate chi and extract ksn data
if strcmp(theta_method,'ref')
C=ChiCalc(Sn,DEMc,A,1,ref_theta);
ak=getnal(Sn,auto_ksn);
elseif strcmp(theta_method,'auto')
C=ChiCalc(Sn,DEMc,A,1);
if redefine_thresh
[auto_ksn]=KSN_Quick(DEM,A,Sn,C.mn);
else
[auto_ksn]=KSN_Quick(DEM,A,S,C.mn);
end
ak=getnal(Sn,auto_ksn);
end
%% Bin data
[DAvg,KsnAvg]=BinAverage(Sn.distance,ak,smooth_distance);
[~,CAvg]=BinAverage(C.distance,C.chi,smooth_distance);
%% Begin fitting loop
while strcmpi(str3,'R')
%% Initiate figure to pick bounds
f2=figure(2);
set(f2,'Units','normalized','Position',[0.5 0.1 0.45 0.8],'renderer','painters');
clf
%% Main swith for different pick methods
if strcmp(pick_method,'chi')
if display_slope_area
[bs,ba,bc,bd,aa,ag,ad,ac]=sa(DEMc,Sn,A,C.chi,smooth_distance);
ax4=subplot(4,1,4);
hold on
scatter(aa,ag,5,ac,'+');
scatter(ba,bs,20,bc,'filled','MarkerEdgeColor','k');
xlabel('Log Area');
ylabel('Log Gradient');
title('Slope-Area');
set(ax4,'YScale','log','XScale','log','XDir','reverse');
if ~verLessThan('matlab','9.5')
disableDefaultInteractivity(ax4);
end
hold off
ax3=subplot(4,1,3);
hold on
pl1=plotdz(Sn,DEM,'dunit','km','Color',[0.5 0.5 0.5]);
pl2=plotdz(Sn,DEMc,'dunit','km','Color','k');
pl3=scatter((C.distance)./1000,C.elev,5,C.chi,'filled');
xlabel('Distance from Mouth (km)')
ylabel('Elevation (m)')
legend([pl1 pl2 pl3],'Unconditioned DEM','Conditioned DEM','\chi','location','best');
title('Long Profile')
if ~verLessThan('matlab','9.5')
disableDefaultInteractivity(ax3);
end
hold off
ax2=subplot(4,1,2);
hold on
scatter(CAvg,KsnAvg,20,CAvg,'filled','MarkerEdgeColor','k');
xlabel('\chi')
ylabel('Auto k_{sn}');
title('\chi - Auto k_{sn}');
if ~verLessThan('matlab','9.5')
disableDefaultInteractivity(ax2);
end
hold off
ax1=subplot(4,1,1);
hold on
plot(C.chi,C.elev,'-k');
scatter(C.chi,C.elev,10,C.chi,'filled');
xlabel('\chi')
ylabel('Elevation (m)')
title(['\chi - Z : \theta = ' num2str(C.mn) ' : Pick Segments - Press Enter When Done'],'Color','r')
ax1.XColor='Red';
ax1.YColor='Red';
if ~verLessThan('matlab','9.5')
disableDefaultInteractivity(ax1);
end
hold off
linkaxes([ax1,ax2],'x');
colormap(ax1,'jet'); colormap(ax2,'jet'); colormap(ax3,'jet'); colormap(ax4,'jet');
else
ax3=subplot(3,1,3);
hold on
pl1=plotdz(Sn,DEM,'dunit','km','Color',[0.5 0.5 0.5]);
pl2=plotdz(Sn,DEMc,'dunit','km','Color','k');
pl3=scatter((C.distance)./1000,C.elev,5,C.chi,'filled');
xlabel('Distance from Mouth (km)')
ylabel('Elevation (m)')
legend([pl1 pl2 pl3],'Unconditioned DEM','Conditioned DEM','\chi','location','best');
title('Long Profile')
if ~verLessThan('matlab','9.5')
disableDefaultInteractivity(ax3);
end
hold off
ax2=subplot(3,1,2);
hold on
scatter(CAvg,KsnAvg,20,CAvg,'filled','MarkerEdgeColor','k');
xlabel('\chi')
ylabel('Auto k_{sn}');
title('\chi - Auto k_{sn}');
if ~verLessThan('matlab','9.5')
disableDefaultInteractivity(ax2);
end
hold off
ax1=subplot(3,1,1);
hold on
plot(C.chi,C.elev,'-k');
scatter(C.chi,C.elev,10,C.chi,'filled');
xlabel('\chi')
ylabel('Elevation (m)')
title(['\chi - Z : \theta = ' num2str(C.mn) ' : Pick Segments - Press Enter When Done'],'Color','r')
ax1.XColor='Red';
ax1.YColor='Red';
if ~verLessThan('matlab','9.5')
disableDefaultInteractivity(ax1);
end
hold off
linkaxes([ax1,ax2],'x');
colormap(ax1,'jet'); colormap(ax2,'jet'); colormap(ax3,'jet');
end
[cv,~,bttn]=ginput;
% Determine if there any non bound knicks
bttn_idx=bttn~=1;
if any(bttn_idx)
% Parse out non bounds
cv_kn=cv(bttn_idx);
cv(bttn_idx)=[];
% Convert to indices
rc=C.chi; rx=C.x; ry=C.y;
kn_ix=zeros(numel(cv_kn),1);
for jj=1:numel(cv_kn);
chidist=sqrt(sum(bsxfun(@minus, rc, cv_kn(jj)).^2,2));
[~,knbix]=min(chidist);
knbx=rx(knbix);
knby=ry(knbix);
kn_ix(jj)=coord2ind(DEM,knbx,knby);
end
else
kn_ix=NaN;
end
if isempty(cv)
if strcmp(theta_method,'ref')
Cbf=ChiCalc(Sn,DEMc,A,1);
ksn_list=[C.x C.y C.area ones(numel(C.x),1)*C.ks ones(numel(C.x),1)*C.ks_neg ones(numel(C.x),1)*C.ks_pos ...
ones(numel(C.x),1)*C.mn ones(numel(C.x),1)*Cbf.mn ones(numel(C.x),1)*snda];
elseif strcmp(theta_method,'auto')
ksn_list=[C.x C.y C.area ones(numel(C.x),1)*C.ks ones(numel(C.x),1)*C.ks_neg ones(numel(C.x),1)*C.ks_pos ...
ones(numel(C.x),1)*C.mn ones(numel(C.x),1)*C.mn ones(numel(C.x),1)*snda];
end
% Determine where ksn value fits into color scale and plot
ksn_val=C.ks;
if ksn_val > mksn;
figure(f1)
hold on
plot(Sn,'Color',KSN_col(end,:),'LineWidth',2);
hold off
else
edges=linspace(0,mksn,10);
n=histc(ksn_val,edges);
figure(f1)
hold on
plot(Sn,'Color',KSN_col(logical(n),:),'LineWidth',2);
hold off
end
[~,lbix]=min(C.chi);
elbl=C.elev(lbix);
if display_slope_area
figure(f2)
subplot(4,1,1);
hold on
plot(C.chi,C.pred+elbl,'-k','LineWidth',2);
hold off
subplot(4,1,3);
hold on
pl4=plot((C.distance)/1000,C.pred+elbl,'-k','LineWidth',2);
legend([pl1 pl2 pl3 pl4],'Unconditioned DEM','Conditioned DEM','\chi','Segment Fit','location','best');
hold off
subplot(4,1,4);
hold on
plot(C.area,ksn_val.*C.area.^(-C.mn),'-k','LineWidth',2);
hold off
else
figure(f2)
subplot(3,1,1);
hold on
plot(C.chi,C.pred+elbl,'-k','LineWidth',2);
hold off
subplot(3,1,3);
hold on
pl4=plot((C.distance)/1000,C.pred+elbl,'-k','LineWidth',2);
legend([pl1 pl2 pl3 pl4],'Unconditioned DEM','Conditioned DEM','\chi','Segment Fit','location','best');
hold off
end
res_list=[C.chi C.res];
bnd_ix=NaN;;
else
% Sort knickpoint list and construct bounds list
cvs=sortrows(cv);
bnds=vertcat(0,cvs,C.chi(1));
num_bnds=numel(bnds);
rc=C.chi;
rx=C.x;
ry=C.y;
rd=C.distance;
for jj=1:num_bnds-1
% Extract bounds
lb=bnds(jj);
rb=bnds(jj+1);
% Clip out stream segment
lb_chidist=sqrt(sum(bsxfun(@minus, rc, lb).^2,2));
rb_chidist=sqrt(sum(bsxfun(@minus, rc, rb).^2,2));
[~,lbix]=min(lb_chidist);
[~,rbix]=min(rb_chidist);
lbx=rx(lbix);
lby=ry(lbix);
rbx=rx(rbix);
rby=ry(rbix);
lix=coord2ind(DEM,lbx,lby);
rix=coord2ind(DEM,rbx,rby);
Seg=modify(Sn,'downstreamto',rix);
Seg=modify(Seg,'upstreamto',lix);
%Remake stream with downstream bound node added back in
WSEG=GRIDobj(DEM,'logical');
WSEG.Z(Seg.IXgrid)=true;
WSEG.Z(lix)=true;
% Add back in upstream node if it's the end of the stream
if jj==num_bnds-1
WSEG.Z(rix)=true;
end
Seg=STREAMobj(FD,WSEG);
% Check length of stream, if it's less than two nodes,
% move down stream until it's greater than two nodes
lbix_new=lbix+1;
first_time=true;
while numel(Seg.IXgrid)<=2
if first_time
wrn_mssg=['Segment ' num2str(jj) ' of chosen segments was too short, segment bound was expanded downstream'];
wd=warndlg(wrn_mssg);
uiwait(wd);
end
lix_new=coord2ind(DEM,rx(lbix_new),ry(lbix_new));
WSEG.Z(lix_new)=true;
Seg=STREAMobj(FD,WSEG);
lbix_new=lbix_new+1;
first_time=false;
end
% Construct bound list