-
Notifications
You must be signed in to change notification settings - Fork 18
/
plot_hillslope_morphology.py
1541 lines (1157 loc) · 51.4 KB
/
plot_hillslope_morphology.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#import modules
from __future__ import print_function
from geopandas import GeoDataFrame
from shapely.geometry import LineString, shape, Point, MultiPolygon, Polygon
import pandas as pd
import numpy as np
from sys import platform, stdout
# import plotting tools and set the back end for running on server
import matplotlib
matplotlib.use('Agg')
from matplotlib import rcParams, ticker, gridspec, cm
import matplotlib.pyplot as plt
# import mapping tools
import rotated_mapping_tools as rmt
def CreateFigure(FigSizeFormat="default", AspectRatio=16./9.):
"""
This function creates a default matplotlib figure object
Args:
FigSizeFormat: the figure size format according to journal for which the figure is intended
values are geomorphology,ESURF, ESPL, EPSL, JGR, big
default is ESURF
AspectRatio: The shape of the figure determined by the aspect ratio, default is 16./9.
Returns:
matplotlib figure object
Author: MDH
"""
# set figure sizes (in inches) based on format
if FigSizeFormat == "geomorphology":
FigWidth_Inches = 6.25
elif FigSizeFormat == "big":
FigWidth_Inches = 16
elif FigSizeFormat == "small":
FigWidth_Inches = 3.3
elif FigSizeFormat == "ESURF":
FigWidth_Inches = 4.92
elif FigSizeFormat == "ESPL":
FigWidth_Inches = 7.08
elif FigSizeFormat == "EPSL":
FigWidth_Inches = 7.48
elif FigSizeFormat == "JGR":
FigWidth_Inches = 6.6
else:
FigWidth_Inches = 4.92126
# Set up fonts for plots
rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['Liberation Sans']
rcParams['font.size'] = 8
rcParams['text.usetex'] = False
Fig = plt.figure(figsize=(FigWidth_Inches,FigWidth_Inches/AspectRatio))
return Fig
def ReadHillslopeData(DataDirectory, FilenamePrefix):
"""
This function reads in the file with the suffix '_HilltopData.csv'
to a pandas dataframe
Args:
DataDirectory: the data directory
FilenamePrefix: the file name prefix
Returns:
pandas dataframe with data from the csv file
Author: MDH
"""
# get the csv filename
Suffix = '_HilltopData.csv'
Filename = FilenamePrefix+Suffix
# read in the dataframe using pandas
HillslopeData = pd.read_csv(DataDirectory+Filename)
# drop any rows with no data (hillslope traces to outside the study domain)
# or with value of -9999 for Basin ID
HillslopeData = HillslopeData.dropna()
HillslopeData = HillslopeData[HillslopeData.BasinID != -9999]
#return the hillslope data
return HillslopeData
def ReadChannelData(DataDirectory, FilenamePrefix):
"""
This function reads in the file with the suffix '_MChiSegmented.csv'
to a pandas dataframe
Args:
DataDirectory: the data directory
FilenamePrefix: the file name prefix
Returns:
pandas dataframe with data from the csv file
Author: MDH
"""
# get the csv filename
Suffix = '_MChiSegmented.csv'
Filename = FilenamePrefix+Suffix
# read in the dataframe using pandas
ChannelData = pd.read_csv(DataDirectory+Filename)
# If there is no chi values due to threshold then chi will be -9999
# throw out these segments
Segments2Remove = ChannelData[ChannelData.chi == -9999].segment_number.unique()
ChannelData = ChannelData[~ChannelData.segment_number.isin(Segments2Remove)]
#return the hillslope data
return ChannelData
def ProcessSegmentedData(DataDirectory, FilenamePrefix):
"""
This function reads channel and hillslope data and organises it by basins and
segments, taking median values for each segment and 16/84 percentiles as range estimates
Args:
DataDirectory: the data directory
FilenamePrefix: the file name prefix
Author: MDH
"""
#load the hillslopes data
HillslopeData = ReadHillslopeData(DataDirectory, FilenamePrefix)
# load the channel data
ChannelData = ReadChannelData(DataDirectory, FilenamePrefix)
# Get a list of unique basins to loop through
Basins = ChannelData.basin_key.unique()
#loop through the basins
for Basin in Basins:
# isolate basin data
BasinChannelData = ChannelData[ChannelData.basin_key == Basin]
BasinJunctions = HillslopeData.BasinID.unique()
BasinHillslopeData = HillslopeData[HillslopeData.BasinID == BasinJunctions[BasinID]]
# how many segments are we dealing with?
Segments = BasinChannelData.segment_number.unique()
def ReadHillslopeTraces(DataDirectory, FilenamePrefix):
"""
This function reads in the file with the suffix '_hillslope_traces.csv'
and creates a geopandas GeoDataFrame
Args:
DataDirectory: the data directory
FilenamePrefix: the file name prefix
Returns:
geopandas GeoDataFrame with data from the csv file spatially organised
Author: MDH
"""
# get the csv filename
Suffix = '_hillslope_traces'
Extension = '.csv'
ReadFilename = DataDirectory+FilenamePrefix+Suffix+Extension
# read in the dataframe using pandas and convert to geopandas geodataframe
df = pd.read_csv(ReadFilename)
geometry = [Point(xy) for xy in zip(df.Longitude, df.Latitude)]
df = df.drop(['Easting','Northing','Longitude', 'Latitude'], axis=1)
crs = {'init': 'epsg:4326'}
geo_df = GeoDataFrame(df, crs=crs, geometry=geometry)
return geo_df
def WriteHillslopeTracesShp(DataDirectory,FilenamePrefix):
"""
This function writes a shapefile of hillslope traces
Args:
DataDirectory: the data directory
FilenamePrefix: the file name prefix
Author: MDH
"""
#read the raw data to geodataframe
geo_df = ReadHillslopeTraces(DataDirectory,FilenamePrefix)
Suffix = '_hillslope_traces'
WriteFilename = DataDirectory+FilenamePrefix+Suffix+'.shp'
#aggregate these points with group by
geo_df = geo_df.groupby(['HilltopID'])['geometry'].apply(lambda x: LineString(x.tolist()))
geo_df = GeoDataFrame(geo_df, geometry='geometry')
geo_df.to_file(WriteFilename, driver='ESRI Shapefile')
def SaveHillslopeDataByBasin(DataDirectory,FilenamePrefix):
"""
This function organises hillslope data by basin number
and writes the results to a new, numbered file
Args:
DataDirectory: the data directory
FilenamePrefix: the file name prefix
Returns:
writes new files to data directory
Author: MDH
"""
# load the hillslope data
HillslopeData = ReadHillslopeData(DataDirectory, FilenamePrefix)
# get a list of basins
Basins = HillslopeData.BasinID.unique()
# get the csv filename
Suffix = '_HilltopData.csv'
# loop through basins
for i in range(0,len(Basins)):
#isolate basin data
BasinHillslopeData = HillslopeData[HillslopeData.BasinID == Basins[i]]
#setup an output file
OutputFilename = DataDirectory + FilenamePrefix + "_" + str(i) + Suffix
#write to file
BasinHillslopeData.to_csv(OutputFilename, index=False)
def SaveChannelDataByBasin(DataDirectory,FilenamePrefix):
"""
This function organises channel data by basin number
and writes the results to a new, numbered file
Args:
DataDirectory: the data directory
FilenamePrefix: the file name prefix
Returns:
writes new files to data directory
Author: MDH
"""
# load the hillslope data
ChannelData = ReadChannelData(DataDirectory, FilenamePrefix)
# get a list of basins
Basins = ChannelData.basin_key.unique()
# get the csv filename
Suffix = '_MChiSegmented.csv'
# loop through basins
for i in range(0,len(Basins)):
#isolate basin data
BasinChannelData = ChannelData[ChannelData.basin_key == Basins[i]]
#setup an output file
OutputFilename = DataDirectory + FilenamePrefix + "_" + str(i) + Suffix
#write to file
BasinChannelData.to_csv(OutputFilename, index=False)
def MapBasinChannelHillslopes(BasinID):
"""
Makes a plot of the basin, this must be the first script to run since the basin sets the plot extent
MDH, September 2017
"""
#import module for converting hillslope data to lat long
from pyproj import Proj, transform
# Open basins shapefile, convert to latlong, and select basin by ID
PolygonDict, CRS = rmt.ReadShapeFile(ShapeFile)
# get a sorted list of keys for selecting the basin
Keys = np.sort(np.array(PolygonDict.keys()))
# select the polygon of the basin we're interested in
BasinPoly = dict((key,value) for key, value in PolygonDict.iteritems() if key == Keys[BasinID])
# create a shapefile of the selected basin
BasinShapeFile = DataDirectory+FilenamePrefix+"_basin_"+str(BasinID)+".shp"
HillshadeRaster = Directory+FilenamePrefix+"_hs_resample_latlong.bil"
# define the output coordinate system
rmt.WriteShapeFile(BasinPoly,CRS,BasinShapeFile)
# Create a map figure with basin shapefile as extent
Fig, Ax, Map = rmt.CreateMapFigure(BasinShapeFile)
# plot the hillshade as base layer
rmt.PlotRaster(HillshadeRaster,Map)
rmt.PlotShapefile(BasinShapeFile,Map,Ax,'k','w')
# load the channel data
ChannelData = ReadChannelData(DataDirectory, FilenamePrefix)
# isolate basin data
BasinChannelData = ChannelData[ChannelData.basin_key == BasinID]
lon = BasinChannelData.longitude.as_matrix()
lat = BasinChannelData.latitude.as_matrix()
x,y = Map(lon,lat)
# channels marked by chi
Chi = BasinChannelData.chi.as_matrix()
Chi -= np.min(Chi)
MarkerSize = 2.-(Chi/np.max(Chi))*2.
plt.scatter(x,y,marker='.',color='b',s=MarkerSize)
#load the hillslopes data
HillslopeData = ReadHillslopeData(DataDirectory, FilenamePrefix)
BasinJunctions = HillslopeData.BasinID.unique()
BasinHillslopeData = HillslopeData[HillslopeData.BasinID == Keys[BasinID]]
X = BasinHillslopeData.X.as_matrix()
Y = BasinHillslopeData.Y.as_matrix()
#Convert to Lat Long
Output_CRS = Proj({'init': "epsg:4326"})
lon, lat = transform(CRS, Output_CRS, X, Y)
x,y = Map(lon,lat)
plt.scatter(x,y,marker='.',color='r',s=2)
plt.savefig(PlotDirectory+FilenamePrefix+"_basin_plot.png", dpi=300)
plt.close()
def PlotChiElevationSegments(BasinID):
# load the channel data
ChannelData = ReadChannelData(DataDirectory, FilenamePrefix)
# isolate basin data
BasinChannelData = ChannelData[ChannelData.basin_key == BasinID]
MinimumChi = BasinChannelData.chi.min()
# how many segments are we dealing with?
Segments = BasinChannelData.segment_number.unique()
# setup the figure
CreateFigure()
# Get the data columns for plotting
for i in range(0, len(Segments)):
#get data arrays
Chi = ChannelData.chi[ChannelData.segment_number == Segments[i]]
Elevation = ChannelData.elevation[ChannelData.segment_number == Segments[i]]
SegmentedElevation = ChannelData.segmented_elevation[ChannelData.segment_number == Segments[i]]
#normalise chi by outlet chi
Chi = Chi-MinimumChi
#plot, colouring segments
Colour = np.random.rand()
plt.plot(Chi,Elevation,'k--',dashes=(2,2), lw=0.5,zorder=10)
plt.plot(Chi, SegmentedElevation, '-', lw=2, c=plt.cm.Paired(Colour),zorder=9)
# Finalise the figure
plt.xlabel(r'$\chi$ (m)')
plt.ylabel('Elevation (m)')
plt.title('Basin ID ' + str(BasinID))
plt.tight_layout()
plt.savefig(PlotDirectory+FilenamePrefix + "_" + str(BasinID) + "_ChiElevSeg.png", dpi=300)
plt.close()
def PlotLongProfileSegments(BasinID):
# load the channel data
ChannelData = ReadChannelData(DataDirectory, FilenamePrefix)
# isolate basin data
BasinChannelData = ChannelData[ChannelData.basin_key == BasinID]
MinimumDistance = BasinChannelData.flow_distance.min()
# how many segments are we dealing with?
Segments = BasinChannelData.segment_number.unique()
# setup the figure
CreateFigure()
# Get the data columns for plotting
for i in range(0, len(Segments)):
#get data arrays
Dist = ChannelData.flow_distance[ChannelData.segment_number == Segments[i]]
Elevation = ChannelData.elevation[ChannelData.segment_number == Segments[i]]
SegmentedElevation = ChannelData.segmented_elevation[ChannelData.segment_number == Segments[i]]
#normalise distance by outlet distance
Dist = Dist-MinimumDistance
#plot, colouring segments
Colour = np.random.rand()
plt.plot(Dist/1000,Elevation,'k--',dashes=(2,2), lw=0.5,zorder=10)
plt.plot(Dist/1000, SegmentedElevation, '-', lw=2, c=plt.cm.Paired(Colour),zorder=9)
# Finalise the figure
plt.xlabel('Distance (km)')
plt.ylabel('Elevation (m)')
plt.title('Basin ID ' + str(BasinID))
plt.tight_layout()
plt.savefig(PlotDirectory+FilenamePrefix + "_" + str(BasinID) + "_LongProfSeg.png", dpi=300)
plt.close()
def PlotChiElevationMChi(BasinID):
# load the channel data
ChannelData = ReadChannelData(DataDirectory, FilenamePrefix)
if (BasinChannelData.count == 0):
print("No Channel Data for Basin ID " + str(BasinID))
# isolate basin data
BasinChannelData = ChannelData[ChannelData.basin_key == BasinID]
MinimumChi = BasinChannelData.chi.min()
MaximumMChi = BasinChannelData.m_chi.max()
# how many segments are we dealing with?
Segments = BasinChannelData.segment_number.unique()
# setup the figure
Fig = CreateFigure()
#choose colormap
ColourMap = cm.viridis
# Get the data columns for plotting
for i in range(0, len(Segments)):
#get data arrays
Chi = ChannelData.chi[ChannelData.segment_number == Segments[i]]
Elevation = ChannelData.elevation[ChannelData.segment_number == Segments[i]]
SegmentedElevation = ChannelData.segmented_elevation[ChannelData.segment_number == Segments[i]]
MChi = ChannelData.m_chi[ChannelData.segment_number == Segments[i]].unique()[0]
#normalise chi by outlet chi
Chi = Chi-MinimumChi
#plot, colouring segments
Colour = MChi/MaximumMChi
plt.plot(Chi,Elevation,'k--',dashes=(2,2), lw=0.5,zorder=10)
plt.plot(Chi, SegmentedElevation, '-', lw=2, c=ColourMap(Colour),zorder=9)
# Finalise the figure
plt.xlabel(r'$\chi$ (m)')
plt.ylabel('Elevation (m)')
plt.title('Basin ID ' + str(BasinID))
plt.tight_layout()
#add colourbar
CAx = Fig.add_axes([0.15,0.8,0.4,0.05])
m = cm.ScalarMappable(cmap=ColourMap)
m.set_array(ChannelData.m_chi)
plt.colorbar(m, cax=CAx,orientation='horizontal')
plt.xlabel('$M_{\chi}$ m$^{0.64}$')
#save output
plt.savefig(PlotDirectory+FilenamePrefix + "_" + str(BasinID) + "_ChiElevMChi.png", dpi=300)
plt.close()
def PlotLongProfileMChi(BasinID):
# load the channel data
ChannelData = ReadChannelData(DataDirectory, FilenamePrefix)
# isolate basin data
BasinChannelData = ChannelData[ChannelData.basin_key == BasinID]
if (BasinChannelData.count == 0):
print("No Channel Data for Basin ID " + str(BasinID))
MinimumDistance = BasinChannelData.flow_distance.min()
MaximumMChi = BasinChannelData.m_chi.max()
# how many segments are we dealing with?
Segments = BasinChannelData.segment_number.unique()
# setup the figure
Fig = CreateFigure()
#choose colormap
ColourMap = cm.viridis
# Get the data columns for plotting
for i in range(0, len(Segments)):
#get data arrays
Dist = ChannelData.flow_distance[ChannelData.segment_number == Segments[i]]
Elevation = ChannelData.elevation[ChannelData.segment_number == Segments[i]]
SegmentedElevation = ChannelData.segmented_elevation[ChannelData.segment_number == Segments[i]]
MChi = ChannelData.m_chi[ChannelData.segment_number == Segments[i]].unique()[0]
#normalise distance by outlet distance
Dist = Dist-MinimumDistance
#plot, colouring segments
Colour = MChi/MaximumMChi
plt.plot(Dist/1000,Elevation,'k--',dashes=(2,2), lw=0.5,zorder=10)
plt.plot(Dist/1000, SegmentedElevation, '-', lw=2, c=ColourMap(Colour),zorder=9)
# Finalise the figure
plt.xlabel('Distance (km)')
plt.ylabel('Elevation (m)')
plt.title('Basin ID ' + str(BasinID))
plt.tight_layout()
#add colourbar
CAx = Fig.add_axes([0.15,0.8,0.4,0.05])
m = cm.ScalarMappable(cmap=ColourMap)
m.set_array(ChannelData.m_chi)
plt.colorbar(m, cax=CAx,orientation='horizontal')
plt.xlabel('$M_{\chi}$ m$^{0.64}$')
#save output
plt.savefig(PlotDirectory+FilenamePrefix + "_" + str(BasinID) + "_LongProfMChi.png", dpi=300)
plt.close()
def PlotLongProfileMChiCht(BasinID):
# load the channel data
ChannelData = ReadChannelData(DataDirectory, FilenamePrefix)
#load the hillslopes data
HillslopeData = ReadHillslopeData(DataDirectory, FilenamePrefix)
# isolate basin data
BasinChannelData = ChannelData[ChannelData.basin_key == BasinID]
BasinJunctions = HillslopeData.BasinID.unique()
BasinHillslopeData = HillslopeData[HillslopeData.BasinID == BasinJunctions[BasinID]]
MinimumDistance = BasinChannelData.flow_distance.min()
MaximumMChi = BasinChannelData.m_chi.max()
# how many segments are we dealing with?
Segments = BasinChannelData.segment_number.unique()
# setup the figure
Fig = CreateFigure(FigSizeFormat="JGR")
Ax = plt.subplot(111)
#choose colormap
ColourMap = cm.viridis
#empty lists for hilltop data
ChtMedian=np.zeros(len(Segments))
Cht25=np.zeros(len(Segments))
Cht75=np.zeros(len(Segments))
Distances=np.zeros(len(Segments))
MinDistances=np.zeros(len(Segments))
MaxDistances=np.zeros(len(Segments))
NTraces=np.zeros(len(Segments))
# Get the data columns for plotting
for i in range(0, len(Segments)):
#get data arrays
Dist = ChannelData.flow_distance[ChannelData.segment_number == Segments[i]]
Elevation = ChannelData.elevation[ChannelData.segment_number == Segments[i]]
SegmentedElevation = ChannelData.segmented_elevation[ChannelData.segment_number == Segments[i]]
MChi = ChannelData.m_chi[ChannelData.segment_number == Segments[i]].unique()[0]
# get hillslope data
SegmentHillslopeData = BasinHillslopeData[BasinHillslopeData.StreamID == Segments[i]]
ChtMedian[i] = SegmentHillslopeData.Cht.quantile(0.5)
Cht25[i] = SegmentHillslopeData.Cht.quantile(0.25)
Cht75[i] = SegmentHillslopeData.Cht.quantile(0.75)
NTraces[i] = SegmentHillslopeData.size
#normalise distance by outlet distance
Dist = Dist-MinimumDistance
Distances[i] = Dist.mean()
MinDistances[i] = Dist.min()
MaxDistances[i] = Dist.max()
#plot, colouring segments
Colour = MChi/MaximumMChi
plt.plot(Dist/1000,Elevation,'k--',dashes=(2,2), lw=0.5,zorder=10)
plt.plot(Dist/1000, SegmentedElevation, '-', lw=2, c=ColourMap(Colour),zorder=9)
# Finalise the figure
plt.xlabel('Distance (km)')
plt.ylabel('Elevation (m)')
#plot the hillslope data
Ax2 = plt.twinx()
Ax.set_zorder(Ax2.get_zorder()+1) # put ax in front of ax2
Ax.patch.set_visible(False) # hide the 'canvas'
print("plotting errorbar")
plt.errorbar(Distances/1000.,ChtMedian,yerr=np.asarray([Cht75,Cht25]),fmt='s',color=[0.6,0.6,0.6],ms=4,elinewidth=1,zorder=-32)
plt.ylabel("$C_{HT}$ (m$^{-1}$)")
#add colourbar
CAx = Fig.add_axes([0.64,0.32,0.2,0.02])
m = cm.ScalarMappable(cmap=ColourMap)
m.set_array(ChannelData.m_chi)
plt.colorbar(m, cax=CAx,orientation='horizontal')
plt.xlabel('$M_{\chi}$ m$^{0.64}$',fontsize=8)
CAx.tick_params(axis='both', labelsize=8)
#save output
plt.suptitle('Basin ID ' + str(BasinID))
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
plt.savefig(PlotDirectory+FilenamePrefix + "_" + str(BasinID) + "_LongProfMChiCht.png", dpi=300)
plt.close()
def PlotMChiCht(BasinID):
# load the channel data
ChannelData = ReadChannelData(DataDirectory, FilenamePrefix)
#load the hillslopes data
HillslopeData = ReadHillslopeData(DataDirectory, FilenamePrefix)
# isolate basin data
BasinChannelData = ChannelData[ChannelData.basin_key == BasinID]
BasinJunctions = np.sort(HillslopeData.BasinID.unique())
BasinHillslopeData = HillslopeData[HillslopeData.BasinID == BasinJunctions[BasinID]]
# segments in the hillslope data
#Segments = BasinHillslopeData.StreamID.unique()
Segments = BasinChannelData.segment_number.unique()
# setup the figure
Fig = CreateFigure()
plt.subplot(111)
#choose colormap
ColourMap = cm.viridis
# For each segment get the MChi value and collect dimensionless hillslope data
# record the number of traces in each segment inbto a new dataframe
Data = pd.DataFrame(columns=['SegmentNo','MChi','FlowLength','SegmentLength','ChtMedian','ChtLower','ChtUpper','NTraces'])
for i in range(0, len(Segments)):
#Get segment hillslope data
SegmentHillslopeData = BasinHillslopeData[BasinHillslopeData.StreamID == float(Segments[i])]
#Get segment channel data and calculate flow length
SegmentChannelData = BasinChannelData[BasinChannelData.segment_number == Segments[i]]
#channels
MChi = SegmentChannelData.m_chi.unique()[0]
TempFL = SegmentChannelData.flow_distance
FlowLength = np.median(TempFL)
SegmentLength = np.max(TempFL)-np.min(TempFL)
#hillslopes
ChtMedian = SegmentHillslopeData.Cht.quantile(0.5)
ChtLower = SegmentHillslopeData.Cht.quantile(0.25)
ChtUpper = SegmentHillslopeData.Cht.quantile(0.75)
NTraces = SegmentHillslopeData.size
#add to data frame
Data.loc[i] = [Segments[i],MChi,FlowLength,SegmentLength,ChtMedian,ChtLower,ChtUpper,NTraces]
# remove rows with no data (i.e. no hillslope traces)
Data = Data.dropna()
Data = Data[Data.NTraces > 50]
# colour code by flow length
MinFlowLength = Data.FlowLength.min()
Data.FlowLength = Data.FlowLength-MinFlowLength
MaxFlowLength = Data.FlowLength.max()
colours = (Data.FlowLength/MaxFlowLength)
# Error bars with colours but faded (alpha)
for i, row in Data.iterrows():
ChtErr = np.array([[row.ChtLower],[row.ChtUpper]])
plt.plot([row.MChi,row.MChi],ChtErr,'-', lw=1.5, color=ColourMap(colours[i]), alpha=0.5,zorder=9)
plt.plot(row.MChi,row.ChtMedian,'s',color=ColourMap(colours[i]),zorder=32)
# Finalise the figure
plt.xlabel('$M_{\chi}$ m$^{0.64}$')
plt.ylabel('$C_{HT}$ m$^{-1}$')
plt.suptitle('Basin ID ' + str(BasinID))
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
# add colour bar
m = cm.ScalarMappable(cmap=ColourMap)
m.set_array(FlowLength)
cbar = plt.colorbar(m)
tick_locator = ticker.MaxNLocator(nbins=5)
cbar.locator = tick_locator
cbar.update_ticks()
cbar.set_label('Flow Length (m)')
#save output
plt.savefig(PlotDirectory+FilenamePrefix + "_" + str(BasinID) + "_MChi_Cht.png", dpi=300)
plt.close()
def PlotMChiEstar(BasinID,Sc=1.):
# load the channel data
ChannelData = ReadChannelData(DataDirectory, FilenamePrefix)
#load the hillslopes data
HillslopeData = ReadHillslopeData(DataDirectory, FilenamePrefix)
# isolate basin data
BasinChannelData = ChannelData[ChannelData.basin_key == BasinID]
BasinJunctions = HillslopeData.BasinID.unique()
BasinHillslopeData = HillslopeData[HillslopeData.BasinID == BasinJunctions[BasinID]]
MinimumDistance = BasinChannelData.flow_distance.min()
MaximumMChi = BasinChannelData.m_chi.max()
# how many segments are we dealing with?
Segments = BasinChannelData.segment_number.unique()
# setup the figure
Fig = CreateFigure(AspectRatio=1.)
Ax = plt.subplot(111)
#choose colormap
ColourMap = cm.viridis
# Calculate E_Star
BasinHillslopeData.E_Star = 2.*BasinHillslopeData.Cht*BasinHillslopeData.Lh/Sc
# For each segment get the MChi value and collect dimensionless hillslope data
# record the number of traces in each segment
MChi = []
EstarMean = []
EstarStD = []
EstarStE = []
NTraces = []
for i in range(0, len(Segments)):
SegmentHillslopeData = BasinHillslopeData[BasinHillslopeData.StreamID == Segments[i]]
if SegmentHillslopeData.size != 0:
MChi.append(ChannelData.m_chi[ChannelData.segment_number == Segments[i]].unique()[0])
EstarMean.append(SegmentHillslopeData.E_Star.mean())
EstarStD.append(SegmentHillslopeData.E_Star.std())
EstarStE.append(SegmentHillslopeData.E_Star.std()/np.sqrt(float(SegmentHillslopeData.size)))
NTraces.append(SegmentHillslopeData.size)
#make the plot and colour code by number of hillslope traces
NTraces = np.asarray(NTraces,dtype=float)
[plt.errorbar(MChi[i],EstarMean[i],yerr=EstarStD[i],fmt='s',elinewidth=1.5,ecolor=ColourMap(NTraces[i]/np.max(NTraces)),mfc=ColourMap(NTraces[i]/np.max(NTraces))) for i in range(0,len(MChi))]
# Finalise the figure
plt.xlabel('$M_{\chi}$ m$^{0.64}$')
plt.ylabel('$E*$')
plt.text(-0.2,-0.3,'Basin ID ' + str(BasinID),transform = Ax.transAxes,color=[0.35,0.35,0.35])
plt.tight_layout()
# add colour bar
m = cm.ScalarMappable(cmap=ColourMap)
m.set_array(FlowLength)
cbar = plt.colorbar(m)
tick_locator = ticker.MaxNLocator(nbins=5)
cbar.locator = tick_locator
cbar.update_ticks()
cbar.set_label('Flow Length (m)')
#save output
plt.savefig(PlotDirectory+FilenamePrefix + "_" + str(BasinID) + "_MChiEstar.png", dpi=300)
plt.close()
def CalculateRStar(EStar):
"""
MDH
"""
RStar = (1./EStar)*(np.sqrt(1.+(EStar**2.)) - np.log(0.5*(1.+np.sqrt(1+EStar**2.))) - 1.)
return RStar
def PlotEStarRStarTheoretical():
"""
MDH
"""
# Calculate analytical relationship
EStar = np.logspace(-1,3,1000)
RStar = CalculateRStar(EStar)
# Plot with open figure
plt.plot(EStar,RStar,'k--')
def CalculateEStarRStar(Basin,Sc=0.71):
"""
returns: pandas data frame with Estar Rstar data and quantiles for hillslopes
organised by channel segments for the specified basin
MDH, Septmeber 2017
"""
# load the channel data
ChannelData = ReadChannelData(DataDirectory, FilenamePrefix)
#load the hillslopes data
HillslopeData = ReadHillslopeData(DataDirectory, FilenamePrefix)
# isolate basin data
BasinChannelData = ChannelData[ChannelData.basin_key == Basin]
# segments in the hillslope data
#Segments = BasinHillslopeData.StreamID.unique()
Segments = BasinChannelData.segment_number.unique()
# For each segment get the MChi value and collect dimensionless hillslope data
# record the number of traces in each segment inbto a new dataframe
Data = pd.DataFrame(columns=['SegmentNo','MChi','FlowLength','SegmentLength','EStar','EStarLower','EStarUpper','RStar','RStarLower','RStarUpper','NTraces'])
for i in range(0,len(Segments)):
#Get segment hillslope data
SegmentHillslopeData = HillslopeData[HillslopeData.StreamID == float(Segments[i])]
#Get segment channel data and calculate flow length
SegmentChannelData = BasinChannelData[BasinChannelData.segment_number == Segments[i]]
#channels
MChi = SegmentChannelData.m_chi.unique()[0]
TempFL = SegmentChannelData.flow_distance
FlowLength = np.median(TempFL)
SegmentLength = np.max(TempFL)-np.min(TempFL)
#hillslopes
TempEs = (-2.*SegmentHillslopeData.Cht*SegmentHillslopeData.Lh)/Sc
TempRs = SegmentHillslopeData.S/Sc
#get the stats to plot
EStar = TempEs.quantile(0.5)
EStarUpper = TempEs.quantile(0.75)
EStarLower = TempEs.quantile(0.25)
RStar = TempRs.quantile(0.5)
RStarUpper = TempRs.quantile(0.75)
RStarLower = TempRs.quantile(0.25)
NTraces = SegmentHillslopeData.size
#add to data frame
Data.loc[i] = [Segments[i],MChi,FlowLength,SegmentLength,EStar,EStarLower,EStarUpper,RStar,RStarLower,RStarUpper,NTraces]
# remove rows with no data (i.e. no hillslope traces)
Data = Data.dropna(0,'any')
# only keep segments with more than 50 hillslope traces
Data = Data[Data.NTraces > 50]
return Data
def PlotEStarRStar(Basin, Sc=0.71):
"""
MDH
"""
Data = CalculateEStarRStar(Basin)
# setup the figure
Fig = CreateFigure(AspectRatio=1.2)
#choose colormap
ColourMap = cm.viridis
#Plot analytical relationship
PlotEStarRStarTheoretical()
# colour code by flow length
MinFlowLength = Data.FlowLength.min()
Data.FlowLength = Data.FlowLength-MinFlowLength
MaxFlowLength = Data.FlowLength.max()
colours = (Data.FlowLength/MaxFlowLength)
#plot the data
plt.loglog()
# Error bars with colours but faded (alpha)
for i, row in Data.iterrows():
EStarErr = np.array([[row.EStarLower],[row.EStarUpper]])
RStarErr = np.array([[row.RStarLower],[row.RStarUpper]])
plt.plot([row.EStar,row.EStar],RStarErr,'-', lw=1, color=ColourMap(colours[i]), alpha=0.5,zorder=9)
plt.plot(EStarErr,[row.RStar,row.RStar],'-', lw=1, color=ColourMap(colours[i]), alpha=0.5,zorder=9)
plt.plot(row.EStar,row.RStar,'o',ms=4,color=ColourMap(colours[i]),zorder=32)
# Finalise the figure
plt.xlabel('$E^*={{-2\:C_{HT}\:L_H}/{S_C}}$')
plt.ylabel('$R^*=S/S_C$')
plt.xlim(0.1,1000)
plt.ylim(0.01,1.5)
# add colour bar
m = cm.ScalarMappable(cmap=ColourMap)
m.set_array(Data.FlowLength)
cbar = plt.colorbar(m)
tick_locator = ticker.MaxNLocator(nbins=5)
cbar.locator = tick_locator
cbar.update_ticks()
cbar.set_label('Distance to Outlet (m)')
plt.suptitle("Basin "+str(Basin)+" Dimensionless Hillslope Morphology")
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
plt.savefig(PlotDirectory+FilenamePrefix + "_" + "%02d" % Basin + "_EStarRStar.png", dpi=300)
plt.close(Fig)
def PlotEStarRStarProgression(Sc=0.71):
"""
Plots the progression of hillslopes along Bolinas in Estar Rstar space
MDH, September 2017
"""
from scipy.stats import gaussian_kde
# setup the figure
Fig = CreateFigure(AspectRatio=1.2)
#choose colormap
ColourMap = cm.viridis
#Plot analytical relationship
plt.loglog()
PlotEStarRStarTheoretical()
#Store median values to plot the track through E* R* space
EStarMedian = np.zeros(NoBasins)
RStarMedian = np.zeros(NoBasins)
# Setup extent for data density calcs
ESmin = np.log10(0.1)
ESmax = np.log10(100.)
RSmin = np.log10(0.05)
RSmax = np.log10(1.5)
# setup grid for density calcs
ESgrid = np.logspace(ESmin,ESmax,(ESmax-ESmin)*100.)
RSgrid = np.logspace(RSmin,RSmax,(RSmax-RSmin)*100.)
#loop through the basins
for Basin in range(0,NoBasins):
#for Basin in range(0,1):
# Get the hillslope data for the basin
Data = CalculateEStarRStar(Basin)
# Get the convex hull
#Points = np.column_stack((Data.EStar,Data.RStar))
#Hull = ConvexHull(Points)
# calculate the 2D density of the data given
#Counts,Xbins,Ybins=np.histogram2d(Data.EStar,Data.RStar,bins=100)
#Counts = Counts.T
#X,Y = np.meshgrid(Xbins,Ybins)
#plt.pcolormesh(X,Y,Counts)
# calculate gaussian kernel density
Values = np.vstack([np.log10(Data.EStar), np.log10(Data.RStar)])
Density = gaussian_kde(Values)
ES,RS = np.meshgrid(np.log10(ESgrid),np.log10(RSgrid))
Positions = np.vstack([ES.ravel(), RS.ravel()])
# colour code by basin number
colour = float(Basin)/float(NoBasins)
Density = np.reshape(Density(Positions).T, ES.shape)
Density /= np.max(Density)
#plt.pcolormesh(10**ES,10**RS,Density,cmap=cm.Reds)
plt.contour(10**ES,10**RS,Density,[0.2,],colors=[ColourMap(colour),],linewidths=1.,alpha=0.5)
#plt.plot(Data.EStar,Data.RStar,'k.',ms=2,zorder=32)
# make the contour plot
#plt.contour(counts.transpose(),extent=[xbins.min(),xbins.max(),
# ybins.min(),ybins.max()],linewidths=3,colors='black',
# linestyles='solid')
# colour code by basin number
#colour = float(Basin)/float(NoBasins)
# Get median EStar RStar
EStarMedian[Basin] = Data.EStar.median()
RStarMedian[Basin] = Data.RStar.median()
plt.plot(Data.EStar.median(),Data.RStar.median(),'o',ms=5,color=ColourMap(colour), zorder=32)
# Plot the Hull
#if Basin % 4 == 0: