def calculateTWI (dem): ''' This function calculates the TWI based on DEM dataset ''' # Calculate the Flow Direction and Accumulation print ("Calculating Flow Direction and Accumulation...") flow_dir = FlowDirection(dem) flow_acc = FlowAccumulation(flow_dir) # Calculate the Slope and convert from Degree to Radians print ("Calculating Slope in radians...") slope_deg = os.path.join (arcpy.env.scratchWorkspace, 'slope_deg') # could'nt write to in_memory (too big?!) arcpy.Slope_3d (dem, slope_deg, "DEGREE") slope_rad = Raster(slope_deg) * (math.pi/180) # Get the DEM pixel area PxsizeX = float(arcpy.GetRasterProperties_management(dem, "CELLSIZEX").getOutput(0)) PxsizeY = float(arcpy.GetRasterProperties_management(dem, "CELLSIZEY").getOutput(0)) pxArea = PxsizeX*PxsizeY # Apply the TWI equation print ("Calculating TWI...") c = 0.0001 exp_1 = Ln(((flow_acc + 1) * pxArea) / Tan(slope_rad)) exp_2 = Ln(((flow_acc + 1) * pxArea) / c + Tan(slope_rad)) TWI = Con(slope_rad > 0, exp_1, exp_2) # Apply a low-pass filter to reduce noise. Only if the DEM Cell size is small (very high resolution) if (PxsizeX <= 2 or PxsizeY <= 2 ): print ("The DEM cell size is {}. A low-pass filter is applied." .format(int(PxsizeX))) TWI_filtered = FocalStatistics(TWI, NbrRectangle(3, 3, "CELL"), "MEAN") TWI_filtered.save(os.path.join (Workspace, 'p_TWI_filtered')) else: TWI.save(os.path.join (Workspace, 'p_TWI'))
def createTopoVars(sitePoly, largeDEM, bufferPoly, path, site, aggFac): import arcpy from arcpy import env #environment corresponds to the specific site env.workspace = "%s\\ChangeModeling\\%s" % (path, site) #allow overwriting arcpy.env.overwriteOutput = True #don't care much about this specific location, mostly here to help avoid arcGIS errors. env.scratchWorkspace = "%s\\ChangeModeling\\Scratch.gdb" % path # clip to approximate extent of poly for calculations of topo vars # uses the 2*scale of analysis buffer (e.g. 2*10 m or 2*40 m; buffer already created outside function) mediumDEM_UTM = arcpy.Clip_management(largeDEM, "#", "mediumDEM.tif", bufferPoly, "0", "ClippingGeometry") # calculate slope (maximum slope) mediumSLOPE = arcpy.Slope_3d(mediumDEM_UTM, "med_slope.tif", "DEGREE") print "Slope calculated" # calculate curvature (provides maximum curvature, plan curvature, and profile curvature) mediumcurvature = arcpy.Curvature_3d(mediumDEM_UTM, "med_curvature.tif", "", "med_curvature_prof.tif", "med_curvature_plan.tif") print "Curvature calculated" # calculate aspect, northness, and eastness mediumAspect = arcpy.Aspect_3d(mediumDEM_UTM, "med_aspect.tif") mediumNorthn = arcpy.sa.Cos(arcpy.Raster(mediumAspect) * 3.14159 / 180) mediumEastn = arcpy.sa.Sin(arcpy.Raster(mediumAspect) * 3.14159 / 180) mediumNorthn.save("med_Northn.tif") mediumEastn.save("med_Eastn.tif") print "aspect (Northness/Eastness) calculated" # calculate Heat Load Index (Stoddard and Hayes 2005 uses it) mediumHeatLoadIndex = 1 - (arcpy.sa.Cos( (arcpy.Raster(mediumAspect) - 45) * 3.14159 / 180)) / 2 mediumHeatLoadIndex.save("med_HeatLoadIndex.tif") print "Heat Load Index calculated" # calculating solar radiation (insolation) mediumInsol = arcpy.sa.AreaSolarRadiation( mediumDEM_UTM, time_configuration=arcpy.sa.TimeWholeYear( "2009")) #,out_global_radiation_raster="med_Insol.tif") mediumInsol.save("med_Insol.tif") print "Insolation calculated" # calculate Topographic Moisture/Wetness Index # how I learned to do this: # http://www.faculty.umb.edu/david.tenenbaum/eeos383/ # http://www.faculty.umb.edu/david.tenenbaum/eeos383/eeos383-exercise03.pdf # http://www.faculty.umb.edu/david.tenenbaum/eeos383/eeos383-exercise05.pdf DEMfilled = arcpy.sa.Fill(mediumDEM_UTM) flowDir = arcpy.sa.FlowDirection(DEMfilled) flowAcc = arcpy.sa.FlowAccumulation(flowDir) contrArea = flowAcc * 10 * aggFac # multiply by cell area and divide by cell length medTMI = arcpy.sa.Ln( (contrArea + 1) / (arcpy.sa.Tan(arcpy.Raster(mediumSLOPE) * 3.14159 / 180))) medTMI.save("med_TMI.tif") print "TMI calculated" # calculating a distance to the nearest ridgeline; something like 'slope position' DistToRidge = arcpy.sa.FlowLength(flowDir, "UPSTREAM", "") DistToRidge.save("med_DistToRidge.tif") print "Distance to Ridgeline calculated"
import arcpy from arcpy import env env.workspace = "C:/Data" if arcpy.CheckExtension("3D") == "Available": arcpy.CheckOutExtension("3D") arcpy.Slope_3d("Yudu_DEM.img","Slope","DEGREES") arcpy.CheckInExtension("3D") else: print "3D Analyst license is unavailable."
arcpy.env.extent = DEM arcpy.env.extent = bndpoly # Resample to desired analysis size DEMres = '{}_{}m'.format(DEM, gridsz) arcpy.Resample_management(DEM, DEMres, gridsz, 'BILINEAR') # Set Snap Raster environment. All subsequent rasters will align to these cells. arcpy.env.snapRaster = DEMres # Make rasters from Elevation aspect = '{}_aspect'.format(DEMres) arcpy.Aspect_3d(DEMres, aspect) slope = '{}_slope'.format(DEMres) arcpy.Slope_3d(DEMres, slope, 'PERCENT_RISE') # Make distance rasters # Distance to dune toes distDL = os.path.join(home, 'y{}_distDL'.format(year)) outDistDL = arcpy.sa.EucDistance(DLpts, cell_size=gridsz) outDistDL.save(distDL) # Distance to dune crests distDH = os.path.join(home, 'y{}_distDH'.format(year)) outDistDH = arcpy.sa.EucDistance(DHpts, cell_size=gridsz) outDistDH.save(distDH) # Distance to shoreline distSL = os.path.join(home, 'y{}_distSL'.format(year)) outDistSL = arcpy.sa.EucDistance(SLpts, cell_size=gridsz) outDistSL.save(distSL)
def execute(self, params, messages): deleteInMemory() rawPath = os.path.dirname( params[1].valueAsText) + "\\" + os.path.basename( params[1].valueAsText) + "_Raw_Data" finalPath = os.path.dirname( params[1].valueAsText) + "\\" + os.path.basename( params[1].valueAsText) + "_Final_Data" testPath = os.path.dirname( params[1].valueAsText) + "\\" + os.path.basename( params[1].valueAsText) + "_Test_Data" if not os.path.exists(rawPath): os.mkdir(rawPath) if not os.path.exists(finalPath): os.mkdir(finalPath) if not os.path.exists(testPath): os.mkdir(testPath) poly = arcpy.MakeFeatureLayer_management(params[0].valueAsText) outRaw = rawPath + "\\" + os.path.basename(params[1].valueAsText) outFinal = finalPath + "\\" + os.path.basename(params[1].valueAsText) outTest = testPath + "\\" + os.path.basename(params[1].valueAsText) arcpy.env.workspace = os.path.dirname(params[1].valueAsText) arcpy.env.scratchWorkspace = os.path.dirname(params[1].valueAsText) Sites = arcpy.MakeFeatureLayer_management(params[2].valueAsText) DEM = params[4].valueAsText zFactor = params[5].value Streams = arcpy.MakeFeatureLayer_management(params[6].valueAsText) #Process Input Polygon lyr = finalPath + "\\" + os.path.basename( params[1].valueAsText) + "_Poly.shp" polyParts = int(arcpy.GetCount_management(poly).getOutput(0)) if polyParts > 1: arcpy.Dissolve_management(poly, lyr) else: arcpy.CopyFeatures_management(poly, lyr) lyrDesc = arcpy.Describe(lyr) lyrFields = lyrDesc.fields lyrExtent = lyrDesc.extent arcpy.env.extent = lyrExtent fieldx = 0 for field in lyrFields: if field.name == "POLY_ACRES": fieldx = 1 if fieldx == 0: arcpy.AddField_management(lyr, "POLY_ACRES", 'DOUBLE', 12, 8) arcpy.CalculateField_management(lyr, "POLY_ACRES", "!shape.area@ACRES!", "PYTHON_9.3", "") Desc = arcpy.Describe(lyr) polyAcres = ([ row[0] for row in arcpy.da.SearchCursor(lyr, ["POLY_ACRES"]) ][0]) arcpy.AddMessage("Polygon acreage = %d" % polyAcres) #Clip Sites siteQuery = params[3].ValueAsText outPoints = outFinal + "_Data_Points.shp" outSites = outRaw + "_Sites" if siteQuery == "Use All Sites": arcpy.MakeFeatureLayer_management(Sites, outSites) else: arcpy.MakeFeatureLayer_management(Sites, outSites, siteQuery) arcpy.SelectLayerByLocation_management(outSites, "INTERSECT", lyr) siteResult = int(arcpy.GetCount_management(outSites).getOutput(0)) arcpy.AddMessage(siteQuery) arcpy.AddMessage("Site Count = " + str(siteResult)) if siteResult < 10: arcpy.AddMessage("There are insufficient site data for analysis") systemExit(0) arcpy.FeatureToPoint_management(outSites, outPoints, "CENTROID") #Add Random field to extract build and test points arcpy.AddField_management(outPoints, "Test_Hold", "Double") with arcpy.da.UpdateCursor(outPoints, "Test_Hold") as cursor: for row in cursor: row[0] = random.random() cursor.updateRow(row) buildPoints = outTest + "_Build_Sites.shp" testPoints = outTest + "_Test_Sites.shp" arcpy.MakeFeatureLayer_management(outPoints, "in_memory\\test", """ "Test_Hold" <= 0.2 """) arcpy.CopyFeatures_management("in_memory\\test", testPoints) arcpy.MakeFeatureLayer_management(outPoints, "in_memory\\build", """ "Test_Hold" > 0.2 """) arcpy.CopyFeatures_management("in_memory\\build", buildPoints) #These are the raw layers of interest outSlope = outRaw + "_slp" outTopoProm = outRaw + "_pro" outHHODist = outRaw + "_dtw" outEleHHO = outRaw + "_eaw" outConfDist = outRaw + "_dtc" outEaConf = outRaw + "_eac" #DEM-based analysis outDEM = outRaw + "_dem" arcpy.Clip_management(DEM, "#", outDEM, lyr, "#", "ClippingGeometry") arcpy.Slope_3d(outDEM, outSlope, "DEGREE", zFactor) outBlk = BlockStatistics(outDEM, NbrCircle(3, "CELL"), "RANGE", "DATA") outBlk.save(outTopoProm) #Stream-based analysis - rubs only if streams are within input polygon outStreams = outFinal + "_str.shp" outVPts = outRaw + "_vpt.shp" vPtsEle = outRaw + "_vpe.shp" vPtsCor = outRaw + "_vpc.shp" outCPts = outRaw + "_cpt.shp" outCPsC = outRaw + "_cpc.shp" outBuff = outRaw + "_buff.shp" outDiss = outRaw + "_diss.shp" outConPts = outRaw + "_con.shp" cPtsEle = outRaw + "_cpe.shp" arcpy.Clip_analysis(Streams, lyr, outStreams) streamCount = arcpy.GetCount_management(outStreams) if not streamCount == 0: arcpy.FeatureVerticesToPoints_management(outStreams, outVPts, "ALL") arcpy.gp.ExtractValuesToPoints_sa(outVPts, outDEM, vPtsEle, "NONE", "VALUE_ONLY") arcpy.MakeFeatureLayer_management(vPtsEle, "in_memory\\vPtsCor", """"RASTERVALU" > 0""") arcpy.CopyFeatures_management("in_memory\\vPtsCor", vPtsCor) arcpy.AddField_management(vPtsCor, "WAT_ELEV", "SHORT") arcpy.CalculateField_management(vPtsCor, "WAT_ELEV", "[RASTERVALU]", "VB", "#") arcpy.gp.EucAllocation_sa(vPtsCor, "in_memory\\outAllo", "#", "#", "10", "WAT_ELEV", outHHODist, "#") arcpy.Minus_3d(outDEM, "in_memory\\outAllo", outEleHHO) deleteList = [outVPts, vPtsEle, vPtsCor] #Confluence-based analysis arcpy.FeatureVerticesToPoints_management(outStreams, "in_memory\\outCPts", "BOTH_ENDS") arcpy.MakeFeatureLayer_management("in_memory\\outCPts", outCPts) arcpy.FeatureToLine_management(lyr, "in_memory\\lyrLine", "#", "ATTRIBUTES") arcpy.SelectLayerByLocation_management(outCPts, "WITHIN_A_DISTANCE", "in_memory\\lyrLine", "100 Meters", "NEW_SELECTION") arcpy.SelectLayerByLocation_management(outCPts, "#", "#", "#", "SWITCH_SELECTION") arcpy.CopyFeatures_management(outCPts, outCPsC) arcpy.Buffer_analysis(outCPsC, outBuff, "10 METERS", "#", "#", "NONE", "#") arcpy.Dissolve_management(outBuff, outDiss, "#", "#", "SINGLE_PART", "#") arcpy.SpatialJoin_analysis(outDiss, outCPsC, "in_memory\\outJoin") arcpy.MakeFeatureLayer_management("in_memory\\outJoin", "in_memory\\joinLayer", """"Join_Count" >= 3""") arcpy.FeatureToPoint_management("in_memory\\joinLayer", outConPts, "CENTROID") arcpy.gp.ExtractValuesToPoints_sa(outConPts, outDEM, cPtsEle, "NONE", "VALUE_ONLY") arcpy.AddField_management(cPtsEle, "CONF_ELEV", "SHORT") arcpy.CalculateField_management(cPtsEle, "CONF_ELEV", "[RASTERVALU]", "VB", "#") arcpy.gp.EucAllocation_sa(cPtsEle, "in_memory\\outConfAllo", "#", "#", "10", "CONF_ELEV", outConfDist, "#") arcpy.Minus_3d(outDEM, "in_memory\\outConfAllo", outEaConf) deleteList = [ outCPts, outCPsC, outBuff, outDiss, outConPts, cPtsEle, outVPts, vPtsEle, vPtsCor ] for delete in deleteList: arcpy.Delete_management(delete) #Extract values to seperate tables and rename fields def extractValues(pointLayer, raster, outPoints, renameField): arcpy.gp.ExtractValuesToPoints_sa(pointLayer, raster, outPoints, "NONE", "ALL") arcpy.AddField_management(outPoints, renameField, "SHORT") arcpy.CalculateField_management(outPoints, renameField, "[RASTERVALU]", "VB", "#") return slopeTable = outRaw + "_slopePts.shp" promTable = outRaw + "_promPts.shp" distTHOtable = outRaw + "_distTHOPts.shp" distAHOtable = outRaw + "_distAHOPts.shp" distTCOtable = outRaw + "_distTCOPts.shp" distACOtable = outRaw + "_distACOPts.shp" extractValues(buildPoints, outSlope, slopeTable, "Slope") extractValues(buildPoints, outTopoProm, promTable, "Relief") if not streamCount == 0: extractValues(buildPoints, outHHODist, distTHOtable, "DTo_Water") extractValues(buildPoints, outEleHHO, distAHOtable, "DAbo_Water") extractValues(buildPoints, outConfDist, distTCOtable, "DTo_Conf") extractValues(buildPoints, outEaConf, distACOtable, "DAbo_Conf") #Get range of values for each layer and populate lists - reject null values def getValues(layer, fieldName): vList = [] with arcpy.da.SearchCursor(layer, [fieldName]) as cursor: for row in cursor: if row[0] != -999 and row[0] != -9999: vList.append(row[0]) return vList slopeList = getValues(slopeTable, "Slope") promList = getValues(promTable, "Relief") if not streamCount == 0: dtwList = getValues(distTHOtable, "DTo_Water") dawList = getValues(distAHOtable, "DAbo_Water") dtcList = getValues(distTCOtable, "DTo_Conf") dacList = getValues(distACOtable, "DAbo_Conf") deleteList = [ slopeTable, promTable, distTHOtable, distAHOtable, distTCOtable, distACOtable ] for item in deleteList: if arcpy.Exists(item): arcpy.Delete_management(item) #Get statistics for range of values def meanstdv(xlist): from math import sqrt n, total, std1 = len(xlist), 0, 0 for x in xlist: total = total + x mean = total / float(n) for x in xlist: std1 = std1 + (x - mean)**2 std = sqrt(std1 / float(n - 1)) return mean, std slopeStats = meanstdv(slopeList) promStats = meanstdv(promList) if not streamCount == 0: dtwStats = meanstdv(dtwList) dawStats = meanstdv(dawList) dtcStats = meanstdv(dtcList) dacStats = meanstdv(dacList) #Remap rasters according to 1-sigma range def remapRaster(inRaster, outRaster, recField, statList): R1 = statList[0] - statList[1] R2 = statList[0] + statList[1] rasterMin = arcpy.GetRasterProperties_management( inRaster, "MINIMUM") rasterMax = arcpy.GetRasterProperties_management( inRaster, "MAXIMUM") if R1 < rasterMin: R1 = rasterMin if R2 > rasterMax: R2 = rasterMax remap = str(rasterMin) + " " + str(R1) + " 0;" + str( R1) + " " + str(R2) + " 1;" + str(R2) + " " + str( rasterMax) + " 0" arcpy.Reclassify_3d(inRaster, recField, remap, outRaster, "NODATA") return outRaster targetSlope = outTest + "_slp" targetTopoProm = outTest + "_pro" targetHHODist = outTest + "_dtw" targetConfDist = outTest + "_dtc" targetEleHHO = outTest + "_eaw" targetEaConf = outTest + "_eac" remapRaster(outSlope, targetSlope, "Value", slopeStats) remapRaster(outTopoProm, targetTopoProm, "Value", promStats) if not streamCount == 0: remapRaster(outHHODist, targetHHODist, "Value", dtwStats) remapRaster(outEleHHO, targetEleHHO, "Value", dawStats) remapRaster(outConfDist, targetConfDist, "Value", dtcStats) remapRaster(outEaConf, targetEaConf, "Value", dacStats) #Test against test points def AreaAndAccuracy(inRaster, inPoly): rasterPoly = outRaw + "_poly.shp" rasterPolyarea = 0 lyrPolyarea = 0 testCount = int(arcpy.GetCount_management(testPoints).getOutput(0)) arcpy.RasterToPolygon_conversion(inRaster, rasterPoly, "SIMPLIFY", "Value") with arcpy.da.SearchCursor(rasterPoly, ("GRIDCODE", "SHAPE@AREA")) as cursor: for row in cursor: if row[0] == 1: rasterPolyarea += row[1] with arcpy.da.SearchCursor(inPoly, "SHAPE@AREA") as cursor: for row in cursor: lyrPolyarea += row[0] targetAcres = rasterPolyarea / lyrPolyarea arcpy.MakeFeatureLayer_management(rasterPoly, "in_memory\\rasterPoly", """ "GRIDCODE" = 1 """) arcpy.MakeFeatureLayer_management(testPoints, "in_memory\\testPoints") arcpy.SelectLayerByLocation_management("in_memory\\testPoints", "WITHIN", "in_memory\\rasterPoly") selectCount = int( arcpy.GetCount_management("in_memory\\testPoints").getOutput( 0)) Accuracy = float(selectCount) / float(testCount) indexValue = float(Accuracy) / float(targetAcres) arcpy.AddMessage( os.path.basename(inRaster) + ": Accuracy = " + (str(Accuracy)[:5]) + ", Target Area Proportion = " + (str(targetAcres)[:5]) + ", Index = " + (str(indexValue)[:5])) arcpy.Delete_management(rasterPoly) return targetAcres, Accuracy, indexValue #Evaluate accuracy and target area proprtion - generate accuracy/area index - eliminate where index < 1 assessList = [ targetSlope, targetTopoProm, targetHHODist, targetEleHHO, targetConfDist, targetEaConf ] sumDict = {} for item in assessList: if arcpy.Exists(item): testX = AreaAndAccuracy(item, lyr) if testX[2] >= 1: sumDict[item] = testX nameList = sumDict.keys() #Weighted overlay outWeight = outFinal + "wgt" weightList = [] for item in sumDict: weightList.append(str(item) + " Value " + str(sumDict[item][2])) weightString = ";".join(weightList) arcpy.gp.WeightedSum_sa(weightString, outWeight) deleteInMemory() return
def runScript(uploaderpk): print("Starting script") startTime = time.time() arcpy.env.overwriteOutput = True arcpy.env.cellSize = 1 # Activate spatial analyst extension if arcpy.CheckExtension("Spatial") == "Available": arcpy.CheckOutExtension("Spatial") if arcpy.CheckExtension("3D") == "Available": arcpy.CheckOutExtension("3D") # basePath = .../apps/findbestroute/workfiles/ global basePath sleep(2) basePath = os.path.join(settings.PROJECT_PATH, 'apps', 'findbestroute', 'workfiles') env.workspace = basePath sleep(2) mxd = arcpy.mapping.MapDocument(os.path.join(basePath, r'mapdocument.mxd')) onlyfiles = [] kart_path = None for file in os.listdir( os.path.join(settings.PROJECT_PATH, r"files", r"user_" + str(uploaderpk))): if file.endswith(".shp"): onlyfiles.append( os.path.join(settings.PROJECT_PATH, r"files", r"user_" + str(uploaderpk), file)) elif file.endswith(".jpg"): kart_path = os.path.join(settings.PROJECT_PATH, r"files", r"user_" + str(uploaderpk), file) for el in onlyfiles: print("File: " + el.__str__()) print("Map file: " + kart_path.__str__()) arealsymboler, linjesymboler, punktsymboler, breakBoolean = geometryType( onlyfiles) if (breakBoolean): print( "Datafiles not containing all shapefiles( either point, polyline or polygon)" ) return kart = kart_path #os.path.join(settings.PROJECT_PATH, r"apps", r"findbestroute", r"workfiles", r"inData", r"kart.jpg") #geoProcess(kart_path, arealsymboler) start = getStart(punktsymboler) destination = getDestination(punktsymboler) mask = setMask(start, destination) arcpy.env.mask = os.path.join(basePath, r"Trash", r"mask.shp") utsnitt = getExtentOfMap(linjesymboler) hoydedata = arcpy.Clip_analysis( in_features=os.path.join(basePath, r"hoydeData", r"trondheiml.shp"), clip_features=utsnitt, out_feature_class=os.path.join(basePath, r"Trash", r"hoydedata.shp"), cluster_tolerance="") #Klipper til symbolene etter mask ar = arcpy.Clip_analysis(in_features=arealsymboler, clip_features=mask, out_feature_class=os.path.join( basePath, r"Trash", r"a5"), cluster_tolerance="") ln = arcpy.Clip_analysis(in_features=linjesymboler, clip_features=mask, out_feature_class=os.path.join( basePath, r"Trash", r"a6"), cluster_tolerance="") pt = arcpy.Clip_analysis(in_features=punktsymboler, clip_features=mask, out_feature_class=os.path.join( basePath, r"Trash", r"a7"), cluster_tolerance="") #Runde ned alle symboler floorSymbols(ar) floorSymbols(ln) floorSymbols(pt) #Lage buffer paa linjer som er lik bredden de skal ha fieldnames = [field.name for field in arcpy.ListFields(ln)] if not "WIDTH" in fieldnames: arcpy.AddField_management(in_table=ln, field_name="WIDTH", field_type="DOUBLE") symbols = [ 106, 107, 201, 203, 304, 305, 307, 502, 503, 504, 505, 506, 507, 508, 509 ] width = [2, 2, 4, 4, 2, 2, 1, 6, 4, 3, 2.5, 2, 2, 2, 2] features = arcpy.UpdateCursor(ln) for feature in features: if feature.SYMBOL in symbols: n = symbols.index(feature.SYMBOL) feature.WIDTH = width[n] features.updateRow(feature) del feature, features, n ln_buff = arcpy.Buffer_analysis(in_features=ln, out_feature_class=os.path.join( basePath, r"Trash", r"a8"), buffer_distance_or_field="WIDTH", line_side="FULL", line_end_type="FLAT", dissolve_option="LIST", dissolve_field="SYMBOL") #Hente ut alle forbudte symboler forbiddenArea = arcpy.Select_analysis( in_features=ar, out_feature_class=os.path.join(basePath, r"Trash", r"a9"), where_clause= '"SYMBOL" = 202 OR "SYMBOL" = 211 OR "SYMBOL" = 301 OR "SYMBOL" = 302 OR "SYMBOL" = 307 OR "SYMBOL" = 415 OR "SYMBOL" = 526 OR "SYMBOL" = 527 OR "SYMBOL" = 528 OR "SYMBOL" = 709' ) forbiddenLineBuff = arcpy.Select_analysis( in_features=ln_buff, out_feature_class=os.path.join(basePath, r"Trash", r"b1"), where_clause= '"SYMBOL" = 201 OR "SYMBOL" = 307 OR "SYMBOL" = 521 OR "SYMBOL" = 524 OR "SYMBOL" = 528 OR "SYMBOL" = 534 OR "SYMBOL" = 709' ) #Hente ut alle passerbare symboler passableArea = arcpy.Select_analysis( in_features=ar, out_feature_class=os.path.join(basePath, r"Trash", r"b2"), where_clause= '"SYMBOL" <> 202 AND "SYMBOL" <> 211 AND "SYMBOL" <> 301 AND "SYMBOL" <> 302 AND "SYMBOL" <> 307 AND "SYMBOL" <> 415 AND "SYMBOL" <> 526 AND "SYMBOL" <> 527 AND "SYMBOL" <> 528 AND "SYMBOL" <> 601 AND "SYMBOL" <> 709' ) passableLineBuff = arcpy.Select_analysis( in_features=ln_buff, out_feature_class=os.path.join(basePath, r"Trash", r"b3"), where_clause= '"SYMBOL" <> 201 AND "SYMBOL" <> 307 AND "SYMBOL" <> 521 AND "SYMBOL" <> 524 AND "SYMBOL" <> 528 AND "SYMBOL" <> 534 AND "SYMBOL" <> 709' ) #Lage skogflater area = arcpy.Update_analysis(in_features=passableArea, update_features=forbiddenArea, out_feature_class=os.path.join( basePath, r"Trash", r"b4")) forest = arcpy.Erase_analysis(in_features=mask, erase_features=area, out_feature_class=os.path.join( basePath, r"Trash", r"b5")) arcpy.AddField_management(in_table=forest, field_name="SYMBOL", field_type="DOUBLE") features = arcpy.UpdateCursor(forest) for feature in features: feature.SYMBOL = 405 features.updateRow(feature) del feature, features #Lage kartet i ArcMap area1 = arcpy.Erase_analysis(in_features=passableArea, erase_features=forbiddenArea, out_feature_class=os.path.join( basePath, r"Trash", r"b6")) area2 = arcpy.Erase_analysis(in_features=area1, erase_features=forbiddenLineBuff, out_feature_class=os.path.join( basePath, r"Trash", r"b7")) passable1 = arcpy.Update_analysis(in_features=area2, update_features=forest, out_feature_class=os.path.join( basePath, r"Trash", r"b8")) mapped = arcpy.Update_analysis(in_features=passable1, update_features=passableLineBuff, out_feature_class=os.path.join( basePath, r"Trash", r"b9")) #Sette kostnad paa alle flater setCost(mapped) print('hey') costRaster = arcpy.FeatureToRaster_conversion( mapped, "COST", os.path.join(basePath, r"Results", r"CostRaster.tif")) #Lage sloperaster #create a TIN of the area tin = arcpy.CreateTin_3d( out_tin=os.path.join(basePath, r"Results", r"TIN"), spatial_reference="#", in_features=os.path.join(basePath, r"Trash", r"hoydedata.shp") + " HOEYDE masspoints") # Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script # The following inputs are layers or table views: "hoydeTIN" tinRaster = arcpy.TinRaster_3d(in_tin=os.path.join(basePath, r"Results", r"TIN"), out_raster=os.path.join( basePath, r"Results", "hRaster"), data_type="FLOAT", method="LINEAR", sample_distance="CELLSIZE 1", z_factor="1") # Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script # The following inputs are layers or table views: "hraster" slope = arcpy.Slope_3d(in_raster=os.path.join(basePath, r"Results", r"hRaster"), out_raster=os.path.join(basePath, r"Results", r"slope"), output_measurement="DEGREE", z_factor="1") # Reklassifisering av slope reMapRange = RemapRange([[0, 0.5, 100], [0.5, 1, 101], [1, 2, 102], [2, 3, 103], [3, 4, 104], [4, 5, 105], [5, 6, 106], [6, 7, 107], [7, 8, 108], [8, 9, 109], [9, 10, 110], [10, 11, 111], [11, 12, 112], [12, 13, 113], [13, 14, 114], [14, 15, 115], [15, 16, 116], [16, 17, 117], [17, 18, 118], [18, 19, 119], [19, 20, 120], [20, 90, 150]]) slope_reclass = Reclassify(in_raster=os.path.join(basePath, r"Results", r"slope"), reclass_field="VALUE", remap=reMapRange) slope_reclass.save(os.path.join(basePath, r"Results", r"slopeReclass")) # Rasterkalkulator som lager raster som tar hensyn til hoyde i kostnadsrasteret finalCostRaster = Raster( os.path.join(basePath, r"Results", r"CostRaster.tif")) * ( Raster(os.path.join(basePath, r"Results", r"slopeReclass")) / 100) #Regne ut leastcostpath cdr = arcpy.sa.CostDistance(start, finalCostRaster) cdr.save(os.path.join(basePath, r"Results", r"costDistance")) cbr = arcpy.sa.CostBackLink(start, finalCostRaster) cbr.save(os.path.join(basePath, r"Results", r"Costback")) cp = arcpy.sa.CostPath(destination, cdr, cbr, "EACH_CELL") cp.save(os.path.join(basePath, r"Results", r"costpath")) #Gjore om til polygon med litt bredde arcpy.RasterToPolygon_conversion( in_raster=os.path.join(basePath, r"Results", r"costpath"), out_polygon_features=os.path.join(basePath, r"Results", r"cpPoly.shp"), simplify="SIMPLIFY") arcpy.Buffer_analysis(in_features=os.path.join(basePath, r"Results", r"cpPoly.shp"), out_feature_class=os.path.join( basePath, r"Results", r"LCP.shp"), buffer_distance_or_field="2", line_side="FULL", line_end_type="FLAT", dissolve_option="LIST") df = arcpy.mapping.ListDataFrames(mxd, "*")[0] for lyr in arcpy.mapping.ListLayers(mxd, "", df): arcpy.mapping.RemoveLayer(df, lyr) print("Deleted lyr's in mxd") #Legge til i ArcMap templateLayer = arcpy.mapping.Layer( os.path.join(basePath, r"Template", r"colorTemplate.lyr")) df = arcpy.mapping.ListDataFrames(mxd, "*")[0] newlayer = arcpy.mapping.Layer( os.path.join(basePath, r"Results", r"LCP.shp")) newlayer.transparency = 50 """ PROBLEMBARN RETT UNDER """ arcpy.ApplySymbologyFromLayer_management(in_layer=newlayer, in_symbology_layer=templateLayer) # in_symbology_layer = os.path.join(basePath, r"Template", r"colorTemplate.lyr")) """ PROBLEMBARN RETT OVER """ arcpy.mapping.AddLayer(df, newlayer, "BOTTOM") arcpy.MakeRasterLayer_management(in_raster=kart, out_rasterlayer=os.path.join( basePath, r"Results", r"rasterkart")) mapLayer = arcpy.mapping.Layer( os.path.join(basePath, r"Results", r"rasterkart")) arcpy.mapping.AddLayer(df, mapLayer, "BOTTOM") # Lage postsirkler og linje og legge til dette i ArcGIS points = arcpy.CreateFeatureclass_management(out_path=os.path.join( basePath, r"Trash"), out_name="points", geometry_type="POINT") del destination start = getStart(pt) destination = getDestination(pt) features = arcpy.UpdateCursor(start) for feature in features: startX = feature.POINT_X startY = feature.POINT_Y features = arcpy.UpdateCursor(destination) for feature in features: destX = feature.POINT_X destY = feature.POINT_Y cursor = arcpy.da.InsertCursor(points, ("fid", "SHAPE@XY")) cursor.insertRow((1, (startX, startY))) cursor.insertRow((2, (destX, destY))) del destination outerCircle = arcpy.CreateFeatureclass_management(out_path=os.path.join( basePath, r"Trash"), out_name="circles1.shp", geometry_type="POLYGON") innerCircle = arcpy.CreateFeatureclass_management(out_path=os.path.join( basePath, r"Trash"), out_name="circles2.shp", geometry_type="POLYGON") circle = arcpy.CreateFeatureclass_management( out_path=os.path.join(basePath, r"Trash"), out_name="circles.shp", geometry_type="POLYGON", ) arcpy.Buffer_analysis(points, outerCircle, 40) arcpy.Buffer_analysis(points, innerCircle, 35) arcpy.Erase_analysis(outerCircle, innerCircle, circle) symLayer = arcpy.mapping.Layer( os.path.join(basePath, r"Template", r"color2.lyr")) circleLayer = arcpy.mapping.Layer( os.path.join(basePath, r"Trash", r"circles.shp")) arcpy.ApplySymbologyFromLayer_management(in_layer=circleLayer, in_symbology_layer=symLayer) arcpy.mapping.AddLayer(data_frame=df, add_layer=circleLayer, add_position="TOP") # Lage postlinje lines = arcpy.CreateFeatureclass_management(out_path=os.path.join( basePath, r"Trash"), out_name="line.shp", geometry_type="POLYGON") directionX = (destX - startX) / ( math.sqrt(math.pow(destX - startX, 2) + math.pow(destY - startY, 2))) directionY = (destY - startY) / ( math.sqrt(math.pow(destX - startX, 2) + math.pow(destY - startY, 2))) features = [] features.append( arcpy.Polyline( arcpy.Array([ arcpy.Point(startX + 45 * directionX, startY + 45 * directionY), arcpy.Point(destX - 45 * directionX, destY - 45 * directionY) ]))) lineFeat = arcpy.CopyFeatures_management( features, os.path.join(basePath, r"Trash", r"lines.shp")) arcpy.Buffer_analysis(in_features=lineFeat, out_feature_class=lines, buffer_distance_or_field=2.5, line_end_type="FLAT") lineLayer = arcpy.mapping.Layer( os.path.join(basePath, r"Trash", r"line.shp")) arcpy.ApplySymbologyFromLayer_management(in_layer=lineLayer, in_symbology_layer=symLayer) arcpy.mapping.AddLayer(data_frame=df, add_layer=lineLayer, add_position="TOP") mxd.save() #Skrive ut bilde av veivalg B = df.extent.XMax - df.extent.XMin H = df.extent.YMax - df.extent.YMin filename = str(uploaderpk) + "_" + time.strftime( "%d-%m-%Y") + "_" + time.strftime("%H-%M-%S") + ".png" relative_path_string = os.path.join(r"Dump", filename) print("hurr " + settings.PROJECT_PATH) print("durr " + relative_path_string) out_path = os.path.join(settings.PROJECT_PATH, "files", r"Dump", filename) print(out_path) arcpy.mapping.ExportToPNG(map_document=mxd, out_png=out_path, data_frame=df, df_export_width=int(3 * B), df_export_height=int(3 * H), resolution=225) print("Finished making image") #relative_path = os.path.join(r"Dump", "MapLCP.png") img = Image() img.uploader = PathUser.objects.get(pk=uploaderpk) img.bilde = relative_path_string img.save() folder = os.path.join(basePath, r"Trash") for file in os.listdir(folder): filepath = os.path.join(folder, file) try: if os.path.isfile(filepath): print "Removing " + filepath os.remove(filepath) elif os.path.isdir(filepath): print "Removing " + filepath shutil.rmtree(filepath) except Exception as e: print(e) folder = os.path.join(basePath, r"Results") for file in os.listdir(folder): filepath = os.path.join(folder, file) try: if os.path.isfile(filepath): print "Removing " + filepath os.remove(filepath) elif os.path.isdir(filepath): print "Removing " + filepath shutil.rmtree(filepath) except Exception as e: print(e) delete_user_uploads.delay(uploaderpk) end = time.time() print(end - startTime)
# Process: Fill - works fill = arcpy.sa.Fill(DEM) fill.save(Fill_DEM) print ("Fill complete.") # Process: Flow Direction - works flow = arcpy.gp.FlowDirection_sa(Fill_DEM, DEM_FlowDir, "Normal", "D8") print ("Flow Direction complete.") # Process: Hillshade - works hshade = arcpy.HillShade_3d(Fill_DEM, Hillshade, "315", "45", "NO_SHADOWS", "1") print ("Hillshade complete.") # Process: Slope Raster slope = arcpy.Slope_3d(Fill_DEM, Slope_Percent, "PERCENT_RISE", 0.3048, "PLANAR", "") print ("Slope Raster complete.") # Process: Aspect Raster aspect = arcpy.sa.Aspect(Fill_DEM, "PLANAR", "") aspect.save (DEM_Aspect) print ("Aspect Raster complete.") # Process: Raster Domain - works arcpy.RasterDomain_3d(Fill_DEM, DEM_Domain, "POLYGON") print ("Raster Domain complete.") # Process: Clip - works tempEnvironment0 = arcpy.env.extent arcpy.Clip_analysis(Trail, DEM_Domain, Trail_Clip) arcpy.env.extent = tempEnvironment0
#enable output overwrite arcpy.env.overwriteOutput = True #output folder arcpy.env.workspace = 'I:\\asignaturas\\sig-I\\2012-2013\\cuatrimestreB\\teoria\\MT7\\salida' #tool parameters grid = 'grid' output_layer = 'slopes' units = 'DEGREE' factor = 1 if arcpy.CheckExtension("3D") == "Available": arcpy.CheckOutExtension("3D") #slope tool arcpy.Slope_3d(grid, output_layer, units, factor) arcpy.CheckInExtension("3D") else: print('License not available') #------------------------------------------------------------------------------- # NDVI #------------------------------------------------------------------------------- #Info: #https://en.wikipedia.org/wiki/Normalized_Difference_Vegetation_Index #importing modules import arcpy from arcpy.sa import * #Acceso a las variable de entorno
def execute(self, params, messages): deleteInMemory() Limit = params[14].value strLimit = params[14].ValueAsText arcpy.AddMessage("Target Data Capture = " + strLimit) rawPath = os.path.dirname( params[1].valueAsText) + "\\" + os.path.basename( params[1].valueAsText) + "_Raw_Data" finalPath = os.path.dirname( params[1].valueAsText) + "\\" + os.path.basename( params[1].valueAsText) + "_Final_Data" if not os.path.exists(rawPath): os.mkdir(rawPath) if not os.path.exists(finalPath): os.mkdir(finalPath) poly = arcpy.MakeFeatureLayer_management(params[0].valueAsText) outRaw = rawPath + "\\" + os.path.basename(params[1].valueAsText) outFinal = finalPath + "\\" + os.path.basename(params[1].valueAsText) outMain = params[1].valueAsText arcpy.env.workspace = os.path.dirname(params[1].valueAsText) arcpy.env.scratchWorkspace = os.path.dirname(params[1].valueAsText) DEM = params[5].valueAsText Geology = arcpy.MakeFeatureLayer_management(params[7].valueAsText) geoField = params[8].valueAsText Soils = arcpy.MakeFeatureLayer_management(params[9].valueAsText) soilField = params[10].valueAsText Vegetation = arcpy.MakeFeatureLayer_management(params[11].valueAsText) vegField = params[12].valueAsText Streams = arcpy.MakeFeatureLayer_management(params[13].valueAsText) Sites = arcpy.MakeFeatureLayer_management(params[2].valueAsText) zFactor = params[6].value try: #Multipart Handling lyr = finalPath + "\\" + os.path.basename( params[1].valueAsText) + "_Poly.shp" polyParts = int(arcpy.GetCount_management(poly).getOutput(0)) if polyParts > 1: arcpy.Dissolve_management(poly, lyr) else: arcpy.CopyFeatures_management(poly, lyr) #Create and calcualte POLY_ACRES arcpy.AddField_management(lyr, "POLY_ACRES", 'DOUBLE', 12, 8) arcpy.CalculateField_management(lyr, "POLY_ACRES", "!shape.area@ACRES!", "PYTHON_9.3", "") Desc = arcpy.Describe(lyr) polyAcres = ([ row[0] for row in arcpy.da.SearchCursor(lyr, ["POLY_ACRES"]) ][0]) arcpy.AddMessage("Analysis area = " + str(polyAcres) + " acres") if polyAcres > 50000: arcpy.AddMessage("Target layer overlap will not be calculated") #Clip Sites siteField = params[3].valueAsText siteValue = params[4].valueAsText outPoints = outFinal + "_Data_Points.shp" outSites = outRaw + "_Sites" if siteValue == "ALL SITES": arcpy.MakeFeatureLayer_management(Sites, outSites) else: siteQuery = '"' + siteField + '"' + " = " + "'" + siteValue + "'" arcpy.MakeFeatureLayer_management(Sites, outSites, siteQuery) arcpy.SelectLayerByLocation_management(outSites, "INTERSECT", lyr) siteResult = int(arcpy.GetCount_management(outSites).getOutput(0)) arcpy.AddMessage(siteValue + " Site Count = " + str(siteResult)) if siteResult < 10: arcpy.AddMessage( "There are insufficient site data for analysis") deleteInMemory() SystemExit(0) siteDensity = str(siteResult / polyAcres) arcpy.AddMessage("Site density = " + siteDensity[0:5] + " sites/acre") if siteResult / polyAcres < 0.01: arcpy.AddMessage( "Site density is too low for reliable analysis (0.010 sites/acre minimum), use discretion when interpreting results" ) arcpy.FeatureToPoint_management(outSites, outPoints, "CENTROID") #Clip DEM, Calculate Slope and Aspect, Reclassify outDEM = outRaw + "_Dem" outSlope = outRaw + "_Slp" outAspect = outRaw + "_Asp" arcpy.AddMessage("Clipping DEM") arcpy.Clip_management(DEM, "#", "in_memory\\DEMClip", lyr, "#", "ClippingGeometry") arcpy.Reclassify_3d( "in_memory\\DEMClip", "VALUE", "0 100 100;100 200 200;200 300 300;300 400 400;400 500 500;500 600 600;600 700 700;700 800 800;800 900 900;900 1000 1000;1000 1100 1100;1100 1200 1200;1200 1300 1300;1300 1400 1400;1400 1500 1500;1500 1600 1600;1600 1700 1700;1700 1800 1800;1800 1900 1900;1900 2000 2000;2000 2100 2100;2100 2200 2200;2200 2300 2300;2300 2400 2400;2400 2500 2500;2500 2600 2600;2600 2700 2700;2700 2800 2800;2800 2900 2900;2900 3000 3000;3000 3100 3100;3100 3200 3200;3200 3300 3300;3300 3400 3400;3400 3500 3500;3500 3600 3600;3600 3700 3700;3700 3800 3800;3800 3900 3900;3900 4000 4000;4000 4100 4100;4100 4200 4200;4200 4300 4300;4300 4400 4400;4400 4500 4500;4500 4600 4600;4600 4700 4700;4700 4800 4800;4800 4900 4900;4900 5000 5000;5000 5100 5100;5100 5200 5200;5200 5300 5300;5300 5400 5400;5400 5500 5500;5500 5600 5600;5600 5700 5700;5700 5800 5800;5800 5900 5900;5900 6000 6000;6000 6100 6100;6100 6200 6200;6200 6300 6300;6300 6400 6400;6400 6500 6500;6500 6600 6600;6600 6700 6700;6700 6800 6800;6800 6900 6900;6900 7000 7000;7000 7100 7100;7100 7200 7200;7200 7300 7300;7300 7400 7400;7400 7500 7500;7500 7600 7600;7600 7700 7700;7700 7800 7800;7800 7900 7900;7900 8000 8000;8000 8100 8100;8100 8200 8200;8200 8300 8300;8300 8400 8400;8400 8500 8500;8500 8600 8600;8600 8700 8700;8700 8800 8800;8800 8900 8900;8900 9000 9000;9000 9100 9100;9100 9200 9200;9200 9300 9300;9300 9400 9400;9400 9500 9500;9500 9600 9600;9600 9700 9700;9700 9800 9800;9800 9900 9900;9900 10000 10000;10000 10100 10100;10100 10200 10200;10200 10300 10300;10300 10400 10400;10400 10500 10500;10500 10600 10600;10600 10700 10700;10700 10800 10800;10800 10900 10900;10900 11000 11000;11000 11100 11100;11100 11200 11200;11200 11300 11300;11300 11400 11400;11400 11500 11500;11500 11600 11600;11600 11700 11700;11700 11800 11800;11800 11900 11900;11900 12000 12000;12000 12100 12100;12100 12200 12200;12200 12300 12300;12300 12400 12400;12400 12500 12500;12500 12600 12600;12600 12700 12700;12700 12800 12800;12800 12900 12900;12900 13000 13000;13000 13100 13100;13100 13200 13200;13200 13300 13300;13300 13400 13400;13400 13500 13500;13500 13600 13600;13600 13700 13700;13700 13800 13800;13800 13900 13900;13900 14000 14000;14000 14100 14100;14100 14200 14200;14200 14300 14300;14300 14400 14400;14400 14500 14500;14500 14600 14600;14600 14700 14700;14700 14800 14800;14800 14900 14900;14900 15000 15000", outDEM) arcpy.AddMessage("Calculating Slope") arcpy.Slope_3d("in_memory\\DEMClip", "in_memory\\outSlope", "DEGREE", zFactor) arcpy.Reclassify_3d( "in_memory\\outSlope", "VALUE", "0 5 5;5 10 10;10 15 15;15 20 20;20 25 25;25 30 30;30 35 35;35 40 40;40 45 45;45 90 90", outSlope) arcpy.AddMessage("Calculating Aspect") arcpy.Aspect_3d("in_memory\\DEMClip", "in_memory\\outAspect") arcpy.Reclassify_3d( "in_memory\\outAspect", "VALUE", "-1 22.5 0;22.5 67.5 1;67.5 112.5 2;112.5 157.5 3;157.5 202.5 4;202.5 247.5 5;247.5 292.5 6;292.5 337.5 7;337.5 360 0", outAspect) #Clip Geology arcpy.AddMessage("Clipping Geology") outGeo = outRaw + "_Geo.shp" arcpy.Clip_analysis(Geology, lyr, "in_memory\\outGeo") arcpy.Dissolve_management("in_memory\\outGeo", outGeo, geoField) #Clip Soils arcpy.AddMessage("Clipping Soils") outSoils = outRaw + "_Soil.shp" arcpy.Clip_analysis(Soils, lyr, "in_memory\\outSoil") arcpy.Dissolve_management("in_memory\\outSoil", outSoils, soilField) #Clip Vegetation arcpy.AddMessage("Clipping Vegetation") outVeg = outRaw + "_Veg.shp" arcpy.Clip_analysis(Vegetation, lyr, "in_memory\\outVeg") arcpy.Dissolve_management("in_memory\\outVeg", outVeg, vegField) #Clip Streams arcpy.AddMessage("Clipping and Buffering Streams") outStr = outRaw + "_Str.shp" strLayer = arcpy.MakeFeatureLayer_management( Streams, "in_memory\\streams") arcpy.SelectLayerByLocation_management("in_memory\\streams", "INTERSECT", lyr, "", "NEW_SELECTION") streamResult = int( arcpy.GetCount_management("in_memory\\streams").getOutput(0)) if streamResult == 0: arcpy.AddMessage("There Are No Streams Within This Polygon") else: outStreams = outRaw + "_Str.shp" arcpy.Clip_analysis(Streams, lyr, "in_memory\\outStreams") arcpy.MultipleRingBuffer_analysis("in_memory\\outStreams", outStr, [200, 400, 600, 800, 1000], "meters") deleteInMemory() #DEM demTarget = outFinal + "_Elevation_Target.shp" demFinal = outRaw + "_DEM.shp" arcpy.AddMessage("Processing DEM") ExtractValuesToPoints(outPoints, outDEM, "in_memory\\pointDEM") arcpy.Frequency_analysis("in_memory\\pointDEM", "in_memory\\DEM_Table", "RASTERVALU") arcpy.Sort_management("in_memory\\DEM_Table", "in_memory\\DEM_Sort", [["FREQUENCY", "DESCENDING"]]) Vdem = 0 Xdem = 0 demList = [] with arcpy.da.SearchCursor("in_memory\\DEM_Sort", ["RASTERVALU", "FREQUENCY"]) as cursor: for row in cursor: if Xdem == 0: Vdem = row[1] demList.append(row[0]) else: Vdem = Vdem + row[1] demList.append(row[0]) if float(Vdem) / float(siteResult) < Limit: Xdem = Xdem + 1 else: break arcpy.RasterToPolygon_conversion(outDEM, demFinal, "SIMPLIFY", "VALUE") DEMdesc = arcpy.Describe(demFinal) fields = DEMdesc.fields for field in fields: if field.name == "GRIDCODE": arcpy.AddField_management(demFinal, "ELEV", field.type, field.precision, field.scale, field.length, "", "", "", "") with arcpy.da.UpdateCursor(demFinal, ["GRIDCODE", "ELEV"]) as cursor: for row in cursor: row[1] = row[0] cursor.updateRow(row) arcpy.DeleteField_management(demFinal, "GRIDCODE") qryList = [str(dem) for dem in demList] expr = "ELEV IN (" + ",".join(qryList) + ")" arcpy.MakeFeatureLayer_management(demFinal, "in_memory\\demTarget", expr) arcpy.Dissolve_management("in_memory\\demTarget", demTarget, "ELEV") #arcpy.Delete_management(outDEM) #SLOPE slopeTarget = outFinal + "_Slope_Target.shp" slopeFinal = outRaw + "_Slope.shp" arcpy.AddMessage("Processing Slope") ExtractValuesToPoints(outPoints, outSlope, "in_memory\\pointSlope") arcpy.Frequency_analysis("in_memory\\pointSlope", "in_memory\\Slope_Table", "RASTERVALU") arcpy.Sort_management("in_memory\\Slope_Table", "in_memory\\Slope_Sort", [["FREQUENCY", "DESCENDING"]]) Vslp = 0 Xslp = 0 slpList = [] with arcpy.da.SearchCursor("in_memory\\Slope_Sort", ["RASTERVALU", "FREQUENCY"]) as cursor: for row in cursor: if Xslp == 0: Vslp = row[1] slpList.append(row[0]) else: Vslp = Vslp + row[1] slpList.append(row[0]) if float(Vslp) / float(siteResult) < Limit: Xslp = Xslp + 1 else: break arcpy.RasterToPolygon_conversion(outSlope, slopeFinal, "SIMPLIFY", "VALUE") Slpdesc = arcpy.Describe(slopeFinal) fields = Slpdesc.fields for field in fields: if field.name == "GRIDCODE": arcpy.AddField_management(slopeFinal, "SLOPE", field.type, field.precision, field.scale, field.length, "", "", "", "") with arcpy.da.UpdateCursor( slopeFinal, ["GRIDCODE", "SLOPE"]) as cursor: for row in cursor: row[1] = row[0] cursor.updateRow(row) arcpy.DeleteField_management(slopeFinal, "GRIDCODE") qryList = [str(slp) for slp in slpList] expr = "SLOPE IN (" + ",".join(qryList) + ")" arcpy.MakeFeatureLayer_management(slopeFinal, "in_memory\\slopeTarget", expr) arcpy.Dissolve_management("in_memory\\slopeTarget", slopeTarget, "SLOPE") #arcpy.Delete_management(outSlope) #ASPECT aspectTarget = outFinal + "_Aspect_Target.shp" aspectFinal = outRaw + "_Aspect.shp" arcpy.AddMessage("Processing Aspect") ExtractValuesToPoints(outPoints, outAspect, "in_memory\\pointAspect") arcpy.Frequency_analysis("in_memory\\pointAspect", "in_memory\\aspect_Table", "RASTERVALU") arcpy.Sort_management("in_memory\\aspect_Table", "in_memory\\aspect_Sort", [["FREQUENCY", "DESCENDING"]]) Vasp = 0 Xasp = 0 aspList = [] with arcpy.da.SearchCursor("in_memory\\aspect_Sort", ["RASTERVALU", "FREQUENCY"]) as cursor: for row in cursor: if Xasp == 0: Vasp = row[1] aspList.append(row[0]) else: Vasp = Vasp + row[1] aspList.append(row[0]) if float(Vasp) / float(siteResult) < Limit: Xasp = Xasp + 1 else: break arcpy.RasterToPolygon_conversion(outAspect, aspectFinal, "SIMPLIFY", "VALUE") Aspdesc = arcpy.Describe(aspectFinal) fields = Aspdesc.fields for field in fields: if field.name == "GRIDCODE": arcpy.AddField_management(aspectFinal, "ASPECT", field.type, field.precision, field.scale, field.length, "", "", "", "") with arcpy.da.UpdateCursor( aspectFinal, ["GRIDCODE", "ASPECT"]) as cursor: for row in cursor: row[1] = row[0] cursor.updateRow(row) arcpy.DeleteField_management(aspectFinal, "GRIDCODE") qryList = [str(asp) for asp in aspList] expr = "ASPECT IN (" + ",".join(qryList) + ")" arcpy.MakeFeatureLayer_management(aspectFinal, "in_memory\\aspectTarget", expr) arcpy.Dissolve_management("in_memory\\aspectTarget", aspectTarget, "ASPECT") #arcpy.Delete_management(outAspect) #GEOLOGY GeoTarget = outFinal + "_Geology_Target.shp" arcpy.AddMessage("Processing Geology") arcpy.SpatialJoin_analysis(outPoints, outGeo, "in_memory\\pointGeo") arcpy.Frequency_analysis("in_memory\\pointGeo", "in_memory\\geo_Table", geoField) arcpy.Sort_management("in_memory\\geo_Table", "in_memory\\geo_Sort", [["FREQUENCY", "DESCENDING"]]) Vgeo = 0 Xgeo = 0 geoList = [] with arcpy.da.SearchCursor("in_memory\\geo_Sort", [geoField, "FREQUENCY"]) as cursor: for row in cursor: if Xgeo == 0: Vgeo = row[1] geoList.append(row[0]) else: Vgeo = Vgeo + row[1] geoList.append(row[0]) if float(Vgeo) / float(siteResult) < Limit: Xgeo = Xgeo + 1 else: break qryList = ["'" + geo + "'" for geo in geoList] expr = '"' + geoField + '"' + " IN (" + ",".join(qryList) + ")" arcpy.MakeFeatureLayer_management(outGeo, "in_memory\\geoTarget", expr) GEOdesc = arcpy.Describe("in_memory\\geoTarget") fields = GEOdesc.fields for field in fields: if field.name == geoField: arcpy.AddField_management("in_memory\\geoTarget", "GEO_TYPE", field.type, field.precision, field.scale, field.length, "", "", "", "") with arcpy.da.UpdateCursor( "in_memory\\geoTarget", [geoField, "GEO_TYPE"]) as cursor: for row in cursor: row[1] = row[0] cursor.updateRow(row) arcpy.Dissolve_management("in_memory\\geoTarget", GeoTarget, "GEO_TYPE") #SOILS SoilTarget = outFinal + "_Soil_Target.shp" arcpy.AddMessage("Processing Soils") arcpy.SpatialJoin_analysis(outPoints, outSoils, "in_memory\\pointSoil") arcpy.Frequency_analysis("in_memory\\pointSoil", "in_memory\\soil_Table", soilField) arcpy.Sort_management("in_memory\\soil_Table", "in_memory\\soil_Sort", [["FREQUENCY", "DESCENDING"]]) Vsoil = 0 Xsoil = 0 soilList = [] with arcpy.da.SearchCursor("in_memory\\soil_Sort", [soilField, "FREQUENCY"]) as cursor: for row in cursor: if Xsoil == 0: Vsoil = row[1] soilList.append(row[0]) else: Vsoil = Vsoil + row[1] soilList.append(row[0]) if float(Vsoil) / float(siteResult) < Limit: Xsoil = Xsoil + 1 else: break qryList = ["'" + soil + "'" for soil in soilList] expr = '"' + soilField + '"' + " IN (" + ",".join(qryList) + ")" arcpy.MakeFeatureLayer_management(outSoils, "in_memory\\soilTarget", expr) SOILdesc = arcpy.Describe("in_memory\\soilTarget") fields = SOILdesc.fields for field in fields: if field.name == soilField: arcpy.AddField_management("in_memory\\soilTarget", "SOIL_TYPE", field.type, field.precision, field.scale, field.length, "", "", "", "") with arcpy.da.UpdateCursor( "in_memory\\soilTarget", [soilField, "SOIL_TYPE"]) as cursor: for row in cursor: row[1] = row[0] cursor.updateRow(row) arcpy.Dissolve_management("in_memory\\soilTarget", SoilTarget, "SOIL_TYPE") #VEGETATION VegTarget = outFinal + "_Veg_Target.shp" arcpy.AddMessage("Processing Vegetation") arcpy.SpatialJoin_analysis(outPoints, outVeg, "in_memory\\pointVeg") arcpy.Frequency_analysis("in_memory\\pointVeg", "in_memory\\veg_Table", vegField) arcpy.Sort_management("in_memory\\veg_Table", "in_memory\\veg_Sort", [["FREQUENCY", "DESCENDING"]]) Vveg = 0 Xveg = 0 vegList = [] with arcpy.da.SearchCursor("in_memory\\veg_Sort", [vegField, "FREQUENCY"]) as cursor: for row in cursor: if Xveg == 0: Vveg = row[1] vegList.append(row[0]) else: Vveg = Vveg + row[1] vegList.append(row[0]) if float(Vveg) / float(siteResult) < Limit: Xveg = Xveg + 1 else: break qryList = ["'" + veg + "'" for veg in vegList] expr = '"' + vegField + '"' + " IN (" + ",".join(qryList) + ")" arcpy.MakeFeatureLayer_management(outVeg, "in_memory\\vegTarget", expr) VEGdesc = arcpy.Describe("in_memory\\vegTarget") fields = VEGdesc.fields for field in fields: if field.name == vegField: arcpy.AddField_management("in_memory\\vegTarget", "VEG_TYPE", field.type, field.precision, field.scale, field.length, "", "", "", "") with arcpy.da.UpdateCursor( "in_memory\\vegTarget", [vegField, "VEG_TYPE"]) as cursor: for row in cursor: row[1] = row[0] cursor.updateRow(row) arcpy.Dissolve_management("in_memory\\vegTarget", VegTarget, "VEG_TYPE") #WATER StreamTarget = outFinal + "_Water_Dist_Target.shp" arcpy.AddMessage("Processing Streams") if not streamResult == 0: arcpy.SpatialJoin_analysis(outPoints, outStreams, "in_memory\\pointStream") arcpy.Frequency_analysis("in_memory\\pointStream", "in_memory\\stream_Table", "distance") arcpy.Sort_management("in_memory\\stream_Table", "in_memory\\stream_Sort", [["FREQUENCY", "DESCENDING"]]) Vstr = 0 Xstr = 0 streamList = [] with arcpy.da.SearchCursor( "in_memory\\stream_Sort", ["distance", "FREQUENCY"]) as cursor: for row in cursor: if Xstr == 0: Vstr = row[1] streamList.append(row[0]) else: Vstr = Vstr + row[1] streamList.append(row[0]) if float(Vstr) / float(siteResult) < Limit: Xstr = Xstr + 1 else: break qryList = [str(stream) for stream in streamList] expr = "distance IN (" + ",".join(qryList) + ")" arcpy.MakeFeatureLayer_management(outStreams, "in_memory\\streamTarget", expr) strDesc = arcpy.Describe("in_memory\\streamTarget") fields = strDesc.fields for field in fields: if field.name == "distance": arcpy.AddField_management("in_memory\\streamTarget", "WAT_DIST", field.type, field.precision, field.scale, field.length, "", "", "", "") with arcpy.da.UpdateCursor( "in_memory\\streamTarget", ["distance", "WAT_DIST"]) as cursor: for row in cursor: row[1] = row[0] cursor.updateRow(row) arcpy.Dissolve_management("in_memory\\streamTarget", StreamTarget, "WAT_DIST") #Overlay and count overlaps if params[15].value == 1 and polyAcres < 50000: arcpy.AddMessage("Calculating target layer overlap") layerList = [ demTarget, slopeTarget, aspectTarget, GeoTarget, SoilTarget, VegTarget, StreamTarget ] existsList = [] for layer in layerList: if arcpy.Exists(layer): existsList.append(layer) outMerge = outFinal + "_Merge.shp" outFtoLine = outFinal + "_FtoLine.shp" outFtoPoly = outFinal + "_FtoPoly.shp" outFtoPoint = outFinal + "_FtoPoint.shp" outJoin1 = outFinal + "_Join1.shp" outDiss1 = outFinal + "_Diss1.shp" outJoin2 = outFinal + "_Join2.shp" outDiss2 = outFinal + "_Diss2.shp" rankPoly = outFinal + "_Rank_Poly.shp" arcpy.Merge_management(existsList, outMerge) arcpy.FeatureToLine_management(outMerge, outFtoLine) arcpy.FeatureToPolygon_management(outFtoLine, outFtoPoly, "#", "NO_ATTRIBUTES", "#") arcpy.FeatureToPoint_management(outFtoPoly, outFtoPoint, "INSIDE") arcpy.SpatialJoin_analysis(outFtoPoint, outMerge, outJoin1, "JOIN_ONE_TO_MANY", "KEEP_ALL", "#", "INTERSECT", "#", "#") arcpy.Dissolve_management(outJoin1, outDiss1, "TARGET_FID", "Join_Count SUM", "MULTI_PART", "DISSOLVE_LINES") arcpy.SpatialJoin_analysis(outFtoPoly, outDiss1, outJoin2, "JOIN_ONE_TO_ONE", "KEEP_ALL", "#", "INTERSECT", "#", "#") rankDesc = arcpy.Describe(outJoin2) fields = rankDesc.fields for field in fields: if field.name == "SUM_Join_C": arcpy.AddField_management(outJoin2, "OVERLAP", field.type, field.precision, field.scale, field.length, "", "", "", "") with arcpy.da.UpdateCursor( outJoin2, ["SUM_Join_C", "OVERLAP"]) as cursor: for row in cursor: row[1] = row[0] cursor.updateRow(row) arcpy.Dissolve_management(outJoin2, outDiss2, "OVERLAP", "#", "MULTI_PART", "DISSOLVE_LINES") arcpy.Clip_analysis(outDiss2, lyr, rankPoly) delList = [ outMerge, outFtoLine, outFtoPoly, outFtoPoint, outJoin1, outDiss1, outJoin2, outDiss2 ] for item in delList: arcpy.Delete_management(item) finally: delList2 = [] for item in delList2: arcpy.Delete_management(item) deleteInMemory() return