-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpc_geomorph_roughness.py
2536 lines (2236 loc) · 154 KB
/
pc_geomorph_roughness.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 19 17:22:03 2017
@author: Bodo Bookhagen, Oct-Nov, 2017
"""
from laspy.file import File
import copy, glob, time, sys
import numpy as np, os, argparse, pickle, h5py, subprocess, gdal, osr, datetime
from numpy.linalg import svd
from pykdtree.kdtree import KDTree
from scipy import interpolate
from scipy import spatial
from scipy import linalg
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import matplotlib.dates as mdates
import matplotlib.patches as mpatches
import matplotlib.cm as cm
from mpl_toolkits.mplot3d import Axes3D
import multiprocessing
from multiprocessing import Pool
from skimage import exposure
### Command Line Parsing
parser = argparse.ArgumentParser(description='PointCloud (PC) processing for geomorphologic purposes. Estimates slopes, curvature, local roughness, and other parameters. B. Bookhagen ([email protected]), Feb 2018.')
# Important and required:
parser.add_argument('--inlas', type=str, default='', help='LAS/LAZ file with point-cloud data. Ideally, this file contains only ground points (class == 2)')
parser.add_argument('--raster_m', type=float, default=1, help='Raster spacing for subsampling seed points on LAS/LAZ PC. Usually 0.5 to 2 m, default = 1.')
parser.add_argument('--sphere_radius_m', type=float, default=1.5, help='Radius of sphere used for selecting lidar points around seed points. These points are used for range, roughness, and density calculations. Default radius 1.5m, i.e., points within a sphere of 3m are chosen.')
parser.add_argument('--slope_sphere_radius_m', type=float, default=0, help='Radius of sphere used for fitting a linear plane and calculating slope and detrending data (slope normalization). By default this is similar to the radius used for calculation roughness indices (srd_m), but this can be set to a different value. For example, larger radii use the slope of larger area to detrend data.')
parser.add_argument('--dem_fname', type=str, default='', help='Filename of DEM to extract point spacing. Used to identify seed-point coordinates')
parser.add_argument('--shapefile_clip', type=str, default='', help='Name of shapefile to be used to clip interpolated surfaces too. This is likely the shapefile you have previously generated to subset/clip the point-cloud data.')
# Optional / additional parameters
parser.add_argument('--raw_pt_cloud', type=int, default=1, help='Process raw point cloud (not homogenized) for seed-point statistcs (default=1).')
parser.add_argument('--nr_random_sampling', type=int, default=10, help='Number of random-point cloud sampling iteration (how many iterations of bootstraping to estimate slope/curvature calculations).')
parser.add_argument('--range_radii', type=int, default=0, help='Use a list of radii to calculate different length scales (i.e., iterate through different length scales to estimate dataset length scaling).')
parser.add_argument('-epsg', '--epsg_code', type=int, default=26911, help='EPSG code (integer) to define projection information. This should be the same EPSG code as the input data (no re-projection included yet) and can be taken from LAS/LAZ input file. Add this to ensure that output shapefile and GeoTIFFs are properly geocoded.')
parser.add_argument('-o', '--outlas', type=str, default='', help='LAS file to be created (currently no writing of LAZ files supported). This has the same dimension and number of points as the input LAS/LAZ file, but replaced color values reflecting roughness calculated over a given radius. Note that this will overwrite existing color information in the output file.')
#parser.add_argument('--shapefile_out', type=str, default='', help='Output shapefile storing calculated attributes for seed points only. Default filename will be generated with radius in the filename.')
parser.add_argument('-odir', '--outputdir', type=str, default='', help='Output directory to store plots and pickle files. Default is directory containing LAS/LAZ file.')
parser.add_argument('-fig', '--figure', type=bool, default=True, help='Generate figures while processing. This often takes significant amount of time and can be turned off with -fig False.')
parser.add_argument('-color', '--store_color', type=bool, default=False, help='Generate a LAS file where deviation from the plane are saved in the color attribute of the LAS file for every point. *Note* that this will replace the color information in the LAS file (but will be saved to separate file). Default is False, can be turned on with --store_color True.')
parser.add_argument('-cores', '--nr_of_cores', type=int, default=0, help='Max. number of cores to use for multi-core processing. Default is to use all cores, set to --nr_of_cores 6 to use 6 cores.')
args = parser.parse_args()
#args.inlas = '/raid-cachi/bodo/Dropbox/California/SCI/Pozo/cat1/Pozo_USGS_UTM11_NAD83_all_color_cl_cat1.laz'
#args.shapefile_clip = '/raid-cachi/bodo/Dropbox/California/SCI/Pozo/shapefiles/Pozo_DTM_noveg_UTM11_NAD83_cat1_b50m.shp'
#args.dem_fname = '/raid-cachi/bodo/Dropbox/California/SCI/Pozo/cat1/Pozo_cat1_UTM11_NAD83_1m.tif'
### Function definitions
def drawSphere(xCenter, yCenter, zCenter, r):
#draw sphere
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x=np.cos(u)*np.sin(v)
y=np.sin(u)*np.sin(v)
z=np.cos(v)
# shift and scale sphere
x = r*x + xCenter
y = r*y + yCenter
z = r*z + zCenter
return (x,y,z)
def planeFit(points):
"""
p, n = planeFit(points)
Given an array, points, of shape (d,...)
representing points in d-dimensional space,
fit an d-dimensional plane to the points.
Return a point, p, on the plane (the point-cloud centroid),
and the normal, n.
source = https://stackoverflow.com/questions/12299540/plane-fitting-to-4-or-more-xyz-points
"""
points = np.reshape(points, (np.shape(points)[0], -1)) # Collapse trialing dimensions
try:
assert points.shape[0] <= points.shape[1], "There are only {} points in {} dimensions.".format(points.shape[1], points.shape[0])
except AssertionError:
return np.nan, np.nan, np.nan
ctr = points.mean(axis=1)
x = points - ctr[:,np.newaxis]
M = np.dot(x, x.T) # Could also use np.cov(x) here.
plane_normal = svd(M)[0][:,-1]
d = -ctr.dot(plane_normal)
z = (-plane_normal[0] * points[0,:] - plane_normal[1] * points[1,:] - d) * 1. /plane_normal[2]
errors = z - points[2,:]
residual = np.linalg.norm(errors)
return ctr, plane_normal, residual
def curvFit_lstsq_polygon(points, order=2):
"""
Fitting a second order polynom to a point cloud and deriving the curvature in a simplified form.
More details: https://gis.stackexchange.com/questions/37066/how-to-calculate-terrain-curvature
"""
points = np.reshape(points, (np.shape(points)[0], -1)) # Collapse trialing dimensions
try:
assert points.shape[0] <= points.shape[1], "There are only {} points in {} dimensions.".format(points.shape[1], points.shape[0])
except AssertionError:
return np.nan, np.nan, np.nan
points = points.T
X,Y = np.meshgrid(np.arange(np.nanmin(points[:,0]),np.nanmax(points[:,0]), args.raster_m/10), np.arange(np.nanmin(points[:,1]),np.nanmax(points[:,1]), args.raster_m/10))
XX = X.flatten()
YY = Y.flatten()
if order == 1:
# best-fit linear plane
A = np.c_[points[:,0], points[:,1], np.ones(points.shape[0])]
C,_,_,_ = linalg.lstsq(A, points[:,2]) # coefficients
# evaluate it on grid
#Z = C[0]*X + C[1]*Y + C[2]
# or expressed using matrix/vector product
#Z_order1 = np.dot(np.c_[XX, YY, np.ones(XX.shape)], C).reshape(X.shape)
slope = np.mean(C[0:2])
curvature = np.nan
elif order == 2:
# best-fit quadratic curve
A = np.c_[np.ones(points.shape[0]), points[:,:2], np.prod(points[:,:2], axis=1), points[:,:2]**2]
C,_,_,_ = linalg.lstsq(A, points[:,2])
# evaluate it on a grid
Z_order2 = np.dot(np.c_[np.ones(XX.shape), XX, YY, XX*YY, XX**2, YY**2], C).reshape(X.shape)
#Z = Dx² + Ey² + Fxy + Gx + Hy + I
#Curvature = -2(D + E)
#Slope = sqrt(G^2 + H ^2)
curvature = -2 * (C[4] + C[5])
slope = np.sqrt( C[1]**2 + C[2]**2 )
Z_pts = np.dot(np.c_[np.ones(points.shape[0]), points[:,0], points[:,1], points[:,0]*points[:,1], points[:,0]**2, points[:,1]**2], C)
errors = points[:,2] - Z_pts
dZ_residuals = np.linalg.norm(errors)
del A, C, Z_order2, Z_pts, errors
return slope, curvature, dZ_residuals
def calc_pts_length_scale_multicore(ii):
#setup multicore loop for all seed points
#Setup array for seed point results:
from_pos = pos_array[ii] #Get start/end from position array
to_pos = pos_array[ii+1]
subarr = np.arange(from_pos, to_pos) #Slice the data into the selected part...
curv_scale_stats_results = np.empty((subarr.shape[0], nr_of_datasets_length_scale))
curv_scale_stats_results.fill(np.nan)
for j in range(subarr.shape[0]):
pts_xyz = pcl_xyzg_rstep_seed[subarr[j]]
pts_idx = points_k_idx[subarr[j]]
pts = pcl_xyzg[pts_idx]
pts_centroid = np.mean(pts, axis=0)
#if pts > 5e4 (50'000), it's better to subsample/random sample
d = spatial.distance.cdist(np.array([pts_xyz]), pts, 'euclidean')[0]
d.sort()
distances = np.hstack((np.array([d.shape[0], d[1::].min(), d.max(), d.mean(), np.std(d)]), np.percentile(d, [25, 50, 75])))
A = np.c_[np.ones(pts.shape[0]), pts[:,:2], np.prod(pts[:,:2], axis=1), pts[:,:2]**2]
C,_,_,_ = linalg.lstsq(A, pts[:,2])
curvature = -2 * ( C[4] + C[5] )
slope = np.sqrt( C[1]**2 + C[2]**2 )
#evaluate fit:
Z_pts = np.dot(np.c_[np.ones(pts.shape[0]), pts[:,0], pts[:,1], pts[:,0]*pts[:,1], pts[:,0]**2, pts[:,1]**2], C)
errors = pts[:,2] - Z_pts
dZ_residuals = np.linalg.norm(errors)
curv_scale_stats_cat = np.concatenate((pts_centroid, distances, np.array([slope, curvature, dZ_residuals])))
curv_scale_stats_results[j,:] = curv_scale_stats_cat
del A, C, Z_pts, errors, d, pts, pts_idx, pts_xyz, curv_scale_stats_cat, pts_centroid
pickle_fn = os.path.join(pickle_dir, 'PC_length_scale_{}.pickle'.format(str(ii).zfill(4)))
pickle.dump((curv_scale_stats_results), open(pickle_fn,'wb'))
if np.mod(ii,10) == 0:
print('{}, '.format(str(ii).zfill(2)), end='', flush=True)
del curv_scale_stats_results
def pcl_xyzg_p_slope_curvature_singlecore(ii, subarr):
slope_lstsq = np.empty(subarr.shape[0])
slope_lstsq.fill(np.nan)
curvature_lstsq = np.empty(subarr.shape[0])
curvature_lstsq.fill(np.nan)
dZ_residuals_lstsq = np.empty(subarr.shape[0])
dZ_residuals_lstsq.fill(np.nan)
random_pts_xyz_normal = np.empty((subarr.shape[0], 3))
random_pts_xyz_normal.fill(np.nan)
slope_plane = np.empty(subarr.shape[0])
slope_plane.fill(np.nan)
for j in range(subarr.shape[0]):
random_pts_xyz = pcl_xyzg_p_random[pcl_xyzg_p_random_seed_radius[subarr[j]],:].T
slope_lstsq[j], curvature_lstsq[j], dZ_residuals_lstsq[j] = curvFit_lstsq_polygon(random_pts_xyz, order=2)
random_pts_xyz_meanpt, random_pts_xyz_normal[j,:], plane_residual = planeFit(random_pts_xyz)
slope_plane[j] = random_pts_xyz_normal[j,2]
del random_pts_xyz
return slope_lstsq, curvature_lstsq, dZ_residuals_lstsq, slope_plane
def pcl_xyzg_p_slope_curvature_multicore(ii):
from_pos = pos_array[ii] #Get start/end from position array
to_pos = pos_array[ii+1]
subarr = np.arange(from_pos, to_pos) #Slice the data into the selected part...
slope_lstsq = np.empty(subarr.shape[0])
slope_lstsq.fill(np.nan)
curvature_lstsq = np.empty(subarr.shape[0])
curvature_lstsq.fill(np.nan)
dZ_residuals_lstsq = np.empty(subarr.shape[0])
dZ_residuals_lstsq.fill(np.nan)
random_pts_xyz_normal = np.empty((subarr.shape[0], 3))
random_pts_xyz_normal.fill(np.nan)
slope_plane = np.empty(subarr.shape[0])
slope_plane.fill(np.nan)
for j in range(subarr.shape[0]):
random_pts_xyz = pcl_xyzg_p_random[pcl_xyzg_p_random_seed_radius[subarr[j]],:].T
slope_lstsq[j], curvature_lstsq[j], dZ_residuals_lstsq[j] = curvFit_lstsq_polygon(random_pts_xyz, order=2)
random_pts_xyz_meanpt, random_pts_xyz_normal[j,:], plane_residual = planeFit(random_pts_xyz)
slope_plane[j] = random_pts_xyz_normal[j,2]
del random_pts_xyz
return slope_lstsq, curvature_lstsq, dZ_residuals_lstsq, slope_plane
def calc_pts_length_scale_singlecore(ii, subarr):
#setup multicore loop for all seed points
#Setup array for seed point results:
curv_scale_stats_results = np.empty((subarr.shape[0], nr_of_datasets_length_scale))
curv_scale_stats_results.fill(np.nan)
for j in range(subarr.shape[0]):
pts_xyz = pcl_xyzg_rstep_seed[subarr[j]]
pts_idx = points_k_idx[subarr[j]]
pts = pcl_xyzg[pts_idx]
pts_centroid = np.mean(pts, axis=0)
#if pts > 5e4 (50'000), it's better to subsample/random sample
d = spatial.distance.cdist(np.array([pts_xyz]), pts, 'euclidean')[0]
d.sort()
distances = np.hstack((np.array([d.shape[0], d[1::].min(), d.max(), d.mean(), np.std(d)]), np.percentile(d, [25, 50, 75])))
A = np.c_[np.ones(pts.shape[0]), pts[:,:2], np.prod(pts[:,:2], axis=1), pts[:,:2]**2]
C,_,_,_ = linalg.lstsq(A, pts[:,2])
curvature = -2 * ( C[4] + C[5] )
slope = np.sqrt( C[1]**2 + C[2]**2 )
#evaluate fit:
Z_pts = np.dot(np.c_[np.ones(pts.shape[0]), pts[:,0], pts[:,1], pts[:,0]*pts[:,1], pts[:,0]**2, pts[:,1]**2], C)
errors = pts[:,2] - Z_pts
dZ_residuals = np.linalg.norm(errors)
curv_scale_stats_cat = np.concatenate((pts_centroid, distances, np.array([slope, curvature, dZ_residuals])))
curv_scale_stats_results[j,:] = curv_scale_stats_cat
del A, C, Z_pts, errors, d, pts, pts_idx, pts_xyz, curv_scale_stats_cat, pts_centroid
pickle_fn = os.path.join(pickle_dir, 'PC_length_scale_{}.pickle'.format(str(ii).zfill(4)))
pickle.dump((curv_scale_stats_results), open(pickle_fn,'wb'))
if np.mod(ii,10) == 0:
print('{}, '.format(str(ii).zfill(2)), end='', flush=True)
del curv_scale_stats_results
def poisson_disk_sampling():
# see here: http://devmag.org.za/2009/05/03/poisson-disk-sampling/
#https://www.pdal.io/stages/filters.poisson.html
#http://hhoppe.com/proj/thesis/
#https://github.com/mkazhdan/PoissonRecon
print('testing')
def plot_length_scales_map(pcl_xyzg_rstep_seed, curv_scale_stats, dist_range_list, distance_n = [0,5,10]):
#Plotting Map view of mean distance of each queried point cloud
for i in range(len(distance_n)):
distance_n_current = distance_n[i]
pts_distance_fig_fn = '_distances_%dm.png'%dist_range_list[distance_n_current]
pts_distance_fig_fn = os.path.join(figure_dir, os.path.basename(args.inlas).split('.')[0] + pts_distance_fig_fn)
fig = plt.figure(figsize=(16.53,11.69), dpi=150)
fig.clf()
ax1 = fig.add_subplot(231)
cax1 = ax1.scatter(pcl_xyzg_rstep_seed[:,0], pcl_xyzg_rstep_seed[:,1], c=curv_scale_stats[distance_n_current,3,:], s=0.5, cmap=plt.get_cmap('jet'), linewidth=0, vmin=np.percentile(curv_scale_stats[distance_n_current,3,:], 10), vmax=np.percentile(curv_scale_stats[distance_n_current,3,:], 90))
cbar = fig.colorbar(cax1)
cbar.set_label('Number of points')
ax1.set_title('Number of points for each sphere for query of r=%0.2fm'%(dist_range_list[distance_n_current]),y=1.05)
ax1.set_xlabel('UTM-X (m)')
ax1.axis('equal')
ax1.grid('on')
ax2 = fig.add_subplot(232)
cax2 = ax2.scatter(pcl_xyzg_rstep_seed[:,0], pcl_xyzg_rstep_seed[:,1], c=curv_scale_stats[distance_n_current,9,:], s=0.5, cmap=plt.get_cmap('PRGn_r'), linewidth=0, vmin=np.percentile(curv_scale_stats[distance_n_current,9,:], 10), vmax=np.percentile(curv_scale_stats[distance_n_current,9,:], 90))
cbar = fig.colorbar(cax2)
cbar.set_label('Distance (m)')
ax2.set_title('Median distance of points for each sphere for query of r=%0.2fm'%(dist_range_list[distance_n_current]),y=1.05)
ax2.set_xlabel('UTM-X (m)')
ax2.axis('equal')
ax2.grid('on')
ax3 = fig.add_subplot(233)
cax3 = ax3.scatter(pcl_xyzg_rstep_seed[:,0], pcl_xyzg_rstep_seed[:,1], c=curv_scale_stats[distance_n_current,10,:]-curv_scale_stats[distance_n_current,8,:], s=0.5, cmap=plt.get_cmap('spring'), linewidth=0, vmin=np.percentile(curv_scale_stats[distance_n_current,10,:]-curv_scale_stats[distance_n_current,8,:], 10), vmax=np.percentile(curv_scale_stats[distance_n_current,10,:]-curv_scale_stats[distance_n_current,8,:], 90))
cbar = fig.colorbar(cax3)
cbar.set_label('Range of 75-25th p distance (m)')
ax3.set_title('Range of 75-25th perc. distance of points for each sphere for query of r=%0.2fm'%(dist_range_list[distance_n_current]),y=1.05)
ax3.set_xlabel('UTM-X (m)')
ax3.axis('equal')
ax3.grid('on')
ax4 = fig.add_subplot(234)
cax4 = ax4.scatter(pcl_xyzg_rstep_seed[:,0], pcl_xyzg_rstep_seed[:,1], c=curv_scale_stats[distance_n_current,11,:], s=0.5, cmap=plt.get_cmap('seismic'), linewidth=0, vmin=np.percentile(curv_scale_stats[distance_n_current,11,:], 10), vmax=np.percentile(curv_scale_stats[distance_n_current,11,:], 90))
cbar = fig.colorbar(cax4)
cbar.set_label('Slope (m/m)')
ax4.set_title('Slope of fitted sphere for query of r=%0.2fm'%(dist_range_list[distance_n_current]),y=1.05)
ax4.set_xlabel('UTM-X (m)')
ax4.set_ylabel('UTM-Y (m)')
ax4.axis('equal')
ax4.grid('on')
ax5 = fig.add_subplot(235)
cax5 = ax5.scatter(pcl_xyzg_rstep_seed[:,0], pcl_xyzg_rstep_seed[:,1], c=curv_scale_stats[distance_n_current,12,:], s=0.5, cmap=plt.get_cmap('PiYG'), linewidth=0,vmin=np.percentile(curv_scale_stats[distance_n_current,12,:], 10), vmax=np.percentile(curv_scale_stats[distance_n_current,12,:], 90))
cbar = fig.colorbar(cax5)
cbar.set_label('Curvature (1/m)')
ax5.set_title('Curvature distance of points for each sphere for query of r=%0.2fm'%(dist_range_list[distance_n_current]),y=1.05)
ax5.set_xlabel('UTM-X (m)')
ax5.set_ylabel('UTM-Y (m)')
ax5.axis('equal')
ax5.grid('on')
ax6 = fig.add_subplot(236)
cax6 = ax6.scatter(pcl_xyzg_rstep_seed[:,0], pcl_xyzg_rstep_seed[:,1], c=curv_scale_stats[distance_n_current,13,:], s=0.5, cmap=plt.get_cmap('autumn_r'), linewidth=0, vmin=np.percentile(curv_scale_stats[distance_n_current,13,:], 10), vmax=np.percentile(curv_scale_stats[distance_n_current,13,:], 90))
cbar = fig.colorbar(cax6)
cbar.set_label('Residual (m)')
ax6.set_title('Plane residual for each sphere for query of r=%0.2fm'%(dist_range_list[distance_n_current]),y=1.05)
ax6.set_xlabel('UTM-X (m)')
ax6.set_ylabel('UTM-Y (m)')
ax6.axis('equal')
ax6.grid('on')
fig.savefig(pts_distance_fig_fn, bbox_inches='tight')
plt.close()
def plot_length_scales_comparison():
fig = plt.figure(figsize=(16.53,11.69), dpi=150)
fig.clf()
ax1 = fig.add_subplot(231)
pt_density = curv_scale_stats[0,3,:] / (curv_scale_stats[0,9,:]**2*np.pi)
cax1 = ax1.scatter(pcl_xyzg_rstep_seed[:,0], pcl_xyzg_rstep_seed[:,1], s=0.75, c=pt_density, vmin=np.percentile(pt_density, 10), vmax=np.percentile(pt_density, 90))
cbar=fig.colorbar(cax1)
cbar.set_label('Point density (pts/m^2)')
ax1.set_xlabel('UTM-X')
ax1.set_ylabel('UTM_Y')
ax1.set_title('Point density for sphere = 1m',y=1.05)
ax2 = fig.add_subplot(232)
ax2.plot(curv_scale_stats[:,9,:], curv_scale_stats[:,3,:] / (curv_scale_stats[:,6,:]**2*np.pi), '.', markersize=0.2, color='gray', label='values')
ax2.plot(np.nanmedian(curv_scale_stats[:,9,:], axis=1), np.nanmedian(curv_scale_stats[:,3,:] / (curv_scale_stats[:,6,:]**2*np.pi), axis=1), 'bo', label='median')
ax2.set_xlabel('Median distance (m)')
ax2.set_ylabel('Point density (pts/m^2)')
ax2.set_title('Median distance and point density ',y=1.05)
ax2.grid('on')
#import numpy as np
#import seaborn as sns
#data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
#sns.set_style('whitegrid')
#sns.kdeplot(np.array(data), bw=0.5)
#see https://stackoverflow.com/questions/30145957/plotting-2d-kernel-density-estimation-with-python for 2D KDE plot
def plot_length_scales_graph(pcl_xyzg_rstep_seed, curv_scale_stats, dist_range_list, xy_point_nr_list = [0,5000,10000]):
#Plot functional relations for all divergent parts
curv_scale_stats_divergent75p_median = np.empty(curv_scale_stats.shape[0])
curv_scale_stats_divergent75p_median.fill(np.nan)
curv_scale_stats_divergent75p_std = np.empty(curv_scale_stats.shape[0])
curv_scale_stats_divergent75p_std.fill(np.nan)
for i in range(curv_scale_stats.shape[0]):
idx_divergent = np.where(curv_scale_stats[i,12,:] > 0.001)[0] #positive curvature, hillslopes
idx_divergent75p = np.where(curv_scale_stats[i,12,idx_divergent] > np.percentile(curv_scale_stats[i,12,idx_divergent], 75))[0]
idx_divergent75p = idx_divergent[idx_divergent75p]
curv_scale_stats_divergent75p_median[i] = np.nanmedian(curv_scale_stats[i,12,idx_divergent75p])
curv_scale_stats_divergent75p_std[i] = np.nanstd(curv_scale_stats[i,12,idx_divergent75p])
idx_divergent90p = np.where(curv_scale_stats[0,12,idx_divergent] > np.percentile(curv_scale_stats[0,12,idx_divergent], 90))[0]
idx_divergent90p = idx_divergent[idx_divergent90p]
fig = plt.figure(figsize=(16.53,11.69), dpi=150)
fig.clf()
ax1 = fig.add_subplot(231)
ax1.plot(np.nanmedian(curv_scale_stats[:,9,idx_divergent90p], axis=1), curv_scale_stats_divergent75p_std, 'o-')
ax1.set_xlabel('Median distance (m)')
ax1.set_ylabel('Median curvature (1/m)')
ax1.set_title('Median distance and curvature of 90th percentile divergent curvature for all k distances',y=1.05)
ax1.grid('on')
idx_convergent = np.where(curv_scale_stats[0,12,:] < -0.001)[0] #negative curvature, channels
ax2 = fig.add_subplot(232)
ax2.plot(curv_scale_stats[:,9,idx_convergent[100]], curv_scale_stats[:,12,idx_convergent[100]], 'bo')
ax2.plot(curv_scale_stats[:,9,idx_divergent], curv_scale_stats[:,12,idx_divergent], 'r+')
ax2 = fig.add_subplot(232)
ax2.plot(np.nanmedian(curv_scale_stats[:,9,:], axis=1), np.nanmean(curv_scale_stats[:,12,:], axis=1), 'bo-')
ax2.plot(np.nanmedian(curv_scale_stats[:,9,:], axis=1), np.nanmean(curv_scale_stats[:,12,:], axis=1)+np.nanstd(curv_scale_stats[:,12,:], axis=1), 'b-')
ax2.plot(np.nanmedian(curv_scale_stats[:,9,:], axis=1), np.nanmean(curv_scale_stats[:,12,:], axis=1)-np.nanstd(curv_scale_stats[:,12,:], axis=1), 'b-')
ax2.set_xlabel('Median distance (m)')
ax2.set_ylabel('std. deviation of curvature (1/m)')
ax2.set_title('Median distance and mean curvature of all point',y=1.05)
ax2.grid('on')
ax3 = fig.add_subplot(233)
ax3.plot(np.nanmedian(curv_scale_stats[:,9,:], axis=1), np.nanmean(curv_scale_stats[:,11,:], axis=1), 'bo-')
ax3.plot(np.nanmedian(curv_scale_stats[:,9,:], axis=1), np.nanmean(curv_scale_stats[:,11,:], axis=1)+np.nanstd(curv_scale_stats[:,11,:], axis=1), 'b-')
ax3.plot(np.nanmedian(curv_scale_stats[:,9,:], axis=1), np.nanmean(curv_scale_stats[:,11,:], axis=1)-np.nanstd(curv_scale_stats[:,11,:], axis=1), 'b-')
ax3.set_xlabel('Median distance (m)')
ax3.set_ylabel('Median slope (1/m)')
ax3.set_title('Median distance and median slope of all point',y=1.05)
ax3.grid('on')
ax3 = fig.add_subplot(234)
ax3.plot(np.nanmedian(curv_scale_stats[:,6,:], axis=1), np.nanmedian(curv_scale_stats[:,3,:], axis=1), 'bo', label='median')
ax3.plot(np.nanmedian(curv_scale_stats[:,6,:], axis=1), np.nanmean(curv_scale_stats[:,3,:], axis=1), 'g+', label='mean')
ax3.plot(np.nanmedian(curv_scale_stats[:,6,:], axis=1), np.nanmax(curv_scale_stats[:,3,:], axis=1), 'r.', label='max')
ax3.set_xlabel('Median distance (m)')
ax3.set_ylabel('Median/Mean/Max number of measurements')
ax3.set_title('Median distance and number of neighboring points',y=1.05)
ax3.legend()
ax3.grid('on')
ax4 = fig.add_subplot(234)
ax4.plot(np.nanmedian(curv_scale_stats[:,6,:], axis=1), np.nanmedian(curv_scale_stats[:,13,:], axis=1), 'bo', label='median')
ax4.plot(np.nanmedian(curv_scale_stats[:,6,:], axis=1), np.nanmean(curv_scale_stats[:,13,:], axis=1), 'g+', label='mean')
ax4.plot(np.nanmedian(curv_scale_stats[:,6,:], axis=1), np.nanmax(curv_scale_stats[:,13,:], axis=1), 'r.', label='max')
ax4.plot(np.nanmedian(curv_scale_stats[:,6,:], axis=1), np.nanmin(curv_scale_stats[:,13,:], axis=1), 'k.', label='min')
ax4.set_xlabel('Median distance (m)')
ax4.set_ylabel('Median/Mean/Max/Min residuals (m)')
ax4.set_title('Median distance and residuals of plane fit',y=1.05)
ax4.legend()
ax4.grid('on')
def gaussian_curvature(Z):
#Gaussian curvature only for gridded data
Zy, Zx = np.gradient(Z)
Zxy, Zxx = np.gradient(Zx)
Zyy, _ = np.gradient(Zy)
K = (Zxx * Zyy - (Zxy ** 2)) / (1 + (Zx ** 2) + (Zy **2)) ** 2
return K
def griddata_clip_geotif(tif_fname, points, data2i, xxyy, ncols, nrows, geotransform):
#interpolate point to a gridded dataset using interpolate.griddata and nearest neighbor interpolation. Next, data will be clipped by shapefile to remove potential interpolation artifacts
#sample call:
#griddata_clip_geotif(nrlidari_tif_fn, points, pts_seed_stats[idx_nonan,17][0], xxyy=(xx,yy), ncols=ncols, nrows=nrows, geotransform=geotransform)
datai = interpolate.griddata(points, data2i, xxyy, method='nearest')
output_raster = gdal.GetDriverByName('GTiff').Create(tif_fname,ncols, nrows, 1 ,gdal.GDT_Float32,['TFW=YES', 'COMPRESS=DEFLATE', 'ZLEVEL=9']) # Open the file, see here for information about compression: http://gis.stackexchange.com/questions/1104/should-gdal-be-set-to-produce-geotiff-files-with-compression-which-algorithm-sh
output_raster.SetGeoTransform(geotransform)
srs = osr.SpatialReference()
srs.ImportFromEPSG(args.epsg_code)
output_raster.SetProjection( srs.ExportToWkt() )
output_raster.GetRasterBand(1).WriteArray(datai)
output_raster.FlushCache()
output_raster=None
if os.path.exists(args.shapefile_clip) == False:
print('Shapefile does not exist: %s'%args.shapefile_clip)
exit()
tif_fname2 = os.path.join(os.path.dirname(tif_fname),'.'.join(os.path.basename(tif_fname).split('.')[0:-1]) + '2.tif')
cmd = ['gdalwarp', '-dstnodata', '-9999', '-co', 'COMPRESS=DEFLATE', '-co', 'ZLEVEL=9', '-crop_to_cutline', '-cutline', args.shapefile_clip, tif_fname, tif_fname2]
logfile_fname = os.path.join(args.outputdir, 'log') + '/gdalwarp_' + datetime.datetime.now().strftime('%Y%b%d_%H%M%S') + '.txt'
logfile_error_fname = os.path.join(args.outputdir, 'log') + '/ogr2ogr_' + datetime.datetime.now().strftime('%Y%b%d_%H%M%S') + '_err.txt'
with open(logfile_fname, 'w') as out, open(logfile_error_fname, 'w') as err:
subprocess_p = subprocess.Popen(cmd, stdout=out, stderr=err)
subprocess_p.wait()
os.remove(tif_fname)
os.rename(tif_fname2, tif_fname)
cmd = ['gdalinfo', '-hist', '-stats', '-mm', tif_fname]
logfile_fname = os.path.join(args.outputdir, 'log') + '/gdalinfo_' + datetime.datetime.now().strftime('%Y%b%d_%H%M%S') + '.txt'
logfile_error_fname = os.path.join(args.outputdir, 'log') + '/gdalinfo_' + datetime.datetime.now().strftime('%Y%b%d_%H%M%S') + '_err.txt'
with open(logfile_fname, 'w') as out, open(logfile_error_fname, 'w') as err:
subprocess_p = subprocess.Popen(cmd, stdout=out, stderr=err)
subprocess_p.wait()
ds = gdal.Open(tif_fname)
datai = np.array(ds.GetRasterBand(1).ReadAsArray())
datai[np.where(datai == ds.GetRasterBand(1).GetNoDataValue())] = np.nan
ds = None
return datai
def pc_density(pts_xyz, pcl_xyzg_ckdtree, nn=51, show_density_information=0):
'''
Takes the seed-point PC and uses the KDTree of the entire pointcloud to calculate statistics.
In this approach, the point density is only calculated for the points given in pts_xyz. One
can also feed the entire point cloud to get the point density for every point.
Number of neighbors are the max. number of points in a 1.5m neighborhood.
For lidar seed point call with:
p_min, p_median, density_min, density_median = pc_density(pcl_xyzg_rstep_seed, pcl_xyzg_ckdtree, nn=nn=int(dxyzn_mean_nre))
For all lidar points, call with:
p_min, p_median, density_min, density_median = pc_density(pcl_xyzg, pcl_xyzg_ckdtree, nn=dxyzn_max_nre)
'''
n = pts_xyz.shape[0]
density_min = np.zeros(n)
density_median = np.zeros(n)
#density_max = np.zeros(n)
p_min = np.zeros(n)
p_median = np.zeros(n)
d,k = pcl_xyzg_ckdtree.query(pts_xyz, k=nn, p=2, n_jobs=-1)
#euclidean distance p=2
del k
#remove first number from array, because it is mostly 0 or the seed point itself
#d = d[:,1::]
#d = np.sqrt(d)
#Get minimum distances for all neighbors and use the minim distance of the last element (largest d)
#Could improve this by using an adaptive kernel to adjust for number of nearest neighbor for each seed point
dmin = d.min(axis = 0)
dmin = dmin[-1] #select last element,
#Repeat for median distances
dmedian = np.median(d, axis = 0)
dmedian = dmedian[-1]
#Repeat for max distances
#dmax = np.max(d, axis = 0)
#dmax = dmax[-1]
#calculate area, assuming min/median distance is a radius
disk_min = np.pi * dmin * dmin
disk_median = np.pi * dmedian * dmedian
#disk_max = np.pi * dmax * dmax
#Calculate density and probability for each seed point
for i in range(n):
di = d[i]
density_min[i] = len(di[di <= dmin]) / disk_min
density_median[i] = len(di[di <= dmedian]) / disk_median
#density_max[i] = len(di[di <= dmax]) / disk_max
#probability is the inverse of the density
if len(di[di <= dmin]) < 1:
print('no point in minimum distance (i=%d)'%i)
p_min[i] = 0
else:
p_min[i] = disk_min / len(di[di <= dmin])
p_median[i] = disk_median / len(di[di <= dmedian])
#normalize probabilities by their sum
p_min /= p_min.sum()
p_median /= p_median.sum()
#probability-based subsampling
if show_density_information == 1:
print('PC density: Find %d nearest neighbors from each of %s seed points with a total of %s points.'%(nn,"{:,}".format(pts_xyz.shape[0]), "{:,}".format(pcl_xyzg_ckdtree.n)))
print('PC density: min distance: %0.3fm, median distance: %0.3fm'%(dmin, dmedian))
print('PC density: Average point density for min. distance (pts/m^2): %0.3f pts/m^2'%(np.mean(density_min)))
print('PC density: Average point density for median distance (pts/m^2): %0.3f pts/m^2'%(np.mean(density_median)))
#print('PC density: Average point density for max. distance (pts/m^2): %0.3f pts/m^2'%(np.mean(density_max)))
print('PC density: Standard deviation of avg. point density from median distances (pts/m^2): %0.3f pts/m^2'%(np.std(density_median)))
del d, disk_min, disk_median, dmedian, dmin, n, pts_xyz
return p_min, p_median, density_min, density_median
def pc_random_p_subsampling(pts_xyz, p, nr_of_points):
'''
Sub-samples indices of PC pcl_xyzg_radius with probability weight p based
on point density of each point. Will result in greatly reduced point cloud.
Give nr_of_points for subsampled point cloud, usually len(p)/2
call with a probability
#pcl_xyzg_radius_equal_nr_random = pc_random_p_subsampling(pcl_xyzg_radius, pts_xyz, nr_of_points)
'''
#iterate through n number of points (length of seed points)
n = len(p)
if pts_xyz.shape[1] > 3:
pcl_xyzg_p_random = np.empty((int(nr_of_points),4))
elif pts_xyz.shape[1] == 3:
pcl_xyzg_p_random = np.empty((int(nr_of_points),3))
pcl_xyzg_p_random.fill(np.nan)
i = np.random.choice(n, size = int(nr_of_points), replace = False, p = p)
pcl_xyzg_p_random[:,0] = pts_xyz[i,0]
pcl_xyzg_p_random[:,1] = pts_xyz[i,1]
pcl_xyzg_p_random[:,2] = pts_xyz[i,2]
if pts_xyz.shape[1] > 3:
pcl_xyzg_p_random[:,3] = pts_xyz[i,3]
return pcl_xyzg_p_random
def pc_random_p_intensity_subsampling(pts_xyzi, p, nr_of_points):
'''
Sub-samples indices of PC pcl_xyzg_radius with probability weight p based
on point density of each point. Will result in greatly reduced point cloud.
Give nr_of_points for subsampled point cloud, usually len(p)/2
call with a probability
#pcl_xyzg_radius_equal_nr_random = pc_random_p_subsampling(pcl_xyzg_radius, pts_xyz, nr_of_points)
'''
#iterate through n number of points (length of seed points)
n = len(p)
if pts_xyzi.shape[1] > 3:
pcl_xyzg_p_random = np.empty((int(nr_of_points),4))
elif pts_xyzi.shape[1] == 3:
pcl_xyzg_p_random = np.empty((int(nr_of_points),3))
pcl_xyzg_p_random.fill(np.nan)
i = np.random.choice(n, size = int(nr_of_points), replace = False, p = p)
pcl_xyzg_p_random[:,0] = pts_xyzi[i,0]
pcl_xyzg_p_random[:,1] = pts_xyzi[i,1]
pcl_xyzg_p_random[:,2] = pts_xyzi[i,2]
pcl_xyzg_p_random[:,3] = pts_xyzi[i,3]
if pts_xyzi.shape[1] > 3:
pcl_xyzg_p_random[:,3] = pts_xyzi[i,3]
return pcl_xyzg_p_random
def plt_point_cloud_densities(pcl_xyzg, pcl_xyzg_rstep_seed,
pcl_xyzg_p_random, pcl_xyzg_p_min,
pcl_xyzg_density_min, pcl_random_density_min, pcl_densities= '_pcl_densities_overview_raster_%0.2fm_radius_%0.2fm.png'%(args.raster_m, args.sphere_radius_m)):
pcl_densities_overview_fn = os.path.join(figure_dir, os.path.basename(args.inlas).split('.')[0] + pcl_densities)
fig = plt.figure(figsize=(16.53,11.69), dpi=150)
fig.clf()
ax1 = fig.add_subplot(221)
cax1 = ax1.scatter(pcl_xyzg[:,0], pcl_xyzg[:,1], c=pcl_xyzg_density_min, s=0.5, cmap=plt.get_cmap('jet'), linewidth=0, vmin=np.percentile(pcl_xyzg_density_min, 10), vmax=np.percentile(pcl_xyzg_density_min, 90))
cbar = fig.colorbar(cax1)
cbar.set_label('Point density (pts/m^2)')
ax1.set_title('Point density for full point cloud \nwith nr=%s points.'%"{:,}".format(pcl_xyzg.shape[0]),y=1.05)
#ax1.set_xlabel('UTM-X (m)')
ax1.set_ylabel('UTM-Y (m)')
ax1.axis('equal')
ax1.grid('on')
ax2 = fig.add_subplot(222)
cax2 = ax2.scatter(pcl_xyzg_rstep_seed[:,0], pcl_xyzg_rstep_seed[:,1], c=pcl_xyzg_rstep_seed_density_min, s=0.5, cmap=plt.get_cmap('jet'), linewidth=0, vmin=np.percentile(pcl_xyzg_density_min, 10), vmax=np.percentile(pcl_xyzg_density_min, 90))
cbar = fig.colorbar(cax2)
cbar.set_label('Point density (pts/m^2)')
ax2.set_title('Point density for equal-spaced PC \nevery %0.2fm (r=%0.2fm), total: %s points.'%(args.raster_m, args.sphere_radius_m, "{:,}".format(pcl_xyzg_rstep_seed.shape[0])),y=1.05)
#ax2.set_xlabel('UTM-X (m)')
#ax2.set_ylabel('UTM-Y (m)')
ax2.axis('equal')
ax2.grid('on')
ax3 = fig.add_subplot(223)
cax3 = ax3.scatter(pcl_xyzg_p_random[:,0], pcl_xyzg_p_random[:,1], c=pcl_random_density_min, s=0.5, cmap=plt.get_cmap('jet'), linewidth=0, vmin=np.percentile(pcl_xyzg_density_min, 10), vmax=np.percentile(pcl_xyzg_density_min, 90))
cbar = fig.colorbar(cax3)
cbar.set_label('Point density (pts/m^2)')
ax3.set_title('Point density for p-random point cloud \nwith avg. density = %0.2f and nr=%s points.'%(np.mean(pcl_random_density_min), "{:,}".format(pcl_xyzg_p_random.shape[0])),y=1.05)
#ax3.set_xlabel('UTM-X (m)')
#ax3.set_ylabel('UTM-Y (m)')
ax3.axis('equal')
ax3.grid('on')
ax6 = fig.add_subplot(224)
cax6 = ax6.scatter(pcl_xyzg_p_random[:,0], pcl_xyzg_p_random[:,1], c=pcl_random_density_min, s=0.5, cmap=plt.get_cmap('jet'), linewidth=0, vmin=np.percentile(pcl_random_density_min, 10), vmax=np.percentile(pcl_random_density_min, 90))
cbar = fig.colorbar(cax6)
cbar.set_label('Point density (pts/m^2)')
ax6.set_title('Point density for p-random point cloud \nwith avg. density = %0.2f and nr=%s points.'%(np.mean(pcl_random_density_min), "{:,}".format(pcl_xyzg_p_random.shape[0])),y=1.05)
ax6.set_xlabel('UTM-X (m)')
#ax6.set_ylabel('UTM-Y (m)')
ax6.axis('equal')
ax6.grid('on')
fig.savefig(pcl_densities_overview_fn, bbox_inches='tight')
plt.close()
def plt_ensemble_slope_curvature():
#plot figure with std. dev and variance
ensemble_densities= '_pcl_ensembles_overview_raster_%0.2fm_radius_%0.2fm.png'%(args.raster_m, args.sphere_radius_m)
pcl_random_ensembles_overview_fn = os.path.join(figure_dir, os.path.basename(args.inlas).split('.')[0] + ensemble_densities)
fig = plt.figure(figsize=(16.53,11.69), dpi=150)
fig.clf()
ax1 = fig.add_subplot(231)
cax1 = ax1.scatter(pcl_xyzg_rstep_seed[:,0], pcl_xyzg_rstep_seed[:,1], c=pc_random_density_min_res[1,:], s=0.5, cmap=plt.get_cmap('jet'), linewidth=0, vmin=np.percentile(pcl_random_density_min[1,:], 10), vmax=np.percentile(pcl_random_density_min[1,:], 90))
cbar = fig.colorbar(cax1)
cbar.set_label('Point density (ts/m^2)')
ax1.set_title('Point Density of last ensemble for equal-spaced PC \nevery %0.2fm (r=%0.2fm), total: %s points.'%(args.raster_m, args.sphere_radius_m, "{:,}".format(pcl_xyzg_rstep_seed.shape[0])),y=1.05)
#ax2.set_xlabel('UTM-X (m)')
ax1.set_ylabel('UTM-Y (m)')
ax1.axis('equal')
ax1.grid('on')
ax4 = fig.add_subplot(234)
cax4 = ax4.scatter(pcl_xyzg_rstep_seed[:,0], pcl_xyzg_rstep_seed[:,1], c=pc_random_density_min_res[2,:], s=0.5, cmap=plt.get_cmap('jet'), linewidth=0, vmin=np.percentile(pcl_random_density_min_res[2,:], 10), vmax=np.percentile(pcl_random_density_min_res[2,:], 90))
cbar = fig.colorbar(cax4)
cbar.set_label('std. dev. of point density (pts/m^2)')
ax4.set_title('Std. Dev. of point density (n=%02d ensembles) for equal-spaced PC \nevery %0.2fm (r=%0.2fm), total: %s points.'%(args.nr_of_bootstraps, args.raster_m, args.sphere_radius_m, "{:,}".format(pcl_xyzg_rstep_seed.shape[0])),y=1.05)
ax4.set_xlabel('UTM-X (m)')
ax4.set_ylabel('UTM-Y (m)')
ax4.axis('equal')
ax4.grid('on')
ax2 = fig.add_subplot(232)
cax2 = ax2.scatter(pcl_xyzg_rstep_seed[:,0], pcl_xyzg_rstep_seed[:,1], c=slope_plane_stats[1,:], s=0.5, cmap=plt.get_cmap('jet'), linewidth=0, vmin=np.percentile(slope_plane_stats[1,:], 10), vmax=np.percentile(slope_plane_stats[1,:], 90))
cbar = fig.colorbar(cax2)
cbar.set_label('Slope (m/m)')
ax2.set_title('Mean slope (n=%02d ensembles) for equal-spaced PC \nevery %0.2fm (r=%0.2fm), total: %s points.'%(nr_of_bootstraps, args.raster_m, args.sphere_radius_m, "{:,}".format(pcl_xyzg_rstep_seed.shape[0])),y=1.05)
#ax2.set_xlabel('UTM-X (m)')
#ax2.set_ylabel('UTM-Y (m)')
ax2.axis('equal')
ax2.grid('on')
ax5 = fig.add_subplot(235)
cax5 = ax5.scatter(pcl_xyzg_rstep_seed[:,0], pcl_xyzg_rstep_seed[:,1], c=slope_plane_stats[2,:], s=0.5, cmap=plt.get_cmap('jet'), linewidth=0, vmin=np.percentile(slope_plane_stats[2,:], 10), vmax=np.percentile(slope_lstsq_stats[2,:], 90))
cbar = fig.colorbar(cax5)
cbar.set_label('Std. Dev. of slope (m/m)')
ax5.set_title('Std. dev. of slope (n=%02d ensembles) for equal-spaced PC \nevery %0.2fm (r=%0.2fm), total: %s points.'%(nr_of_bootstraps, args.raster_m, args.sphere_radius_m, "{:,}".format(pcl_xyzg_rstep_seed.shape[0])),y=1.05)
#ax5.set_xlabel('UTM-X (m)')
#ax5.set_ylabel('UTM-Y (m)')
ax5.axis('equal')
ax5.grid('on')
ax3 = fig.add_subplot(233)
cax3 = ax3.scatter(pcl_xyzg_rstep_seed[:,0], pcl_xyzg_rstep_seed[:,1], c=curvature_lstsq_stats[1,:], s=0.5, cmap=plt.get_cmap('jet'), linewidth=0, vmin=np.percentile(curvature_lstsq_stats[1,:], 10), vmax=np.percentile(curvature_lstsq_stats[1,:], 90))
cbar = fig.colorbar(cax3)
cbar.set_label('Mean curvature (1/m)')
ax3.set_title('Mean curvature (n=%02d ensembles) for equal-spaced PC \nevery %0.2fm (r=%0.2fm), total: %s points.'%(nr_of_bootstraps, args.raster_m, args.sphere_radius_m, "{:,}".format(pcl_xyzg_rstep_seed.shape[0])),y=1.05)
#ax3.set_xlabel('UTM-X (m)')
#ax3.set_ylabel('UTM-Y (m)')
ax3.axis('equal')
ax3.grid('on')
ax6 = fig.add_subplot(236)
cax6 = ax6.scatter(pcl_xyzg_rstep_seed[:,0], pcl_xyzg_rstep_seed[:,1], c=curvature_lstsq_stats[2,:], s=0.5, cmap=plt.get_cmap('jet'), linewidth=0, vmin=np.percentile(curvature_lstsq_stats[2,:], 10), vmax=np.percentile(curvature_lstsq_stats[2,:], 90))
cbar = fig.colorbar(cax6)
cbar.set_label('Std. Dev. of curvature (1/m)')
ax6.set_title('Std. dev. of curvature (n=%02d ensembles) for equal-spaced PC \nevery %0.2fm (r=%0.2fm), total: %s points.'%(nr_of_bootstraps, args.raster_m, args.sphere_radius_m, "{:,}".format(pcl_xyzg_rstep_seed.shape[0])),y=1.05)
#ax6.set_xlabel('UTM-X (m)')
#ax6.set_ylabel('UTM-Y (m)')
ax6.axis('equal')
ax6.grid('on')
fig.savefig(pcl_random_ensembles_overview_fn, bbox_inches='tight')
plt.close()
def pc_random_equal_subsampling(pcl_xyzg_radius, pts_xyz, nr_of_points):
'''
Sub-samples indices of PC pcl_xyzg_radius with point locations pts_xyz based
with an equal number of points nr_of_points. nr_of_points can be calculated
as an average point density.
call with a probability
#pcl_xyzg_radius_equal_nr_random = pc_random_equal_subsampling(pcl_xyzg_radius, pts_xyz, nr_of_points)
'''
#iterate through n number of points (length of seed points)
n = len(pcl_xyzg_radius)
pcl_xyzg_radius_random = np.empty((n,int(nr_of_points),3))
pcl_xyzg_radius_random.fill(np.nan)
#find indices for each seed point and randomly select points based on probability p
for i in range(n):
current_ptx_idx = np.array(pcl_xyzg_radius[i]) #get indices for current point
#Use the following if you have varying number of points
#random_pt_idx = np.random.choice(current_ptx_idx, size = int(nr_of_points[i]), replace = True)
random_pt_idx = np.random.choice(current_ptx_idx, size = int(nr_of_points), replace = True)
#pcl_xyzg_radius_random contains the same number of points for each seed point
pcl_xyzg_radius_random[i,:,:] = np.array([pcl_xyzg[random_pt_idx,0], pcl_xyzg[random_pt_idx,1], pcl_xyzg[random_pt_idx,2]]).T
del current_ptx_idx
return pcl_xyzg_radius_random
def calc_stats_for_bootstrap_seed_points_wrapper(i):
#print('starting {}/{}'.format(i+1, len(pos_array)))
from_pos = pos_array[i] #Get start/end from position array
to_pos = pos_array[i+1]
#Setup array for seed point results:
subarr = np.arange(from_pos,to_pos) #Slice the data into the selected part...
pts_seed_stats_result = np.empty((subarr.shape[0], nr_of_datasets))
#Setup array for PC results (X, Y, Z, Dz)
dxyzn_subarr_result = np.empty((subarr.shape[0], dxyzn_max_nre, 4))
for ii in range(subarr.shape[0]):
pts_seed_stats_result[ii,:], dxyzn_subarr_result[ii,:,:] = calc_stats_for_bootstrap_seed_points(subarr[ii]) #Run point cloud processing for this index
pickle_fn = os.path.join(pickle_dir, 'PC_seed_points_{}.pickle'.format(str(i).zfill(4)))
pickle.dump((pts_seed_stats_result, dxyzn_subarr_result), open(pickle_fn,'wb'))
if np.mod(i,10) == 0:
print('{}, '.format(str(i).zfill(2)), end='', flush=True)
pts_seed_stats_result = None
dxyzn_subarr_result = None
def calc_stats_for_bootstrap_seed_points(i):
pts_xyz = pcl_xyzg_p_random[pcl_xyzg_equal_density_radius[i],0:3]
#pts_xyz_slope = pcl_xyzg[pcl_xyzg_p_random_seed_radius_slope[i]]
pts_xyz_slope = pcl_xyzg_p_random[pcl_xyzg_equal_density_radius_slope[i],0:3]
#getting intensity values
pts_xyzi = pcl_xyzg_p_random[pcl_xyzg_equal_density_radius[i],3]
nr_pts_xyz = pts_xyz.shape[0]
if pts_xyz.shape[0] < 5:
#print('Less than 5 points, plane fitting not meaningful for i = %s'%"{:,}".format(i))
pts_xyz_meanpt = np.nan
pts_xyz_normal = np.nan
pts_seed_stats = np.array([pcl_xyzg_rstep_seed[i,0], pcl_xyzg_rstep_seed[i,1], pcl_xyzg_rstep_seed[i,2],
np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan,
np.nan, np.nan, np.nan, np.nan, nr_pts_xyz, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan])
dxyzn = np.empty((dxyzn_max_nre, 4))
dxyzn.fill(np.nan)
else:
pts_xyz_meanpt, pts_xyz_normal, plane_residual = planeFit(pts_xyz_slope.T)
#residual calculated from = np.linalg.norm(errors)
#calculate curvature
slope_lstsq, curvature_lstsq, curv_residuals = curvFit_lstsq_polygon(pts_xyz_slope.T, order=2)
#normalize /detrend points with plane
d = -pts_xyz_meanpt.dot(pts_xyz_normal)
z = (-pts_xyz_normal[0] * pts_xyz[:,0] - pts_xyz_normal[1] * pts_xyz[:,1] - d) * 1. /pts_xyz_normal[2]
plane_slope = pts_xyz_normal[2]
#calculate offset for each point from plane
dz = pts_xyz[:,2] - z
#stack points into X, Y, Z, delta-Z for each point
dxyzn = np.empty((dxyzn_max_nre, 4))
dxyzn.fill(np.nan)
dxyzn[range(pts_xyz.shape[0]),:] = np.vstack([np.vstack((pts_xyz[:,0], pts_xyz[:,1], pts_xyz[:,2], dz)).T])
#calculate intensity statistics for this seed point
i_mean = np.mean(pts_xyzi)
i_stddev = np.std(pts_xyzi)
i_median = np.median(pts_xyzi)
i_10_25_75_90p = np.percentile(pts_xyzi, [10, 25, 75, 90])
#for each seed point, store relevant point statistics. Columns are:
#0: Seed-X, 1: Seed-Y, 2: Seed-Z, 3: Mean-X, 4: Mean-Y, 5: Mean-Z, 6: Z-min, 7: Z-max, 8: Dz-max, 9: Dz-min, 10: Dz-std.dev, 11: Dz-range, \
#12: Dz-90-10th percentile range, 13: Dz-75-25th percentile range, 14: slope of fitted plane, 15: plane residuals, \
#16: variance dz, 17: nr. of lidar points, 18: slope_lstsq, 19: curvature_lstsq, 20: curvature residuals, \
#21:intensity mean, 22:intensity std., 23: intensity median, 24: 10, 25: 27, 26: 75, 27: 90th percentile intensity
pts_seed_stats = np.array([pcl_xyzg_rstep_seed[i,0], pcl_xyzg_rstep_seed[i,1], pcl_xyzg_rstep_seed[i,2],
pts_xyz_meanpt[0], pts_xyz_meanpt[1], pts_xyz_meanpt[2],
np.min(pts_xyz, axis=0)[2], np.max(pts_xyz, axis=0)[2], dz.max(), dz.min(), np.std(dz), dz.max()-dz.min(), \
np.percentile(dz, 90)-np.percentile(dz,10), np.percentile(dz, 75)-np.percentile(dz,25), plane_slope, plane_residual, \
np.var(dz), nr_pts_xyz, slope_lstsq, curvature_lstsq, curv_residuals, i_mean, i_stddev, i_median, i_10_25_75_90p[0], i_10_25_75_90p[1], i_10_25_75_90p[2], i_10_25_75_90p[3],])
return pts_seed_stats, dxyzn
def calc_stats_for_seed_points_wrapper(i):
#print('starting {}/{}'.format(i+1, len(pos_array)))
from_pos = pos_array[i] #Get start/end from position array
to_pos = pos_array[i+1]
#Setup array for seed point results:
subarr = np.arange(from_pos,to_pos) #Slice the data into the selected part...
pts_seed_stats_result = np.empty((subarr.shape[0], nr_of_datasets))
#Setup array for PC results (X, Y, Z, Dz)
dxyzn_subarr_result = np.empty((subarr.shape[0], dxyzn_max_nre, 4))
for ii in range(subarr.shape[0]):
pts_seed_stats_result[ii,:], dxyzn_subarr_result[ii,:,:] = calc_stats_for_seed_points(subarr[ii]) #Run point cloud processing for this inddex
pickle_fn = os.path.join(pickle_dir, 'PC_seed_points_{}.pickle'.format(str(i).zfill(4)))
pickle.dump((pts_seed_stats_result, dxyzn_subarr_result), open(pickle_fn,'wb'))
if np.mod(i,10) == 0:
print('{}, '.format(str(i).zfill(2)), end='', flush=True)
pts_seed_stats_result = None
dxyzn_subarr_result = None
def calc_stats_for_seed_points(i):
pts_xyz = pcl_xyzg[pcl_xyzg_radius[i]]
pts_xyz_slope = pcl_xyzg[pcl_xyzg_radius_slope[i]]
#getting intensity values
pts_xyzi = pcl_xyzig[pcl_xyzg_radius[i],3]
nr_pts_xyz = pts_xyz.shape[0]
if pts_xyz.shape[0] < 5:
#print('Less than 5 points, plane fitting not meaningful for i = %s'%"{:,}".format(i))
pts_xyz_meanpt = np.nan
pts_xyz_normal = np.nan
pts_seed_stats = np.array([pcl_xyzg_rstep_seed[i,0], pcl_xyzg_rstep_seed[i,1], pcl_xyzg_rstep_seed[i,2],
np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan,
np.nan, np.nan, np.nan, np.nan, nr_pts_xyz, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan])
dxyzn = np.empty((dxyzn_max_nre, 4))
dxyzn.fill(np.nan)
else:
pts_xyz_meanpt, pts_xyz_normal, plane_residual = planeFit(pts_xyz_slope.T)
#residual calculated from = np.linalg.norm(errors)
#calculate curvature
slope_lstsq, curvature_lstsq, curv_residuals = curvFit_lstsq_polygon(pts_xyz_slope.T, order=2)
#normalize /detrend points with plane
d = -pts_xyz_meanpt.dot(pts_xyz_normal)
z = (-pts_xyz_normal[0] * pts_xyz[:,0] - pts_xyz_normal[1] * pts_xyz[:,1] - d) * 1. /pts_xyz_normal[2]
plane_slope = pts_xyz_normal[2]
#calculate offset for each point from plane
dz = pts_xyz[:,2] - z
#stack points into X, Y, Z, delta-Z for each point
dxyzn = np.empty((dxyzn_max_nre, 4))
dxyzn.fill(np.nan)
dxyzn[range(pts_xyz.shape[0]),:] = np.vstack([np.vstack((pts_xyz[:,0], pts_xyz[:,1], pts_xyz[:,2], dz)).T])
#calculate intensity statistics for this seed point
i_mean = np.mean(pts_xyzi)
i_stddev = np.std(pts_xyzi)
i_median = np.median(pts_xyzi)
i_10_25_75_90p = np.percentile(pts_xyzi, [10, 25, 75, 90])
#for each seed point, store relevant point statistics. Columns are:
#0: Seed-X, 1: Seed-Y, 2: Seed-Z, 3: Mean-X, 4: Mean-Y, 5: Mean-Z, 6: Z-min, 7: Z-max, 8: Dz-max, 9: Dz-min, 10: Dz-std.dev, 11: Dz-range, \
#12: Dz-90-10th percentile range, 13: Dz-75-25th percentile range, 14: slope of fitted plane, 15: plane residuals, \
#16: variance dz, 17: nr. of lidar points, 18: slope_lstsq, 19: curvature_lstsq, 20: curvature residuals, \
#21:intensity mean, 22:intensity std., 23: intensity median, 24: 10, 25: 27, 26: 75, 27: 90th percentile intensity
pts_seed_stats = np.array([pcl_xyzg_rstep_seed[i,0], pcl_xyzg_rstep_seed[i,1], pcl_xyzg_rstep_seed[i,2],
pts_xyz_meanpt[0], pts_xyz_meanpt[1], pts_xyz_meanpt[2],
np.min(pts_xyz, axis=0)[2], np.max(pts_xyz, axis=0)[2], dz.max(), dz.min(), np.std(dz), dz.max()-dz.min(), \
np.percentile(dz, 90)-np.percentile(dz,10), np.percentile(dz, 75)-np.percentile(dz,25), plane_slope, plane_residual, \
np.var(dz), nr_pts_xyz, slope_lstsq, curvature_lstsq, curv_residuals, i_mean, i_stddev, i_median, i_10_25_75_90p[0], i_10_25_75_90p[1], i_10_25_75_90p[2], i_10_25_75_90p[3],])
return pts_seed_stats, dxyzn
### Program starts here
### Defining input and setting global variables
if args.inlas == '':
print('No input LAS/LAZ file given. Rerun with -i for input LAS/LAZ file. Exit.')
exit()
if args.outputdir == '':
if len(os.path.dirname(args.inlas)) > 0:
args.outputdir = os.path.dirname(args.inlas)
else:
args.outputdir = os.getcwd()
if args.outlas == '':
args.outlas = os.path.join(args.outputdir, os.path.basename(args.inlas).split('.')[0] + '_raster_%0.2fm_rsphere%0.2fm.las'%(args.raster_m,args.sphere_radius_m))
if args.slope_sphere_radius_m == 0:
#set to sphere_radius_m
args.slope_sphere_radius_m = args.sphere_radius_m
if os.path.exists(os.path.join(args.outputdir, 'log')) == False:
os.mkdir(os.path.join(args.outputdir, 'log'))
pickle_dir = os.path.join(args.outputdir, 'pickle')
if os.path.exists(pickle_dir) == False:
os.mkdir(pickle_dir)
figure_dir = os.path.join(args.outputdir, 'figures')
if os.path.exists(figure_dir) == False:
os.mkdir(figure_dir)
geotif_dir = os.path.join(args.outputdir, 'geotif')
if os.path.exists(geotif_dir) == False:
os.mkdir(geotif_dir)
### Loading data and filtering
print('\nLoading input file: %s'%args.inlas)
inFile = File(args.inlas, mode='r')
pcl_xyzic = np.vstack((inFile.get_x()*inFile.header.scale[0]+inFile.header.offset[0], inFile.get_y()*inFile.header.scale[1]+inFile.header.offset[1], inFile.get_z()*inFile.header.scale[2]+inFile.header.offset[2], inFile.get_intensity(), inFile.get_classification())).transpose()
#pcl_xyzic is now a point cloud with x, y, z, intensity, and classification
#if args.store_color == True:
# pcl_i = inFile.get_intensity().copy()
# pcl_blue = inFile.get_blue().copy()
# pcl_green = inFile.get_green().copy()
# pcl_red = inFile.get_red().copy()
print('Loaded %s points'%"{:,}".format(pcl_xyzic.shape[0]))
print('\nFiltering points to only work with ground points (class == 2)... ',end='\n')
#get only ground points:
idx_ground = np.where(pcl_xyzic[:,4] == 2)[0]
pcl_xyzig = pcl_xyzic[idx_ground,0:4]
pcl_xyzg = pcl_xyzic[idx_ground,0:3]
#pcl_xyzg is a point cloud with x, y, z, and for class == 2 only
pcl_xyg = pcl_xyzic[idx_ground,0:2]
#if args.store_color == True:
## pcl_i = pcl_i[idx_ground,:]
# pcl_blue = pcl_blue[idx_ground,:]
# pcl_green = pcl_green[idx_ground,:]
# pcl_red = pcl_red[idx_ground,:]
if np.max(pcl_xyzic[:,4]) > 2:
idx_vegetation = np.where(pcl_xyzic[:,4] == 5)[0] # and pcl_xyzic[:,4] == 4 and pcl_xyzic[:,4] == 5)[0]
#getting vegetation indices
vegetation_intensity= pcl_xyzic[idx_vegetation,3]
vegetation_intensity_mean = np.mean(vegetation_intensity)
vegetation_intensity_std = np.std(vegetation_intensity)
print('\nNumber of vegetation points (class==5): %s'%"{:,}".format(idx_vegetation.shape[0]))
print('Vegetation intensity mean: %2.1f +-std.dev.: %2.1f, 10th perc.: %2.1f, 90th perc.: %2.1f'%(vegetation_intensity_mean, vegetation_intensity_std, np.percentile(vegetation_intensity, 10), np.percentile(vegetation_intensity, 90)) )
#getting ground values
ground_intensity = pcl_xyzic[idx_ground,3]
ground_intensity_mean = np.mean(ground_intensity)
ground_intensity_std = np.std(ground_intensity)
print('\nNumber of ground points (class==2): %s'%"{:,}".format(idx_ground.shape[0]))
print('Ground intensity mean: %2.1f +-std.dev.: %2.1f, 10th perc.: %2.1f, 90th perc.: %2.1f'%(ground_intensity_mean, ground_intensity_std, np.percentile(ground_intensity,10), np.percentile(ground_intensity,90)) )
### cKDTree setup and calculation
#Generate KDTree for fast searching
#cKDTree is faster than KDTree, pyKDTree is fast then cKDTree
print('\nGenerating XY-cKDTree... ',end='', flush=True)
pcl_xyg_ckdtree_fn = os.path.join(pickle_dir, os.path.basename(args.inlas).split('.')[0] + '_xyg_cKDTree.pickle')
if os.path.exists(pcl_xyg_ckdtree_fn):
pcl_xyg_ckdtree = pickle.load(open( pcl_xyg_ckdtree_fn, "rb" ))
else:
pcl_xyg_ckdtree = spatial.cKDTree(pcl_xyg, leafsize=32)
pickle.dump(pcl_xyg_ckdtree, open(pcl_xyg_ckdtree_fn,'wb'))
print('done.')
print('Generating XYZ-cKDTree... ',end='',flush=True)
pcl_xyzg_ckdtree_fn = os.path.join(pickle_dir, os.path.basename(args.inlas).split('.')[0] + '_xyzg_cKDTree.pickle')