if pest_path <> os.getcwd(): for cf in [heads_lyr, streams_lyr]: shutil.copyfile(cf, os.path.join(pest_path, os.path.split(cf)[-1])) # plot dry cells os.chdir(os.path.join(pest_path)) ascii_dry_files = [ f for f in os.listdir(os.getcwd()) if 'dry' in f and '.asc' in f ] if len(ascii_dry_files) == 0: print "no ascii grids of dry cells found!" for f in ascii_dry_files: print 'converting %s to raster...' % (f) rastername = f[:-4] arcpy.ASCIIToRaster_conversion(pest_path + '\\' + f, pest_path + '\\' + rastername, "FLOAT") arcpy.DefineProjection_management(pest_path + '\\' + rastername, prjfile) add_raster(df, pest_path + '\\' + rastername, rastername, pest_path, os.path.join(os.getcwd(), dry_cells_lyr)) # convert ascii grids (e.g. of K and R), and add them to the mxd also # I think this could alternatively be done directly with the K-arrays using the numpy-array-to-raster command if add_ascii_grids: os.chdir(os.path.join(pest_path)) ascii_Kfiles = [ f for f in os.listdir(os.getcwd()) if '_k' in f and '.asc' in f ] # add recharge array arcpy.env.workspace = os.getcwd() rch_file = [
csm_path = os.path.join(Las2Rastertool_output,"las_CanopySurface.dtm") parameters = [Executable_Path, csm_path, "5", "M", "M", "1", "16", "2", "2", txt_path] subprocess.call(parameters) output_dtm = csm_path arcpy.AddMessage(Choose_Model + " dtm format is completed!") elif (Choose_Model == "Canopy Height Model"): Executable_Path = os.path.join(Fusion_Folder,"canopymodel.exe") dtm_path = os.path.join(Las2Rastertool_output,"las_surface.dtm") chm_path = os.path.join(Las2Rastertool_output,"las_CanopyaHeight.dtm") parameters = [Executable_Path,"/ground:" + dtm_path, chm_path , "5", "M", "M", "1", "16", "2", "2", txt_path] subprocess.call(parameters) output_dtm = chm_path arcpy.AddMessage(Choose_Model + " dtm format is completed!") else : exit(-1) arcpy.AddMessage("ERROR! dtm format is not completed!") # Process5:Export the model(dtm) into Ascii format: arcpy.AddMessage("Processing: Export the dtm model into Ascii format...") Executable_Path = os.path.join(Fusion_Folder,"DTM2ASCII.exe") output_Ascii = os.path.splitext(output_dtm)[0] + ".asc" parameters = [Executable_Path,output_dtm,output_Ascii] subprocess.call(parameters) # Process6: Using Arcgis toolbox to convert the Ascii format into raster format: arcpy.AddMessage("Processing: Using Arcgis toolbox to convert the Ascii format into raster format...") arcpy.ASCIIToRaster_conversion(output_Ascii, Output_Raster, "FLOAT") arcpy.AddMessage(Choose_Model + "raster data conversion is complete! Check the raster dataset in your selected output folder")
# parse_coordinates(params[0]) # Reverse the remaining entries doc_reversed = reversed(list(doc_reader)) # Create output file to be loaded into ArcMap with open(out_file, 'wb') as new_file: doc_writer = csv.writer(new_file, delimiter=' ', quoting=csv.QUOTE_NONE, escapechar=' ') # Re-write header back to the top of reversed list for line in header: new_file.write(line + '\n') # Write remaining entries into newly created file for row in doc_reversed: doc_writer.writerow(row) arcpy.ASCIIToRaster_conversion(out_file, Output_raster, "INTEGER") # Process: Mirror arcpy.Mirror_management(Output_raster, Output_Raster_Dataset) # Process: Raster to Point arcpy.RasterToPoint_conversion(Output_Raster_Dataset, Output_point_features, "") # Process: Delete arcpy.Delete_management(Output_raster, "")
# Name: batchAscii2Raster.py # Purpose: Converts one or more ASCII input files to Raster files # # Author: Johanson Onyegbula # # Created: 01/07/2020 #------------------------------------------------------------------------------- import os, tkFileDialog, Tkinter, arcpy tkBox = Tkinter.Tk() tkBox.withdraw() infile = tkFileDialog.askopenfilename( initialdir='C:\Users\owner\Downloads\Sample_scripts\ch22', parent=tkBox, title='Select at least one ESRI ASCII file', initialfile='park.shp', multiple=True, filetypes=[('ASCII Files', '*.asc'), ('ASCII Textfiles', '*.txt')]) print('User selections: {}'.format(infile.split(' '))) arcpy.env.workspace = os.path.dirname(infile) t = 0 for filename in infile.split(' '): outname = 'out{}'.format(t) t = t + 1 arcpy.ASCIIToRaster_conversion(infile, outname) print('Created output raster: {}'.format(os.path.abspath(outname))) tkBox.destroy()
coor_sys = "F:/GIS_Projects/420/Quarterman_ENVS420_Lab5/Sitka_Spruce_Correct_Projection/Lambert_Conformal_Conic_VARIABLES.prj" arcpy.env.workspace = "F:/GIS_Projects/420/Quarterman_ENVS420_Lab5/Climate_Variables/Climate_Variables_2080.gdb" dir_name = "F:/GIS_Projects/420/Quarterman_ENVS420_Lab5/Climate_Variables/Climate_Variables_2080" for filename in os.listdir(dir_name): if not filename.endswith(".asc"): continue print(filename) full_path = os.path.join(dir_name, filename) print(full_path) # outASCII = '%s.asc' % (full_path,) out_int = filename.rstrip(".asc") print(out_int) out_ras = out_int.replace(".", "_") print(out_ras) print("Starting ASCII to Raster conversion for %s"%(out_ras)) arcpy.ASCIIToRaster_conversion(full_path, out_ras) print("%s raster created in Climate_Variables.gdb"%(out_ras)) print("Defining the projection for %s as:\n %s"%(out_ras, coor_sys)) arcpy.DefineProjection_management(out_ras, coor_sys) print("Projection successfully defined! \n") #NAD_1983_HARN_StatePlane_ Washington_South_FIPS_4602 outworkspace = "F:/GIS_Projects/420/Quarterman_ENVS420_Lab5/Climate_Variables/Climate_Variables_2080_projected_BL.gdb" from_sr = arcpy.Describe(out_ras).spatialReference outfc = os.path.join(outworkspace, out_ras) outCS = arcpy.SpatialReference("F:/GIS_Projects/420/Quarterman_ENVS420_Lab5/Sitka_Spruce_Correct_Projection/Sitka_Spruce_Range.prj") print("Input spatial reference for %s is:\n %s"%(out_ras, from_sr)) exte = arcpy.Describe(out_ras).extent print("Spatial extent of impot:") print(exte) trans_list = arcpy.ListTransformations(from_sr, outCS, exte)
arcpy.Select_analysis("LAKE_Riv.shp", "nonConnect_Lake.shp", '"ARCID" <= 0') copyfile(OutputFolder + "/" + "HyMask.prj", OutputFolder + "/" + "Connect_Lake.prj") copyfile(OutputFolder + "/" + "HyMask.prj", OutputFolder + "/" + "nonConnect_Lake.prj") arcpy.env.XYTolerance = cellSize arcpy.arcpy.env.cellSize = cellSize arcpy.env.extent = arcpy.Describe("dir").extent arcpy.env.snapRaster = "dir" arcpy.RasterToASCII_conversion("Cat1", "hybasinfid.asc") arcpy.RasterToASCII_conversion(Strlink, 'strlink.asc') if (Thresholdacc > 0): arcpy.RasterToASCII_conversion(StreamRaster, 'riv1.asc') else: arcpy.ASCIIToRaster_conversion(StreamRaster, "str", "INTEGER") arcpy.DefineProjection_management("hybasinfid.asc", int(SptailRef.factoryCode)) arcpy.DefineProjection_management('strlink.asc', int(SptailRef.factoryCode)) arcpy.DefineProjection_management('riv1.asc', int(SptailRef.factoryCode)) arcpy.PolygonToRaster_conversion(OutputFolder + "/" + "Connect_Lake.shp", "Hylak_id", OutputFolder + "/" + "cnlake", "MAXIMUM_COMBINED_AREA", "Hylak_id", cellSize) copyfile(OutputFolder + "/" + "dir.prj", OutputFolder + "/" + "cnlake.prj") arcpy.RasterToASCII_conversion(OutputFolder + "/" + "cnlake", OutputFolder + "/" + "cnlake.asc") arcpy.PolygonToRaster_conversion(OutputFolder + "/" + "nonConnect_Lake.shp", "Hylak_id", OutputFolder + "/" + "noncnLake", "MAXIMUM_COMBINED_AREA", "Hylak_id", cellSize) copyfile(OutputFolder + "/" + "dir.prj", OutputFolder + "/" + "noncnLake.prj") arcpy.RasterToASCII_conversion(OutputFolder + "/" + "noncnLake",
ischecked1 = arcpy.GetParameterAsText(2) ischecked2 = arcpy.GetParameterAsText(3) ascFileList = arcpy.ListFiles("*.asc") if str(ischecked1) == 'true': for ascFile in ascFileList: if int(ascFile[1:-1]) >= (int(arcpy.GetParameterAsText(8)) * 100 + int(arcpy.GetParameterAsText(9))): # get the file name without extension (replaces the %Name% variable from ModelBuidler) ascFileName = os.path.splitext(ascFile)[0] # define the output file rastFile = env.workspace + '/' + ascFileName + 'o' ascinFile = env.workspace + '/' + ascFile arcpy.ASCIIToRaster_conversion(ascinFile, rastFile, 'INTEGER') if str(ischecked2) == 'true': # the following defines projections and clips the PRISM raster file imgFileList = arcpy.ListRasters() for imgFile in imgFileList: if int(imgFile[1:-1]) >= (int(arcpy.GetParameterAsText(8)) * 100 + int(arcpy.GetParameterAsText(9))): imgFileName = os.path.splitext(imgFile)[0] imgFile1 = env.workspace + '/' + imgFileName + 'p' incoords = arcpy.GetParameterAsText(4) # Process: Projektion definieren arcpy.DefineProjection_management(imgFile, incoords) outExtractByMask = ExtractByMask(imgFile, arcpy.GetParameterAsText(5)) outExtractByMask.save(imgFile1)
def execute_RunSim(str_zonefolder, str_simfolder, str_lisfloodfolder, r_q, str_lakes, field_z, voutput, simtime, channelmanning, r_zbed, messages): str_inbci = str_zonefolder + "\\inbci.shp" str_outbci = str_zonefolder + "\\outbci.shp" zbed = RasterIO(r_zbed) discharge = RasterIO(r_q) # count est utilisé pour compter le nombre de zones, pour la barre de progression lors des simulations count = 0 bcipointcursor = arcpy.da.SearchCursor(str_inbci, ["SHAPE@", "zoneid", "flowacc", "type", "fpid"]) dictsegmentsin = {} for point in bcipointcursor: if point[1] not in dictsegmentsin: dictsegmentsin[point[1]] = [] dictsegmentsin[point[1]].append(point) allzones = list(dictsegmentsin.keys()) allzones.sort() dictzones_fp = {} for zone in allzones: if dictsegmentsin[zone][0][4] not in dictzones_fp: dictzones_fp[dictsegmentsin[zone][0][4]] = [] dictzones_fp[dictsegmentsin[zone][0][4]].append(zone) sortedzones = [] listfp = list(dictzones_fp.keys()) listfp.sort() for fp in listfp: listzones_fp = dictzones_fp[fp] listzones_fp.sort(reverse=True) sortedzones.extend(listzones_fp) # Ajout des information du fichier outbci.shp listzonesout = {} bcipointcursor = arcpy.da.SearchCursor(str_outbci, ["zoneid", "side", "lim1", "lim2", "side2", "lim3", "lim4", "SHAPE@"]) for point in bcipointcursor: listzonesout[point[0]] = point zones = str_zonefolder + "\\envelopezones.shp" # récupération du bci lac zonesscursor = arcpy.da.SearchCursor(zones, ["GRID_CODE", "SHAPE@", "Lake_ID"]) lakeid_byzone = {} for zoneshp in zonesscursor: if zoneshp[2] != -999: lakeid_byzone[zoneshp[0]] = zoneshp[2] # Z BCI fieldidlakes = arcpy.Describe(str_lakes).OIDFieldName shplakes = arcpy.da.SearchCursor(str_lakes, [fieldidlakes, field_z]) fieldz_bylakeid = {} for shplake in shplakes: fieldz_bylakeid[shplake[0]] = shplake[1] # Lancement de LISFLOOD-FP arcpy.SetProgressor("step", "Simulation 2D", 0, count, 1) progres = 0 arcpy.SetProgressorPosition(progres) if os.path.exists(str_simfolder + "\\lisflood_res"): arcpy.Delete_management(str_simfolder + "\\lisflood_res") for zone in sortedzones: segment = dictsegmentsin[zone] for point in sorted(segment, key=lambda q: q[2]): zonename = "zone" + str(point[1]) if point[3]=="main": if not arcpy.Exists(str_simfolder + "\\elev_zone" + str(point[1])): outpointshape = listzonesout[point[1]][7].firstPoint if point[1] in lakeid_byzone: hfix = fieldz_bylakeid[lakeid_byzone[point[1]]] else: if not os.path.exists(str_simfolder + "\\lisflood_res"): messages.addErrorMessage("Condition limite aval non trouvée : zone " + str(point[1])) else: # issue with Mosaic_management, used later with lisflood_res: # crash sometimes if the file is read here # so we make a tmp copy if arcpy.Exists(str_simfolder + "\\tmp_zone" + str(point[1])): arcpy.Delete_management(str_simfolder + "\\tmp_zone" + str(point[1])) arcpy.Copy_management(str_simfolder + "\\lisflood_res", str_simfolder + "\\tmp_zone" + str(point[1])) res_downstream = RasterIO(arcpy.Raster(str_simfolder + "\\tmp_zone" + str(point[1]))) hfix = res_downstream.getValue(res_downstream.YtoRow(outpointshape.Y), res_downstream.XtoCol(outpointshape.X)) if hfix == res_downstream.nodata: messages.addErrorMessage("Condition limite aval non trouvée : zone " + str(point[1])) arcpy.Delete_management(str_simfolder + "\\tmp_zone" + str(point[1])) # par newfile = str_simfolder + "\\zone" + str(point[1]) + ".par" filepar = open(newfile, 'w') filepar.write("DEMfile\tzone" + str(point[1]) + ".txt\n") filepar.write("resroot\tzone" + str(point[1]) + "\n") filepar.write("dirroot\t" + "res\n") filepar.write("manningfile\tnzone" + str(point[1]) + ".txt\n") filepar.write("bcifile\tzone" + str(point[1]) + ".bci" + "\n") filepar.write("sim_time\t" + str(simtime) + "\n") filepar.write("saveint\t" + str(simtime) + "\n") filepar.write("bdyfile\tzone" + str(point[1]) + ".bdy" + "\n") filepar.write("SGCwidth\twzone" + str(point[1]) + ".txt\n") filepar.write("SGCbank\tzone" + str(point[1]) + ".txt\n") filepar.write("SGCbed\tdzone" + str(point[1]) + ".txt\n") filepar.write("SGCn\t" + str(channelmanning) + "\n") filepar.write("chanmask\tmzone" + str(point[1]) + ".txt\n") # Vitesses du courant if voutput: filepar.write("qoutput\n") filepar.write("cfl\t0.5\n") filepar.write("max_Froude\t1\n") # filepar.write("debug\n") filepar.close() # bdy newfilebdy = str_simfolder + "\\zone" + str(point[1]) + ".bdy" for point2 in sorted(segment, key=lambda q: q[2]): raster_q_value = discharge.getValue(discharge.YtoRow(point2[0].firstPoint.Y), discharge.XtoCol(point2[0].firstPoint.X)) if point2[3] == "main": # Création du fichier bdy pointdischarge = raster_q_value / ( (discharge.raster.meanCellHeight + discharge.raster.meanCellWidth) / 2) lastdischarge = raster_q_value latnum = 0 filebdy = open(newfilebdy, 'w') filebdy.write("zone"+str(point[1]) + ".bdy\n") filebdy.write("zone"+str(point[1]) + "\n") filebdy.write("3\tseconds\n") filebdy.write("0\t0\n") filebdy.write("{0:.3f}".format(pointdischarge) + "\t50000\n") filebdy.write("{0:.3f}".format(pointdischarge) + "\t" + str(simtime)) filebdy.close() else: latnum += 1 pointdischarge = (raster_q_value - lastdischarge) / ( (discharge.raster.meanCellHeight + discharge.raster.meanCellWidth) / 2) lastdischarge = raster_q_value filebdy = open(newfilebdy, 'a') filebdy.write("\nzone" + str(point[1]) + "_" + str(latnum) + "\n") filebdy.write("3\tseconds\n") filebdy.write("0\t0\n") filebdy.write("{0:.3f}".format(pointdischarge) + "\t50000\n") filebdy.write("{0:.3f}".format(pointdischarge) + "\t" + str(simtime)) filebdy.close() # condition aval: 30cm au dessus du lit pour commencer zdep = min(zbed.getValue(zbed.YtoRow(outpointshape.Y), zbed.XtoCol(outpointshape.X)) + 0.3, hfix) filebdy = open(newfilebdy, 'a') filebdy.write("\nhvar\n") filebdy.write("4\tseconds\n") filebdy.write("{0:.2f}".format(zdep) + "\t0\n") filebdy.write("{0:.2f}".format(zdep) + "\t50000\n") filebdy.write("{0:.2f}".format(hfix) + "\t55000\n") filebdy.write("{0:.2f}".format(hfix) + "\t" + str(simtime)) filebdy.close() # calcul pour le -steadytol # Divise le débit par 200 et ne conserve qu'un chiffre significatif steadytol = str(round(lastdischarge / 200., - int(math.floor(math.log10(abs(lastdischarge / 200.)))))) subprocess.check_call([str_lisfloodfolder + "\\lisflood_intelRelease_double.exe", "-steady", "-steadytol", steadytol, str_simfolder + "\\zone" + str(point[1]) + ".par"], shell=True, cwd=str_simfolder) progres += 1 arcpy.SetProgressorPosition(progres) # Conversion des fichiers output # on renomme les fichiers créés (nécessaire pour être acceptés par l'outil de convsersion ASCII vers raster) if os.path.exists(str_simfolder + "\\res\\" + zonename + "elev.txt"): os.remove(str_simfolder + "\\res\\" + zonename + "elev.txt") if os.path.exists(str_simfolder + "\\res\\" + zonename + "-9999.elev"): os.rename(str_simfolder + "\\res\\" + zonename + "-9999.elev", str_simfolder + "\\res\\" + zonename + "elev.txt") else: os.rename(str_simfolder + "\\res\\" + zonename + "-0001.elev", str_simfolder + "\\res\\" + zonename + "elev.txt") messages.addWarningMessage("Steady state not reached : " + zonename) # Conversion des fichiers de sortie en raster pour ArcGIS str_elev = str_simfolder + "\\elev_" + zonename arcpy.ASCIIToRaster_conversion(str_simfolder + "\\res\\" + zonename + "elev.txt", str_elev, "FLOAT") # Ajout de la projection arcpy.DefineProjection_management(str_simfolder + "\\elev_" + zonename, r_q.spatialReference) messages.addMessage(str(point[1]) + " done") if not arcpy.Exists(str_simfolder + "\\lisflood_res"): arcpy.Copy_management(str_simfolder + "\\elev_" + zonename, str_simfolder + "\\lisflood_res") else: arcpy.Mosaic_management(str_simfolder + "\\elev_" + zonename, str_simfolder + "\\lisflood_res", mosaic_type="MAXIMUM") #arcpy.Copy_management(str_output + "\\lisflood_res", str_output + "\\tmp_mosaic") #arcpy.Delete_management(str_output + "\\lisflood_res") # arcpy.MosaicToNewRaster_management(';'.join([str_output + "\\tmp_mosaic", str_output + "\\elev_" + point[1]]), # str_output,"lisflood_res", # pixel_type="32_BIT_FLOAT", # number_of_bands=1) return
temp.close() os.remove(old) os.rename(new, old) break else: arcpy.AddError('Circuitscape executable not found. Make sure Circuitscape is insalled \nor manually edit the cs_path variable in local_params.py') # Execute Circuitscape os.system('"' + lp.cs_path + '" ' + cs_ini) inASCII = outName + "_cum_curmap.asc" outRaster = outName + "_cum_curmap.img" curTemp = os.path.dirname(outName) + os.sep + "curTemp.img" arcpy.AddMessage("\tConverting Circuit Map to Raster...") arcpy.ASCIIToRaster_conversion(inASCII, curTemp, "FLOAT") if arcpy.Describe(curTemp).SpatialReference.name == 'Unknown': sr = arcpy.Describe(linkLayer).SpatialReference arcpy.DefineProjection_management(curTemp, sr) # Process Circuitscape output and bring into map arcpy.AddMessage("\tSetting Source Areas to NULL...") outCon = arcpy.sa.Con(arcpy.sa.IsNull(sourceRaster),-9999, sourceRaster) curRaster = arcpy.sa.SetNull(outCon, curTemp, "Value <> -9999") curRaster = arcpy.sa.SetNull(curRaster, curRaster, "Value = 0") # outRaster = curMapName curRaster.save(outRaster) desc = arcpy.Describe(linkLayer) sr = desc.SpatialReference arcpy.DefineProjection_management(outRaster, sr)
# 地図データの名称の配列を作成する rasterList = [] for m in range(mapcount): # MapCodeのみを抽出する mapname =os.path.basename(LemList[m]).split('.') mapcode = mapname[0] # ASCII ラスターファイル名を生成する outasciifile = AsciiPath + '\\' + mapcode + ".asc" ###lem2ascii Lem2Ascii(HeaderList[m],LemList[m],outasciifile) # 上で出力したASCIIファイルを入力ファイルとして指定 inasciifile = outasciifile print inasciifile # 出力用ラスターファイル名を生成 outrasterfile = RasterPath + '\\' + mapcode + '.tif' rasterList.append(outrasterfile) # ASCII 形式のデータをラスターにインポート arcpy.ASCIIToRaster_conversion(inasciifile, outrasterfile,"FLOAT") # 選択した投影法を設定する arcpy.DefineProjection_management(outrasterfile, sr) except arcpy.ExecuteError as e: print str(e).decode("UTF-8")
] input_rasters = [ tmp_dir + '\\{}_raster.tif'.format(x.stem) for x in input_files ] resampled = [tmp_dir + '\\{}.tif'.format(x.stem) for x in input_files] output_files = [ Path(str(x).replace('ellsworth_velma', 'ellsworth_5m_velma')) for x in input_files ] proj = config.proj_wkt for i, file in enumerate(input_files): arcpy.ASCIIToRaster_conversion(str(file), input_rasters[i], "FLOAT") arcpy.ProjectRaster_management( in_raster=input_rasters[i], out_raster=resampled[i], out_coor_system= "PROJCS['NAD_1983_UTM_Zone_10N',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',500000.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-123.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]", in_coor_system= "PROJCS['NAD_1983_UTM_Zone_10N',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',500000.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-123.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]", resampling_type='NEAREST', cell_size=config.cell_size) try: output_files[i].parents[0].mkdir(parents=True) except WindowsError: pass arcpy.RasterToASCII_conversion(in_raster=resampled[i],
RasterFolder = arcpy.GetParameterAsText(8) arcpy.AddMessage("Checking for ASCII rasters in; " + str(RasterFolder)) if os.path.exists(RasterFolder): arcpy.env.workspace = RasterFolder ASCIICheck = arcpy.ListRasters("*asc", "ALL") if not ASCIICheck: arcpy.AddMessage("No ASCII rasters found- OK") else: arcpy.AddMessage("ASCII rasters found, converting to ") for i in ASCIICheck: RasterOutput = RasterFolder + "\\" + (i[:-4]) + "_G.tif" RasterInput = RasterFolder + "\\" + i arcpy.AddMessage(RasterInput) arcpy.ASCIIToRaster_conversion(RasterInput, RasterOutput, "FLOAT") else: arcpy.AddMessage( "Raster folder location not found, please check and try again.") exit arcpy.env.workspace = arcpy.GetParameterAsText(0) #03 Convert D-V-V-D Raster to Classified FeatureClasses #Set variables arcpy.AddMessage("Converting Rasters to Classified FeatureClasses") #...DEPTHS Depth10D = GDBHoldingFolder + "\\" + str(Version) + "\\" + str( HA) + "_Final_10_D_v" + str(Version) + ".gdb" + "\\" + str( HA) + "_DEPTH_10_d_v" + str(Version)
# -*- coding: cp936 -*- #批量将ASCII数据转为栅格并定义投影 print "批量将ASCII数据转为栅格并定义投影" #修改部分 asc_path=r"E:\VI_LPfat_GPP\VI_Cap01\LP_out\Ta\ASC" #ASCII文本数据存储文件夹 suffix='*.asc' #数据后缀 proj_file=r'E:\LP_landcover\IGBP\VIreal.prj' #*.prj投影文件 ras_path=r"E:\VI_LPfat_GPP\VI_Cap01\LP_out\Ta\GEOTIFF" #ASCII转栅格结果存储文件夹 #计算部分 import arcpy import arcpy.sa arcpy.env.workspace=asc_path ascfs=arcpy.ListFiles(suffix) print "共有"+str(len(ascfs))+"个ASCII数据" print "Processing......" for as_f in ascfs: as_file=str(as_f) rasname=ras_path+"\\"+as_file[0:len(as_file)-3]+"tif" arcpy.ASCIIToRaster_conversion(asc_path+'\\'+as_file,rasname,"FLOAT") #ASCII to raster arcpy.DefineProjection_management(rasname,proj_file) #define Projection print as_file print "Finsh!"
# Batch process multiple ASCII to Raster files # Method from: https://geonet.esri.com/thread/46801 # See bottom of page, comment by user "madanksuwal" (15 Mar 2013). # Import system modules import arcgisscripting, os # Create the Geoprocessor object gp = arcgisscripting.create() import arcpy import os import glob # Path to ascii files filepath = r"I:\\APS2008Resource\\blockfiles\\2017_02_17_pyr2\\filtered" # Path where to put rasters outFolder = filepath ascList = glob.glob(filepath + "/*.asc") print ascList for ascFile in ascList: outRaster = outFolder + "/" + os.path.split(ascFile)[1][:-3] + "img" print outRaster arcpy.ASCIIToRaster_conversion(ascFile, outRaster, "FLOAT")
# !Cautions: check current working directory (input files location)! os.chdir("D:\\radar_project\cho215_project\program_georeferencing\HRAPGrid") cwd = os.getcwd() HRAPGrid = os.listdir(cwd) # return a list of the files in cwd # print HRAPGrid (check!) for files in HRAPGrid: print "Processing" + " " + files inputfiles = "D:\\radar_project\cho215_project\program_georeferencing\HRAPGrid" + str("/") + files # set inputfiles path # [Geo-referencing in ArcGIS; true] # ASCII to Raster (HRAP gird) arcpy.ASCIIToRaster_conversion(inputfiles, "grid_harp", "FLOAT") # Define Projection (Polar_Stereographic) arcpy.DefineProjection_management("grid_harp", "PROJCS['Polar_Stereographic',\ GEOGCS['Sphere',\ DATUM['<custom>',\ SPHEROID['<custom>',6371200.0,0.0]],\ PRIMEM['Greenwich',0.0],\ UNIT['Degree',0.0174532925199433]],\ PROJECTION['Stereographic_North_Pole'],\ PARAMETER['False_Easting',0.0],\ PARAMETER['False_Northing',0.0],\ PARAMETER['Central_Meridian',-105.0],\ PARAMETER['Standard_Parallel_1',60.0],\ UNIT['Meter',1.0]]")
os.mkdir(env.workspace) # Parameters. inputFile = os.path.join(root, "gosper.txt") outputFile = os.path.join(root, "gosper.mp4") iterations = 30 # Conway's Game of Life via Spatial Analyst. def tick(grid): g = FocalStatistics(grid, NbrRectangle(3, 3), "SUM", "DATA") - grid return (grid == 1) & (g == 2) | (g == 3) # Import the seed raster. grid = Int(arcpy.ASCIIToRaster_conversion(inputFile)) # Process. for i in range(1, iterations + 1): print(f"Processing {i} of {iterations}") path = os.path.join(env.workspace, str(i).rjust(3, "0")) # Generate, save and reload. This is a workaround for the performance issue. tick(grid).save(path) grid = Raster(path) # Stretch, resample and save. Resample(SetNull(grid == 0, 255), None, 1000, 100).save(f"{path}.tif") # Generate a video from the tif files. images = [img for img in os.listdir(env.workspace) if img.endswith(".tif")]
def individualmode(intervalfile,points,outpath): os.chdir(path) if os.path.exists("Scratch"): arcpy.AddMessage("Using existing scratch folder") else: os.mkdir("Scratch") #load point shapefile arcpy.MakeFeatureLayer_management(points,sourcepoints) #calculate the number of points contained in point shapefile FIDmax = arcpy.GetCount_management(sourcepoints) #generate array of FID values from point shapefile FIDrange = range(0,int(FIDmax[0])) #create header string for output distance matrices header = "FID,"+",".join(map(str,FIDrange))+"\n" #start looping through interval file for i in intervalfile['Interval'].tolist(): #convert interval column into list and iterate through each interval if i == 0: #because Euclidean distance between points should only be calculated for the first interval, run interval0 separately arcpy.AddMessage("Calculating outputs for interval "+ str(i)) #setup search cursors for source and destination points source = arcpy.da.SearchCursor(sourcepoints,["FID","SHAPE@","SHAPE@X","SHAPE@Y"]) sink = arcpy.da.SearchCursor(sourcepoints,["FID","SHAPE@","SHAPE@X","SHAPE@Y"]) arcpy.MakeFeatureLayer_management(outpath+"/shapefile/interval0.shp",intervalshp) #load island polygon for interval 0 #open output files and write header row f = open(outpath+"/individual_euclidean_interval0.csv","w") #this output file is for the inter-point Euclidean distance g = open(outpath+"/individual_leastcost_interval0.csv","w") #this output file is for the least-cost path distance f.write(header) g.write(header) inraster = arcpy.ASCIIToRaster_conversion(outpath+"/raster/interval0.asc") #convert cost raster into a readable format arcpy.DefineProjection_management(inraster,outpath+"/raster/interval0.prj") #set projection of input raster for pf in source: #start first order for loop for origin points euclideandist = [str(pf[0])] #write source point FID as first value to container variable leastcostdist = [str(pf[0])] #write source point FID as first value to container variable for pt in sink: #start second order for loop for destination points if pf == pt: #set distance to NA for self-comparisons euclideandist.append("NA") leastcostdist.append("NA") else: #this subroutine checks for submerged points strSQL1 = """ "FID" = {0}""".format(pf[0]) #define SQL search string for source point strSQL2 = """ "FID" = {0}""".format(pt[0]) #define SQL search string for destination point arcpy.SelectLayerByAttribute_management(sourcepoints,"NEW_SELECTION",strSQL1) #select source point in sourcepoints shapefile arcpy.SelectLayerByLocation_management(intervalshp,"INTERSECT",sourcepoints, selection_type = "NEW_SELECTION") #using source point, select the overlapping polygon on the intervalshp shapefile if int(arcpy.GetCount_management(intervalshp).getOutput(0)) < 1: #test to see if point is below sea level, write NA if true arcpy.AddMessage("Point "+str(pf[0])+" is below sea level during interval "+str(i)+", writing distance value of NA") euclideandist.append("NA") #write NA if source point is submerged leastcostdist.append("NA") else: arcpy.SelectLayerByAttribute_management(sourcepoints,"ADD_TO_SELECTION",strSQL2) #if source point is on valid landmass, select destination point in sourcepoints shapefile arcpy.SelectLayerByLocation_management(intervalshp,"INTERSECT",sourcepoints, selection_type = "ADD_TO_SELECTION") #select island polygon based on destination point if int(arcpy.GetCount_management(intervalshp).getOutput(0)) == 1: #two possibilities here: either both points lie on the same island or the destination point is underwater arcpy.SelectLayerByAttribute_management(sourcepoints,"NEW_SELECTION",strSQL2) #reselect destination point as a new selection arcpy.SelectLayerByLocation_management(intervalshp,"INTERSECT",sourcepoints,selection_type = "REMOVE_FROM_SELECTION") #based on destination point, remove intersecting island polygon from selection if int(arcpy.GetCount_management(intervalshp).getOutput(0)) == 1: #if there is no change to the number of selected polygons, then the destination point is underwater, write NA value. arcpy.AddMessage("Destination point "+str(pt[0])+" is underwater, writing a distance value of NA") euclideandist.append("NA") #write NA if sink point is submerged. leastcostdist.append("NA") else: eucdist = math.sqrt(((pt[2]-pf[2])**2)+((pt[3]-pf[3])**2)) #calculate euclidean distance between points arcpy.AddMessage("The Euclidean distance between point " + str(pf[0]) + " and point " + str(pt[0])+ " is " + str(eucdist)) euclideandist.append(str(eucdist)) #write value to container variable arcpy.SelectLayerByAttribute_management(sourcepoints,"NEW_SELECTION",strSQL1) #reselect source point in sourcepoints layer costdist = CostDistance(sourcepoints,inraster,"","Scratch/backlink") #generate cost distance raster for source point arcpy.SelectLayerByAttribute_management(sourcepoints,"NEW_SELECTION",strSQL2) #now select destination point in sourcepoints layer arcpy.sa.CostPathAsPolyline(sourcepoints,costdist,"Scratch/backlink","Scratch/leastcostline.shp") #calculate least cost path from source to destination with arcpy.da.SearchCursor("Scratch/leastcostline.shp","SHAPE@LENGTH") as cursor: #open least cost line and calculate length for line in cursor: leastcostdist.append(str(line[0])) #write length to container variable arcpy.AddMessage("The least cost distance between point " + str(pf[0]) + " and point " + str(pt[0])+ " is " + str(line[0])) del cursor else: #either the points are on the same island or on different islands eucdist = math.sqrt(((pt[2]-pf[2])**2)+((pt[3]-pf[3])**2)) #calculate euclidean distance between points arcpy.AddMessage("The Euclidean distance between point " + str(pf[0]) + " and point " + str(pt[0])+ " is " + str(eucdist)) euclideandist.append(str(eucdist)) #write value to container variable arcpy.SelectLayerByAttribute_management(sourcepoints,"NEW_SELECTION",strSQL1) #reselect source point in sourcepoints layer costdist = CostDistance(sourcepoints,inraster,"","Scratch/backlink") #generate cost distance raster for source point arcpy.SelectLayerByAttribute_management(sourcepoints,"NEW_SELECTION",strSQL2) #now select destination point in sourcepoints layer arcpy.sa.CostPathAsPolyline(sourcepoints,costdist,"scratch/backlink","scratch/leastcostline.shp") #calculate least cost path from source to destination. with arcpy.da.SearchCursor("Scratch/leastcostline.shp","SHAPE@LENGTH") as cursor: #open least cost line and calculate length for line in cursor: leastcostdist.append(str(line[0])) #write length of least cost line to container variable arcpy.AddMessage("The least cost distance between point " + str(pf[0]) + " and point " + str(pt[0])+ " is " + str(line[0])) del cursor #clean up cursors, reset layer selections, and write data to file. sink.reset() euclideandist_final = ','.join(euclideandist) leastcostdist_final = ','.join(leastcostdist) f.write(euclideandist_final+"\n") g.write(leastcostdist_final+"\n") source.reset() arcpy.SelectLayerByAttribute_management(sourcepoints,"CLEAR_SELECTION") f.close() g.close() del source del sink else: os.chdir(path) #resert directory to home folder if os.path.exists("Scratch"): arcpy.AddMessage("Using existing scratch folder") else: os.mkdir("Scratch") arcpy.AddMessage("Calculating outputs for interval "+ str(i)) #setup search cursors for source and destination points source1 = arcpy.da.SearchCursor(sourcepoints,["FID","SHAPE@","SHAPE@X","SHAPE@Y"]) sink1 = arcpy.da.SearchCursor(sourcepoints,["FID","SHAPE@","SHAPE@X","SHAPE@Y"]) arcpy.MakeFeatureLayer_management(outpath+"/shapefile/interval"+str(i)+".shp",intervalshp) #open output files and write header h = open(outpath+"/individual_leastcost_interval"+str(i)+".csv","w") h.write(header) inraster = arcpy.ASCIIToRaster_conversion(outpath+"/raster/interval"+str(i)+".asc") #convert cost raster into a readable format #inraster = Raster(inraster) arcpy.DefineProjection_management(inraster,outpath+"/raster/interval"+str(i)+".prj") #set projection of input raster for pf1 in source1: #start first order for loop for origin points leastcostdist = [str(pf1[0])] #write source point FID as first value to container variable for pt1 in sink1: if pf1 == pt1: leastcostdist.append("NA") else: strSQL1 = """ "FID" = {0}""".format(pf1[0]) #define SQL search string for source point strSQL2 = """ "FID" = {0}""".format(pt1[0]) #define SQL search string for destination point arcpy.SelectLayerByAttribute_management(sourcepoints,"NEW_SELECTION",strSQL1) #select source point in sourcepoints shapefile arcpy.SelectLayerByLocation_management(intervalshp,"INTERSECT",sourcepoints, selection_type = "NEW_SELECTION") #using source point, select the overlapping polygon on the intervalshp shapefile if int(arcpy.GetCount_management(intervalshp).getOutput(0)) < 1: #test to see if point is below sea level, write NA if true arcpy.AddMessage("Point "+str(pf1[0])+" is below sea level during interval "+str(i)+", writing distance value of NA") leastcostdist.append("NA") else: arcpy.SelectLayerByAttribute_management(sourcepoints,"ADD_TO_SELECTION",strSQL2) #if source point is on valid landmass, select destination point in sourcepoints shapefile arcpy.SelectLayerByLocation_management(intervalshp,"INTERSECT",sourcepoints, selection_type = "ADD_TO_SELECTION") #select island polygon based on destination point if int(arcpy.GetCount_management(intervalshp).getOutput(0)) == 1: #two possibilities here: either both points lie on the same island or the destination point is underwater arcpy.SelectLayerByAttribute_management(sourcepoints,"NEW_SELECTION",strSQL2) #reselect destination point as a new selection arcpy.SelectLayerByLocation_management(intervalshp,"INTERSECT",sourcepoints,selection_type = "REMOVE_FROM_SELECTION") #based on destination point, remove intersecting island polygon from selection if int(arcpy.GetCount_management(intervalshp).getOutput(0)) == 1: #if there is no change to the number of selected polygons, then the destination point is underwater, write NA value. arcpy.AddMessage("Destination point "+str(pt1[0])+" is underwater, writing a distance value of NA") leastcostdist.append("NA") else: arcpy.SelectLayerByAttribute_management(sourcepoints,"NEW_SELECTION",strSQL1) #reselect source point in sourcepoints layer costdist = CostDistance(sourcepoints,inraster,"","Scratch/backlink") #generate cost distance raster for source point arcpy.SelectLayerByAttribute_management(sourcepoints,"NEW_SELECTION",strSQL2) #now select destination point in sourcepoints layer arcpy.sa.CostPathAsPolyline(sourcepoints,costdist,"Scratch/backlink","Scratch/leastcostline.shp") with arcpy.da.SearchCursor("Scratch/leastcostline.shp","SHAPE@LENGTH") as cursor: for line1 in cursor: leastcostdist.append(str(line1[0])) arcpy.AddMessage("The least cost distance between point " + str(pf1[0]) + " and point " + str(pt1[0])+ " is " + str(line1[0])) del cursor else: #either the points are on the same island or on different islands arcpy.SelectLayerByAttribute_management(sourcepoints,"NEW_SELECTION",strSQL1) #reselect source point in sourcepoints layer costdist = CostDistance(sourcepoints,inraster,"","Scratch/backlink") #generate cost distance raster for source point arcpy.SelectLayerByAttribute_management(sourcepoints,"NEW_SELECTION",strSQL2) #now select destination point in sourcepoints layer arcpy.sa.CostPathAsPolyline(sourcepoints,costdist,"Scratch/backlink","scratch/leastcostline.shp") with arcpy.da.SearchCursor("Scratch/leastcostline.shp","SHAPE@LENGTH") as cursor: for line1 in cursor: leastcostdist.append(str(line1[0])) arcpy.AddMessage("The least cost distance between point " + str(pf1[0]) + " and point " + str(pt1[0])+ " is " + str(line1[0])) del cursor leastcostdist_final = ','.join(leastcostdist) #format container variable into writable string h.write(leastcostdist_final+"\n") #write distances to output file sink1.reset() #reset cursor arcpy.SelectLayerByAttribute_management(sourcepoints,"CLEAR_SELECTION") #unselect all points for subsequent iterations h.close() source1.reset() #reset cursor del source1 #delete cursors to release memory del sink1 shutil.rmtree("Scratch") #wipe scratch folder
c = open( "G:\\pheasant\\1.maxent\\3.results\\1km all tif renamed\\1.species.csv", "w") #writer = csv.writer(open('E:\\pheasant\\1.maxent\\3.results\\1km all tif renamed\\1.species.txt', 'w'), delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) #writer = csv.writer(open('E:\\1.species.txt', 'w'), delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) ww = 1 for f in files: if os.path.splitext(f)[1] == '.asc': # Script arguments... Input_raster_file = dir + os.sep + f # Local variables... Output_data_type = "TIFF" Raster_Format = "ASCII" Output_Workspace = "G:\\pheasant\\1.maxent\\3.results\\1km all tif renamed" # =============== file name process ====================== basename = os.path.splitext(f)[0] Output_raster = Output_Workspace + os.sep + str(ww) + ".tif" if os.path.exists(Output_raster) == False: print Input_raster_file # Process: Raster To Other Format (multiple)... arcpy.ASCIIToRaster_conversion(Input_raster_file, Output_raster, "FLOAT") c.write(f + '\n') c.flush() ww = ww + 1 print Output_raster
import arcpy import os inFiles = "c://workspace/py_spectro/out_veg/" outFiles = "c://workspace/py_spectro/out_veg_ras/" rasType = "FLOAT" for f in os.listdir(inFiles): fname = f[:-4] ascii = inFiles + "/" + f outRas = outFiles + "/" + fname + ".tif" arcpy.ASCIIToRaster_conversion(ascii, outRas,rasType) print f + " ok!!"