def visualize_range(tin, output_shp, roads_shp, travel_time, edge_average_time): points = [] for row in arcpy.da.SearchCursor(roads_shp, ["SHAPE@", "FID"]): if row[1] in edge_average_time: edge_id = row[1] mid_point = (row[0].positionAlongLine(0.50, True).firstPoint.X, row[0].positionAlongLine(0.50, True).firstPoint.Y) travel_time[mid_point] = edge_average_time[edge_id] cursor = arcpy.InsertCursor(output_shp, ['Id', 'SHAPE', 'Distance']) for point in travel_time: points.append(point) for point in points: row = cursor.newRow() row.setValue('Id', points.index(point)) row.setValue('SHAPE', arcpy.Point(point[0], point[1])) row.setValue('Distance', travel_time[point]) cursor.insertRow(row) del cursor del row projection = arcpy.Describe(roads_shp).spatialReference arcpy.CreateTin_3d(tin, projection, '{} Distance Mass_Points <None>'.format(output_shp), 'CONSTRAINED_DELAUNAY') # visualisation via tin
def make_TIN(in_,prj): arcpy.MakeXYEventLayer_management(in_,"Lon","Lat","temp",prj,"SWL") arcpy.CreateTin_3d(out_tin=wrkdir+"\\"+in_[:-4], spatial_reference=wrkdir+"\\Eq_Albs_USGS.prj", in_features="temp SWL Mass_Points <None>", constrained_delaunay="CONSTRAINED_DELAUNAY")
def points2tin(self, field_name="Z", edge_length=400): """ Converts point shapefile to TIN :param field_name: STR :param edge_length: maximum length of TIN edges :return: None """ print(" * converting points to TIN...") arcpy.env.workspace = self.out_dir arcpy.env.outputCoordinateSystem = self.sr arcpy.CreateTin_3d(out_tin=self.tin, in_features=[[self.point_shp, field_name]]) print(" * clipping edges longer than %s ..." % str(edge_length)) arcpy.DelineateTinDataArea_3d(in_tin=self.tin, max_edge_length=edge_length, method="PERIMETER_ONLY") # The following command can be activate to overwrite the boundary shapefile as a function of the TIN # arcpy.TinDomain_3d(in_tin=self.tin, out_feature_class=self.boundary_shp, out_geometry_type="POLYGON") print(" - OK (saved as %s)" % self.tin)
def tinraster_3d(self, layer_name, input_fc_name, raster_field_name): self.layer_name = layer_name self.input_fc_name = input_fc_name self.raster_field = raster_field_name # Check out any necessary licenses print "Checking out extension licenses..." arcpy.CheckOutExtension("3D") arcpy.CheckOutExtension("spatial") # overwrite output arcpy.env.overwriteOutput = True # tin outTIN = os.getcwd() + r'\Data\tin_' + self.layer_name # raster outRASTER = os.getcwd() + r'\Data\RST_' + self.layer_name input_fc = join(os.getcwd(), 'Precip.gdb', layer_name) print(input_fc) try: # Process: Create TIN print "Creating TIN..." arcpy.CreateTin_3d( outTIN, "PROJCS['NAD_1983_StatePlane_Texas_Central_FIPS_4203_Feet'," "GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983'," "SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0]," "UNIT['Degree',0.0174532925199433]],PROJECTION['Lambert_Conformal_Conic']," "PARAMETER['False_Easting',2296583.333333333]," "PARAMETER['False_Northing',9842500.0]," "PARAMETER['Central_Meridian',-100.3333333333333]," "PARAMETER['Standard_Parallel_1',30.11666666666667]," "PARAMETER['Standard_Parallel_2',31.88333333333333]," "PARAMETER['Latitude_Of_Origin',29.66666666666667]," "UNIT['Foot_US',0.3048006096012192]]", "'" + self.input_fc_name + "' " + self.raster_field + " Mass_Points <None>", "DELAUNAY") # arcpy.CreateTin_3d(outTIN, "PROJCS['NAD_1983_StatePlane_Texas_Central_FIPS_4203_Feet'," # "GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983'," # "SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0]," # "UNIT['Degree',0.0174532925199433]],PROJECTION['Lambert_Conformal_Conic']," # "PARAMETER['False_Easting',2296583.333333333]," # "PARAMETER['False_Northing',9842500.0]," # "PARAMETER['Central_Meridian',-100.3333333333333]," # "PARAMETER['Standard_Parallel_1',30.11666666666667]," # "PARAMETER['Standard_Parallel_2',31.88333333333333]," # "PARAMETER['Latitude_Of_Origin',29.66666666666667]," # "UNIT['Foot_US',0.3048006096012192]]", # "'Database Connections\\Connection to FWSDE.sde\\sde_wjt.\"FREESE\\wjt\".hrap\\" # "sde_wjt.\"FREESE\\wjt\"." + self.input_fc_name + "' " + self.raster_field + # " Mass_Points <None>", "DELAUNAY") # Process: TIN to Raster print "Creating raster..." # typical cellsize is 12500 arcpy.TinRaster_3d(outTIN, outRASTER, "FLOAT", "LINEAR", "CELLSIZE 5000", "1") self.run_status = 'OK' except Exception as e: self.run_status = e root = tk.Tk() # allows tkMessageBox to be shown without displaying Tkinter root window root.withdraw() tkMessageBox.showinfo("Python error", e) return self.run_status return self.run_status
arcpy.AddMessage(in_features) except: # assuming that not having SB points is cause for fail MergeList = [MBpointMerge, inTopoPts] arcpy.Merge_management(MergeList, AllPtsMerge) in_features = str(MBpointMerge + " POINT_Z masspoints; " + inTopoPts + " POINT_Z masspoints;" + inTopoBRK + " <None> softline;" + inTopoWE + " <None> softline") arcpy.AddMessage("did not create merged points with all files...") print arcpy.GetMessages() arcpy.AddMessage("created without SB points") print arcpy.GetMessages() # ############################################################# ############################################################# # ## Create TIN # out_tin = str(outTinFolder + "\\" + "Seg_" + inSegment + "_" + inYear + "_tin") try: arcpy.CreateTin_3d(out_tin, spatialRef, in_features, False) except arcpy.ExecuteError: print arcpy.GetMessages() # arcpy.DelineateTinDataArea_3d(out_tin, TinDelineationLength, "PERIMETER_ONLY") # copy TIN for editing copy_tin = str(outTinFolder + "\\" + "Seg_" + inSegment + "_" + inYear + "_tin_EDT") arcpy.CopyTin_3d(out_tin, copy_tin)
param_peak = peaks + " elevation <none> masspoints false" param_water = water + " <none> <none> hardline false" param_contourline = contourline + " elevation <none> softline false" parameters = param_peak + ";" + param_water + ";" + param_contourline ## ##inFCs = [[peaks, "elevation", "<None>", "masspoints", False], ## [param_water, "<None>", "<None>", "hardline", False], ## [param_contourline, "elevation", "<None>", "softline", False]] ##params = [[param_peak],[param_water],[param_contourline]] #checking license availability if arcpy.CheckExtension("3D") == "Available": #Take a license arcpy.CheckOutExtension("3D") #Create a new empty TIN arcpy.CreateTin_3d("tin2") #Edit TIN arcpy.EditTin_3d("tin2", parameters) ## arcpy.EditTin_3d("tin2", inFCs) #Tin to raster data_type = "FLOAT" interp_method = "LINEAR" samp_method = "CELLSIZE 10" factor = 1 arcpy.TinRaster_3d(output_folder + "\\tin2", output_folder + "\\grid", interp_method, samp_method, factor) #release the license arcpy.CheckInExtension("3D") else: print('License not available')
#------------------------------------------------------------------------------- #importing module import arcpy #enable output overwrite arcpy.env.overwriteOutput = True #output folder arcpy.env.workspace = 'I:\\asignaturas\\sig-I\\2012-2013\\cuatrimestreB\\teoria\\MT7\\salida' #ckeking license availability if arcpy.CheckExtension("3D") == "Available": #Take a license arcpy.CheckOutExtension("3D") #Create a new empty TIN arcpy.CreateTin_3d('tin') #release the license arcpy.CheckInExtension("3D") else: print('License not available') #------------------------------------------------------------------------------- # EDIT TIN #------------------------------------------------------------------------------- #importing module import arcpy #enable output overwrite arcpy.env.overwriteOutput = True #output folder
arcpy.MakeFeatureLayer_management(endPoints, endPointsLyr) IDs = [] with arcpy.da.SearchCursor(endPointsLyr, ('RIGHT_FID', )) as cursor: for row in cursor: if row not in IDs: IDs.append(row) IDlist = [] for values in IDs: for x in values: IDlist.append(x) for patchID in IDlist: selection = arcpy.SelectLayerByAttribute_management( endPointsLyr, "ADD_TO_SELECTION", 'RIGHT_FID = ' + str(patchID)) outTIN = scratchFolder + '\TIN_' + str(patchID) depthfield = ' Heights' mp = ' Mass_Points' none = ' <None>' inFeatures = str(selection) + depthfield + mp + none arcpy.CreateTin_3d(outTIN, '', inFeatures, "DELAUNAY") arcpy.TinRaster_3d( outTIN, patchOutputFolder + '\Patch_' + str(patchID) + '.tif', "FLOAT", '', "CELLSIZE " + str(cellsize), ) arcpy.SelectLayerByAttribute_management(endPointsLyr, "CLEAR_SELECTION") print('All processes complete')
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)
if int(row[0]) in boundaryIDs: searchPoints[int(row[0])] = arcpy.Point(row[1], row[2]) # Store individual points in a particular order to form the boundary for vertex in boundaryIDs: boundaryPoints.append(searchPoints[vertex]) # Boundary creation polygon = arcpy.Polygon(arcpy.Array(boundaryPoints)) arcpy.CreateFeatureclass_management(arcpy.env.workspace, name + '_Boundary.shp', 'POLYGON', polygon) arcpy.CopyFeatures_management(polygon, name + '_Boundary.shp') arcpy.AddMessage(name + '_Boundary.shp generated.') # Create TIN based on topo data and boundary arcpy.CreateTin_3d(name + '_TIN') arcpy.EditTin_3d( name + '_TIN', [[name + '_Points.shp', 'Z', '<None>', 'Mass_Points', False], [name + '_Boundary.shp', '<None>', '<None>', 'Soft_Clip', False]]) arcpy.AddMessage(name + '_TIN generated.') # Create raster out of TIN arcpy.TinRaster_3d(name + '_TIN', name + '_Raster.tif', 'FLOAT', 'LINEAR', sample_distance='CELLSIZE {}'.format(cellsize), z_factor=1) arcpy.AddMessage(name + '_Raster.tif generated.')
#Project Points From HRAP to State Plane arcpy.Project_management( in_dataset="/nws_precip.shp", out_dataset="/nws_precip_projected.shp", out_coor_system= "GEOGCS['HRAP_Sphere',DATUM['<custom>',SPHEROID['<custom>',6371200.0,0.0]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]", transform_method="#", in_coor_system= "GEOGCS['HRAP_Sphere',DATUM['<custom>',SPHEROID['<custom>',6371200.0,0.0]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]" ) print "Projecting Points Completed" #Create Tin from Points arcpy.CreateTin_3d( "E:/Tasks/NightlyWeatherShapefile/Shapefile/precipitation", "PROJCS['NAD_1983_StatePlane_Nebraska_FIPS_2600_Feet',GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Lambert_Conformal_Conic'],PARAMETER['False_Easting',1640416.666666667],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-100.0],PARAMETER['Standard_Parallel_1',40.0],PARAMETER['Standard_Parallel_2',43.0],PARAMETER['Latitude_Of_Origin',39.83333333333334],UNIT['Foot_US',0.3048006096012192]]", "C:/Tasks/NightlyWeatherShapefile/Shapefile/nws_precip_projected.shp Globvalue masspoints <None>", "DELAUNAY") print "Creating Tin from Points Completed" #Create Contours from Tin arcpy.SurfaceContour_3d(in_surface="/precipitation", out_feature_class="/Contours.shp", interval="1", base_contour="0", contour_field="Contour", contour_field_precision="0", index_interval="#", index_interval_field="Index_Cont", z_factor="1", pyramid_level_resolution="0")
def inundation_map_builder(cut_line_file, profile, output_raster, output_shapefile): xs_cut_lines = cut_line_file profile = profile output_shapefile = output_shapefile output_raster = output_raster try: if arcpy.CheckExtension("3D") == "Available": arcpy.CheckOutExtension("3D") else: # Raise a custom exception # raise LicenseError if arcpy.CheckExtension("Spatial") == "Available": arcpy.CheckOutExtension("Spatial") else: # Raise a custom exception # raise LicenseError # Local variables: modelbuild = "D:\\LittleCal_Inundations\\TINS\\modelbuildtin" modelbuild11 = "D:\\LittleCal_Inundations\\Rasters\\modelbuild11" cook_thorn = "D:\GIS\cook_thorn" modelbuild13 = "D:\\LittleCal_Inundations\\Rasters\\" + output_raster mdelbuild1int = "D:\\LittleCal_Inundations\\Rasters\\mdelbuild1int" modelbuild1dis_shp = "D:\\LittleCal_Inundations\\Shapefiles\\modelbuild1dis.shp" modelbuild1_shp = "D:\\LittleCal_Inundations\\Shapefiles\\" + output_shapefile mapping_xs = "D:\LittleCal_Inundations\Shapefiles\MappingXS.shp" bound_poly = "D:\\LittleCal_Inundations\\Shapefiles\\BoundingPolygonLeveet.shp" params = mapping_xs + " " + profile + " Soft_Line <None>; " + bound_poly + " <None> " + "Hard_Clip <None>" #params = "XSCutlines2.shp 05FEB2008_2400 Soft_Line <None>; BoundingPolygonLeveet.shp <None> Hard_Clip <None>" coord = "PROJCS['NAD83 / Illinois East (ftUS)',GEOGCS['GCS_North_American_1983'," + \ "DATUM['D_North_American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]]," + \ "PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]," + \ "PROJECTION['Transverse_Mercator'],PARAMETER['false_easting',984250.0]," + \ "PARAMETER['false_northing',0.0],PARAMETER['central_meridian',-88.33333333333333]," + \ "PARAMETER['scale_factor',0.999975]," + \ "PARAMETER['latitude_of_origin',36.66666666666666]," + \ "UNIT['Foot_US',0.3048006096012192]]" # 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: "Mapping_XS", "XS Cut Lines" arcpy.JoinField_management(in_data=mapping_xs, in_field="ProfileM", join_table=xs_cut_lines, join_field="ProfileM", fields=profile) # Process: Create TIN arcpy.CreateTin_3d(modelbuild, coord, params, "DELAUNAY") # Process: TIN to Raster arcpy.TinRaster_3d(modelbuild, modelbuild11, "FLOAT", "LINEAR", "CELLSIZE 2", "1") # Process: Raster Calculator modelbuild12 = ((Raster(modelbuild11) - Raster(cook_thorn)) * ((Raster(modelbuild11) - Raster(cook_thorn)) > 0)) # Process: Set Null arcpy.gp.SetNull_sa(modelbuild12, modelbuild12, modelbuild13, "VALUE = 0") # Process: Int arcpy.Int_3d(modelbuild13, mdelbuild1int) # Process: Raster to Polygon arcpy.RasterToPolygon_conversion(mdelbuild1int, modelbuild1dis_shp, "SIMPLIFY", "Value") arcpy.RepairGeometry_management(modelbuild1dis_shp) # Process: Dissolve arcpy.Dissolve_management(modelbuild1dis_shp, modelbuild1_shp, "", "", "MULTI_PART", "DISSOLVE_LINES") arcpy.DeleteField_management(in_table=mapping_xs, drop_field=profile) except LicenseError: print("3D or Spatial Analyst license is unavailable") except arcpy.ExecuteError: print(arcpy.GetMessages(2)) finally: arcpy.CheckInExtension("3D") arcpy.CheckInExtension("Spatial")
for num in range(2, tran_num): Transectnum = str(num) y = num tid = '\"TransectLa\" <> \'' + str( y ) + '\'' #Make sure the attribute label is Transect, the newer surveys may have it as TransectLa #tid = str('"TransectLa" <> ' + '\''+ str(y) + '\'') # Need to put single quotes around str(y) in SQL query print tid lyr = locshp + Site + "_3D_" + data[0] + ".shp" arcpy.MakeFeatureLayer_management( locshp + Site + "_3D_" + data[0] + ".shp", "lyr") arcpy.SelectLayerByAttribute_management("lyr", "NEW_SELECTION", tid) TIN = loctin + "no_" + Transectnum #create TIN without one transect RAS = locras + "no_" + Transectnum #create RASTER without one transect arcpy.CreateTin_3d(TIN, sr, [["lyr", "z", "masspoints"]], "CONSTRAINED_DELAUNAY") arcpy.TinRaster_3d(TIN, RAS, "FLOAT", "LINEAR", "CELLSIZE 1.0") #1 m cell size mRAS = locras + 'm_' + "no_" + Transectnum #merge transectless DEM with base temp = "in_memory/t1" + integ tempn = "t1" + integ mRASname = 'm_' + "_no_" + Transectnum arcpy.MosaicToNewRaster_management([RAS, 'extlyr'], "in_memory", tempn, sr, "32_BIT_FLOAT", "1.0", "1", "MAXIMUM", "FIRST") #1 m cell size arcpy.gp.ExtractByMask_sa(temp, compartments, mRAS) arcpy.Delete_management("in_memory") #print "Raster without transect " + Transectnum + "created" #subtract from full dataset DEM
def create_tin(outTin, prj, inputStr): """ Execute Create TIN from 3D Analyst Tools """ arcpy.CreateTin_3d(outTin, prj, inputStr, "DELAUNAY")
############################################################################################################################################################################ ##Convert the features to 3D features, Create TINs, and extrude between the TINs to create the block feature arcpy.FeatureTo3DByAttribute_3d( topsname1 + "clean", topsname1 + "_ThreeD", "True_Elev" ) ##This converts the tops file processed up until this point and creates 3D features of it using the "True_Elev" as the height field arcpy.FeatureTo3DByAttribute_3d( topsname2 + "clean", topsname2 + "_ThreeD", "True_Elev" ) ##The same as above, but for the tops file of the formation directly below the formation the user wants to create a block feature of tinfc1 = topsname1 + "_ThreeD" ##Creates a variable of the 3D features created above to be used in the Create TIN scriptinput tinfc2 = topsname2 + "_ThreeD" ##Same as above, but for the tops file of the formation directly below the formation the user wants to create a block feature of tin1 = arcpy.CreateTin_3d(outFolder + "/" + topsname1, prj, [ [tinfc1, "True_Elev", "masspoints"] ]) ##Creates a TIN from the 3D features, using "True_Elev" as its height field tin2 = arcpy.CreateTin_3d( outFolder + "/" + topsname2, prj, [[tinfc2, "True_Elev", "masspoints"]] ) ##Same as above, but for the tops file of the formation directly below the formation the user wants to create a block feature of extrude = arcpy.MinimumBoundingGeometry_management( "points", "tin_boundary", "CONVEX_HULL" ) ##The boundary of the area covered by the two tops files, this will then be extruded to create the 3D feature arcpy.ExtrudeBetween_3d( tin1, tin2, extrude, outputlocation ) ##Extrude between the two TINs to create the final, output 3D block feature to be viewed and analyzed in ArcScene ############################################################################################################################################################################ ##Check in the extensions used in this script
TIN = "TIN" RasterFromTIN = "RasterFromTIN_{0}".format(stage) Subtracted = "Subtracted_{0}".format(stage) Reclassified = "Reclassified_{0}".format(stage) ExtractedRaster = "ExtractedRaster_{0}".format(stage) # Create TIN arcpy.AddMessage("Creating TIN for {0}".format(stage)) if stage == "MIN_Z_Value": stage_name_for_table = "MIN_Z_Value" else: stage_name_for_table = "{0}.{1}".format(Table, stage) expression = "{0} <None> Soft_Clip <None>;{1} {2} Mass_Points <None>;{3} {4} Hard_Line <None>".format( Reaches, New_CrossSections, stage_name_for_table, New_CrossSections, stage_name_for_table) arcpy.CreateTin_3d(TIN, spatial_ref, expression, "CONSTRAINED_DELAUNAY") # TIN to Raster arcpy.AddMessage("Converting TIN to raster for {0}".format(stage)) input_cell_size = "CELLSIZE {0}".format(Cell_Size) arcpy.TinRaster_3d(TIN, RasterFromTIN, "FLOAT", "LINEAR", input_cell_size, "1") # Raster subtraction arcpy.AddMessage( "Subtracting the raster from TIN with the input DEM for {0}".format( stage)) arcpy.Minus_3d(RasterFromTIN, DEM, Subtracted) # Reclassify raster arcpy.AddMessage(
# Step 2: Create point feature class from depth and canopy height data # Create points shapefile from XY table (.csv file) print('Creating point shapefile from XY table...') mod_points = 'model_points.shp' spat_ref = arcpy.Describe(bndry_shp).spatialReference arcpy.management.XYTableToPoint(mod_data, mod_points, x_field, y_field, coordinate_system=spat_ref) # Step 3: Create TINs from depth and velocity point shapefiles # Create TINs from model points shapefile print('Creating TINs from model XY point shapefiles...') mod_depth = arcpy.CreateTin_3d('mod_depth', spatial_reference=spat_ref, in_features='%s D Mass_Points' % mod_points, constrained_delaunay='Delaunay') mod_vel = arcpy.CreateTin_3d('mod_vel', spatial_reference=spat_ref, in_features='%s V Mass_Points' % mod_points, constrained_delaunay='Delaunay') # Step 4: Convert TINS to rasters (depth and velocity) # Convert TINs to rasters print('Converting TINs to rasters...') depth_ras_full = arcpy.TinRaster_3d(mod_depth, 'depth_ras_full.tif', sample_distance='CELLSIZE', sample_value=3) vel_ras_full = arcpy.TinRaster_3d(mod_vel, 'vel_ras_full.tif', sample_distance='CELLSIZE', sample_value=3)
#set environment arcpy.MakeRasterLayer_management(in_dem, "extlyr") env.extent = "extlyr" print "Running " + AnalysisType + " Analysis" # Create TINs and merged rasters if the TinRASCreation is set to "0" if TinRASCreation != 1: if AnalysisType == "Total": #Create TINs for n in xrange(1, len(data) + 1): shp = locshp + data2[n - 1] + ".shp" #breakl = locshp + data2[n-1] + "_Cliff.shp" TIN = loctin + data[n - 1] RAS = locras + data[n - 1] arcpy.CreateTin_3d(TIN, sr, [[shp, "Z", "masspoints"]], "CONSTRAINED_DELAUNAY") arcpy.DelineateTinDataArea_3d(TIN, tin_length) print data[n - 1] + ' TIN created' #Tins to rasters for n in xrange(1, len(data) + 1): TIN = loctin + data[n - 1] RAS = locras + data[n - 1] arcpy.TinRaster_3d(TIN, RAS, "FLOAT", "LINEAR", "CELLSIZE 1.0") #1 m cell size print data[n - 1] + ' raster created' else: print "Using Rasters created from previous 'Total Analysis' Run" #Merge rasters for n in xrange(1, len(data) + 1):
y_coords = "Y" z_coords = "Z" #vytvoreni bodoveho mracna do layer pro zpracovani arcpy.MakeXYEventLayer_management(table, x_coords, y_coords, out_Layer, arcpy.SpatialReference(5514, 5705), z_coords) print(arcpy.GetCount_management(out_Layer)) #kontrolni print poctu bodu #ulozeni bodoveho mracna saved_Layer = "out.lyr" arcpy.SaveToLayerFile_management(out_Layer, saved_Layer) print("Point cloud created") #vytvoreni TIN triangle = arcpy.CreateTin_3d("TIN", arcpy.SpatialReference(5514, 5705), saved_Layer) print("TIN created") #vytvoreni vrstevnic contours = arcpy.SurfaceContour_3d(triangle, "contour.shp", 1) print("Contours created") #vytvoreni hranicnich vrstevnic contour_low = arcpy.SurfaceContour_3d(triangle, "/output/db.gdb/contour_low", 1, 0.1) contour_high = arcpy.SurfaceContour_3d(triangle, "/output/db.gdb/contour_high", 1, -0.1) point_contour_low = arcpy.FeatureVerticesToPoints_management( contour_low, "/output/db.gdb/p_contour_low", "ALL") point_contour_high = arcpy.FeatureVerticesToPoints_management( contour_high, "/output/db.gdb/p_contour_high", "ALL")
def calculate_height(lc_input_features, lc_ws, lc_tin_dir, lc_input_surface, lc_output_features, lc_log_dir, lc_debug, lc_memory_switch): try: # create dem desc = arcpy.Describe(lc_input_features) if desc.spatialReference.linearUnitName in ['Foot_US', 'Foot']: unit = 'Feet' else: unit = 'Meters' # Generate raster from lasd if arcpy.Exists(lc_input_features): if arcpy.Exists(lc_output_features): arcpy.Delete_management(lc_output_features) # make a copy bridge_polys = lc_output_features + "_height" if arcpy.Exists(bridge_polys): arcpy.Delete_management(bridge_polys) arcpy.CopyFeatures_management(lc_input_features, bridge_polys) # create string field for featureFID oidFieldName = arcpy.Describe(bridge_polys).oidFieldName common_lib.delete_add_field(bridge_polys, esri_featureID, "TEXT") arcpy.CalculateField_management(bridge_polys, esri_featureID, "!" + oidFieldName + "!", "PYTHON_9.3") msg_body = create_msg_body( "Calculating height above surface for: " + common_lib.get_name_from_feature_class(lc_input_features), 0, 0) msg(msg_body) # create bridge tin out_tin = os.path.join(lc_tin_dir, "bridge_tin") if arcpy.Exists(out_tin): arcpy.Delete_management(out_tin) msg_body = create_msg_body( "Creating raster for: " + common_lib.get_name_from_feature_class(lc_input_features), 0, 0) msg(msg_body) arcpy.CreateTin_3d( out_tin, arcpy.Describe(bridge_polys).spatialReference, "{} Shape.Z Hard_Clip <None>".format(bridge_polys), "DELAUNAY") # turn to raster if 0: bridge_raster = "in_memory/bridge_raster" else: bridge_raster = os.path.join(lc_ws, "bridge_raster") if arcpy.Exists(bridge_raster): arcpy.Delete_management(bridge_raster) # use same cell size as input surface cell_size = arcpy.GetRasterProperties_management( lc_input_surface, "CELLSIZEX")[0] dataType = "FLOAT" method = "LINEAR" sampling = "CELLSIZE " + str(cell_size) zfactor = "1" arcpy.TinRaster_3d(out_tin, bridge_raster, dataType, method, sampling, zfactor) add_minimum_height_above_water_surface(lc_ws, bridge_polys, bridge_raster, lc_input_surface, lc_memory_switch) # create point file for labeling if lc_memory_switch: bridge_points = "in_memory/bridge_points" else: bridge_points = os.path.join(lc_ws, "bridge_points") if arcpy.Exists(bridge_points): arcpy.Delete_management(bridge_points) arcpy.FeatureToPoint_management(bridge_polys, bridge_points, "INSIDE") bridge_points3D = lc_output_features + "_points_3D" if arcpy.Exists(bridge_points3D): arcpy.Delete_management(bridge_points3D) # create 3D point arcpy.FeatureTo3DByAttribute_3d(bridge_points, bridge_points3D, zmin_field) # add unit field common_lib.delete_add_field(bridge_points3D, esri_unit, "TEXT") expression = """{} IS NOT NULL""".format( arcpy.AddFieldDelimiters(bridge_points3D, has_field)) # select all points with good elevation values local_layer = common_lib.get_name_from_feature_class( bridge_points3D) + "_lyr" select_lyr = arcpy.MakeFeatureLayer_management( bridge_points3D, local_layer).getOutput(0) arcpy.SelectLayerByAttribute_management(select_lyr, "NEW_SELECTION", expression, None) z_unit = common_lib.get_z_unit(bridge_points3D, lc_debug) if z_unit == "Meters": expression = "'m'" else: expression = "'ft'" arcpy.CalculateField_management(select_lyr, esri_unit, expression, "PYTHON_9.3") arcpy.SelectLayerByAttribute_management(select_lyr, "CLEAR_SELECTION") common_lib.delete_fields(bridge_polys, [min_field, zmin_field]) common_lib.delete_fields(bridge_points3D, [min_field, zmin_field]) return bridge_polys, bridge_points3D else: msg_body = create_msg_body( "Couldn't find input feature class: " + str(lc_input_features), 0, 0) msg(msg_body, WARNING) return None except arcpy.ExecuteError: # Get the tool error messages msgs = arcpy.GetMessages(2) arcpy.AddError(msgs) except Exception: e = sys.exc_info()[1] arcpy.AddMessage("Unhandled exception: " + str(e.args[0]))
# -*- coding: utf-8 -*- import arcpy """ 此脚本的优势是能够解决用gispro或arcmap不能对县域大量等高线和高程点数据进行处理的问题 """ # 输入参数 dgx = "I:\\毕节国土空间规划\\分析库\\地形图信息提取.gdb\\等高线_首曲线" gcd = "I:\\毕节国土空间规划\\分析库\\地形图信息提取.gdb\\高程点" # 输出参数 cellsize = "5" # 以米为单位 tin = "F:\\test\\tin" dem = "F:\\test\\dem" arcpy.env.overwriteOutput = True arcpy.AddMessage("begin to create TIN.....") arcpy.CreateTin_3d(out_tin=tin, spatial_reference="", in_features=[[dgx, "Elevation", "Hard_Line", "<None>"], [gcd, "Elevation", "Mass_Points", "<None>"]], constrained_delaunay="DELAUNAY") arcpy.AddMessage("begin to create DEM.....") arcpy.TinRaster_3d(in_tin=tin, out_raster=dem, data_type="FLOAT", method="LINEAR", sample_distance="CELLSIZE " + cellsize, z_factor=1, sample_value=250)
#Check to see if the folder containing the TIN already exists, if so exit the script. if os.path.exists(os.path.split(args.OutputTIN)[0] + '\\' + os.path.split(args.OutputTIN)[1].lower()): arcpy.AddMessage(str(args.OutputTIN) + ' already exists.') arcpy.CheckInExtension('3D') sys.exit() else: arcpy.AddMessage('Creating TIN....') '''Create TIN with user inputs. However user is not given option for following parameters: Interpolation method: defaults to NATURAL NEIGHBORS Triangulation: defaults to DELAUNAY **This is for simplicity reason for IPC techs but can be changed upon request ''' arcpy.CreateTin_3d(args.OutputTIN, args.SpatialReference, [[args.InputPointCloud, args.InputZField, 'Mass_Points', '<None>'], [args.InputExtentPolygon, '<None>', 'Hard_Clip', '<None>']]) arcpy.AddMessage('Your TIN ' + str(args.OutputTIN) + ' has been successfully created.') #If the user checked the create DEM then create DEM, if user said to delete the TIN then delete TIN if args.OutputDEM: if os.path.exists(args.OutputDEM): arcpy.AddMessage(args.OutputDEM + ' already exists.') arcpy.CheckInExtension('3D') sys.exit() else: arcpy.AddMessage('Creating DEM...') outDEM = args.OutputDEM