def createMZ_Route(inCurvesRemovedPath, outFeatureClass, surfaceForZ, routeIdField): """Input the shapefile with curves removed, calc Z values and create the routes with temp M values that will be overridden""" extStatus = arcpy.CheckOutExtension("3D") arcpy.AddMessage("3D analyst: " + str(extStatus)) outPolyLineZ = outFeatureClass + "LineZ" tempOutsList.append(outPolyLineZ) outRouteMZ = outFeatureClass rtPartNumField = "PrtNum" rtPartCalcExp = "!" + routeIdField + "![-1:]" arcpy.InterpolateShape_3d(surfaceForZ, inCurvesRemovedPath, outPolyLineZ, '', 1, '', True) arcpy.AddMessage(arcpy.GetMessages()) arcpy.CreateRoutes_lr(outPolyLineZ, routeIdField, outRouteMZ) arcpy.AddMessage(arcpy.GetMessages()) arcpy.AddField_management(outRouteMZ, rtPartNumField, "SHORT") arcpy.CalculateField_management(outRouteMZ, rtPartNumField, rtPartCalcExp, "PYTHON_9.3") arcpy.AddMessage( "Routes with Z values and M place holders have been created") extStatus = arcpy.CheckInExtension("3D") arcpy.AddMessage("3D analyst: " + str(extStatus)) return [outRouteMZ, rtPartNumField]
def execute(self, parameters, messages): """The source code of the tool.""" surface = parameters[0].valueAsText observer_points = parameters[1].valueAsText observer_offset = parameters[2].valueAsText target_points = parameters[3].valueAsText target_offset = parameters[4].valueAsText sampling_distance = parameters[5].valueAsText output_los = parameters[6].valueAsText sightlines = arcpy.ConstructSightLines_3d( observer_points, target_points, arcpy.CreateScratchName(prefix="sightlines", workspace=arcpy.env.scratchGDB), observer_offset, target_offset, "<None>", 1, "NOT_OUTPUT_THE_DIRECTION") raster_extent = arcpy.sa.Raster(surface).extent maximal_possible_distance = math.sqrt( math.pow( max(raster_extent.XMax - raster_extent.XMin, raster_extent.YMax - raster_extent.YMin), 2) * 2) spatial_ref = arcpy.Describe(sightlines).spatialReference visibility.makeGlobalLoS(sightlines, maximal_possible_distance, spatial_ref) arcpy.AddField_management(sightlines, "ID_OBSERV", "LONG") arcpy.CalculateField_management(sightlines, "ID_OBSERV", "!OID_OBSERV!", "PYTHON") arcpy.AddField_management(sightlines, "ID_TARGET", "LONG") arcpy.CalculateField_management(sightlines, "ID_TARGET", "!OID_TARGET!", "PYTHON") arcpy.DeleteField_management(sightlines, ["OID_TARGET", "OID_OBSERV"]) temp_los_name = arcpy.CreateScratchName(prefix="los", workspace=arcpy.env.scratchGDB) arcpy.InterpolateShape_3d(surface, sightlines, temp_los_name, sample_distance=sampling_distance, method="BILINEAR") visibility.updateLoS(temp_los_name, output_los, sightlines, target_points, True) arcpy.DeleteField_management(output_los, "SourceOID") visibility.verifyShapeStructure(sightlines, output_los) functions_arcmap.addLayer(output_los) return
def interpolate(inLayer, dem, Zfeat): #interpolates elevations from dem, any feature type #creates new Z-aware feature class as a shapefile or gdb feature class #depending on the type of output workspace - folder or gdb. try: arcpy.AddMessage('Getting elevation values for features in ' + inLayer) arcpy.InterpolateShape_3d(dem, inLayer, Zfeat) except: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] pymsg = tbinfo + '\n' + str(sys.exc_type) + ': ' + str(sys.exc_value) arcpy.AddError(pymsg) raise SystemError finally: arcpy.AddMessage(Zfeat + ' written to ' + arcpy.env.scratchWorkspace)
def generate_3d_features(): number_of_features = str(arcpy.GetCount_management(InputFeatureClass)) arcpy.AddMessage(number_of_features + " segments found") arcpy.InterpolateShape_3d(InputDEM, InputFeatureClass, OutputBraut3d) # convert 2D to 3D arcpy.AddMessage("Feature class braut3d created") arcpy.CalculateField_management(OutputBraut3d, "ID", "!OBJECTID!", "PYTHON_9.3") # populate fields arcpy.CalculateField_management(OutputBraut3d, "start", "0", "PYTHON_9.3") arcpy.CalculateField_management(OutputBraut3d, "end", "!shape.length@meters!", "PYTHON_9.3") arcpy.AddMessage("Fields ID, START and END populated") arcpy.env.MTolerance = "0.001" # set tolerance for M coordinate arcpy.CreateRoutes_lr(OutputBraut3d, "ID", OutputBraut3did, "TWO_FIELDS", "start", "end", "UPPER_LEFT", "1", "0", "IGNORE", "INDEX") arcpy.AddMessage("Feature class braut3did created")
def add_elev(): try: # Set the local variables arcpy.env.overwriteOutput = True inraster = 'G:\Elevation Data\one_third_arcsecond_usgs_dems\NED_elevation_1_3rd_arcsecond.gdb\\elevation' infc = 'AL_TN_KY_wells83' outfc = 'AL_TN_KY_wells83_elv' method = "BILINEAR" Z_factor="3.28084" #Z_factor converts meters to feet arcpy.InterpolateShape_3d(in_surface=inraster, in_feature_class=infc, out_feature_class=outfc, method=method) print('zvalues added to well points') except Exception as err: print(err.args[0])
def execute(self, parameters, messages): """The source code of the tool.""" surface = parameters[0].valueAsText observer_points = parameters[1].valueAsText observer_offset = parameters[2].valueAsText target_points = parameters[3].valueAsText target_offset = parameters[4].valueAsText sampling_distance = parameters[5].valueAsText output_los = parameters[6].valueAsText temp_los_name = arcpy.CreateScratchName(prefix="los", workspace=arcpy.env.scratchGDB) sightlines_name = arcpy.CreateScratchName( prefix="sightlines", workspace=arcpy.env.scratchGDB) sightlines = arcpy.ConstructSightLines_3d( observer_points, target_points, sightlines_name, observer_offset, target_offset, "<None>", 1, "NOT_OUTPUT_THE_DIRECTION") arcpy.AddField_management(sightlines, "ID_OBSERV", "LONG") arcpy.CalculateField_management(sightlines, "ID_OBSERV", "!OID_OBSERV!", "PYTHON") arcpy.AddField_management(sightlines, "ID_TARGET", "LONG") arcpy.CalculateField_management(sightlines, "ID_TARGET", "!OID_TARGET!", "PYTHON") arcpy.DeleteField_management(sightlines, ["OID_TARGET", "OID_OBSERV"]) arcpy.InterpolateShape_3d(surface, sightlines, temp_los_name, sample_distance=sampling_distance, method="BILINEAR") visibility.updateLoS(temp_los_name, output_los, sightlines, target_points, False) visibility.verifyShapeStructure(sightlines, output_los) functions_arcmap.addLayer(output_los) return
def editLines(fc_bacis, fc_output, dem, inExField): # Edits lines and prepares them for next step fc_extra = fc_output + "/extra" fc_intra = fc_output + "/intra" fc_merge = fc_output + "/merge" fc_dissolve = fc_output + "/dissolve" fc_SpatialJoin = fc_output + "/SpatialJoin" fc_input = fc_output + "/ready_lines" expression1 = inExField + "=1" expression2 = inExField + "=0" arcpy.FeatureClassToFeatureClass_conversion(fc_bacis, fc_output, "intra", expression1) arcpy.FeatureClassToFeatureClass_conversion(fc_bacis, fc_output, "extra", expression2) arcpy.Dissolve_management(fc_extra, fc_dissolve, "", "", "SINGLE_PART", "UNSPLIT_LINES") arcpy.SpatialJoin_analysis(fc_dissolve, fc_bacis, fc_SpatialJoin, "JOIN_ONE_TO_ONE", "", "", "INTERSECT") arcpy.Merge_management([fc_SpatialJoin, fc_intra], fc_merge) arcpy.InterpolateShape_3d(dem, fc_merge, fc_input) return fc_input
fOutText = 'test.csv' fOutFigure = 'test.pdf' tempPoly = 'temp.shp' # interpolated polyline tempPoly2 = 'kenn_xg_bins.shp' # polygons for zonal statistics ZSarea = 'tempTable.dbf' # zonal statistics table ####################### End User Defined Inputs ############################## #### KRB August 2014 update notes # 1. add something that checks the inputs (e.g. inPoly must be a line) print "interpolate line to the raster" coordSys = arcpy.Describe(inPoly).spatialReference.exporttostring() arcpy.InterpolateShape_3d(inRast, inPoly, tempPoly, height) # initialize output part 1 xOut = [] yOut = [] print "get all points along the swath line" ptArray = [] rows = arcpy.SearchCursor(tempPoly) for row in rows: points = row.shape.getPart(0) for point in points: xOut.append(point.X) yOut.append(point.Y) ptArray.append([point.X, point.Y]) del row, rows
raise SystemError #environment variables arcpy.env.overwriteOutput = True scratchDir = arcpy.env.scratchWorkspace arcpy.env.workspace = scratchDir #add an rkey field to the table that consists of values from the OID desc = arcpy.Describe(linesLayer) idField = desc.OIDFieldName addAndCalc(linesLayer, 'ORIG_FID', '[' + idField + ']') #interpolate the lines zLines = outName + '_z' arcpy.AddMessage('Getting elevation values for features in ' + linesLayer) arcpy.InterpolateShape_3d(dem, linesLayer, zLines) arcpy.AddMessage(' ' + zLines + ' written to ' + arcpy.env.scratchWorkspace) #measure the lines zmLines = outName + '_zm' arcpy.AddMessage('Measuring the length of the line(s) in ' + zLines) arcpy.CreateRoutes_lr(zLines, 'ORIG_FID', zmLines, 'LENGTH', '#', '#', cp) arcpy.AddMessage(' ' + zmLines + ' written to ' + arcpy.env.scratchWorkspace) #hook the attributes back up #transferAtts(inFC, joinTable, parentKey, childKey, fInfo, outName) zmAtts = outName + '_zmAtts' transferAtts(zmLines, linesLayer, 'ORIG_FID', 'ORIG_FID', '#', zmAtts) #make an empty container with an 'Unknown' SR zmProfiles = outName + '_profiles'
# clip if debug: addMsgAndPrint(' clipping') arcpy.Clip_analysis(fc, clipPoly, clippedName) if numberOfRows(clippedName) == 0: if debug: addMsgAndPrint(' empty output') testAndDelete(clippedName) else: if debug: addMsgAndPrint(' clipped dataset has ' + str(numberOfRows(clippedName)) + ' rows') # enable Z if debug: addMsgAndPrint(' adding Z to make ' + os.path.basename(ZName)) arcpy.InterpolateShape_3d(dem, clippedName, ZName, sampleDistance, zFactor) if os.path.basename(fc) == xsLine: ### this isn't very robust! if debug: addMsgAndPrint( ' **Making line segments of surface mapunit polys**') SMUL = xsFDS + '/CS' + token + 'SurfaceMapUnitLines' testAndDelete(SMUL) arcpy.Intersect_analysis( [ZName, gdb + '/GeologicMap/MapUnitPolys'], SMUL) minY, maxY = transformAndSwap(SMUL, xsFDS + '/trans_SurfaceMapUnitLines', linkFeatures, tanPlunge) testAndDelete(xsFDS + '/trans_SurfaceMapUnitLines') arcpy.RecalculateFeatureClassExtent_management(SMUL)
ZonalStatisticsAsTable(stationBuffer, "STATIONID", inputDEM, stationElev, "NODATA", "ALL") arcpy.AddJoin_management(stationLyr, "StationID", stationElev, "StationID", "KEEP_ALL") expression = "round(!stationElev.MEAN! * " + str(Zfactor) + ",1)" arcpy.CalculateField_management(stationLyr, "stations.POINT_Z", expression, "PYTHON") arcpy.RemoveJoin_management(stationLyr, "stationElev") arcpy.DeleteField_management(stationTemp, "STATIONID; POINT_M") # ---------------------------------------------------------------------- Create final output # Interpolate Line to 3d via Z factor arcpy.InterpolateShape_3d(inputDEM, lineTemp, outLine, "", Zfactor) # Copy Station Points arcpy.CopyFeatures_management(stationTemp, outPoints) arcpy.Delete_management(stationElev) arcpy.Delete_management(stationTemp) # Create Txt file if selected and write attributes of station points if text == True: AddMsgAndPrint("Creating Output text file:\n") AddMsgAndPrint("\t" + str(outTxt) + "\n") t = open(outTxt, 'w') t.write("ID, STATION, X, Y, Z")
#environment variables arcpy.env.overwriteOutput = True scratchDir = arcpy.env.scratchWorkspace arcpy.env.workspace = scratchDir #add an ORIG_FID field to the table that consists of values from the OID desc = arcpy.Describe(lineLayer) idField = desc.OIDFieldName addAndCalc(lineLayer, 'ORIG_FID', '[' + idField + ']') #interpolate the line to add z values zLine = lineLayer + '_z' arcpy.AddMessage('Getting elevation values for the cross-section in ' + lineLayer) arcpy.InterpolateShape_3d(dem, lineLayer, zLine) arcpy.AddMessage(' ' + zLine + ' written to ' + arcpy.env.scratchWorkspace) #measure it and turn it into a route zmLine = lineLayer + '_zm' arcpy.AddMessage('Measuring the length of ' + zLine) arcpy.CreateRoutes_lr(zLine, 'ORIG_FID', zmLine, 'LENGTH', '#', '#', cp) arcpy.AddMessage(' ' + zmLine + ' written to ' + arcpy.env.scratchWorkspace) #figure out where the collar elevation is coming from, a user specified field or to be #calculated by interpolation from the DEM and stored in 'zDEM' if not bhzField == '': zField = bhzField zBoreholes = bhLayer
for nm in xslfields: if nm not in specialFields: try: arcpy.DeleteField_management(tempXsLine, nm) except: pass ## check for Z and M values desc = arcpy.Describe(tempXsLine) if desc.hasZ and desc.hasM: ZMline = tempXsLine else: #Add Z values addMsgAndPrint(' getting elevation values for ' + shortName(tempXsLine)) Zline = arcpy.CreateScratchName('xx', outFdsTag + '_Z', 'FeatureClass', scratch) arcpy.InterpolateShape_3d(dem, tempXsLine, Zline) #Add M values addMsgAndPrint(' measuring ' + shortName(Zline)) ZMline = arcpy.CreateScratchName('xx', outFdsTag + '_ZM', 'FeatureClass', scratch) arcpy.CreateRoutes_lr(Zline, idField, ZMline, 'LENGTH', '#', '#', startQuadrant) ## buffer line to get selection polygon addMsgAndPrint(' buffering ' + shortName(tempXsLine) + ' to get selection polygon') tempBuffer = arcpy.CreateScratchName('xx', outFdsTag + "xsBuffer", 'FeatureClass', scratch) arcpy.Buffer_analysis(ZMline, tempBuffer, bufferDistance, 'FULL', 'FLAT') ## get lists of feature classes to be projected lineFCs = []
print(arcpy.GetMessages()) # Convert segements to 3D shape. Requires checking out #3D Analyst to perform operation, then checking back in. Borrowed from <http://desktop.arcgis.com/en/arcmap/10.3/analyze/python/access-to-licensing-and-extensions.htm> class LicenseError(Exception): pass try: if arcpy.CheckExtension("3D") == "Available": arcpy.CheckOutExtension("3D") else: # Raise a custom exception raise LicenseError # Convert segements to 3D shape arcpy.InterpolateShape_3d(rasterSurface, outFeature1, outFeature2) print(arcpy.GetMessages()) except LicenseError: print("3D Analyst license is unavailable") except arcpy.ExecuteError: print(arcpy.GetMessages()) finally: # Check in the ArcGIS 3D Analyst extension arcpy.CheckInExtension("3D") # Add new field to outFeature2 that will hold slope values arcpy.AddField_management(outFeature2, newField, "FLOAT") print(arcpy.GetMessages()) # Calculate slopes in the new field of outFeature2. Must be done with by creating a new function that calculates slope (%). Uses cursor to update slope field
xStart = startXYArray[0] yStart = startXYArray[1] # Generate points along the plan profile line each 6 meters and calculate their coordinates pointsAlongLine = arcpy.GeneratePointsAlongLines_management(planProfileLineFC, 'in_memory\pointsAlongLineT', "DISTANCE", "6 meters", "", "END_POINTS") arcpy.AddXY_management(pointsAlongLine) # Add Distance field and calculate the distance between start point and each generated point arcpy.AddField_management(pointsAlongLine, "Distance", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") arcpy.CalculateField_management(pointsAlongLine, "Distance", "math.sqrt( ( !POINT_X! - "+str(xStart) +")**2 + ( !POINT_Y! - "+str(yStart) +")**2 )", "PYTHON_9.3", "") # Join Geology attributes to points along the plan profile line geologyPoints = arcpy.SpatialJoin_analysis(pointsAlongLine, geologyFC, 'in_memory\geologyPointsT', "JOIN_ONE_TO_ONE", "KEEP_ALL", "", "INTERSECT", "", "") # Interpolate the points along the plan profile line with the DEM geologyPoints3D = arcpy.InterpolateShape_3d(DEM, geologyPoints, 'in_memory\geologyPoints3DT', "", "1", "BILINEAR", "DENSIFY", "0") # Add X Y Z Coordinates arcpy.AddXY_management(geologyPoints3D) # Recalculate Y coordinate to draw the profile arcpy.CalculateField_management(geologyPoints3D, "POINT_Y", "!POINT_Z! * "+str(exaggerationVal)+"", "PYTHON_9.3", "") # Make the Geology Profile Points through the profile Distance vs Heigh and export to Feature Class or Shapefile geologyProfilePointsLyr = arcpy.MakeXYEventLayer_management(geologyPoints3D, "Distance", "POINT_Y", 'in_memory\geologyProfilePointsLyrT', sr, "") geologyProfilePoints = arcpy.CopyFeatures_management(geologyProfilePointsLyr, 'in_memory\geologyProfilePointsT', "", "0", "0", "0") # Generate line whit the Geology Profile Points line3D = arcpy.PointsToLine_management(geologyProfilePoints, 'in_memory\line3DT', "", "", "NO_CLOSE") # Split the line with each point
def flood_from_raster(input_source, input_type, no_flood_value, baseline_elevation_raster, baseline_elevation_value, outward_buffer, output_polygons, smoothing, debug): try: # Get Attributes from User if debug == 0: # script variables aprx = arcpy.mp.ArcGISProject("CURRENT") home_directory = aprx.homeFolder tiff_directory = home_directory + "\\Tiffs" tin_directory = home_directory + "\\Tins" scripts_directory = aprx.homeFolder + "\\Scripts" rule_directory = aprx.homeFolder + "\\rule_packages" log_directory = aprx.homeFolder + "\\Logs" layer_directory = home_directory + "\\layer_files" project_ws = aprx.defaultGeodatabase enableLogging = True DeleteIntermediateData = True verbose = 0 use_in_memory = True else: # debug home_directory = r'D:\Gert\Work\Esri\Solutions\3DFloodImpact\work2.3\3DFloodImpact' tiff_directory = home_directory + "\\Tiffs" tin_directory = home_directory + "\\Tins" scripts_directory = home_directory + "\\Scripts" rule_directory = home_directory + "\\rule_packages" log_directory = home_directory + "\\Logs" layer_directory = home_directory + "\\layer_files" project_ws = home_directory + "\\Results.gdb" enableLogging = False DeleteIntermediateData = True verbose = 1 use_in_memory = False scratch_ws = common_lib.create_gdb(home_directory, "Intermediate.gdb") arcpy.env.workspace = scratch_ws arcpy.env.overwriteOutput = True # fail safe for Europese's comma's baseline_elevation_value = float( re.sub("[,.]", ".", baseline_elevation_value)) if not os.path.exists(tiff_directory): os.makedirs(tiff_directory) if not os.path.exists(tin_directory): os.makedirs(tin_directory) common_lib.set_up_logging(log_directory, TOOLNAME) start_time = time.clock() if arcpy.CheckExtension("3D") == "Available": arcpy.CheckOutExtension("3D") if arcpy.CheckExtension("Spatial") == "Available": arcpy.CheckOutExtension("Spatial") flood_level_layer_mp = None desc = arcpy.Describe(input_source) arcpy.AddMessage( "Processing input source: " + common_lib.get_name_from_feature_class(input_source)) spatial_ref = desc.spatialReference # create IsNull to be used to clip and check for NoData. if use_in_memory: is_null0 = "in_memory/is_null0" else: is_null0 = os.path.join(scratch_ws, "is_null0") if arcpy.Exists(is_null0): arcpy.Delete_management(is_null0) is_null_raster = arcpy.sa.IsNull(input_source) is_null_raster.save(is_null0) if spatial_ref.type == 'PROJECTED' or spatial_ref.type == 'Projected': # check input source type: projected rasters ONLY!!!! # check type, if polygon -> convert to raster if input_type == "RasterLayer" or input_type == "RasterDataset" or input_type == "raster": # prep raster # smooth result using focal stats if smoothing > 0: if use_in_memory: focal_raster = "in_memory/focal_raster" else: focal_raster = os.path.join( scratch_ws, "focal_raster") if arcpy.Exists(focal_raster): arcpy.Delete_management(focal_raster) if not (1 <= smoothing <= 100): smoothing = 30 neighborhood = arcpy.sa.NbrRectangle( smoothing, smoothing, "CELL") flood_elev_raster = arcpy.sa.FocalStatistics( input_source, neighborhood, "MEAN", "true") flood_elev_raster.save(focal_raster) # con if use_in_memory: smooth_input = "in_memory/smooth_input" else: smooth_input = os.path.join( scratch_ws, "smooth_input") if arcpy.Exists(smooth_input): arcpy.Delete_management(smooth_input) output = arcpy.sa.Con(is_null0, input_source, flood_elev_raster) output.save(smooth_input) input_raster = smooth_input else: input_raster = input_source else: raise NotSupported # use numeric value for determining non flooded areas: set these values to NoData. We need NoData for clippng later on if no_flood_value != "NoData": if common_lib.is_number(no_flood_value): msg_body = create_msg_body( "Setting no flood value: " + no_flood_value + " to NoData in copy of " + common_lib.get_name_from_feature_class( input_raster) + "...", 0, 0) msg(msg_body) if use_in_memory: null_for_no_flooded_areas_raster = "in_memory/null_for_flooded" else: null_for_no_flooded_areas_raster = os.path.join( scratch_ws, "null_for_flooded") if arcpy.Exists( null_for_no_flooded_areas_raster): arcpy.Delete_management( null_for_no_flooded_areas_raster) whereClause = "VALUE = " + no_flood_value # Execute SetNull outSetNull_temp = arcpy.sa.SetNull( input_raster, input_raster, whereClause) outSetNull_temp.save( null_for_no_flooded_areas_raster) input_raster = null_for_no_flooded_areas_raster else: raise ValueError else: pass msg_body = create_msg_body( "Checking for NoData values in raster: " + common_lib.get_name_from_feature_class(input_raster) + ". NoData values are considered to be non-flooded areas!", 0, 0) msg(msg_body) max_value = arcpy.GetRasterProperties_management( is_null0, "MAXIMUM")[0] # has_nodata = arcpy.GetRasterProperties_management(input_raster, "ANYNODATA")[0] ## fails on some rasters if int(max_value) == 1: # 1. get the outline of the raster as polygon via RasterDomain xy_unit = common_lib.get_xy_unit(input_raster, 0) if xy_unit: cell_size = arcpy.GetRasterProperties_management( input_raster, "CELLSIZEX") if baseline_elevation_raster: # check celll size cell_size_base = arcpy.GetRasterProperties_management( baseline_elevation_raster, "CELLSIZEX") if cell_size_base.getOutput( 0) == cell_size.getOutput(0): # Execute Plus if use_in_memory: flood_plus_base_raster = "in_memory/flooding_plus_base" else: flood_plus_base_raster = os.path.join( scratch_ws, "flooding_plus_base") if arcpy.Exists( flood_plus_base_raster): arcpy.Delete_management( flood_plus_base_raster) listRasters = [] listRasters.append(input_raster) listRasters.append( baseline_elevation_raster) desc = arcpy.Describe(listRasters[0]) arcpy.MosaicToNewRaster_management( listRasters, scratch_ws, "flooding_plus_base", desc.spatialReference, "32_BIT_FLOAT", cell_size, 1, "SUM", "") # check where there is IsNull and set the con values if use_in_memory: is_Null = "in_memory/is_Null" else: is_Null = os.path.join( scratch_ws, "is_Null") if arcpy.Exists(is_Null): arcpy.Delete_management(is_Null) is_Null_raster = arcpy.sa.IsNull( input_raster) is_Null_raster.save(is_Null) # Con if use_in_memory: flood_plus_base_raster_null = "in_memory/flooding_plus_base_null" else: flood_plus_base_raster_null = os.path.join( scratch_ws, "flooding_plus_base_null") if arcpy.Exists( flood_plus_base_raster_null): arcpy.Delete_management( flood_plus_base_raster_null) msg_body = create_msg_body( "Adding baseline elevation raster to input flood layer...", 0, 0) msg(msg_body) fpbrn = arcpy.sa.Con( is_Null, input_raster, flood_plus_base_raster) fpbrn.save(flood_plus_base_raster_null) input_raster = flood_plus_base_raster_null else: arcpy.AddWarning( "Cell size of " + input_raster + " is different than " + baseline_elevation_raster + ". Ignoring Base Elevation Raster.") else: if baseline_elevation_value > 0: if use_in_memory: flood_plus_base_raster = "in_memory/flood_plus_base" else: flood_plus_base_raster = os.path.join( scratch_ws, "flooding_plus_base") if arcpy.Exists( flood_plus_base_raster): arcpy.Delete_management( flood_plus_base_raster) arcpy.Plus_3d(input_raster, baseline_elevation_value, flood_plus_base_raster) input_raster = flood_plus_base_raster msg_body = create_msg_body( "Creating 3D polygons...", 0, 0) msg(msg_body) if use_in_memory: raster_polygons = "in_memory/raster_polygons" else: raster_polygons = os.path.join( scratch_ws, "raster_polygons") if arcpy.Exists(raster_polygons): arcpy.Delete_management(raster_polygons) out_geom = "POLYGON" # output geometry type arcpy.RasterDomain_3d(input_raster, raster_polygons, out_geom) # 2. buffer it inwards so that we have a polygon only of the perimeter plus a few ???????cells inward???????. if use_in_memory: polygons_inward = "in_memory/inward_buffer" else: polygons_inward = os.path.join( scratch_ws, "inward_buffer") if arcpy.Exists(polygons_inward): arcpy.Delete_management(polygons_inward) x = float( re.sub("[,.]", ".", str(cell_size.getOutput(0)))) # x = float(str(cell_size.getOutput(0))) if x < 0.1: arcpy.AddError( "Raster cell size is 0. Can't continue. Please check the raster properties." ) raise ValueError else: buffer_in = 3 * int(x) if xy_unit == "Feet": buffer_text = "-" + str( buffer_in) + " Feet" else: buffer_text = "-" + str( buffer_in) + " Meters" sideType = "OUTSIDE_ONLY" arcpy.Buffer_analysis(raster_polygons, polygons_inward, buffer_text, sideType) msg_body = create_msg_body( "Buffering flood edges...", 0, 0) msg(msg_body) # 3. mask in ExtractByMask: gives just boundary raster with a few cells inwards if use_in_memory: extract_mask_raster = "in_memory/extract_mask" else: extract_mask_raster = os.path.join( scratch_ws, "extract_mask") if arcpy.Exists(extract_mask_raster): arcpy.Delete_management( extract_mask_raster) extract_temp_raster = arcpy.sa.ExtractByMask( input_raster, polygons_inward) extract_temp_raster.save(extract_mask_raster) # 4. convert the output to points if use_in_memory: extract_mask_points = "in_memory/extract_points" else: extract_mask_points = os.path.join( scratch_ws, "extract_points") if arcpy.Exists(extract_mask_points): arcpy.Delete_management( extract_mask_points) arcpy.RasterToPoint_conversion( extract_mask_raster, extract_mask_points, "VALUE") msg_body = create_msg_body( "Create flood points...", 0, 0) msg(msg_body) # 5. Interpolate: this will also interpolate outside the flood boundary which is # what we need so we get a nice 3D poly that extends into the surrounding DEM if use_in_memory: interpolated_raster = "in_memory/interpolate_raster" else: interpolated_raster = os.path.join( scratch_ws, "interpolate_raster") if arcpy.Exists(interpolated_raster): arcpy.Delete_management( interpolated_raster) zField = "grid_code" power = 2 searchRadius = arcpy.sa.RadiusVariable( 12, 150000) msg_body = create_msg_body( "Interpolating flood points...", 0, 0) msg(msg_body) # Execute IDW out_IDW = arcpy.sa.Idw(extract_mask_points, zField, cell_size, power) # Save the output out_IDW.save(interpolated_raster) extent_poly = common_lib.get_extent_feature( scratch_ws, polygons_inward) msg_body = create_msg_body( "Clipping terrain...", 0, 0) msg(msg_body) # clip the input surface if use_in_memory: extent_clip_idwraster = "in_memory/extent_clip_idw" else: extent_clip_idwraster = os.path.join( scratch_ws, "extent_clip_idw") if arcpy.Exists(extent_clip_idwraster): arcpy.Delete_management( extent_clip_idwraster) # clip terrain to extent arcpy.Clip_management(interpolated_raster, "#", extent_clip_idwraster, extent_poly) # 6. clip the interpolated raster by (outward buffered) outline polygon if use_in_memory: polygons_outward = "in_memory/outward_buffer" else: polygons_outward = os.path.join( scratch_ws, "outward_buffer") if arcpy.Exists(polygons_outward): arcpy.Delete_management( polygons_outward) outward_buffer += 0.5 * int( x ) # we buffer out by half the raster cellsize if outward_buffer > 0: if xy_unit == "Feet": buffer_text = str( outward_buffer) + " Feet" else: buffer_text = str( outward_buffer) + " Meters" sideType = "FULL" arcpy.Buffer_analysis( raster_polygons, polygons_outward, buffer_text, sideType) raster_polygons = polygons_outward # clip the input surface if use_in_memory: flood_clip_raster = "in_memory/flood_clip_raster" else: flood_clip_raster = os.path.join( scratch_ws, "flood_clip_raster") if arcpy.Exists(flood_clip_raster): arcpy.Delete_management( flood_clip_raster) msg_body = create_msg_body( "Clipping flood raster...", 0, 0) msg(msg_body) # clip terrain to extent # arcpy.Clip_management(interpolated_raster, "#", flood_clip_raster, raster_polygons) Check again arcpy.Clip_management(interpolated_raster, "#", flood_clip_raster, raster_polygons) # 7. Isnull, and Con to grab values from flood_clip_raster for # create NUll mask if use_in_memory: is_Null = "in_memory/is_Null" else: is_Null = os.path.join( scratch_ws, "is_Null") if arcpy.Exists(is_Null): arcpy.Delete_management(is_Null) is_Null_raster = arcpy.sa.IsNull(input_raster) is_Null_raster.save(is_Null) # Con if use_in_memory: con_raster = "in_memory/con_raster" else: con_raster = os.path.join( scratch_ws, "con_raster") if arcpy.Exists(con_raster): arcpy.Delete_management(con_raster) temp_con_raster = arcpy.sa.Con( is_Null, interpolated_raster, input_raster) temp_con_raster.save(con_raster) msg_body = create_msg_body( "Merging rasters...", 0, 0) msg(msg_body) # 8. focal stats on raster to smooth? # 9. copy raster to geotiff if use_in_memory: con_raster_tif = "in_memory/con_raster_tif" else: con_raster_tif = os.path.join( tiff_directory, "con_raster.tif") if arcpy.Exists(con_raster_tif): arcpy.Delete_management(con_raster_tif) arcpy.CopyRaster_management( con_raster, con_raster_tif, "#", "#", "#", "#", "#", "32_BIT_FLOAT") msg_body = create_msg_body( "Copying to tiff...", 0, 0) msg(msg_body) # 10. raster to TIN zTol = 0.1 maxPts = 1500000 zFactor = 1 con_tin = os.path.join(tin_directory, "con_tin") if arcpy.Exists(con_tin): arcpy.Delete_management(con_tin) # Execute RasterTin arcpy.RasterTin_3d(con_raster_tif, con_tin, zTol, maxPts, zFactor) msg_body = create_msg_body( "Creating TIN...", 0, 0) msg(msg_body) # 11. TIN triangles if use_in_memory: con_triangles = "in_memory/con_triangles" else: con_triangles = os.path.join( scratch_ws, "con_triangles") if arcpy.Exists(con_triangles): arcpy.Delete_management(con_triangles) arcpy.TinTriangle_3d(con_tin, con_triangles) msg_body = create_msg_body( "Creating polygons...", 0, 0) msg(msg_body) # 12. make 2D polygons feature to feature class arcpy.FeatureClassToFeatureClass_conversion( con_triangles, scratch_ws, "con_triangles_2D") # 12. clip with smooth polygon smooth_polygons = os.path.join( scratch_ws, "smooth_raster_polygons") if arcpy.Exists(smooth_polygons): arcpy.Delete_management(smooth_polygons) msg_body = create_msg_body( "Smoothing edges...", 0, 0) msg(msg_body) CA.SmoothPolygon(os.path.join(raster_polygons), smooth_polygons, "PAEK", x, "", "FLAG_ERRORS") if use_in_memory: clip_smooth_triangles = "in_memory/clip_smooth_triangles" else: clip_smooth_triangles = os.path.join( scratch_ws, "clip_smooth_triangles") if arcpy.Exists(clip_smooth_triangles): arcpy.Delete_management( clip_smooth_triangles) msg_body = create_msg_body( "Clipping smooth edges...", 0, 0) msg(msg_body) # clip terrain to extent arcpy.Clip_analysis(con_triangles, smooth_polygons, clip_smooth_triangles) # clip to slightly lesser extent because of InterpolateShape fail. area_extent = common_lib.get_extent_feature( scratch_ws, clip_smooth_triangles) if use_in_memory: extent_inward = "in_memory/inward_extent_buffer" else: extent_inward = os.path.join( scratch_ws, "inward_extent_buffer") if arcpy.Exists(extent_inward): arcpy.Delete_management(extent_inward) buffer_in = 3 if xy_unit == "Feet": buffer_text = "-" + str( buffer_in) + " Feet" else: buffer_text = "-" + str( buffer_in) + " Meters" sideType = "FULL" arcpy.Buffer_analysis(area_extent, extent_inward, buffer_text, sideType) if use_in_memory: clip2_smooth_triangles = "in_memory/clip2_smooth_triangles" else: clip2_smooth_triangles = os.path.join( scratch_ws, "clip2_smooth_triangles") if arcpy.Exists(clip2_smooth_triangles): arcpy.Delete_management( clip2_smooth_triangles) msg_body = create_msg_body( "Clipping smooth edges a second time...", 0, 0) msg(msg_body) # clip terrain to extent arcpy.Clip_analysis(clip_smooth_triangles, extent_inward, clip2_smooth_triangles) # 13. interpolate on TIN if use_in_memory: clip_smooth_triangles3D = "in_memory/clip_smooth_traingles3D" else: clip_smooth_triangles3D = os.path.join( scratch_ws, "clip_smooth_triangles3D") if arcpy.Exists(clip_smooth_triangles3D): arcpy.Delete_management( clip_smooth_triangles3D) msg_body = create_msg_body( "Interpolating polygons on TIN", 0, 0) msg(msg_body) arcpy.InterpolateShape_3d( con_tin, clip2_smooth_triangles, clip_smooth_triangles3D, "#", 1, "LINEAR", "VERTICES_ONLY") # 13. to multipatch z_unit = common_lib.get_z_unit( clip_smooth_triangles3D, verbose) # temp layer flood_level_layer = "flood_level_layer" arcpy.MakeFeatureLayer_management( clip_smooth_triangles3D, flood_level_layer) # flood_level_mp = os.path.join(project_ws, common_lib.get_name_from_feature_class(input_raster) + "_3D") flood_level_mp = output_polygons + "_3D" if arcpy.Exists(flood_level_mp): arcpy.Delete_management(flood_level_mp) arcpy.Layer3DToFeatureClass_3d( flood_level_layer, flood_level_mp) # layer to be added to TOC flood_level_layer_mp = common_lib.get_name_from_feature_class( flood_level_mp) arcpy.MakeFeatureLayer_management( flood_level_mp, flood_level_layer_mp) # apply transparency here // checking if symbology layer is present if z_unit == "Feet": floodSymbologyLayer = layer_directory + "\\flood3Dfeet.lyrx" else: floodSymbologyLayer = layer_directory + "\\flood3Dmeter.lyrx" if not arcpy.Exists(floodSymbologyLayer): arcpy.AddWarning( "Can't find: " + floodSymbologyLayer + ". Symbolize features by error attribute to see data errors." ) arcpy.AddMessage("Results written to: " + output_polygons) if use_in_memory: arcpy.Delete_management("in_memory") if DeleteIntermediateData: fcs = common_lib.listFcsInGDB(scratch_ws) msg_prefix = "Deleting intermediate data..." msg_body = common_lib.create_msg_body( msg_prefix, 0, 0) common_lib.msg(msg_body) for fc in fcs: arcpy.Delete_management(fc) return flood_level_layer_mp # 14. adjust 3D Z feet to meters??? else: raise NoUnits else: raise NoNoDataError end_time = time.clock() msg_body = create_msg_body( "Create 3D Flood Leveles completed successfully.", start_time, end_time) else: raise NotProjected else: raise LicenseErrorSpatial else: raise LicenseError3D arcpy.ClearWorkspaceCache_management() msg(msg_body) except NotProjected: print( "Input data needs to be in a projected coordinate system. Exiting..." ) arcpy.AddError( "Input data needs to be in a projected coordinate system. Exiting..." ) except NoLayerFile: print("Can't find Layer file. Exiting...") arcpy.AddError("Can't find Layer file. Exiting...") except LicenseError3D: print("3D Analyst license is unavailable") arcpy.AddError("3D Analyst license is unavailable") except LicenseErrorSpatial: print("Spatial Analyst license is unavailable") arcpy.AddError("Spatial Analyst license is unavailable") except NoNoDataError: print("Input raster does not have NODATA values") arcpy.AddError("Input raster does not have NODATA values") except NoUnits: print("No units detected on input data") arcpy.AddError("No units detected on input data") except NoPolygons: print("Input data can only be polygon features or raster datasets.") arcpy.AddError( "Input data can only be polygon features or raster datasets.") except ValueError: print("Input no flood value is not a number.") arcpy.AddError("Input no flood value is not a number.") except arcpy.ExecuteError: line, filename, synerror = trace() msg("Error on %s" % line, ERROR) msg("Error in file name: %s" % filename, ERROR) msg("With error message: %s" % synerror, ERROR) msg("ArcPy Error Message: %s" % arcpy.GetMessages(2), ERROR) except FunctionError as f_e: messages = f_e.args[0] msg("Error in function: %s" % messages["function"], ERROR) msg("Error on %s" % messages["line"], ERROR) msg("Error in file name: %s" % messages["filename"], ERROR) msg("With error message: %s" % messages["synerror"], ERROR) msg("ArcPy Error Message: %s" % messages["arc"], ERROR) except: line, filename, synerror = trace() msg("Error on %s" % line, ERROR) msg("Error in file name: %s" % filename, ERROR) msg("with error message: %s" % synerror, ERROR) finally: arcpy.CheckInExtension("3D") arcpy.CheckInExtension("Spatial")
bufferSize = str(cellSize) + " Feet" else: bufferSize = str(cellSize) + " Unknown" arcpy.Buffer_analysis(stationTemp, stationBuffer, bufferSize, "FULL", "ROUND", "NONE", "") arcpy.sa.ZonalStatisticsAsTable(stationBuffer, "STATIONID", DEM_aoi, stationElev, "NODATA", "ALL") arcpy.AddJoin_management(stationLyr, "StationID", stationElev, "StationID", "KEEP_ALL") expression = "round(!stationElev.MEAN! * " + str(Zfactor) + ",1)" arcpy.CalculateField_management(stationLyr, "stations.POINT_Z", expression, "PYTHON") arcpy.RemoveJoin_management(stationLyr, "stationElev") arcpy.DeleteField_management(stationTemp, "STATIONID; POINT_M") del expression # ---------------------------------------------------------------------- Create final output # Interpolate Line to 3d via Z factor arcpy.InterpolateShape_3d(DEM_aoi, lineTemp, outLine, "", Zfactor) # Copy Station Points arcpy.CopyFeatures_management(stationTemp, outPoints) # Copy output to tables folder arcpy.CopyRows_management(outPoints, pointsTable, "") arcpy.CopyRows_management(stakeoutPoints, stakeoutTable, "") # ------------------------------------------------------------------- Delete Temp Layers AddMsgAndPrint("\nDeleting temporary files..\n",0) layersToRemove = (lineTemp,routes,stationTable,stationEvents,stationTemp,stationLyr,stationBuffer,stationElev) x = 0 for layer in layersToRemove: if arcpy.Exists(layer):
arcpy.env.workspace = scratchDir #add an rkey field to the table that consists of values from the OID desc = arcpy.Describe(xsecLayer) idField = desc.OIDFieldName addAndCalc(xsecLayer, 'ORIG_FID', '[' + idField + ']') #interpolate the line to add z values #despite the documentation for InterpolateShape, the function may not deal #appropriately with spatial references that differ between the features and the surface #particularly if one is UTM and one is state plane in feet #the user may have to re-project the surface to the same as the features #should this be a fatal error with a warning? zLine = xsecName + '_z' arcpy.AddMessage('Getting elevation values for cross-section line in ' + xsecLayer) arcpy.InterpolateShape_3d(dem, xsecLayer, zLine) arcpy.AddMessage(' ' + zLine + ' written to ' + scratchDir) #measure the lines zmLine = xsecName + '_zm' arcpy.AddMessage('Measuring the length of the line in ' + zLine) arcpy.CreateRoutes_lr(zLine, 'ORIG_FID', zmLine, 'LENGTH', '#', '#', cp) arcpy.AddMessage(' ' + zmLine + ' written to ' + scratchDir) #intersect with lines layer #creates a table with only the original FIDs of the input features. #FID field is named FID_<fcname> so we can find it later to transfer attributes #otherwise, we get a ton of fields, which may be redundant if the same feature class #(with different selections or definition queries) is being passed for both #the cross-section layer and the lines layer, which was the case when I was developing, #that is, I was looking for intersections between the main cross-section line and
# Tarkistetaan lisenssi arcpy.CheckOutExtension("3D") # Korkeusmalli surface = r"[fp]" # Käydään läpi segmentoidut reitit for fc in segmentList: if "Split_AC" in fc: # vaihdetaan ja yhtenäistetään nimet newname = fc.replace("Split_A", "Z") elif "Split_LC" in fc: newname = fc.replace("Split_L", "Z") outFC = os.path.join(path_3D, newname) # output feature class method = "BILINEAR" # InterpolateShape arcpy.InterpolateShape_3d(surface, fc, outFC, "", 1, method) # Lisätään kenttä reitin nimelle arcpy.AddField_management(outFC, "Name", "STRING") # Lisätään kenttä gradientin laskemiseksi arcpy.AddField_management(outFC, "Gradientti", "DOUBLE") # Lisätään nimi name = "'" + newname + "'" arcpy.CalculateField_management(outFC, "Name", name, "PYTHON_9.3") # Lasketaan gradientti lausekkeen avulla expression = "(!Shape!.lastPoint.Z- !Shape!.firstPoint.Z)/ !Shape!.length*100" arcpy.CalculateField_management(outFC, "Gradientti", expression, "PYTHON_9.3") # Poistetaan pelkkä splitattu reitti arcpy.Delete_management(fc)
####################### End User Defined Inputs ############################## #### KRB August 2014 update notes # 1. add something that checks the inputs (e.g. inPoly must be a line) # 2. The problem that billy has comes from interpolateshape3D with no data # values in the underlying raster. See if there is an interpolation method that # fixes this. Alternatively we can brute force fix this. Or just interpolate to # a dummy raster with the same cell size and locations but full of ones. #Fortunatly zonal statistics can deal with no-data values. method = 'LINEAR' print "interpolate line to the raster" coordSys = arcpy.Describe(inPoly).spatialReference.exporttostring() arcpy.InterpolateShape_3d(dummyInterpRast, inPoly, tempPoly, height, 1, method) # initialize output part 1 xOut = [] yOut = [] print "get all points along the swath line" ptArray = [] rows = arcpy.SearchCursor(tempPoly) for row in rows: points = row.shape.getPart(0) for point in points: xOut.append(point.X) yOut.append(point.Y) ptArray.append([point.X, point.Y]) del row, rows
if HeightField == '#' or not HeightField: HeightField = "defBaseH" # provide a default value if unspecified arcpy.AddField_management(Output_Point, HeightField, "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") arcpy.CalculateField_management(Output_Point, HeightField, "0", "VB", "") if ShieldField == '#' or not ShieldField: ShieldField = "defShed" # provide a default value if unspecified # Process: Add Field arcpy.AddField_management(Output_Point, ShieldField, "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") ####3/5/2020: Use the Interpolate Shape tool to extract DEM values to a 3D feature output arcpy.InterpolateShape_3d(Input_DEM, Output_Point, point3d) # An interation of all points. Each point will be selected and run the skyline and skyline graph functions to calculate the shielding and # then assign the shielding value to the output file. The corresponding output row is determined by Select by Attribute function nCount = arcpy.GetCount_management(point3d) for i in range(int(nCount[0])): #Start from 0: only for shapefile con_for_shp = "FID = " + str( i) #if the output is a shapefile, FID starts from 0 con_for_fc = "ObjectID = " + str( i + 1) #if the output is a feature class, FID starts from 1 arcpy.AddMessage("Processing Point #" + str(i)) #Select each feature for Skyline analysis arcpy.Select_analysis(point3d, singlePoint3d, con_for_shp) #Select by attribute for output for saving shielding result if (out_is_shapefile > 0): arcpy.SelectLayerByAttribute_management(output_layer, "NEW_SELECTION",
arcpy.env.overwriteOutput = True scratchDir = arcpy.env.scratchWorkspace arcpy.env.workspace = scratchDir if arcpy.Exists(outFC): arcpy.Delete_management(outFC) #add an ORIG_FID field to the table that consists of values from the OID desc = arcpy.Describe(lineLayer) idField = desc.OIDFieldName addAndCalc(lineLayer, 'ORIG_FID', '[' + idField + ']') #interpolate the line to add z values zLine = lineLyrName + '_z' arcpy.AddMessage('Getting elevation values for the cross-section in ' + lineLyrName) arcpy.InterpolateShape_3d(dem, lineLayer, zLine) arcpy.AddMessage(' ' + zLine + ' written to ' + arcpy.env.scratchWorkspace) #measure it and turn it into a route zmLine = lineLyrName + '_zm' if arcpy.Exists(zmLine): arcpy.Delete_management(zmLine) arcpy.AddMessage('Measuring the length of ' + zLine) arcpy.CreateRoutes_lr(zLine, 'ORIG_FID', zmLine, 'LENGTH', '#', '#', cp) arcpy.AddMessage(' ' + zmLine + ' written to ' + arcpy.env.scratchWorkspace) #select points according to the section distance arcpy.SelectLayerByLocation_management(ptLayer, 'WITHIN_A_DISTANCE', zmLine, buff) zPts = outName + '_z'
array.add(point) NumberofPoints = len(coords) arcpy.CalculateField_management('line2.shp', 'numPnts', str(NumberofPoints)) Polyline = arcpy.Polyline(array) Cursor.insertRow([Polyline]) del Cursor print "*******Part II********" print "Conducting 3D analysis" #Extensions, such as 3D analyst and Spatial Analyst must be "Checked Out" to use arcpy.CheckOutExtension("3D") print "Creating 3D shape" #use 2D polyline and DEM to create 3D polyline. Hint: use InterpolateShape_3d function arcpy.InterpolateShape_3d('dem_lab2', 'line2.shp', '3DLine.shp') print "Adding fields." #Add fields (numPnts, 2Dlength and 3Dlength) to 3D feature class arcpy.AddField_management('3dLine.shp', 'length2d', 'FLOAT') arcpy.AddField_management('3dLine.shp', 'length3d', 'FLOAT') print "updating fields" #use cursor to populate numPnts, 2D and 3D length fieldss length2D = arcpy.da.SearchCursor('3dLine.shp', 'SHAPE@LENGTH').next() length2Dbutnotatuple = length2D[0] arcpy.CalculateField_management('3dLine.shp', 'length2d', length2Dbutnotatuple) cursor2 = arcpy.da.SearchCursor('3dLine.shp', 'SHAPE@').next() for geom in cursor2: length3D = geom.length3D
import arcpy from arcpy.sa import * import os pointFC = r"Q:\arcpy-scripts\VerticleBufferScript\New File Geodatabase.gdb\test_point" origDEM = r"Q:\arcpy-scripts\VerticleBufferScript\New File Geodatabase.gdb\zion_dem_utm12" elevDiff = 25 arcpy.InterpolateShape_3d(origDEM, pointFC, os.path.join(pointFC + "_3d")) interpShapeFC = r"Q:\arcpy-scripts\VerticleBufferScript\New File Geodatabase.gdb\test_point_3d" arcpy.AddField_management(interpShapeFC, "BufferZ", "DOUBLE") zCurs = arcpy.UpdateCursor(interpShapeFC, ["SHAPE", "BufferZ"]) for row in zCurs: print(row.getValue("name") + " " + str(row.getValue("SHAPE").getPart().Z)) elev = row.getValue("SHAPE").getPart().Z + elevDiff row.setValue("BufferZ", elev) zCurs.updateRow(row)
arcpy.CheckInExtension("3D") outTin = os.path.splitext(os.path.basename(RasterFile))[0] + "_TIN" print("Creating TIN from " + RasterFile + ".") # Set local variables maxPts = 1500000 zFactor = 1 # Excecute RasterTin in_surface = arcpy.RasterTin_3d(RasterFile, outTin, "", maxPts, zFactor) print("Finished.") # Create a line feature: in_feature_class = arcpy.GetParameterAsText( 2) # Set data parameter as "Feature Set" # eg., in_feature_class="C:/Users/oc3512/Documents/ArcGIS/Projects/MMSP/MMSP_utm.gdb/Elevation_profile" # Name the Output (elevation profile) line to be used for creating Elevation profile out_feature_class = arcpy.GetParameterAsText(3) outFC = os.path.join(outFolder, out_feature_class) # Interpolate shape arcpy.InterpolateShape_3d(in_surface, in_feature_class, outFC) except LicenseError: print("3D Analyst license is unavailable") except arcpy.ExecuteError: print(arcpy.GetMessages(2))
str(demSR.factoryCode)) # rename inPts xlbt2 = xlbt + '_2' testAndDelete(xlbt2) arcpy.Rename_management(xlbt, xlbt2) # project inPts2 arcpy.Project_management(xlbt2, xlbt, demSR) testAndDelete(xlbt2) ## add z values addMsgAndPrint('Adding Z values') arcpy.CheckOutExtension('3D') xlbtdz = xlbt + '_dz' testAndDelete(xlbtdz) # note that we densify arcpy.InterpolateShape_3d(dem, xlbt, xlbtdz, dens, 1, 'BILINEAR', 'DENSIFY') if nRows(xlbtdz) == 0: print ' Bedding trace(s) appear to be outside extent of DEM' forceExit() ## Make point lists addMsgAndPrint('Building point lists') xyzListd, meanXYZd = makeXyzList(xlbtdz, stackLines) ## Fit a plane addMsgAndPrint('Fitting a plane') strike, dip, eigenVals, eigenVects, centroid, n = planeFit(xyzListd) strike = strike + gridDec # Fernandez, 2005; Woodcock, 1977, Gallo and others (2018) M = math.log(eigenVals[0] / eigenVals[2]) K = math.log(eigenVals[0] / eigenVals[1]) / math.log(
arcpy.env.workspace = scratchDir #add an rkey field to the table that consists of values from the OID desc = arcpy.Describe(xsecLayer) idField = desc.OIDFieldName addAndCalc(xsecLayer, 'ORIG_FID', '[' + idField + ']') #interpolate the line to add z values #despite the documentation for InterpolateShape, the function may not deal #appropriately with spatial references that differ between the features and the surface #particularly if one is UTM and one is state plane in feet #the user may have to re-project the surface to the same as the features #should this be a fatal error with a warning? zLine = xsecName + '_z' arcpy.AddMessage('Getting elevation values for cross-section line in ' + xsecLayer) arcpy.InterpolateShape_3d(dem, xsecLayer, zLine) arcpy.AddMessage(' ' + zLine + ' written to ' + scratchDir) #measure the line zmLine = xsecName + '_zm' arcpy.AddMessage('Measuring the length of the line in ' + zLine) arcpy.CreateRoutes_lr(zLine, 'ORIG_FID', zmLine, 'LENGTH', '#', '#', cp) arcpy.AddMessage(' ' + zmLine + ' written to ' + scratchDir) #load the coordinates of the vertices into a dictionary and a list of M values dl = vertexDictionary(zmLine) vList = dl[0] vDict = dl[1] #all output classes need to be Z-aware arcpy.env.outputZFlag = 'Enabled'
def convert3D(inFC, inGrid): outFC = recycleName(inFC) arcpy.InterpolateShape_3d(inGrid, inFC, outFC) arcpy.Delete_management(inFC) arcpy.Rename_management(outFC, inFC)
ZonalStatisticsAsTable(stationBuffer, "STATIONID", ProjectDEM, stationElev, "NODATA", "ALL") arcpy.AddJoin_management(stationLyr, "StationID", stationElev, "StationID", "KEEP_ALL") expression = "round(!stationElev.MEAN! * " + str(Zfactor) + ",1)" arcpy.CalculateField_management(stationLyr, "stations.POINT_Z", expression, "PYTHON") arcpy.RemoveJoin_management(stationLyr, "stationElev") arcpy.DeleteField_management(stationTemp, "STATIONID; POINT_M") # ---------------------------------------------------------------------- Create final output # Interpolate Line to 3d via Z factor arcpy.InterpolateShape_3d(ProjectDEM, lineTemp, outLine, "", Zfactor) # Copy Station Points arcpy.CopyFeatures_management(stationTemp, outPoints) # Copy output to tables folder arcpy.CopyRows_management(outPoints, pointsTable) arcpy.CopyRows_management(stakeoutPoints, stakeoutTable) arcpy.Delete_management(stationElev) arcpy.Delete_management(stationTemp) # ------------------------------------------------------------------------------------------------ Compact FGDB arcpy.Compact_management(watershedGDB_path) AddMsgAndPrint("Successfully Compacted FGDB: " + os.path.basename(watershedGDB_path) + "\n")
buildCur = arcpy.da.InsertCursor(theme, 'SHAPE@') print "Populating geometry with array" buildCur.insertRow([poly]) arcpy.CalculateField_management(theme, 'numPnts', len(CoordList)) del buildCur print "************** part II ****************" print "Conducting 3D analysis" arcpy.CheckOutExtension("3D") #Check out the extention 3D print "Creating 3D shape" feature3d = arcpy.InterpolateShape_3d(env.workspace + "/dem_lab2", theme, "colo14ers_interp5.shp") interp = "colo14ers_interp5.shp" fields = ["length2D", "length3D"] dataset = env.workspace + "/dem_lab2" spatial_ref = arcpy.Describe(dataset).spatialReference print "Adding fields." arcpy.AddField_management(interp, "length2D", "FLOAT") arcpy.AddField_management(interp, "length3D", "FLOAT") print "updating fields" #use cursor to populate numPnts, 2D and 3D length fields updCur3 = arcpy.UpdateCursor(interp) updRow3 = updCur3.next() updCur2 = arcpy.UpdateCursor(theme)