def processFile(netcdf_file, input_fc, input_fc_10, input_fc_1, output_fc, output_fc_10, output_fc_1): print(config) logging.info("Processing NetCDF :: " + netcdf_file) # Get the number of time indexes (normally 66 hours) nc_FP = arcpy.NetCDFFileProperties(netcdf_file) top = nc_FP.getDimensionSize(config["nc_time_dimension"]) logging.info(str(top) + " time slices...") time_from_nc = nc_FP.getDimensionValue(config["nc_time_dimension"], 0) if len(time_from_nc) == 19: start_date = datetime.datetime.strptime(time_from_nc, "%d.%m.%Y %H:%M:%S") else: start_date = datetime.datetime.strptime(time_from_nc, "%d.%m.%Y") # For each time slice for i in range(0, top): # New time dimension dimension_value = config["nc_time_dimension"] + " " + str(i) new_time = start_date + datetime.timedelta(hours=i) logging.info("Processing date: " + new_time.strftime("%d.%m.%Y %H.%M") + " - index " + str(i)) # Update the time-field on the input data date_expr = "datetime.datetime(%s,%s,%s,%s,%s)" % (new_time.year, new_time.month, new_time.day, new_time.hour, new_time.minute) arcpy.CalculateField_management(input_fc, "time", date_expr) arcpy.CalculateField_management(input_fc_10, "time", date_expr) arcpy.CalculateField_management(input_fc_1, "time", date_expr) # For each variable for variable in ["air_temperature_2m", "cloud_area_fraction", "relative_humidity_2m", "low_type_cloud_area_fraction", "high_type_cloud_area_fraction", "precipitation_amount_acc"]: temp_raster = "temp_raster_%s_%s" % (i, variable) logging.info("Processing variable %s for date %s " % (variable, new_time)) # Create the raster for the given time/variable arcpy.MakeNetCDFRasterLayer_md(netcdf_file, variable, "x", "y", temp_raster, "#", dimension_value, "BY_INDEX") # Calculate the value on the input arcpy.AddSurfaceInformation_3d(input_fc, temp_raster, "Z_MEAN", "LINEAR") arcpy.AddSurfaceInformation_3d(input_fc_10, temp_raster, "Z_MEAN", "LINEAR") arcpy.AddSurfaceInformation_3d(input_fc_1, temp_raster, "Z_MEAN", "LINEAR") # Update the correct field arcpy.CalculateField_management(input_fc, variable, "!Z_MEAN!", "PYTHON_9.3") arcpy.CalculateField_management(input_fc_10, variable, "!Z_MEAN!", "PYTHON_9.3") arcpy.CalculateField_management(input_fc_1, variable, "!Z_MEAN!", "PYTHON_9.3") # Copy features to output fc logging.info("Copying output data for date %s" % new_time) arcpy.arcpy.Append_management([input_fc], output_fc) arcpy.arcpy.Append_management([input_fc_10], output_fc_10) arcpy.arcpy.Append_management([input_fc_1], output_fc_1)
def generateHighLow(workspace, name, clip_contours, ref_md): cont_poly1 = os.path.join(workspace, 'O12_poly_' + name + '.shp') cont_poly2 = os.path.join(workspace, 'O13_poly_' + name + '.shp') arcpy.FeatureToPolygon_management(in_features=clip_contours, out_feature_class=cont_poly1, cluster_tolerance="", attributes="ATTRIBUTES", label_features="") arcpy.MultipartToSinglepart_management(in_features=cont_poly1, out_feature_class=cont_poly2) select_set = [] with arcpy.da.UpdateCursor( cont_poly2, ["FID", "SHAPE@"]) as cursor: # @UndefinedVariable for row in cursor: parts = row[1].partCount boundaries = row[1].boundary().partCount if boundaries > parts: select_set.append(row[0]) cont_poly3 = 'O13_poly_' + name + '_layer' arcpy.MakeFeatureLayer_management(in_features=cont_poly2, out_layer=cont_poly3, where_clause='"FID" IN(' + ','.join(select_set) + ')', workspace="", field_info="") arcpy.DeleteFeatures_management(cont_poly3) arcpy.AddSurfaceInformation_3d(in_feature_class=cont_poly2, in_surface=ref_md, out_property="Z_MEAN", method="BILINEAR")
def locateEventTable(gdb,inFC,pts,dem,sDistance,eventProperties,zType,isLines = False): desc = arcpy.Describe(pts) if not desc.hasZ: addMsgAndPrint(' adding Z values') arcpy.AddSurfaceInformation_3d (pts, dem, zType, 'LINEAR') ## working around bug in LocateFeaturesAlongRoutes # add special field for duplicate detection dupDetectField = 'xDupDetect' arcpy.AddField_management(pts,dupDetectField,'LONG') # and calc this field = OBJECTID OID = arcpy.Describe(pts).OIDFieldName expr = '"!'+OID+'!"' arcpy.CalculateField_management(pts,dupDetectField,expr,"PYTHON") # locate linePts along route addMsgAndPrint(' making event table') eventTable = gdb+'/evTb_'+inFC testAndDelete(eventTable) arcpy.LocateFeaturesAlongRoutes_lr(pts,ZMline,idField,sDistance,eventTable,eventProperties) nRows = numberOfRows(eventTable) nPts = numberOfRows(pts) if nRows > nPts and not isLines: # if LocateFeaturesAlongRoutes has made duplicates (A BUG!) addMsgAndPrint(' correcting for bug in LocateFeaturesAlongRoutes') addMsgAndPrint(' '+str(nRows)+' rows in event table') addMsgAndPrint(' removing duplicate entries in event table') arcpy.DeleteIdentical_management(eventTable, dupDetectField) addMsgAndPrint(' '+str(numberOfRows(eventTable))+' rows in event table') arcpy.DeleteField_management(eventTable,dupDetectField) return eventTable
def add_elevation(points, dem="", detrend_dem=""): """ Adds elevation fields to the input feature class. Writes all outputs to the environment workspace. Args: points -- Path to a point feature class dem -- Path to the digital elevation model (DEM) detrend_dem -- Path to the detrended digital elevation model (DEM) Outputs: elevation attributes written to the input feature class """ # Add elevations to the `points` feature class if dem: arcpy.AddSurfaceInformation_3d(in_feature_class=points, in_surface=dem, out_property="Z", z_factor=1.0) # Change `Z` field name to `DEM_Z` arcpy.AlterField_management(in_table=points, field="Z", new_field_name="DEM_Z") arcpy.AddMessage("Added DEM elevations") else: arcypy.AddMessage("Error: DEM not supplied") # Add detrended elevations to the `points` feature class if detrend_dem: arcpy.AddSurfaceInformation_3d(in_feature_class=points, in_surface=detrend_dem, out_property="Z", z_factor=1.0) # Change `Z` field name to `Detrend_DEM_Z` arcpy.AlterField_management(in_table=points, field="Z", new_field_name="Detrend_DEM_Z") arcpy.AddMessage("Added Detrended DEM elevations") else: arcpy.AddMessage("Warning: Detrended DEM not supplied")
def getDepthFromTif(tifPath, table): arcpy.AddMessage('getDepthFromTif()') arcpy.AddSurfaceInformation_3d(table, tifPath, "Z") arcpy.AddField_management(table, "Depth", "DOUBLE") fields = ["Z", "elevation", "Depth"] with arcpy.da.UpdateCursor(table, fields) as cursor: for row in cursor: if row[1] is None: row[2] = -10 else: row[2] = row[0] - row[1] cursor.updateRow(row)
print("\nGenerating Random Points on: \n {0} for the DEM".format(buildingFC)) RandomPointsDEM = "PointsDEM" DistanceApart2 = "1 FEET" DEMPoints = arcpy.CreateRandomPoints_management(FileGDB, RandomPointsDEM, buildingFC, "", 200, DistanceApart2, "MULTIPOINT") print("\nRandom points generated for DEM...") #Step 4: Adding Surface Information to both Point Feature Classes print("\nAdding Surface information to DSM points...") PointsDSM = DSMPoints elevationSurfaceDSM = r"C:\Users\1594783367E\Desktop\Andy_GIO\Projects\Multipatch_Buildings\Mosaic2NewRaster\Andrews_DSM_ALLMERGE.tif" OutputProperty1 = ['Z_MIN', 'Z_MAX', 'Z_MEAN'] surfaceDSM = arcpy.AddSurfaceInformation_3d(PointsDSM, elevationSurfaceDSM, OutputProperty1) print("\nAdding Surface information to DEM Points...") PointsDEM = DEMPoints elevationSurfaceDEM = r"C:\Users\1594783367E\Desktop\Andy_GIO\Projects\Multipatch_Buildings\Mosaic2NewRaster\Andrews_DEM_ALLMERGE.tif" OutputProperty2 = ['Z_MIN', 'Z_MAX', 'Z_MEAN'] surfaceDEM = arcpy.AddSurfaceInformation_3d(PointsDEM, elevationSurfaceDEM, OutputProperty2) arcpy.CheckInExtension('3D') #Step 5: Do a Spatial Join on both DEM Points and DSM Points print("\nJoining DSM Points with Building Features...") TargetFC = buildingFC OutputName = "BuildingsDSM"
arcpy.AddField_management('{}lfp_points_table_{}'.format(PROCESS_GDB, i), 'Y', 'DOUBLE') with arcpy.da.InsertCursor('{}lfp_points_table_{}'.format(PROCESS_GDB, i), ['X', 'Y']) as cur: for row in lfp_points: cur.insertRow(row) arcpy.MakeXYEventLayer_management( '{}lfp_points_table_{}'.format(PROCESS_GDB, i), 'X', 'Y', 'lfp_points_layer') arcpy.FeatureToPoint_management( 'lfp_points_layer', '{}/lfp_points_points_{}'.format(PROCESS_GDB, i)) arcpy.SplitLineAtPoint_management( '{}/Layers/longestflowpath_{}.shp'.format(HOME_DIRECTORY, i), '{}/lfp_points_points_{}'.format(PROCESS_GDB, i), '{}/slope_lines_{}'.format(PROCESS_GDB, i), '0 feet') arcpy.AddSurfaceInformation_3d('{}/slope_lines_{}'.format(PROCESS_GDB, i), TEMP_DEM, 'AVG_SLOPE') slope_numerator = 0 slope_denominator = 0 with arcpy.da.SearchCursor('{}/slope_lines_{}'.format(PROCESS_GDB, i), ['Shape_Length', 'Avg_Slope']) as cur: for row in cur: slope_numerator += row[0] * (row[1] * 0.01)**0.24 slope_denominator += row[0] weighted_slope = (slope_numerator / slope_denominator)**4.17 print( 'Catchment length-weighted slope [ft/ft] = {}'.format(weighted_slope)) arcpy.SelectLayerByAttribute_management(in_layer_or_view=basins, where_clause=clause_ID_FIELD)
if row[0] == "" or row[0] == None: arcpy.AddError( "Cross_Sections feature class has Null values in the XS_ID field" ) raise RuntimeError # Create Stage_Data Table arcpy.AddMessage("Creating Stage_Data table") table_name = "Stage_Data" arcpy.CreateTable_management(input_geodatabase, table_name) # Add Z column to table arcpy.AddZInformation_3d(CrossSections, 'Z_MIN', 'NO_FILTER') # Get the Z_min value arcpy.AddSurfaceInformation_3d(CrossSections, DEM, "Z_MIN") # Extract XS_IDs XS_IDs = [row[0] for row in arcpy.da.SearchCursor(CrossSections, "XS_ID")] # Extract Min_Z Values Min_Zs = [row[0] for row in arcpy.da.SearchCursor(CrossSections, "Z_min")] # Insert values into Stage Data Table zipped = zip(XS_IDs, Min_Zs) arcpy.AddField_management(table_name, "XS_ID", "TEXT") arcpy.AddField_management(table_name, "MIN_Z_Value", "FLOAT") # Use insert cursor to add rows rows = arcpy.InsertCursor(table_name) for i in zipped:
Out = arcpy.CopyFeatures_management(inFC, "%ScratchWorkspace%\\OutTemp") arcpy.AddField_management(Out, "Z_Up", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(Out, "Z_Down", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") UPD_SL.UpToDateShapeLengthField(Out) ncurrentstep+=1 arcpy.AddMessage("Converting input line into points and adding surface information - Step " + str(ncurrentstep) + "/" + str(nstep)) Pts = arcpy.FeatureVerticesToPoints_management(Out, "%ScratchWorkspace%\\Pts", "BOTH_ENDS") arcpy.AddXY_management(Pts) #/extraction and calculation of the topologic metrics # Ajout Aurelie arcpy.CheckOutExtension("3D") # Fin Ajout Aurelie arcpy.AddSurfaceInformation_3d(Out, DEM, "Z_MEAN", "BILINEAR") arcpy.AddSurfaceInformation_3d(Pts, DEM, "Z", "BILINEAR") arcpy.AddField_management(Out, "Slope", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(Out, "Slope3D", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") ncurrentstep+=1 arcpy.AddMessage("Calculating metrics - Step " + str(ncurrentstep) + "/" + str(nstep)) rows1 = arcpy.UpdateCursor(Out) rows2 = arcpy.SearchCursor(Pts) rows3 = arcpy.SearchCursor(Pts) line2 = rows2.next() line3 = rows3.next() line3 = rows3.next()
arcpy.SelectLayerByAttribute_management(park_with_5_score2__2_, "NEW_SELECTION", "\"Shape_Area\" >1500") # Process: Copy Features (2) arcpy.CopyFeatures_management(park_with_5_score2__4_, parkwith5scoreover1500_shp, "", "0", "0", "0") # Process: Feature To Point arcpy.FeatureToPoint_management(parkwith5scoreover1500_shp, point1500score5_shp, "CENTROID") # Process: Add XY Coordinates arcpy.AddXY_management(point1500score5_shp) # Process: Mosaic To New Raster arcpy.MosaicToNewRaster_management("'D:\\OneDrive\\Mahdiyeh\\my course 2\\gis\\small project\\data\\DEM\\021l14_0200_deme.dem';'D:\\OneDrive\\Mahdiyeh\\my course 2\\gis\\small project\\data\\DEM\\021l14_0200_demw.dem'", DEM, "alldem.tif", "", "8_BIT_UNSIGNED", "", "1", "LAST", "FIRST") # Process: Add Surface Information arcpy.AddSurfaceInformation_3d(point1500score5_shp__2_, alldem_tif, "Z", "BILINEAR", "", "1", "0", "NO_FILTER") # Process: Near 3D arcpy.Near3D_3d(point1500score5_shp__3_, "'D:\\OneDrive\\Mahdiyeh\\my course 2\\gis\\small project\\data\\Shapefiles\\line river\\out_lineriver.shp'", "", "NO_LOCATION", "NO_ANGLE", "NO_DELTA") # Create the search cursor alternatives = Path(r':\OneDrive\Mahdiyeh\my course 2\gis\small project\data\Shapefiles\input file\2final_empty.shp') schools = Path(r'D:\OneDrive\Mahdiyeh\my course 2\gis\small project\data\Shapefiles\input file\to distance\school\out_school final.shp') # Iterate through the rows in the cursor alt_info_set = [] nearest_school_set = [] for row in arcpy.SearchCursor(alternatives): print(row.FID, row.Z, row.FID_1) alt_info_set.append( [row.FID, row.Z, row.FID_1] ) nearest_school_set.append(row.FID_1)
arcpy.AddMessage("Converting VELOCITY DIRECTION Rasters to Classified FeatureClasses") VelocityDirList= [Grid150HAClip10YrPT, Grid150HAClip200YrPT, Grid150HAClip1000YrPT, Grid150HAClip200CCYrPT] for i in VelocityDirList: if VelocityDirList.index(i) == 0: RP= "10_D" elif VelocityDirList.index(i) == 1: RP= "200_D" elif VelocityDirList.index(i) == 2: RP= "1000_ND" elif VelocityDirList.index(i) == 3: RP= "200_D_2080H_67" PreWBF= GDBHoldingFolder+"\\"+str(HA)+"_"+str(RP)+"_v"+str(Version)+".gdb\\"+str(HA)+"_VELOCITY_DIRECTION_"+str(RP)+"_v"+str(Version) arcpy.AddSurfaceInformation_3d(i,PreWBF,"Z","BILINEAR") arcpy.AddField_management(i,"GRIDCODE", "SHORT", "", "", "","", "NULLABLE") arcpy.CalculateField_management(i,"GRIDCODE", '!Z!', "PYTHON_9.3") arcpy.DeleteField_management(i, ["id", "XMIN", "XMAX", "YMIN", "YMAX", "ORIG_FID", "Z"]) arcpy.AddField_management(i,"SOURCE", "TEXT", "", "", "","", "NULLABLE") arcpy.CalculateField_management(i,"SOURCE", "RIVER") arcpy.AddField_management(i,"PROB", "TEXT", "", "", "","", "NULLABLE") if VelocityDirList.index(i) == 0: arcpy.CalculateField_management(i,"PROB", '"""H"""', "PYTHON_9.3") elif VelocityDirList.index(i) == 1: arcpy.CalculateField_management(i,"PROB", '"""M"""', "PYTHON_9.3") elif VelocityDirList.index(i) == 2: arcpy.CalculateField_management(i,"PROB", '"""L"""', "PYTHON_9.3") elif VelocityDirList.index(i) == 3: arcpy.CalculateField_management(i,"PROB", '"""M_2080H_67"""', "PYTHON_9.3")
# Process: Stream Definition By Threshold arcpy.gp.StreamDefByThreshold(FA, "", threshold, "8", streamGrid + str(threshold) + ".tif") # Process: Stream Reach And Watershed arcpy.gp.StreamReachAndWatershed( fillDEM, FD, FA, streamGrid + str(threshold) + ".tif", "", "false", "8", streamOrderGrid_tif + str(threshold) + ".tif", networkTree_txt + str(threshold) + ".txt", networkCoord_txt + str(threshold) + ".txt", stream_shp + str(threshold) + ".shp", watershed_tif + str(threshold) + ".tif") # converting watershed grids to vector arcpy.RasterToPolygon_conversion(watershed_tif + str(threshold) + ".tif", watershed_shp + str(threshold), simplify="SIMPLIFY", raster_field="Value") # Run Add surface information tool arcpy.AddSurfaceInformation_3d( stream_shp + str(threshold) + ".shp", fillDEM, out_property="Z_MIN;Z_MAX;SURFACE_LENGTH;AVG_SLOPE", method="BILINEAR", sample_distance="", z_factor="1", pyramid_level_resolution="0", noise_filtering="NO_FILTER")
def arcFns(dem, res, transects, Id, sampleSize): #Use DEM to add surface information to transects using bilinear method #Check ID to find measurement for one transect only if Id == 1: #create a TIN file to permit the use of linear, natural neighbor, and nearest methods arcpy.RasterTin_3d(dem, 'out_tin' + str(res)) #bilinear arcpy.CopyFeatures_management(transects, 'transects' + str(res) + 'bil') arcpy.AddSurfaceInformation_3d('transects' + str(res) + 'bil.shp', dem, 'SURFACE_LENGTH', 'BILINEAR', sampleSize) #linear arcpy.CopyFeatures_management(transects, 'transects' + str(res) + 'TIN') arcpy.AddSurfaceInformation_3d('transects' + str(res) + 'TIN.shp', 'out_tin' + str(res), 'SURFACE_LENGTH', 'LINEAR', sampleSize) #natural neighbors arcpy.CopyFeatures_management(transects, 'transects' + str(res) + 'NN') arcpy.AddSurfaceInformation_3d('transects' + str(res) + 'NN.shp', 'out_tin' + str(res), 'SURFACE_LENGTH', 'NATURAL_NEIGHBORS', sampleSize) #conflate nearest arcpy.CopyFeatures_management(transects, 'transects' + str(res) + 'close') arcpy.AddSurfaceInformation_3d('transects' + str(res) + 'close.shp', 'out_tin' + str(res), 'SURFACE_LENGTH', 'CONFLATE_NEAREST', sampleSize) #use cursors to explore the ouputted surface distances in the attribute table sCursBil = arcpy.da.SearchCursor('transects' + str(res) + 'bil.shp', 'SLENGTH') sCursTIN = arcpy.da.SearchCursor('transects' + str(res) + 'TIN.shp', 'SLENGTH') sCursNN = arcpy.da.SearchCursor('transects' + str(res) + 'NN.shp', 'SLENGTH') sCursClose = arcpy.da.SearchCursor( 'transects' + str(res) + 'close.shp', 'SLENGTH') d1 = sCursBil.next()[0] d2 = sCursTIN.next()[0] d3 = sCursNN.next()[0] d4 = sCursClose.next()[0] #delete cursors del sCursBil, sCursTIN, sCursNN, sCursClose #return surface distance values return [d1, d2, d3, d4] else: #for consequential transects, we only need to explore the table, as the surface information as already been added in the previous step expression = '"Id" = {0:d}'.format(Id) with arcpy.da.SearchCursor('transects' + str(res) + 'bil.shp', ['SLENGTH', 'Id'], expression) as sCursBil: row = sCursBil.next() d1 = row[0] with arcpy.da.SearchCursor('transects' + str(res) + 'TIN.shp', ['SLENGTH', 'Id'], expression) as sCursTIN: row = sCursTIN.next() d2 = row[0] with arcpy.da.SearchCursor('transects' + str(res) + 'NN.shp', ['SLENGTH', 'Id'], expression) as sCursNN: row = sCursNN.next() d3 = row[0] with arcpy.da.SearchCursor('transects' + str(res) + 'close.shp', ['SLENGTH', 'Id'], expression) as sCursClose: row = sCursClose.next() d4 = row[0] return [d1, d2, d3, d4]
arcpy.Intersect_analysis(inList, intersectPts, 'ONLY_FID', '#', 'point') except: arcpy.AddWarning('Intersect process failed!') arcpy.AddWarning('You may need to permanently project all layers') arcpy.AddWarning('to the same spatial reference.') arcpy.AddMessage(' {} written to {}'.format(intersectPts, scratchDir)) #f-ing intersect analysis created multipoints, on which you can't call #AddSurfaceInformation explode_pts = intersectPts + '_exp' arcpy.MultipartToSinglepart_management(intersectPts, explode_pts) #get elevations for the intersection locations arcpy.AddMessage('Adding elevations from {}'.format(dem)) arcpy.AddSurfaceInformation_3d(explode_pts, dem, 'Z') #locate intersection points on measured cross-section eventTable = outName + '_interEvents' rProps = 'rkey POINT RouteM' arcpy.AddMessage('Locating lines in {} on {}'.format(linesLayer, mLine)) arcpy.LocateFeaturesAlongRoutes_lr(explode_pts, mLine, 'ORIG_FID', '10', eventTable, rProps, 'FIRST', 'NO_DISTANCE', 'NO_ZERO') arcpy.AddMessage(' {} written to {}'.format(eventTable, scratchDir)) if outShape == 'lines': xInterFeats = outName + '_xsecLines' xsecLines(xInterFeats, explode_pts, eventTable, 'Z') else: xInterFeats = outName + '_xsecPts'
## clean up any existing temporary or output entitites delArcStuff( (tempBuff, tempPoints, secLinePts, outWorkspace + '/' + outFeatureClass)) addMsgAndPrint(' getting cross-section line') # make feature layer that contains single line from sectionline featureclass whereExpr = '"Label" =\'%s\'' % sectionLineLabelValue arcpy.MakeFeatureLayer_management(sectionLineClass, secLine, whereExpr) # create subset of points within maxDistance of section line arcpy.Buffer_analysis(secLine, tempBuff, maxDistance) arcpy.Clip_analysis(pointClass, tempBuff, tempPoints) addMsgAndPrint(' adding Z and XY to points') # Add Z to subset of points arcpy.AddSurfaceInformation_3d(tempPoints, DEM, 'Z', 'LINEAR') # return 3D analyst license arcpy.CheckInExtension("3D") # Add XY values to subset of points arcpy.AddXY_management(tempPoints) addMsgAndPrint(' getting section line endpoints') # Get coordinates of section line endpoints ### this is probably a r-e-a-l-l-l-ly clumsy way to do so arcpy.FeatureVerticesToPoints_management(secLine, secLinePts, 'BOTH_ENDS') arcpy.AddXY_management(secLinePts) pts = [] rows = arcpy.SearchCursor(secLinePts) for row in rows: pts.append([row.POINT_X, row.POINT_Y]) startX = pts[0][0]
ElevationPoints_Layer = "ElevationPoints_Layer" ElevationProfile = "C:\\PROJECTS\\UMAR\\Default.gdb\\ElevationProfile" SectionBends = "C:\\PROJECTS\\UMAR\\Default.gdb\\SectionBends" SectionBends_Layer = "SectionBends_Layer" SectionBendPoints = "C:\\PROJECTS\\UMAR\\Default.gdb\\SectionBendPoints" # Process: Densify arcpy.Densify_edit(SectionLine, "DISTANCE", Distance, "0.1 Meters", "10") # Process: Feature Vertices To Points (2) arcpy.FeatureVerticesToPoints_management(Output_Feature_Class__3_, Output_Feature_Class__6_, "ALL") # Process: Add Surface Information arcpy.AddSurfaceInformation_3d(Output_Feature_Class__6_, NED10m1, "Z", "BILINEAR", "", "1", "0", "NO_FILTER") # Process: Add XY Coordinates (2) arcpy.AddXY_management(SectionLine_FeatureVerticesT1) # Process: Create Routes arcpy.CreateRoutes_lr(SectionLine, Route_Identifier_Field__2_, SectionRoute, "LENGTH", "", "", "UPPER_LEFT", Measure_Factor, "0", "IGNORE", "INDEX") arcpy.CreateRoutes_lr(SectionLine, Route_Identifier_Field__2_, SectionRoute, "LENGTH", "", "", direction, Measure_Factor, "0", "IGNORE", "INDEX") # Process: Locate Features Along Routes arcpy.LocateFeaturesAlongRoutes_lr(SectionLine_FeatureVerticesT1__3_, SectionRoute, Route_Identifier_Field__2_, "0 Meters", ElevationPoints, Output_Event_Table_Properties, "FIRST", "DISTANCE", "ZERO", "FIELDS", "M_DIRECTON") # Process: Simplify Line arcpy.SimplifyLine_cartography(SectionLine, SectionLine_SimplifyLine, "POINT_REMOVE", "10 Meters", "FLAG_ERRORS", "NO_KEEP", "NO_CHECK")
def StreamProfilePoints(output_workspace, flowline, dem, km_to_mouth, station_distance, calibration_points, point_id_field, measure_field, search_radius): # Check out the extension licenses arcpy.CheckOutExtension("3D") # Set environment variables arcpy.env.overwriteOutput = True arcpy.env.workspace = output_workspace # List parameter values arcpy.AddMessage("Workspace: {}".format(arcpy.env.workspace)) arcpy.AddMessage("flowline: {}".format(arcpy.Describe(flowline).baseName)) arcpy.AddMessage("km_to_mouth: {}".format(str(km_to_mouth))) arcpy.AddMessage("DEM: {}".format(arcpy.Describe(dem).baseName)) arcpy.AddMessage("Station distance: {}".format(str(station_distance))) if calibration_points: arcpy.AddMessage("Calibration points: {}".format(str(calibration_points))) arcpy.AddMessage("point_id_field: {}".format(str(point_id_field))) arcpy.AddMessage("measure_field: {}".format(str(measure_field))) arcpy.AddMessage("search_radius: {}".format(str(search_radius))) # Add a field to hold the linear referencing route from measure # Check if the field already exists and if not add it field_names = [f.name for f in arcpy.ListFields(flowline)] if "from_measure" not in field_names: arcpy.AddField_management(in_table = flowline, field_name = "from_measure", field_type = "DOUBLE") # Set the value of the flowline `from_measure` to the input parameter # `km_to_mouth` in units kilometers arcpy.CalculateField_management(in_table = flowline, field = "from_measure", expression = km_to_mouth, expression_type = "PYTHON_9.3") # Add a field to hold the linear referencing route to measure if "to_measure" not in field_names: arcpy.AddField_management(in_table = flowline, field_name = "to_measure", field_type = "DOUBLE") # Set the value of the flowline `to_measure` to the length of the flowline # in units kilometers plus the value of km_to_mouth expression = "!shape.length@kilometers! + {}".format(str(km_to_mouth)) arcpy.CalculateField_management(in_table = flowline, field = "to_measure", expression = expression, expression_type = "PYTHON_9.3") # Simplify the flowline to speed interpolation arcpy.SimplifyLine_cartography(in_features = flowline, out_feature_class = "flowline_simplify", algorithm = "POINT_REMOVE", tolerance = "1 Feet") arcpy.AddMessage("Simplified flowline: flowline_simplify") # Densify vertices of the flowline_simplify feature class using the Densify tool. arcpy.CopyFeatures_management(in_features = "flowline_simplify", out_feature_class = "flowline_densify") arcpy.Densify_edit(in_features = "flowline_densify", densification_method = "DISTANCE", distance = station_distance) arcpy.AddMessage("Densified verticies of flowline: flowline_densify") # Convert the flowline feature class to a route arcpy.CreateRoutes_lr(in_line_features = "flowline_densify", route_id_field = "ReachName", out_feature_class = "flowline_densify_route", measure_source = "TWO_FIELDS", from_measure_field = "from_measure", to_measure_field = "to_measure") arcpy.AddMessage("Converted densfied flowline to a route: " "flowline_densify_route") # Calibrate route if calibration_points: arcpy.CalibrateRoutes_lr(in_route_features = "flowline_densify_route", route_id_field = "ReachName", in_point_features = calibration_points, point_id_field = point_id_field, measure_field = measure_field, out_feature_class = "flowline_route_calibrate", calibrate_method = "DISTANCE", search_radius = search_radius) arcpy.CopyFeatures_management(in_features = "flowline_route_calibrate", out_feature_class = "flowline_densify_route") arcpy.AddMessage("Calibrated route") # Convert flowline feature vertices to points flowline_points = os.path.join(output_workspace, "flowline_points") arcpy.FeatureVerticesToPoints_management( in_features = "flowline_densify_route", out_feature_class = flowline_points) arcpy.AddMessage("Converted densified flowline route to points: " "flowline_points") # Add x, y, z, and m values to the `flowline_points` feature class arcpy.AddGeometryAttributes_management(Input_Features = flowline_points, Geometry_Properties = "POINT_X_Y_Z_M", Length_Unit = "METERS") # Set the first m-value for the flowline_points to zero. The `create # route` tool sets it to NULL. # Create code block that inserts the km_to_mouth value for the NULL record # (the first record) #arcpy.AddMessage("Set Null m-values to zero - start: {}".format(datetime.now().strftime("%H:%M:%S"))) codeBlock = """def setNull2Zero(m): if m is None: return {} else: return m""".format(km_to_mouth) arcpy.CalculateField_management(in_table = flowline_points, field = "POINT_M", expression = "setNull2Zero(!POINT_M!)", code_block = codeBlock, expression_type = "PYTHON_9.3") #arcpy.AddMessage("Set Null m-values to zero - end: {}".format(datetime.now().strftime("%H:%M:%S"))) # Delete un-needed fields arcpy.DeleteField_management(in_table = flowline_points, drop_field = ["ORIG_FID","POINT_Z"]) # Add elevations to the `flowline_points` feature class arcpy.AddSurfaceInformation_3d(in_feature_class = flowline_points, in_surface = dem, out_property = "Z", z_factor = 1.0) arcpy.AddMessage("Added geometry fields to flowline points.") # Return arcpy.SetParameter(9, flowline_points) # Cleanup arcpy.Delete_management(in_data = "flowline_simplify") arcpy.Delete_management(in_data = "flowline_simplify_Pnt") arcpy.Delete_management(in_data = "flowline_densify") arcpy.Delete_management(in_data = "flowline_route_calibrate") arcpy.Delete_management(in_data = "flowline_densify_route") return
buff) points_near_line = os.path.join(scratchDir, outName + '_sel') arcpy.CopyFeatures_management(ptLayer, points_near_line) arcpy.SelectLayerByAttribute_management(ptLayer, 'CLEAR_SELECTION') #figure out where the point elevation is coming from: a user specified field or to be #calculated by interpolation from the DEM and stored in 'zDEM' if not ptz_field == '': arcpy.AddMessage( 'Using elevations stored in the field {}'.format(ptz_field)) #if the elevation values are in the table, copy the selection to an #output fc z_field = ptz_field else: arcpy.AddMessage('Adding elevations from {}'.format(dem)) arcpy.AddSurfaceInformation_3d(points_near_line, dem, 'Z') z_field = 'Z' #add ORIG_ID for deleting identical events and for joining attributes later addAndCalc(points_near_line, 'ORIG_PTID', '[OBJECTID]') # locate points along the cross-section eventTable = outName + '_ptEvents' rProps = 'rkey POINT RouteM' arcpy.AddMessage('Locating {} on {}'.format(points_near_line, mLine)) arcpy.LocateFeaturesAlongRoutes_lr(points_near_line, mLine, 'ORIG_FID', buff, eventTable, rProps, '#', 'DISTANCE') arcpy.AddMessage(' {} written to {}'.format(eventTable, scratchDir)) #remove duplicate records that result from what appears to be
arcpy.gp.SnapPourPoint_sa(Pour_Point, FlowAcc_Flow1, SnapPou_1, "15", "Id") # Process: Watershed arcpy.gp.Watershed_sa(FlowDir_Fill1, SnapPou_1, rasteroutput, "VALUE") # Process: Raster to Polygon arcpy.RasterToPolygon_conversion(rasteroutput, watershdshp, "SIMPLIFY", "") # Process: Extract by Mask arcpy.gp.ExtractByMask_sa(FlowDir_Fill1, watershdshp, Extract_fill2) # Process: Flow Length arcpy.gp.FlowLength_sa(Extract_fill2, Flow_Length_surface, "UPSTREAM", "") # Process: Add Surface Information arcpy.AddSurfaceInformation_3d(watershdshp, Fill_, "Z_MIN;Z_MAX;SURFACE_AREA;MIN_SLOPE;MAX_SLOPE;AVG_SLOPE", "BILINEAR", "", "1", "0", "NO_FILTER") # Process: Add Field arcpy.AddField_management(wtrshedinfo, "Acres", "FLOAT", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") # Process: Calculate Field arcpy.CalculateField_management(watershedshp3, "Acres", "[SArea] /4046.86", "VB", "") # Process: Extract by Mask (2) arcpy.gp.ExtractByMask_sa(Input_AOI_Lidar, watershdshp, wshd) # Process: Slope arcpy.gp.Slope_sa(wshd, ShedSlope, "DEGREE", "1") # Process: Zonal Statistics arcpy.gp.ZonalStatistics_sa(Watershed_Shape, "ID", ShedSlope, SlopeMean, "MEAN", "DATA")
def elev_slope(inFC, DEM, Output): # creation of the output with the new fields arcpy.AddMessage("Creating output with new fields...") Out = arcpy.CopyFeatures_management(inFC, "in_memory\\OutTemp") arcpy.AddField_management(Out, "Z_Up", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(Out, "Z_Down", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") UPD_SL.UpToDateShapeLengthField(Out) arcpy.AddMessage( "Converting input line into points and adding surface information...") Pts = arcpy.FeatureVerticesToPoints_management(Out, "in_memory\\Pts", "BOTH_ENDS") arcpy.AddXY_management(Pts) # extraction and calculation of the topologic metrics arcpy.AddSurfaceInformation_3d(Out, DEM, "Z_MEAN", "BILINEAR") arcpy.AddSurfaceInformation_3d(Pts, DEM, "Z", "BILINEAR") arcpy.AddField_management(Out, "Slope", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(Out, "Slope3D", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") arcpy.AddMessage("Calculating metrics...") rows1 = arcpy.UpdateCursor(Out) rows2 = arcpy.SearchCursor(Pts) rows3 = arcpy.SearchCursor(Pts) line2 = rows2.next() line3 = rows3.next() line3 = rows3.next() for line1 in rows1: line1.Z_Up = line2.Z line1.Z_Down = line3.Z try: line1.Slope = (line1.Z_Up - line1.Z_Down) / ( ((line3.POINT_X - line2.POINT_X)**2 + (line3.POINT_Y - line2.POINT_Y)**2)**0.5) except Exception as e: print e pass line1.Slope3D = (line1.Z_Up - line1.Z_Down) / line1.Shape_Length rows1.updateRow(line1) line2 = rows2.next() line2 = rows2.next() line3 = rows3.next() line3 = rows3.next() arcpy.CopyFeatures_management(Out, Output) # removing of the residual fields arcpy.AddMessage("Removing the residual fields...") fieldnamesfromFC = [f.name for f in arcpy.ListFields(Output)] fieldnamestoFC = [f.name for f in arcpy.ListFields(inFC)] for field in fieldnamesfromFC: if field not in fieldnamestoFC and field != "Z_Up" and field != "Z_Down" and field != "Z_Mean" and field != "Slope" and field != "Slope3D": try: arcpy.DeleteField_management(Output, str(field)) except: continue arcpy.AddMessage("Deleting temporary files...") arcpy.Delete_management(Pts) arcpy.Delete_management(Out) return Output
def execute(self, parameters, messages): """The source code of the tool.""" #Extensions if arcpy.CheckExtension("3D") == "Available": arcpy.CheckOutExtension("3D") else: arcpy.ExcecuteError("ERROR: The 3D Analyst extension is required to run this tool.") arcpy.env.overwriteOutput = True File_GDB_Name = parameters[0].valueAsText File_GDB_Location = parameters[1].valueAsText Watershed_Boundary = parameters[2].valueAsText Number_of_cells_to_define_stream = parameters[3].valueAsText Output_Coordinate_System = parameters[4].valueAsText Buffer_Option = parameters[5].valueAsText Input_DEM_Rasters = parameters[6].valueAsText Watershed_Flow_Direction_Rasters = parameters[7].valueAsText # Local variables: Path_to_GDB = os.path.join(File_GDB_Location, File_GDB_Name) Dataset = "Layers" Path_to_GDB_dataset = os.path.join(Path_to_GDB, Dataset) Coordinate_System = "GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984'," \ "SPHEROID['WGS_1984',6378137.0,298.257223563]]," \ "PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]];" \ "-400 -400 1000000000;-100000 10000;-100000 10000;" \ "8.98315284119522E-09;0.001;0.001;IsHighPrecision" Buffer_Distance = "20 Kilometers" Watershed_Buffer = os.path.join(Path_to_GDB_dataset, "Watershed_Buffer") Output_Mosaic_Elevation_DEM = os.path.join(Path_to_GDB, "Mosaic_Elevation_DEM") Output_Elevation_DEM = os.path.join(Path_to_GDB, "Elevation_DEM") Output_Mosiac_Flow_Direction_Raster = os.path.join(Path_to_GDB, "Mosaic_Flow_Direction") Output_Flow_Direction_Raster = os.path.join(Path_to_GDB, "Flow_Direction") # Process: Create File GDB arcpy.CreateFileGDB_management(File_GDB_Location, File_GDB_Name, "CURRENT") # Process: Create Feature Dataset arcpy.CreateFeatureDataset_management(Path_to_GDB, Dataset, Coordinate_System) # Process: Optional Buffer if str(Buffer_Option) == 'true': arcpy.Buffer_analysis(Watershed_Boundary, Watershed_Buffer, Buffer_Distance, "FULL", "ROUND", "NONE", "", "PLANAR") else: Watershed_Buffer = Watershed_Boundary # Process: Mosaic To New Raster for DEM arcpy.MosaicToNewRaster_management(Input_DEM_Rasters, Path_to_GDB, "Mosaic_Elevation_DEM", "", "16_BIT_SIGNED", "", "1", "LAST", "FIRST") # Process: Extract by Mask for DEM arcpy.gp.ExtractByMask_sa(Output_Mosaic_Elevation_DEM, Watershed_Buffer, Output_Elevation_DEM) arcpy.Delete_management(Output_Mosaic_Elevation_DEM) if Watershed_Flow_Direction_Rasters: # Process: Mosaic To New Raster for Flow Direction arcpy.MosaicToNewRaster_management(Watershed_Flow_Direction_Rasters, Path_to_GDB, "Mosaic_Flow_Direction", "", "16_BIT_SIGNED", "", "1", "LAST", "FIRST") # Process: Extract by Mask for Flow Direction arcpy.gp.ExtractByMask_sa(Output_Mosiac_Flow_Direction_Raster, Watershed_Buffer, Output_Flow_Direction_Raster) arcpy.Delete_management(Output_Mosiac_Flow_Direction_Raster) else: #generate flow direction raster ArcHydroTools.FlowDirection(Output_Elevation_DEM, Output_Flow_Direction_Raster) # Process: Flow Accumulation Output_Flow_Accumulation_Raster = os.path.join(Path_to_GDB, "Flow_Accumulation") ArcHydroTools.FlowAccumulation(Output_Flow_Direction_Raster, Output_Flow_Accumulation_Raster) # Process: Stream Definition Output_Str_Raster_Initial = os.path.join(Path_to_GDB, "StrInitial") ArcHydroTools.StreamDefinition(Output_Flow_Accumulation_Raster, Number_of_cells_to_define_stream, Output_Str_Raster_Initial) #NOTE: Sometimes ArcHydro does not catch really large flow accumulations, this fixes that Output_Str_Raster = os.path.join(Path_to_GDB, "Str") str_con_raster = arcpy.sa.Con(arcpy.sa.Raster(Output_Flow_Accumulation_Raster) > max(100000, int(Number_of_cells_to_define_stream)), 1, Output_Str_Raster_Initial) str_con_raster.save(Output_Str_Raster) arcpy.Delete_management(Output_Str_Raster_Initial) # Process: Stream Segmentation Output_StrLnk_Raster = os.path.join(Path_to_GDB, "StrLnk") ArcHydroTools.StreamSegmentation(Output_Str_Raster, Output_Flow_Direction_Raster, Output_StrLnk_Raster) # Process: Catchment Grid Delineation Output_Cat = os.path.join(Path_to_GDB, "Cat") ArcHydroTools.CatchmentGridDelineation(Output_Flow_Direction_Raster, Output_StrLnk_Raster, Output_Cat) # Process: Catchment Polygon Processing Output_Catchment = os.path.join(Path_to_GDB_dataset, "Catchment") ArcHydroTools.CatchmentPolyProcessing(Output_Cat, Output_Catchment) # Process: Drainage Line Processing Output_DrainageLine = os.path.join(Path_to_GDB_dataset, "DrainageLine") ArcHydroTools.DrainageLineProcessing(Output_StrLnk_Raster, Output_Flow_Direction_Raster, Output_DrainageLine) # Process: Add DrainLnID to Catchment arcpy.AddField_management(Output_Catchment, "DrainLnID", "LONG", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") arcpy.JoinField_management(Output_Catchment, "HydroID", Output_DrainageLine, "GridID", "HydroID") arcpy.CalculateField_management(Output_Catchment, "DrainLnID", "[HydroID_1]", "VB", "") arcpy.DeleteField_management(Output_Catchment, "HydroID_1") # Process: Delete rows that do not have a drainage line associated with it up_curs = arcpy.UpdateCursor(Output_Catchment,"{0} IS NULL".format("DrainLnID")) for row in up_curs: if not row.DrainLnID: up_curs.deleteRow(row) # Process: Adjoint Catchment Processing ## Output_Adjoint_Catchment = os.path.join(Path_to_GDB_dataset, "AdjointCatchment") ## ArcHydroTools.AdjointCatchment(Output_DrainageLine, Output_Catchment, Output_Adjoint_Catchment) # Process: Project Output_Projected_DrainageLine = os.path.join(Path_to_GDB, "Proj_DrainageLine") arcpy.Project_management(Output_DrainageLine, Output_Projected_DrainageLine, Output_Coordinate_System) # Process: Add Surface Information arcpy.CheckOutExtension("3D") arcpy.AddSurfaceInformation_3d(Output_Projected_DrainageLine,Output_Elevation_DEM, "SURFACE_LENGTH;AVG_SLOPE") #add field arcpy.AddField_management(Output_Projected_DrainageLine, "LENGTHKM", "FLOAT", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") cursor = arcpy.UpdateCursor(Output_Projected_DrainageLine, ["SLength", "LENGTHKM"]) for row in cursor: SLength = row.getValue("SLength") LENGTHKM = SLength/1000.0 row.setValue("LENGTHKM", LENGTHKM) cursor.updateRow(row) #CLEANUP arcpy.Delete_management(Output_Str_Raster) arcpy.Delete_management(Output_Cat) arcpy.Delete_management(Output_StrLnk_Raster) arcpy.Delete_management(Output_DrainageLine) arcpy.Project_management(Output_Projected_DrainageLine, Output_DrainageLine, Coordinate_System) arcpy.Delete_management(Output_Projected_DrainageLine) arcpy.Delete_management(Watershed_Buffer) return(Output_DrainageLine, Output_Catchment)
class LicenseError(Exception): pass try: if arcpy.CheckExtension("3D") == "Available": arcpy.CheckOutExtension("3D") else: raise LicenseError arcpy.CreateRandomPoints_management( outfolder, "points", constraining_feature_class=foot, minimum_allowed_distance="0,9") arcpy.AddSurfaceInformation_3d(outfolder + "\points.shp", relative_heights_raster, "Z") arcpy.Statistics_analysis(outfolder + "\points.shp", outfolder + "\points_cal.shp", [["Z", "MEAN"]], case_field="CID") arcpy.AddField_management(foot, "height", "DOUBLE") arcpy.CalculateField_management(foot, "height", "[Z_Max] - [Z_Min]") arcpy.AddGeometryAttributes_management(foot, "AREA") arcpy.AddField_management(foot, "volume", "DOUBLE") arcpy.CalculateField_management(foot, "volume", "[height] * [POLY_AREA]") arcpy.DeleteField_management( foot, ["height", "POLY_AREA", "Z_MIN", "Z_MAX"]) except LicenseError:
FGDBexists = False # if GDB already existed but feature dataset doesn't if not arcpy.Exists(watershedFD): arcpy.CreateFeatureDataset_management(watershedGDB_path, "Layers", sr) # Copy Features will use the spatial reference of the geoprocessing environment that has been set # Transformation between WGS84 and NAD83 will default to WGS_1984_(ITRF00)_To_NAD_1983, per env settings # No other areas of transformation can be used - document this in help and manuals arcpy.CopyFeatures_management(inputPoints, pointsProj) # ------------------------------------------------------------- Recalculate X,Y values in output table arcpy.AddXY_management(pointsProj) # --------------------------------------------------------------------- Update Elevation values in feet arcpy.AddSurfaceInformation_3d(pointsProj, inputDEM, "Z", "", "", Zfactor) expression = "round(!Z!,1)" arcpy.CalculateField_management(pointsProj, "POINT_Z", expression, "PYTHON_9.3") del expression # --------------------------------------------------------------------- Clean up extra fields arcpy.DeleteField_management(pointsProj, "POINT_M") arcpy.DeleteField_management(pointsProj, "Z") # ---------------------------------------------------------------------- Create final output # Copy Station Points arcpy.CopyFeatures_management(pointsProj, outPoints) # Create Txt file if selected and write attributes of station points if text == True: AddMsgAndPrint("Creating Output text file:\n",0)
def XSCreateStationPoints(output_workspace, cross_section, dem, dem_units, detrend_dem, station_distance): # Check out the extension licenses arcpy.CheckOutExtension("3D") # Set environment variables arcpy.env.overwriteOutput = True arcpy.env.workspace = output_workspace # List parameter values arcpy.AddMessage("Workspace: {}".format(arcpy.env.workspace)) arcpy.AddMessage("Cross Section: " "{}".format(arcpy.Describe(cross_section).baseName)) arcpy.AddMessage("DEM: {}".format(arcpy.Describe(dem).baseName)) arcpy.AddMessage("DEM vertical units: {}".format(dem_units)) if detrend_dem is True: arcpy.AddMessage("Detrended DEM: " "{}".format(arcpy.Describe(detrend_dem).baseName)) arcpy.AddMessage("Station distance: {0}".format(str(station_distance))) # Set cross_section name xs_name = arcpy.Describe(cross_section).baseName # Add a field to hold the linear referencing route `from_measure` # Check if the field already exists and if not add it field_names = [f.name for f in arcpy.ListFields(cross_section)] if "from_measure" not in field_names: arcpy.AddField_management(in_table=cross_section, field_name="from_measure", field_type="DOUBLE") # Set the value of the cross section `from_measure` to zero in units meters arcpy.CalculateField_management(in_table=cross_section, field="from_measure", expression="0", expression_type="PYTHON_9.3") # Add a field to hold the linear referencing route `to_measure` if "to_measure" not in field_names: arcpy.AddField_management(in_table=cross_section, field_name="to_measure", field_type="DOUBLE") # Set value of xs `to_measure` to length of xs in units meters arcpy.CalculateField_management(in_table=cross_section, field="to_measure", expression="!shape.length@meters!", expression_type="PYTHON_9.3") # Densify vertices of the cross_section fc arcpy.AddMessage("Densifying cross section vertices...") xs_densify = os.path.join(output_workspace, xs_name + "_densify") arcpy.CopyFeatures_management(in_features=cross_section, out_feature_class=xs_densify) arcpy.Densify_edit(in_features=xs_densify, densification_method="DISTANCE", distance=station_distance) # Convert the cross_section fc to a route arcpy.AddMessage("Creating cross section routes...") xs_densify_route = os.path.join(output_workspace, xs_name + "_densify_route") arcpy.CreateRoutes_lr(in_line_features=xs_densify, route_id_field="Seq", out_feature_class=xs_densify_route, measure_source="TWO_FIELDS", from_measure_field="from_measure", to_measure_field="to_measure") # Convert cross section feature vertices to points arcpy.AddMessage("Converting cross section vertices to points...") xs_points = os.path.join(output_workspace, xs_name + "_points") arcpy.FeatureVerticesToPoints_management(in_features=xs_densify_route, out_feature_class=xs_points) # Add x, y, z, and m values to the `cross_section_points` feature class arcpy.AddGeometryAttributes_management(Input_Features=xs_points, Geometry_Properties="POINT_X_Y_Z_M", Length_Unit="METERS") # Set the first m-value for each xs to zero (because the `create route` # tool sets it to NULL). arcpy.AddMessage("Setting XS NULL m-values to zero...") arcpy.CalculateField_management(in_table=xs_points, field="POINT_M", expression="setNull2Zero(!POINT_M!)", code_block="""def setNull2Zero(m): if m is None: return 0 else: return m""", expression_type="PYTHON_9.3") # Delete un-needed fields arcpy.DeleteField_management(in_table=xs_points, drop_field=["ORIG_FID", "POINT_Z"]) # Add a field to hold the linear referencing `route_units` arcpy.AddField_management(in_table=xs_points, field_name="POINT_M_units", field_type="TEXT") # Set the `route_units` field to "meter" arcpy.CalculateField_management(in_table=xs_points, field="POINT_M_units", expression="'m'", expression_type="PYTHON_9.3") # Join fields from the `cross_section` fc to `cross_section_points` fc fields = ["ReachName", "Watershed_Area_SqMile", "km_to_mouth"] arcpy.JoinField_management(in_data=xs_points, in_field="Seq", join_table=cross_section, join_field="Seq", fields=fields) # Add elevations to the `cross_section_points` feature class arcpy.AddMessage("Adding DEM surface information...") ## DEM arcpy.AddMessage("DEM: {}".format(dem)) arcpy.AddSurfaceInformation_3d(in_feature_class=xs_points, in_surface=dem, out_property="Z", z_factor=1.0) ## Change `Z` field name to `DEM_Z` arcpy.AlterField_management(in_table=xs_points, field="Z", new_field_name="DEM_Z") ## Create and set the value of the dem_units field arcpy.AddField_management(in_table=xs_points, field_name="dem_units", field_type="TEXT") arcpy.CalculateField_management(in_table=xs_points, field="dem_units", expression="'{}'".format(dem_units), expression_type="PYTHON_9.3") ## Detrend if detrend_dem: arcpy.AddMessage("Detrend DEM: {}".format(detrend_dem)) ## Add detrended elevations to the `cross_section_points` feature class arcpy.AddSurfaceInformation_3d(in_feature_class=xs_points, in_surface=detrend_dem, out_property="Z", z_factor=1.0) ## Change `Z` field name to `Detrend_DEM_Z` arcpy.AlterField_management(in_table=xs_points, field="Z", new_field_name="Detrend_DEM_Z") # Return arcpy.SetParameter(6, xs_points) # Cleanup arcpy.Delete_management(in_data=xs_densify) arcpy.Delete_management(in_data=xs_densify_route) return
if demSR <> inPtsSR: addMsgAndPrint('Projecting structure points from WKID ' + str(inPtsSR.factoryCode) + ' to WKID ' + str(demSR.factoryCode)) # rename inPts inPts2 = inPts + '_2' testAndDelete(inPts2) arcpy.Rename_management(inPts, inPts2) # project inPts2 arcpy.Project_management(inPts2, inPts, demSR) testAndDelete(inPts2) ## Add XYZ values addMsgAndPrint('Getting XYZ values') arcpy.AddXY_management(inPts) arcpy.AddSurfaceInformation_3d(inPts, dem, 'Z') ## for each orientation point # extract xyz, azi, inc # validate azi and inc values with arcpy.da.SearchCursor( inPts, ['OID@', 'POINT_X', 'POINT_Y', 'Z', aziField, incField]) as cursor: for row in cursor: oid = row[0] xyz = [row[1], row[2], row[3]] azi = row[4] + gridDec ############### or is it minus? inc = row[5] addMsgAndPrint('OID=' + str(oid) + ' strike=' + str(azi) + ' dip=' + str(inc)) if inc == 90:
import arcpy inPointFeatures = "ZeleznicniStanice" inRaster = "dem" output_path = "C:\\" arcpy.CheckOutExtension("3D") # Adds a column with Z value reading from dem raster arcpy.AddSurfaceInformation_3d(inPointFeatures, inRaster, "Z") # Find FID of the row with maximum Z value fidMax = arcpy.SearchCursor(inPointFeatures, "", "", "", "Z" + " D").next().getValue("FID") # Find FID of the row with maximum Z value fidMin = arcpy.SearchCursor(inPointFeatures, "", "", "", "Z" + " A").next().getValue("FID") # Selects the heighest and lowest stations arcpy.SelectLayerByAttribute_management( inPointFeatures, "NEW_SELECTION", "FID IN ({}, {})".format(fidMin, fidMax)) # Exports the selected features to an output shapefile in C:\output.shp You may change this path at the top arcpy.FeatureClassToFeatureClass_conversion(inPointFeatures, output_path, "output.shp") # Prints the heighest and lowest train stations on console cursor = arcpy.SearchCursor(inPointFeatures) for row in cursor: if row.getValue("FID") == fidMax: