-
Notifications
You must be signed in to change notification settings - Fork 12
/
plot_results.py
451 lines (332 loc) · 15.1 KB
/
plot_results.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
#!/usr/bin/env python
# Filename: plot_results
"""
introduction: plot some statistic of the results
authors: Huang Lingcao
email:[email protected]
add time: 28 October, 2017
"""
import os,sys
from optparse import OptionParser
import parameters
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.axislines import Subplot
import plotly.plotly as py
import plotly.graph_objs as go
# import vector_features
from vector_features import shape_opeation
import basic_src.io_function as io_function
import basic_src.basic as basic
import json
import numpy as np
plt.rc('xtick',labelsize=20)
plt.rc('ytick',labelsize=20)
from vector_features import read_attribute
def draw_one_attribute_histogram(shp_file,field_name,attribute, output,color='grey',hatch=""):
"""
draw the figure of one attribute's histograms
Args:
shp_file: shape file path
attribute_name: name of attribute
output: output the figure
Returns: True if successful, False otherwise
"""
values = read_attribute(shp_file,field_name)
if field_name == 'INarea': # m^2 to km^2
values = [item/1000000.0 for item in values]
fig_obj = plt.figure() # create a new figure
ax = Subplot(fig_obj, 111)
fig_obj.add_subplot(ax)
# n, bins, patches = plt.hist(values, bins="auto", alpha=0.75,ec="black") # ec means edge color
n, bins, patches = ax.hist(values, bins="auto", alpha=0.75, ec="black",linewidth='1.5',color=color,hatch=hatch)
# print(n,bins,patches)
# n_label = [str(i) for i in n]
# plt.hist(values, bins="auto", alpha=0.75, ec="black",label=n_label)
# plt.gcf().subplots_adjust(bottom=0.15) # reserve space for label
# plt.xlabel(attribute,fontsize=15)
# # plt.ylabel("Frequency")
# plt.ylabel("Number",fontsize=15) #
# plt.title('Histogram of '+attribute)
# plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
# plt.axis([40, 160, 0, 0.03])
# hide the right and top boxed axis
ax.axis["right"].set_visible(False)
ax.axis["top"].set_visible(False)
# plt.grid(True)
plt.savefig(output)
basic.outputlogMessage("Output figures to %s"%os.path.abspath(output))
basic.outputlogMessage("ncount: " + str(n))
basic.outputlogMessage("bins: "+ str(bins))
# plt.show()
def draw_one_attribute_windrose(shp_file,field_name,attribute, output,color='grey',hatch=""):
"""
draw the figure of one attribute's wind rose
Args:
shp_file: shape file path
attribute_name: name of attribute
output: output the figure
Returns: True if successful, False otherwise
"""
values = read_attribute(shp_file,field_name)
from windrose import WindroseAxes
wind_dir = np.array(values)
wind_sd = np.ones(wind_dir.shape[0]) #np.ones(wind_dir.shape[0]) #np.arange(1, wind_dir.shape[0] + 1)
bins_range = np.arange(1, 2, 1) # this sets the legend scale
ax = WindroseAxes.from_ax()
ax.bar(wind_dir, wind_sd, normed=True, bins=bins_range,colors=color)
ax.set_yticks(np.arange(5, 16, step=5))
ax.set_yticklabels(np.arange(5, 16, step=5))
# plt.show()
plt.savefig(output)
# plt.grid(True)
# plt.savefig(output)
# basic.outputlogMessage("Output figures to %s"%os.path.abspath(output))
# basic.outputlogMessage("ncount: " + str(n))
# basic.outputlogMessage("bins: "+ str(bins))
return True
def draw_two_attribute_scatter(shp_file,field_name_1,field_name_2, output,color='grey',hatch=""):
"""
draw a scatter of two attributes
Args:
shp_file: shape file path
field_name_1: x
field_name_2: y
output: save file path
color:
hatch:
Returns:True if successful, False otherwise
"""
x_values = read_attribute(shp_file,field_name_1)
y_values = read_attribute(shp_file,field_name_2)
fig_obj = plt.figure() # create a new figure
ax = Subplot(fig_obj, 111)
fig_obj.add_subplot(ax)
# n, bins, patches = plt.hist(values, bins="auto", alpha=0.75,ec="black") # ec means edge color
# n, bins, patches = ax.hist(values, bins="auto", alpha=0.75, ec="black",linewidth='3',color=color,hatch=hatch)
plt.scatter(x_values, y_values,marker='^',color=color)
# print(n,bins,patches)
# n_label = [str(i) for i in n]
# plt.hist(values, bins="auto", alpha=0.75, ec="black",label=n_label)
# plt.gcf().subplots_adjust(bottom=0.15) # reserve space for label
# plt.xlabel(attribute,fontsize=15)
# # plt.ylabel("Frequency")
# plt.ylabel("Number",fontsize=15) #
# # plt.title('Histogram of '+attribute)
# # plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
# # plt.axis([40, 160, 0, 0.03])
# marked area values
area_range = [1500]
for area in area_range:
ax.axvline(x=area,color='k',linewidth=0.8,linestyle='--')
ax.text(area+100, 0.55, '%d $\mathrm{m^2}$'%area, rotation=90,fontsize=20)
# hide the right and top boxed axis
# ax.axis["right"].set_visible(False)
# ax.axis["top"].set_visible(False)
# plt.grid(True)
plt.savefig(output)
basic.outputlogMessage("Output figures to %s"%os.path.abspath(output))
# basic.outputlogMessage("ncount: " + str(n))
# basic.outputlogMessage("bins: "+ str(bins))
# plt.show()
pass
def get_hisogram_of_oneband_raster(image_path):
if io_function.is_file_exist(image_path) is False:
return False
CommandString = 'gdalinfo -json -hist -mm ' + image_path
imginfo = basic.exec_command_string_output_string(CommandString)
if imginfo is False:
return False
imginfo_obj = json.loads(imginfo)
try:
bands_info = imginfo_obj['bands']
band_info = bands_info[0] # only care band one (suppose only have one band)
histogram_info = band_info["histogram"]
hist_count = histogram_info["count"]
hist_min = histogram_info["min"]
hist_max = histogram_info["max"]
hist_buckets = histogram_info["buckets"]
return (hist_count,hist_min,hist_max,hist_buckets)
except KeyError:
basic.outputlogMessage(str(KeyError))
pass
return (False, False,False,False)
pass
def draw_dem_slope_hist(dem_path,slope_path,output):
# get histogram of the dem
dem_count,dem_min,dem_max,dem_buckets = get_hisogram_of_oneband_raster(dem_path)
if dem_count is False:
return False
# get histogram of the slope
slope_count,slope_min,slope_max,slope_buckets = get_hisogram_of_oneband_raster(slope_path)
if slope_count is False:
return False
fig = plt.figure(figsize=(6,4)) #
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny() #have another x-axis
# plot slope histogram
slope_y = np.array(slope_buckets)
slope_x = np.linspace(slope_min, slope_max, slope_count)
slope_per = 100.0 * slope_y / np.sum(slope_y) # draw the percentage
#output slope informaton
with open("whole_area_slope_hist.txt",'w') as f_obj:
f_obj.writelines("slope_count:" + str(slope_count)+'\n')
f_obj.writelines("slope_min:" + str(slope_min) + '\n')
f_obj.writelines("slope_max:" + str(slope_max) + '\n')
f_obj.writelines("slope_buckets:" + str(slope_buckets) + '\n')
f_obj.writelines("slope_x:" + str(slope_x) + '\n')
f_obj.writelines("slope_per:" + str(slope_per) + '\n')
line_slope, = ax1.plot(slope_x,slope_per,'k-', label="Slope Histogram", linewidth=0.8)
# marked the range of gully slope
slope_range = [8.0, 17.4]
for slope in slope_range:
ax1.axvline(x=slope,color='k',linewidth=0.8,linestyle='--')
ax1.text(slope, 0.15, '%.1f'%slope, rotation=90,fontsize=16)
# ax1.set_xlabel("Slope ($^\circ$)",fontsize=15)
ax1.yaxis.tick_right()
# ax1.yaxis.set_label_position("right")
# ax1.set_ylabel("Percentage (%)",fontsize=15)
# plot dem histogram
dem_y = np.array(dem_buckets)
dem_y = np.delete(dem_y,0)
dem_y = np.delete(dem_y, -1)
dem_per = 100.0 * dem_y / np.sum(dem_y) # draw the percentage
dem_x = np.linspace(dem_min, dem_max, dem_count)
dem_x = np.delete(dem_x,0)
dem_x = np.delete(dem_x, -1)
line_dem, = ax2.plot(dem_x, dem_per,'r-', label="DEM Histogram", linewidth=0.8)
# ax2.set_xlabel("Elevation (m)",color="red",fontsize=15)
# ax2.spines['bottom'].set_color('blue')
ax2.spines['top'].set_color('red')
# ax2.xaxis.label.set_color('blue')
ax2.tick_params(axis='x', colors='red')
# marked the range of gully dem
dem_range = [3526, 3667]
for dem in dem_range:
ax2.axvline(x=dem, color='r', linewidth=0.8, linestyle='--')
ax2.text(dem-5, 1.79, str(dem), rotation=90, fontsize=16,color='r')
print(np.sum(slope_y),np.sum(dem_y))
# plt.gcf().subplots_adjust(bottom=0.15) #add space for the buttom
plt.gcf().subplots_adjust(top=0.8) # the value range from [0,1], 1 is toppest, 0 is bottom
# plt.gcf().subplots_adjust(left=0.15)
# plt.gcf().subplots_adjust(right=0.15)
# ax1.legend(loc="upper right")
# fig.legend((line_slope,line_dem),('Slope Histogram', 'DEM Histogram'))
ax1.legend((line_slope, line_dem), ('Slope', 'DEM'), fontsize=16,loc='upper center')
plt.savefig(output,dpi=300)
# plt.show()
pass
def draw_image_histogram_oneband(image_path,output):
CommandString = 'gdalinfo -json -hist -mm ' + image_path
imginfo = basic.exec_command_string_output_string(CommandString)
if imginfo is False:
return False
imginfo_obj = json.loads(imginfo)
try:
bands_info = imginfo_obj['bands']
band_info = bands_info[0] # only care band one (suppose only have one band)
histogram_info = band_info["histogram"]
hist_count = histogram_info["count"]
hist_min = histogram_info["min"]
hist_max = histogram_info["max"]
hist_buckets = histogram_info["buckets"]
hist_array = np.array(hist_buckets)
hist_x = np.linspace(hist_min,hist_max,hist_count)
hist_percent = 100.0*hist_array/np.sum(hist_array)
print(np.sum(hist_array))
# print(hist_percent)
# matplotlib build-in color
# b: blue
# g: green
# r: red
# c: cyan
# m: magenta
# y: yellow
# k: black
# w: white
# plt.figure(figsize=(12, 8))
# color_used_count = 5
# line_color = ['w', 'k'] #['b', 'g', 'r', 'c', 'm', 'y', 'k']
# # linestyle = ['-','--','-.']
# # linestyle = ['*', '+', 's', 'h', 'x', 'd', 'p', 'H', 'D']
# ncount = hist_count
#
# # plot line
# plt.ylim(0,2)
plt.plot(list(hist_x), list(hist_percent), 'b-', label="label", linewidth=1.5)
print(hist_x)
print(hist_percent)
# plt.xlabel("Distance (meter)")
# plt.ylabel("Average Offset Of One Year (meter)")
# plt.title("Offset meters Per Year of Jakobshavn glacier")
# plt.ylim(0, 15000)
# plt.legend()
# plt.show()
plt.savefig(output)
except KeyError:
basic.outputlogMessage(str(KeyError))
pass
return (False, False)
pass
def main(options, args):
shape_file = args[0]
if io_function.is_file_exist(shape_file) is False:
return False
# draw_image_histogram_oneband("/Users/huanglingcao/Data/eboling/DEM/20160728-Large-DSM-NaN_slope.tif","slope_hist.jpg")
# draw_image_histogram_oneband("/Users/huanglingcao/Data/eboling/DEM/20160728-Large-DSM-NaN.tif","dem_hist.jpg")
# draw_dem_slope_hist("/Users/huanglingcao/Data/eboling/DEM/20160728-Large-DSM-NaN.tif",
# "/Users/huanglingcao/Data/eboling/DEM/20160728-Large-DSM-NaN_slope.tif",
# "dem_slope_histogram.jpg")
# draw_two_attribute_scatter(shape_file, "INarea", "IoU", "IoU_InArea_scatter.jpg",color='k')
# draw_one_attribute_histogram(shape_file, "IoU", "IoU (0-1)", "IoU.jpg") # ,hatch='-'
draw_one_attribute_histogram(shape_file, "INarea", "Area ($m^2$)", "area.jpg") #,hatch='-'
# draw_one_attribute_histogram(shape_file, "INperimete", "Perimeter (m)", "Perimeter.jpg") #,hatch='\\'
# draw_one_attribute_histogram(shape_file, "ratio_w_h", "ratio of HEIGHT over WIDTH (W>H)", "ratio_w_h.jpg")
# draw_one_attribute_histogram(shape_file, "ratio_p_a", "ratio of $perimeter^2$ over area", "ratio_p_a.jpg")
# draw_one_attribute_histogram(shape_file, "circularit", "Circularity", "Circularity.jpg") # ,hatch='.'
# #
# # # topography
# draw_one_attribute_histogram(shape_file, "dem_std", "standard variance of DEM", "dem_std.jpg")
# draw_one_attribute_histogram(shape_file, "dem_max", "maximum value of DEM (meter)", "dem_max.jpg")
draw_one_attribute_histogram(shape_file, "dem_mean", "Mean Elevation (m)", "dem_mean.jpg") # ,hatch='x'
# draw_one_attribute_histogram(shape_file, "dem_min", "minimum value of DEM (meter)", "dem_min.jpg")
# #
# draw_one_attribute_histogram(shape_file, "slo_std", "standard variance of Slope", "slo_std.jpg")
# draw_one_attribute_histogram(shape_file, "slo_max", "maximum value of Slope ($^\circ$)", "slo_max.jpg")
# draw_one_attribute_histogram(shape_file, "slo_mean", "Mean Slope ($^\circ$)", "slo_mean.jpg") #,hatch='/'
# draw_one_attribute_histogram(shape_file, "slo_min", "minimum value of Slope ($^\circ$)", "slo_min.jpg")
#
# #hydrology
# draw_one_attribute_histogram(shape_file, "F_acc_std", "standard variance of Flow accumulation", "F_acc_std.jpg")
# draw_one_attribute_histogram(shape_file, "F_acc_max", "maximum value of Flow accumulation", "F_acc_max.jpg")
# draw_one_attribute_histogram(shape_file, "F_acc_mean", "mean value of Flow accumulation", "F_acc_mean.jpg")
# draw_one_attribute_histogram(shape_file, "F_acc_min", "minimum value of Flow accumulation", "F_acc_min.jpg")
#
# draw wind rose of aspect
# draw_one_attribute_windrose(shape_file, "asp_std", "standard variance of Aspect", "asp_std.jpg")
# draw_one_attribute_windrose(shape_file, "asp_max", "maximum value of Aspect ($^\circ$)", "asp_max.jpg")
# draw_one_attribute_windrose(shape_file, "asp_mean", "Mean Aspect ($^\circ$)", "asp_mean.jpg") #,hatch='/'
# draw_one_attribute_windrose(shape_file, "asp_min", "minimum value of Aspect ($^\circ$)", "asp_min.jpg")
# draw wind rose of azimuth from manually draw lines
# draw_one_attribute_windrose(shape_file, "aspectLine", "Mean Aspect ($^\circ$)", "aspectLine.jpg") # ,hatch='/'
os.system("mv processLog.txt bins.txt")
pass
if __name__ == '__main__':
usage = "usage: %prog [options] shapefile"
parser = OptionParser(usage=usage, version="1.0 2017-10-28")
parser.description = 'Introduction: plot some statistic of the results '
parser.add_option("-p", "--para",
action="store", dest="para_file",default='para.ini',
help="the parameters file")
(options, args) = parser.parse_args()
if len(sys.argv) < 2 or len(args) < 1:
parser.print_help()
sys.exit(2)
## set parameters files
# if options.para_file is None:
# print('error, no parameters file')
# parser.print_help()
# sys.exit(2)
# else:
# parameters.set_saved_parafile_path(options.para_file)
main(options, args)
pass