-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd_build_DEM.pyt
2149 lines (1759 loc) · 102 KB
/
cmd_build_DEM.pyt
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 -*-
"""Creates DEMs and derivatives (return counts, intensity) from lidar datasets
available via the Entwine Point cloud format for a given polygon (usually
buffered HUC12 watershed boundary). Uses a previous created merge of
the USGS WESM data and the EPT GeoJSON dataset to locate the AWS bucket for each
project, then joins multiple projects and creates a lidar DEM and derivatives
at one or multiple resolutions. Also creates a feature class of lidar datasets
used to generate the DEM and derivatives."""
import arcpy
from arcpy.sa import *
import arcpy.metadata as md
import sys
import os
import time
import subprocess
import platform
import glob
import traceback
from os.path import join as opj
sys.path.append("C:\\DEP\\Scripts\\basics")
# login = os.getlogin()
# if login == 'bkgelder':
# boxes = ['C:\\Users\\bkgelder\\Box\\Data_Sharing\\Scripts\\basics', 'O:\\DEP\\Scripts\\basics']
# else:
# boxes = ['C:\\Users\\idep2\\Box\\Scripts\\basics', 'O:\\DEP\\Scripts\\basics']
# for box in boxes:
# if os.path.isdir(box):
# sys.path.append(box)
import dem_functions as df
class msgStub:
def addMessage(self,text):
arcpy.AddMessage(text)
def addErrorMessage(self,text):
arcpy.AddErrorMessage(text)
def addWarningMessage(self,text):
arcpy.AddWarningMessage(text)
class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the
.pyt file)."""
self.label = "Toolbox"
self.alias = "toolbox"
# List of tool classes associated with this toolbox
self.tools = [Tool]
class Tool(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Build DEMs from LiDAR by EPT download"
self.description = "Must install PDAL and run get_merge_lidar_datasets first to merge EPT and WESM. Build a DEM for a polygon by downloading the data through EPT format via PDAL."
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
param0 = arcpy.Parameter(
name="monthly_ept_wesm_mashup",
displayName="EPT WESM Merged Features",
datatype="DEFeatureClass",
parameterType='Required',
direction="Input")
param1 = arcpy.Parameter(
name="dem_polygon",
displayName="Buffered HUC12 Feature",
datatype="DEFeatureClass",
parameterType='Required',
direction="Input")
param2 = arcpy.Parameter(
name = "pdal_exe",
displayName="PDAL.exe Location",
datatype="DEFile",
parameterType='Required',
direction="Input")
param3 = arcpy.Parameter(
name = "gsds",
displayName="Integer Resolution/Ground Sample Distance of output rasters, multiples joined by comma",
datatype="GPString",
parameterType='Required',
direction="Input")
param3.values = "3,2,1"#default gsds value to create 3, 2, and 1 meter rasters
param4 = arcpy.Parameter(
name = "fElevFile",
displayName="Output Pit-Filled Elevation Model",
datatype="DERasterDataset",
parameterType='Required',
direction="Output")
param5 = arcpy.Parameter(
name = "procDir",
displayName="Local Processing Directory",
datatype="DEFolder",
parameterType='Optional',
direction="Input")
param6 = arcpy.Parameter(
name="snap",
displayName="Snap Raster",
datatype="DERasterDataset",
parameterType='Optional',
direction="Input")
param7 = arcpy.Parameter(
name = "bareEarthReturnMinFile",
displayName="Output Bare Earth Minimum Elevation Model",
datatype="DERasterDataset",
parameterType='Optional',
direction="Output")
param8 = arcpy.Parameter(
name = "firstReturnMaxFile",
displayName="Output First Return Maximum Elevation/Surface Model",
datatype="DERasterDataset",
parameterType='Optional',
direction="Output")
param9 = arcpy.Parameter(
name = "cntFile",
displayName="Output Bare Earth Return Count Raster",
datatype="DERasterDataset",
parameterType='Optional',
direction="Output")
param10 = arcpy.Parameter(
name = "cnt1rFile",
displayName="Output First Return Count Raster",
datatype="DERasterDataset",
parameterType='Optional',
direction="Output")
param11 = arcpy.Parameter(
name = "int1rMinFile",
displayName="Output Intensity First Return Minimum Raster",
datatype="DERasterDataset",
parameterType='Optional',
direction="Output")
param12 = arcpy.Parameter(
name = "int1rMaxFile",
displayName="Output Intensity First Return Maximum Raster",
datatype="DERasterDataset",
parameterType='Optional',
direction="Output")
param13 = arcpy.Parameter(
name = "intBeMaxFile",
displayName="Output Intensity Bare Earth Maximum Raster",
datatype="DERasterDataset",
parameterType='Optional',
direction="Output")
param14 = arcpy.Parameter(
name = "breakpolys",
displayName="Output HUC12 Merged Breakline Polygon Features",
datatype="DEFeatureClass",
parameterType='Optional',
direction="Output")
param15 = arcpy.Parameter(
name = "breaklines",
displayName="Output HUC12 Merged Breakline Polyline Features",
datatype="DEFeatureClass",
parameterType='Optional',
direction="Output")
param16 = arcpy.Parameter(
name = "ept_wesm_project_file",
displayName="EPT WESM Feature for AOI",
datatype="DEFeatureClass",
parameterType='Optional',
direction="Output")
params = [param0, param1, param2, param3,
param4, param5, param6, param7,
param8, param9, param10, param11,
param12, param13, param14, param15,
param16]
return params
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
def execute(self, parameters, messages):
"""The source code of the tool."""
cleanup = False
doLidarDEMs(parameters[0].valueAsText, cleanup, messages)
return
def postExecute(self, parameters):
"""This method takes place after outputs are processed and
added to the display."""
return
##----------------------------------------------------------------------
## Set environments and begin
def fillOCSinks(inDEM):
# Return a raster will all one-cell-sinks filled
## arcpy.AddMessage("-----Find Pits...")
sinkFDir = FlowDirection(inDEM)
allSinks = Sink(sinkFDir)
arcpy.BuildRasterAttributeTable_management(allSinks)
## log.warning('sinks for ' + str(inDEM) + ' is ' + str(int(arcpy.GetCount_management(allSinks).getOutput(0))))
## arcpy.AddMessage("-----Fill everything else...")
## Make a No-one-cell-sink DEM
AllButSinks_DEM = Con(IsNull(allSinks), inDEM)
## Fill the No-one-cell-sink DEM
absDEM_fill = Fill(AllButSinks_DEM)
## Add the Original 'real' sinks back into the filled DEM
fill_DEM = Con(IsNull(absDEM_fill), inDEM, absDEM_fill)
return(fill_DEM, allSinks)
def getfields(infc, fieldString = '', fieldType = ''):
flds = arcpy.ListFields(infc, fieldString, fieldType)
if len(flds) > 0:
fieldNames = [fld.name for fld in flds]
else:
fieldNames = []
return fieldNames
def processEptLas(sgdb, sfldr, srOutCode, fixedFolder, geom, ept_las, srOut, inm, FDSet, procDir, allTilesList, log, time, work_id):
'''process a cursor row of data by creating a suitable las file from the input las/laz/zlas dataset
This inlcudes project and clipping las data files into output dataset and also creating a multipoint
file from the las data if there is any within the extent'''
try:
ept_las_base = os.path.splitext(os.path.basename(ept_las))[0]
sfx = arcpy.ValidateTableName('_' + ept_las_base, sgdb)
log.debug('lidar file suffix is: ' + sfx + ' at ' + time.asctime())
# put in las or zlas format
# fixedLasPath = ept_las#lasCopy
## allTilesList.append(fixedLasPath)
allLasd = arcpy.CreateLasDataset_management(ept_las, opj(sfldr, 'all' + sfx))
# allLasdDescDa = arcpy.da.Describe(allLasd)
# extract to tile geometry and project if necessary
nameSfx = '_' + str(srOutCode)
fixedLasBasename = os.path.basename(ept_las)[:-4] + nameSfx + '.las'
## log.debug('fixedLasBasename: ' + fixedLasBasename)
# some old 3DEP projects don't alway have boundaries and data lining up...
log.debug(f'ExtractLas arguments are {allLasd}, {fixedFolder}, name_suffix = {nameSfx}, rearrange_points = {"MAINTAIN_POINTS"}, out_las_dataset = {opj(fixedFolder, "fixed" + sfx + ".lasd")}')
if work_id < 0:
tileGeomBuffer5 = geom.buffer(5) #tile Geometry column
log.debug('--- Use ExtractLas, boundary option, at ' + time.asctime())
fixedLasd = arcpy.ExtractLas_3d(allLasd, fixedFolder, name_suffix = nameSfx, rearrange_points = "MAINTAIN_POINTS", out_las_dataset = opj(fixedFolder, 'fixed' + sfx + '.lasd'), boundary = tileGeomBuffer5)
else:
log.debug('--- Use ExtractLas, no boundary option, at ' + time.asctime())
fixedLasd = arcpy.ExtractLas_3d(allLasd, fixedFolder, name_suffix = nameSfx, rearrange_points = "MAINTAIN_POINTS", out_las_dataset = opj(fixedFolder, 'fixed' + sfx + '.lasd'))#, boundary = tileGeomBuffer5)
log.debug(fixedLasd.getMessages())
fixedLasdDescDa = arcpy.da.Describe(fixedLasd)
fixedLasPath = opj(fixedLasdDescDa['path'], fixedLasBasename)
log.debug('--- Done creating LAS dataset and extracting LAS at ' + time.asctime())
if fixedLasdDescDa['pointCount'] > 0:
allTilesList.append(fixedLasPath)
if fixedLasPath in allTilesList:#non 0 amount of lidar points in las
## generate multipoint feature class from lidar class 2 (BE) points
# ptOut, cl2Las = genClass2AndMultiPoints(fixedLasPath, sfx, srOut, inm, FDSet, procDir, log)
# def genClass2AndMultiPoints(allLAZ, sfx, srOut, inm, FDSet, procDir, log):
# try:
allLAZ = fixedLasPath
if allLAZ.endswith('.laz') or allLAZ.endswith('.las'):
"""Filters LAS points to class 2 and creates multipoints in FDSet"""
lasBase = os.path.splitext(os.path.basename(allLAZ))[0]
if allLAZ.endswith('.laz'):
log.debug('--- Using ConvertLas to decompress LAZ at ' + time.asctime())
las_from_laz = arcpy.ConvertLas_conversion(allLAZ, target_folder=procDir, compression=None, las_options=None)
else:
las_from_laz = allLAZ
log.debug('--- Create las non-Minnesota Multipoint at ' + time.asctime())
lasMP = arcpy.LASToMultipoint_3d(las_from_laz, inm + "\\pts" + sfx, "1", class_code = [2,8], input_coordinate_system = srOut)
elif allLAZ.endswith('.zlas'):
log.debug('--- Create zlas non-Minnesota Multipoint at ' + time.asctime())
lasMP = arcpy.LASToMultipoint_3d(allLAZ, inm + "\\pts" + sfx, "1", class_code = [2,8], input_coordinate_system = srOut)
las_from_laz = allLAZ
if lasMP:
ptsName = arcpy.ValidateTableName('pts_' + lasBase, os.path.join(str(FDSet)))
ptOut = projIfNeeded(lasMP, os.path.join(str(FDSet), ptsName), srOut)
else:
log.warning('no ptOut created, setting to None')
ptOut = None
# ## return cl2LAS, ptOut
# return ptOut, cl2LAS
cl2Las = las_from_laz
# ready so there is something to return
if 'cl2Las' not in locals():
cl2Las = None
if 'ptOut' not in locals():
ptOut = None
log.info('ptOut: ' + str(ptOut) + ' and cl2Las ' + str(cl2Las))
return cl2Las
except Exception as e:
print('handling as exception')
## log.debug(e.message)
if sys.version_info.major == 2:
arcpy.AddError(e.message)
print(e.message)
elif sys.version_info.major == 3:
arcpy.AddError(e)
print(e)
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
# Concatenate information together concerning the error into a message string
pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
# Return python error messages for use in script tool or Python Window
arcpy.AddError(pymsg)
# Print Python error messages for use in Python / Python Window
print(pymsg + "\n")
if arcpy.GetMessages(2) not in pymsg:
msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
arcpy.AddError(msgs)
print(msgs)
except:
print('handling as except')
# Get the traceback object
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
# Concatenate information together concerning the error into a message string
pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
# Return python error messages for use in script tool or Python Window
arcpy.AddError(pymsg)
# Print Python error messages for use in Python / Python Window
print(pymsg + "\n")
if arcpy.GetMessages(2) not in pymsg:
msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
arcpy.AddError(msgs)
print(msgs)
def prepPolygonBoundary(dem_polygon, log, sgdb, srOut, srSfx, maskRastBase, demLists):
try:
assert int(arcpy.GetCount_management(dem_polygon).getOutput(0)) < 2, 'multiple features in feature class'
maskFc = arcpy.CopyFeatures_management(dem_polygon)
maskFc_area = [s[0] for s in arcpy.da.SearchCursor(maskFc, ['SHAPE@AREA'])][0]
# geom_copy = arcpy.management.CopyFeatures(huc12fc, opj(sgdb, 'huc' + huc12))
geom_copy = arcpy.Buffer_analysis(maskFc, buffer_distance_or_field = '-1000 METERS')
if 'id' not in df.getfields(maskFc):
arcpy.AddField_management(maskFc, 'id', 'LONG')
arcpy.CalculateField_management(maskFc, 'id', 1, 'PYTHON')
log.info("maskFcPrelim complete at: " + time.asctime())
## Set up geodatabase to store the multipoint files and terrains (necessary all inputs be in feature dataset
# Vertical units are in meters (float) so use a meter-based reference
FDSet = arcpy.CreateFeatureDataset_management(sgdb, "Lidar_pts", srOut)
maskFcOut = projIfNeeded(maskFc, os.path.join(str(FDSet), 'buf_huc' + srSfx), srOut)
log.info("maskFcOut complete at: " + time.asctime())
for demList in demLists:
maskRastOut = arcpy.PolygonToRaster_conversion(maskFcOut, 'id', opj(sgdb, maskRastBase + str(demList[0])), cellsize = demList[0])
huc_rast_out = arcpy.conversion.PolygonToRaster(geom_copy, 'OBJECTID', opj(sgdb, 'huc_rast' + str(demList[0])), cellsize = demList[0])
return maskFc, maskFc_area, maskFcOut, maskRastOut, huc_rast_out, FDSet
except Exception as e:
print('handling as exception')
## log.debug(e.message)
if sys.version_info.major == 2:
print('handling as 2 exception')
arcpy.AddError(e.message)
print(e.message)
elif sys.version_info.major == 3:
print('handling as 3 exception')
arcpy.AddError(e)
print(e)
# Get the traceback object
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
# Concatenate information together concerning the error into a message string
pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
# Return python error messages for use in script tool or Python Window
arcpy.AddError(pymsg)
# Print Python error messages for use in Python / Python Window
print(pymsg + "\n")
if arcpy.GetMessages(2) not in pymsg:
msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
arcpy.AddError(msgs)
print(msgs)
except:
print('handling as except')
# Get the traceback object
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
# Concatenate information together concerning the error into a message string
pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
# Return python error messages for use in script tool or Python Window
arcpy.AddError(pymsg)
# Print Python error messages for use in Python / Python Window
print(pymsg + "\n")
if arcpy.GetMessages(2) not in pymsg:
msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
arcpy.AddError(msgs)
print(msgs)
def getLidarTimeframes(merged):#, tilesClip_local):
try:
# if merged is not None:#in locals():
collect_starts = [s[0] for s in arcpy.da.SearchCursor(merged, ['collect_start'])]
collect_starts_min = min(collect_starts).strftime('%Y %b %d')
collect_ends = [s[0] for s in arcpy.da.SearchCursor(merged, ['collect_end'])]
collect_ends_max = max(collect_ends).strftime('%Y %b %d')
first_by_area = [s[0] for s in arcpy.da.SearchCursor(merged, ['collect_start', 'area_field'], sql_clause = (None, 'ORDER BY area_field DESC'))][0]
collect_majority = first_by_area.strftime('%Y %b %d')
except:
# else:
collect_ends_max = 'Unknown'
collect_starts_min = 'Unknown'
collect_majority = 'Unknown'
#### if df.testForZero(tilesClip_local):
#### tiles_t_or_f = 'True'
#### else:
#### tiles_t_or_f = 'False'
return collect_ends_max, collect_starts_min, collect_majority#, tiles_t_or_f
def getLasRasterArguments(lasToRaster):
raster_arguments_list = [lasToRaster.getInput(t) for t in range(0, 7)]
raster_arguments = 'LasToRaster arguments: ' + ', '.join(raster_arguments_list)
return raster_arguments
def createCountsFromMultipoints(sgdb, maskRastBase, demList, huc12, finalMPinm, finalMP, log, cntFile):#locDict):
try:
maskRastOut = opj(sgdb, maskRastBase + str(demList[0]))
log.warning('---Counting Bare Earth Returns for ' + str(demList[0]) + ' at ' + time.asctime())
terrCountName = arcpy.ValidateTableName("cnt" + str(demList[0]) + "m_fl_" + huc12, sgdb)
terrCount = arcpy.PointToRaster_conversion(finalMPinm, arcpy.Describe(finalMP).OIDFieldName, os.path.join(sgdb, terrCountName), "COUNT", "NONE", str(demList[0]))
cntFileRasterObj = clipCountRaster(terrCount, maskRastOut, cntFile)
return cntFileRasterObj
except Exception as e:
print('handling as exception')
## log.debug(e.message)
if sys.version_info.major == 2:
print('handling as 2 exception')
arcpy.AddError(e.message)
print(e.message)
elif sys.version_info.major == 3:
print('handling as 3 exception')
arcpy.AddError(e)
print(e)
# Get the traceback object
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
# Concatenate information together concerning the error into a message string
pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
# Return python error messages for use in script tool or Python Window
arcpy.AddError(pymsg)
# Print Python error messages for use in Python / Python Window
print(pymsg + "\n")
if arcpy.GetMessages(2) not in pymsg:
msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
arcpy.AddError(msgs)
print(msgs)
except:
print('handling as except')
# Get the traceback object
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
# Concatenate information together concerning the error into a message string
pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
# Return python error messages for use in script tool or Python Window
arcpy.AddError(pymsg)
# Print Python error messages for use in Python / Python Window
print(pymsg + "\n")
if arcpy.GetMessages(2) not in pymsg:
msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
arcpy.AddError(msgs)
print(msgs)
def buildTerrains(finalMP, FDSet, tcdFdSet, finalHb, finalHl, finalNoZHb, poorZHb, log, windows, time):
terrains = []
# create one terrain with ZMinMax option
tp = ["1", "", "", "WINDOWSIZE", "ZMEAN", "MILD", 0.18]
pyrmd_str = "2 1000;4 2500;8 5000;16 10000;32 20000;64 40000"
#### windowsizeMethods = windows#['ZMEAN', 'ZMINMAX']
for window in windows:
log.info(f'creating and setting up terrain: {window} at {time.asctime()}')
tp[4] = window
LTrrn = arcpy.CreateTerrain_3d(FDSet, "Lidar_Trn" + "_" + tp[4], tp[0], tp[1], tp[2], tp[3], tp[4], tp[5], tp[6])
pyrmd_str = "2 1000;4 2500;8 5000;16 10000;32 20000;64 40000"
pyramids = arcpy.AddTerrainPyramidLevel_3d(LTrrn, "WINDOWSIZE", pyrmd_str)
pyramids_arguments = 'WINDOWSIZE, ' + pyrmd_str
tf = setupTerrain(LTrrn, tcdFdSet, finalHb, finalHl, finalMP, finalNoZHb, poorZHb, log)#, badHb)
arcpy.BuildTerrain_3d(LTrrn)
terrains.append(LTrrn)
terrain_arguments_list = [LTrrn.getInput(t) for t in range(0,10)]
terrain_arguments = ', '.join(terrain_arguments_list)
return terrains, tf, terrain_arguments, pyramids_arguments
def createRastersFromTerrains(log, demList, procDir, terrains, huc12):
try:
# log.debug('snapRaster for Terrain to raster: ' + arcpy.env.snapRaster)
interpTechnique = 'NATURAL_NEIGHBORS'
pyramidLevel = '4'
dem_cellSize = demList[0]
arcpy.env.cellSize = dem_cellSize
for terrain in terrains:
log.warning('---Creating Raster from Terrain for ' + str(demList[0]) + ' using ' + terrain.getInput(6) + ' at ' + time.asctime())
tempTerrName = generateTempTerrName(procDir, terrain.getInput(6), dem_cellSize, huc12)
pfFileTemp = os.path.join(procDir, '_'.join(['tmp_ter', terrain.getInput(6), str(demList[0]) + 'm', huc12, 'out.tif']))
demOut = arcpy.TerrainToRaster_3d(terrain, pfFileTemp, "FLOAT", interpTechnique, "CELLSIZE " + str(demList[0]), pyramidLevel)
#### demList.append(demOut.getOutput(0))
except Exception as e:
print('handling as exception')
## log.debug(e.message)
if sys.version_info.major == 2:
print('handling as 2 exception')
arcpy.AddError(e.message)
print(e.message)
elif sys.version_info.major == 3:
print('handling as 3 exception')
arcpy.AddError(e)
print(e)
# Get the traceback object
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
# Concatenate information together concerning the error into a message string
pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
# Return python error messages for use in script tool or Python Window
arcpy.AddError(pymsg)
# Print Python error messages for use in Python / Python Window
print(pymsg + "\n")
if arcpy.GetMessages(2) not in pymsg:
msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
arcpy.AddError(msgs)
print(msgs)
except:
print('handling as except')
# Get the traceback object
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
# Concatenate information together concerning the error into a message string
pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
# Return python error messages for use in script tool or Python Window
arcpy.AddError(pymsg)
# Print Python error messages for use in Python / Python Window
print(pymsg + "\n")
if arcpy.GetMessages(2) not in pymsg:
msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
arcpy.AddError(msgs)
print(msgs)
def setupLasDataset(lasIn, mask, procDir, breakpolys, breaklines, counterId, badHb, log, time, proj = ''):
try:
surfcons = ''
if breakpolys:
surfcons += str(breakpolys) + " Shape.Z Hard_Replace;"# " + str(mask) + " <None> Hard_Clip"
if breaklines:
surfcons += str(breaklines) + " Shape.Z Hard_Line;"# " + str(mask) + " <None> Hard_Clip"
if badHb:
surfcons += str(badHb) + " Z_Max Hard_Line;"# " + str(mask) + " <None> Hard_Clip"
else:
surfcons += str(mask) + " <None> Hard_Clip"
log.info(f'surfcons are: {surfcons} at {time.asctime()}')
## log.warning('surfcons are ' + surfcons)
lasd = arcpy.CreateLasDataset_management(lasIn, os.path.join(procDir, 'huc_cl2' + counterId + '.lasd'), in_surface_constraints = surfcons, spatial_reference = proj)
return lasd
except:
# Get the traceback object
#
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
# Concatenate information together concerning the error into a message string
#
pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
log.warning(pymsg)
log.warning(msgs)
def setupTerrain(terrain, mask, breakpolys, breaklines, points, noZbreakpolys, poorZ, log):#, badHb):
group = 1#0
# list of terrain features
tf = []
ret = arcpy.AddFeatureClassToTerrain_3d(terrain, str(points) + " SHAPE masspoints " + str(group) + " 0 64 true true LASmerge_emb <None>")
tf.append(ret)
group += 1
if breakpolys:
ret = arcpy.AddFeatureClassToTerrain_3d(terrain, str(breakpolys) + " SHAPE hardreplace " + str(group) + " 0 32 true false <None> <None>")
tf.append(ret)
group += 1
if breaklines:
ret = arcpy.AddFeatureClassToTerrain_3d(terrain, str(breaklines) + " SHAPE hardline " + str(group) + " 0 32 true false <None> <None>")
tf.append(ret)
group += 1
if poorZ:
ret = arcpy.AddFeatureClassToTerrain_3d(terrain, str(poorZ) + " Z_Max hardline " + str(group) + " 0 32 true false <None> <None>")
tf.append(ret)
group += 1
if noZbreakpolys:
ret = arcpy.AddFeatureClassToTerrain_3d(terrain, str(noZbreakpolys) + " <None> hardline " + str(group) + " 0 32 true false <None> <None>")
tf.append(ret)
group += 1
ret = arcpy.AddFeatureClassToTerrain_3d(terrain, str(mask) + " <None> hardclip " + str(group) + " 0 32 true false <None> <None>")
tf.append(ret)
return tf
def clipCountRaster(cnt3mFull, maskRastUTM, cntFileName):
cntUTMpre = Con(IsNull(cnt3mFull), 0, cnt3mFull)
cntUTMter = Con(maskRastUTM, cntUTMpre)
cntUTMter.save(cntFileName)
arcpy.BuildPyramids_management(cntUTMter)
return cntUTMter
def testForZero(dataset):
if type(dataset) == 'Raster':
if dataset.hasRAT != True:
arcpy.BuildRasterAttributeTable_management(dataset)
try:
fcount = int(arcpy.GetCount_management(dataset).getOutput(0))
except:
fcount = 0
return fcount
def projIfNeeded(input2, output, srOut):
srInput = arcpy.Describe(input2).spatialReference#maybe use projectionCode?
try:
if srInput.PCSCode != srOut.PCSCode:
## log.warning('projecting ' + str(input2))
projInput = arcpy.Project_management(input2, output, srOut)
else:
projInput = arcpy.CopyFeatures_management(input2, output)
except arcpy.ExecuteError:
## assume there is a terrain created for the input, so must copy point feature class before projecting
ptCopy = arcpy.CopyFeatures_management(input2, os.path.join(os.path.dirname(os.path.dirname(output)), os.path.basename(output) + '_copy'))
projInput = arcpy.CopyFeatures_management(ptCopy, output)
return projInput
def fill_donut_slow(fc):
'''Edits a layer in-place and fills all donut holes or gaps in the selected
features. Will operate on entire layer if there are no features selected.
Requires layer to honor selected features.
'''
desc = arcpy.Describe(fc)
shapefield = desc.ShapeFieldName
rows = arcpy.UpdateCursor(fc)
n = 0
polyGeo = arcpy.Array() # to hold edited shape
polyOuter = arcpy.Array() # to hold outer ring
for row in rows:
feat = row.getValue(shapefield)
qInterior = False
for partNum in range(feat.partCount) :
part = feat.getPart(partNum)
for pt in iter(lambda:part.next(),None) : # iter stops on null pt
polyOuter.append(pt)
if part.count > len(polyOuter) :
qInterior = True
polyGeo.append(polyOuter) # reassemble each part
polyOuter.removeAll() # ready for next part
if qInterior : # in any part of this feature, otherwise skip update
n+=1
row.setValue(shapefield,polyGeo)
rows.updateRow(row)
polyGeo.removeAll()
del rows,row
def genClass2AndMultiPoints(allLAZ, sfx, srOut, inm, FDSet, procDir, log):
try:
if allLAZ.endswith('.laz') or allLAZ.endswith('.las'):
"""Filters LAS points to class 2 and creates multipoints in FDSet"""
lasBase = os.path.splitext(os.path.basename(allLAZ))[0]
cl2LAS = os.path.join(procDir, arcpy.ValidateTableName(lasBase + '_cl2', procDir) + '.las')
## Filter LAS to class 2 and 8 (key points), LAS 1.4 now has class 8 as reserved
# LASTools requires " around file names with spaces, ' not allowed, (Windows Command Line too?)
# Use pdal for this? https://pdal.io/en/stable/apps/translate.html#example-1
# log.debug('--- Use las2las at ' + time.asctime())
if allLAZ.endswith('.laz'):
log.debug('--- Using ConvertLas to decompress LAZ at ' + time.asctime())
las_from_laz = arcpy.ConvertLas_conversion(allLAZ, target_folder=procDir, compression=None, las_options=None)
else:
las_from_laz = allLAZ
# rc = subprocess.call(os.path.join(softwareDir, 'LASTools', 'bin', 'las2las') + ' -i "' + allLAZ + '" -keep_class 2 8 -o ' + cl2LAS, shell=True)
# if rc == 0 and not os.path.isfile(cl2LAS):
# log.warning('las2las did not create class 2 points file: ' + cl2LAS)
# lasMP = None
# elif rc == 0:
log.debug('--- Create las non-Minnesota Multipoint at ' + time.asctime())
lasMP = arcpy.LASToMultipoint_3d(cl2LAS, inm + "\\pts" + sfx, "1", class_code = [2,8], input_coordinate_system = srOut)
# else:
# log.warning('las2las did not execute successfully')
## os.remove(cl2LAS)
elif allLAZ.endswith('.zlas'):
log.debug('--- Create zlas non-Minnesota Multipoint at ' + time.asctime())
lasMP = arcpy.LASToMultipoint_3d(allLAZ, inm + "\\pts" + sfx, "1", class_code = [2,8], input_coordinate_system = srOut)
if lasMP:#allLAZ.endswith('.laz') and os.path.isfile(cl2LAS) or allLAZ.endswith('.zlas'):
## Clip multipoints
#### if untiledByLas:
#### lasMP = arcpy.Clip_analysis(lasMP, untiledByLas, inm + "\\pts_clp_" + str(rowCounter))
ptsName = arcpy.ValidateTableName('pts_' + lasBase, os.path.join(str(FDSet)))
ptOut = projIfNeeded(lasMP, os.path.join(str(FDSet), ptsName), srOut)
else:
log.warning('no ptOut created, setting to None')
ptOut = None
## return cl2LAS, ptOut
return ptOut, cl2LAS
except Exception as e:
print('handling as exception')
## log.debug(e.message)
if sys.version_info.major == 2:
arcpy.AddError(e.message)
print(e.message)
elif sys.version_info.major == 3:
arcpy.AddError(e)
print(e)
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
# Concatenate information together concerning the error into a message string
pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
# Return python error messages for use in script tool or Python Window
arcpy.AddError(pymsg)
# Print Python error messages for use in Python / Python Window
print(pymsg + "\n")
if arcpy.GetMessages(2) not in pymsg:
msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
arcpy.AddError(msgs)
print(msgs)
except:
print('handling as except')
# Get the traceback object
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
# Concatenate information together concerning the error into a message string
pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
# Return python error messages for use in script tool or Python Window
arcpy.AddError(pymsg)
# Print Python error messages for use in Python / Python Window
print(pymsg + "\n")
if arcpy.GetMessages(2) not in pymsg:
msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
arcpy.AddError(msgs)
print(msgs)
def buildSelection(inList, field):
sel = ''
for index, item in enumerate(inList):
if index == 0:
sel = field + ' = ' + str(item)
else:
sel += ' OR ' + field + ' = ' + str(item)
return sel
##def convertDEMunitsIfNeeded(srVCS, coDEM):
def convertDEMunitsIfNeeded(srVCS, coDEM, state, log):
'''convert units, but not to centimeters'''
log.warning('coDEM is: ' + coDEM)
if srVCS is not None:
log.warning('srVCS: ' + str(srVCS.factoryCode) + ', ' + str(srVCS.name) + ', ' + srVCS.linearUnitName)
unitsLower = srVCS.linearUnitName.lower()
if 'foot' in unitsLower or 'feet' in unitsLower:
log.warning('Converting DEM')# at ' + str(time.clock()))
if 'survey' in unitsLower and 'foot' in unitsLower:
regionDEM = Raster(coDEM)* 1200.0/3937.0
elif 'foot' in unitsLower or 'feet' in unitsLower:
regionDEM = Raster(coDEM)*0.3048
elif 'meter' in unitsLower:
regionDEM = Raster(coDEM)
elif state == 'Illinois' or state == 'Wisconsin':
log.warning('srVCS is None for ' + coDEM)
# assume data in feet
regionDEM = Raster(coDEM)*0.3048
elif state == 'Missouri':
log.warning('srVCS is None for ' + coDEM)
# assume data in meters
regionDEM = Raster(coDEM)
return regionDEM
def setupPointsAndBreaklines(finalMP, inm, FDSet, breakpolys, breaklines, log):
try:
fd_string = FDSet.getOutput(0)
## with arcpy.EnvManager(workspace = str(FDSet)):
log.info('setting up points and breaklines')
# an in-memory version of the feature class for faster generation of count statistics
finalMPinm = arcpy.CopyFeatures_management(finalMP, os.path.join(inm, 'mp_merge'))
# a list of breakpoint feature classes to merge together at the end, saved for later
breakpolyList = []
# list of polygon breakline feature classes, some are 'better' than others, Minnesota you kill me!
hbList = arcpy.ListFeatureClasses('hb_sel_*', feature_type = 'POLYGON', feature_dataset = os.path.basename(fd_string))
fd_hbList = [opj(os.path.basename(fd_string), c) for c in hbList]
hbListM = arcpy.ListFeatureClasses('hbm_sel_*', feature_type = 'POLYGON', feature_dataset = os.path.basename(fd_string))
fd_hbListM = [opj(os.path.basename(fd_string), c) for c in hbListM]
# put those with M values first (largest number of characters in text field)
#### hbListM += hbList
fd_hbListM += fd_hbList
if len(fd_hbListM) > 0:
finalHb = arcpy.Merge_management(fd_hbListM, os.path.join(str(FDSet), 'hb_merge'))
breakpolyList.append(finalHb)
else:
finalHb = None
poorZHbList = arcpy.ListFeatureClasses('hb_poor_*', feature_type = 'POLYGON', feature_dataset = os.path.basename(fd_string))
if len(poorZHbList) > 0:
poorZHb = arcpy.Merge_management(poorZHbList, os.path.join(str(FDSet), 'poor_z_hb_merge'))
breakpolyList.append(poorZHb)
else:
poorZHb = None
noZHbList = arcpy.ListFeatureClasses('bad_hb_*', feature_type = 'POLYGON', feature_dataset = os.path.basename(fd_string))
if len(noZHbList) > 0:
finalNoZHb = arcpy.Merge_management(noZHbList, os.path.join(str(FDSet), 'no_z_hb_merge'))
breakpolyList.append(finalNoZHb)
else:
finalNoZHb = None
# merge the breakline feature classes together
breakGdb = os.path.dirname(breaklines)
if not arcpy.Exists(breakGdb):
if not os.path.isdir(os.path.basename(breakGdb)):
os.makedirs(os.path.dirname(breakGdb))
breakGdbResult = arcpy.CreateFileGDB_management(os.path.dirname(breakGdb), os.path.basename(breakGdb))
log.warning(f'breakpolyList: {breakpolyList}')
if len(breakpolyList) > 0:
# mergedBreakpolys = arcpy.Merge_management(breakpolyList, os.path.join(breakGdb, 'break_polys_' + huc12))
mergedBreakpolys = arcpy.Merge_management(breakpolyList, breakpolys)
hlList = arcpy.ListFeatureClasses('hl_*', feature_type = 'POLYLINE', feature_dataset = os.path.basename(fd_string))
log.warning(f'hlList: {hlList}')
if len(hlList) > 0:
finalHl = arcpy.Merge_management(hlList, os.path.join(str(FDSet), 'hl_merge'))
copiedBreaklines = arcpy.CopyFeatures_management(finalHl, breaklines)
# copiedBreaklines = arcpy.CopyFeatures_management(finalHl, os.path.join(breakGdb, 'break_lines_' + huc12))
log.warning(f'copiedBreaklines: {copiedBreaklines}')
else:
finalHl = None
return finalMPinm, finalHb, poorZHb, finalNoZHb, finalHl
except Exception as e:
print('handling as exception')
## log.debug(e.message)
if sys.version_info.major == 2:
arcpy.AddError(e.message)
print(e.message)
elif sys.version_info.major == 3:
arcpy.AddError(e)
print(e)
errorhandle(sys.exc_info(), arcpy, traceback)#[2])
except:
errorhandle(sys.exc_info(), arcpy, traceback)#[2])
def errorhandle(sei, arcpy, traceback):
'''Try to handle the errors and output information about them'''
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
# Concatenate information together concerning the error into a message string
pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
# Return python error messages for use in script tool or Python Window
arcpy.AddError(pymsg)
# Print Python error messages for use in Python / Python Window
print(pymsg + "\n")
if arcpy.GetMessages(2) not in pymsg:
msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
arcpy.AddError(msgs)
print(msgs)
# def generateLasArea(tilesClip, FDSet):
# ## try:
# # buffer/debuffer this by 2 meters to get rid of some gaps in lidar file characterization
# tilesClipBuffer = arcpy.Buffer_analysis(tilesClip, buffer_distance_or_field = '2 METERS', dissolve_option = 'ALL')
# tilesClipDeBuffer = arcpy.Buffer_analysis(tilesClipBuffer, buffer_distance_or_field = '-2 METERS')
# tilesClipDslv = arcpy.Dissolve_management(tilesClipDeBuffer)
# tilesClipDslvElim = arcpy.EliminatePolygonPart_management(tilesClipDslv, condition = 'PERCENT', part_area_percent = 50)
# tcdFdSet = arcpy.CopyFeatures_management(tilesClipDslvElim, os.path.join(str(FDSet), 'local_las_area'))
# return tcdFdSet
def updateResolution(filename, init_res, new_res, huc12, log):
"""Take a filename with a specified resolution and alter it to the current processing resolution.
This is done to reduce the number of arguments that are passed to the program."""
# try: