def _saveRaster(self, raster_to_save, output_raster_fullpath, factory_specifications): self.debug_logger("Saving Final Raster") if factory_specifications.get('AddColormap_management_config', None): self.debug_logger("Adding Color Map...") color_map_config = factory_specifications[ 'AddColormap_management_config'] r = arcpy.AddColormap_management( raster_to_save, color_map_config.get('in_template_raster', ''), color_map_config['input_CLR_file']) self.debug_logger("AddColormap_management Result", r.status) raster_name = os.path.basename(output_raster_fullpath) raster_to_save.save(raster_name) local_raster_fullpath = os.path.join(self.workspace_fullpath, raster_name) self.debug_logger("local_raster_fullpath", local_raster_fullpath) self.debug_logger("output_raster_fullpath", output_raster_fullpath) self._removeExistingRasterIfExists(output_raster_fullpath) self._copyRaster( factory_specifications['CopyRaster_management_config'], local_raster_fullpath, output_raster_fullpath) self._removeExistingRasterIfExists(local_raster_fullpath)
def _addColorMap(self, trmm_raster): cmc = self.add_color_map_config color_map_result = arcpy.AddColormap_management( trmm_raster, cmc.get('in_template_raster', ''), cmc['input_CLR_file']) self.debug_logger("AddColormap_management result", color_map_result.status)
def addColorMap(inraster, template): ##Add Colormap ##Usage: AddColormap_management in_raster {in_template_raster} {input_CLR_file} try: import arcpy # arcpy.env.workspace = r'C:/Users/Bougie/Documents/ArcGIS/Default.gdb' ##Assign colormap using template image arcpy.AddColormap_management(inraster, "#", template) except: print "Add Colormap example failed." print arcpy.GetMessages()
def addColorMap(production_type,inraster,template): ##Add Colormap ##Usage: AddColormap_management in_raster {in_template_raster} {input_CLR_file} try: import arcpy # arcpy.CheckOutExtension("Spatial") # arcpy.env.workspace = 'C:/Users/bougie/Desktop/gibbs/'+production_type+'/ytc.gdb' ##Assign colormap using template image arcpy.AddColormap_management(inraster, "#", template) except: print "Add Colormap example failed." print arcpy.GetMessages()
return u"较高" elif a == 3: return u"较低" elif a == 4: return u"低" """ arcpy.CalculateField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "fbl", FBLL, "PYTHON_9.3") arcpy.CalculateField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "dengji", expression, "PYTHON_9.3", codeblock) arcpy.CalculateField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "mj", "(!fbl!)*(!COUNT!)", "PYTHON_9.3") arcpy.DeleteField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "fbl") ############################################# arcpy.Delete_management(MIFBC) arcpy.Delete_management("krigfb.tif") arcpy.Delete_management("clipfb.tif") if os.path.exists(in_fb_csv) == True: os.remove(in_fb_csv) ########################################### RasterTableToTxtAndExcel.write2excel(OUTPUTPATH + OUTPUTNAME + ".tif", OUTPUTPATH, OUTPUTNAME) if IN_XZQQ != "99999": StaticticsByXZQ.StatisticBYXZQ(OUTPUTPATH + OUTPUTNAME + ".tif", IN_XZQQ, OUTPUTPATH, OUTPUTNAME + "_XZQ") arcpy.AddColormap_management(OUTPUTPATH + OUTPUTNAME + ".tif", "#", "C:\\yz_spj\\clr\\Month4_fengbaochao_4J.clr") arcpy.CheckInExtension("3D") arcpy.CheckInExtension("Spatial")
arcpy.DeleteField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "fbl") arcpy.Delete_management("fengzhi.tif") arcpy.Delete_management("jj.tif") arcpy.Delete_management("clipdz.tif") arcpy.Delete_management("weixianxing.tif") arcpy.Delete_management("wxx.shp") arcpy.Delete_management("yfx.shp") arcpy.Delete_management("txyfx.shp") arcpy.Delete_management("cjl.tif") arcpy.Delete_management("cjsl.tif") arcpy.Delete_management("cjl.shp") arcpy.Delete_management("cjsl.shp") arcpy.Delete_management("cjyfx.shp") arcpy.Delete_management("cjsl.tif") arcpy.Delete_management("cjl.shp") arcpy.Delete_management("cjsl.shp") arcpy.Delete_management("jc.tif") if arcpy.Exists("tihuan.tif"): arcpy.Delete_management("tihuan.tif") if arcpy.Exists("tihuan1.tif"): arcpy.Delete_management("tihuan1.tif") ######################################### RasterTableToTxtAndExcel.write2excel(OUTPUTPATH + OUTPUTNAME + ".tif", OUTPUTPATH, OUTPUTNAME) if IN_XZQQ != "99999": StaticticsByXZQ.StatisticBYXZQ(OUTPUTPATH + OUTPUTNAME + ".tif", IN_XZQQ, OUTPUTPATH, OUTPUTNAME + "_XZQ") arcpy.AddColormap_management(OUTPUTPATH + OUTPUTNAME + ".tif", "#", "C:\\yz_spj\\clr\\Month4_tu_huan_5J.clr") arcpy.CheckInExtension("3D") arcpy.CheckInExtension("Spatial")
str = "=== Predictions on user test set ===" str_len = len(str) line = stream.readline() while line[0:str_len] != str: line = stream.readline() line = stream.readline() line = stream.readline() line = stream.readline() stop = 0 for row in range(row_start, row_end): for col in range(col_start, col_end, 1): #if(not(stop)): land_use_class = line.split(":")[2].split(" ")[0] int_val = new_dict[land_use_class] if (int_val > 20 and int_val < 25): raster_array[row, col] = int_val line = stream.readline() if (line == "\n"): stop = 1 newRaster = arcpy.NumPyArrayToRaster(raster_array, lowerLeft, cellSize, value_to_nodata=0) file_name = r"C:\Users\Thomas Peacemaker\Desktop\Senior_Research\data\land_cover\predicted\2016_predicted_2.tif" color_map = r"C:\Users\Thomas Peacemaker\Desktop\Senior_Research\data\land_cover\nlcd_2011_landcover_2011_edition_2014_10_10\color_map.clr" newRaster.save(file_name) arcpy.AddColormap_management(file_name, "#", color_map)
arcpy.Delete_management("qita.tif") arcpy.Delete_management("zhenghendvi.tif") arcpy.Delete_management("ndvifinal.tif") arcpy.Delete_management("ndvif2.tif") arcpy.Delete_management('trqsf.tif') arcpy.Delete_management("trfinal.tif") arcpy.Delete_management(outputjy) arcpy.Delete_management("jy2.shp") arcpy.Delete_management("jy3.shp") arcpy.Delete_management("jy4.shp") arcpy.Delete_management("jykrigph.tif") arcpy.Delete_management("resamplejy.tif") arcpy.Delete_management("clipjy.tif") arcpy.Delete_management("stbc.tif") arcpy.Delete_management("qqq.tif") if os.path.exists(in_jy_csv) == True: os.remove(in_jy_csv) ############################### RasterTableToTxtAndExcel.write2excel(OUTPUTPATH + OUTPUTNAME + ".tif", OUTPUTPATH, OUTPUTNAME) if IN_XZQQ != "99999": StaticticsByXZQ.StatisticBYXZQ(OUTPUTPATH + OUTPUTNAME + ".tif", IN_XZQQ, OUTPUTPATH, OUTPUTNAME + "_XZQ") arcpy.AddColormap_management(OUTPUTPATH + OUTPUTNAME + ".tif", "#", "C:/yz_spj/clr/Month4_fuwu_3J.clr") #arcpy.ApplySymbologyFromLayer_management(OUTPUTPATH+OUTPUTNAME+".tif", "C:/yz_spj/clr/Month4_fuwu_3J.lyr") #arcpy.ApplySymbologyFromLayer_management(fin, "F:\\1clr\\Month4_mingan_3J.lyr") ############################################ arcpy.CheckInExtension("3D") arcpy.CheckInExtension("Spatial")
arcpy.CalculateField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "fbl", FBLL, "PYTHON_9.3") arcpy.CalculateField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "dengji", expression, "PYTHON_9.3", codeblock) arcpy.CalculateField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "mj", "(!fbl!)*(!COUNT!)", "PYTHON_9.3") arcpy.DeleteField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "fbl") arcpy.Delete_management("ff.tif") if arcpy.Exists("tihuan.tif"): arcpy.Delete_management("tihuan.tif") if arcpy.Exists("tihuan1.tif"): arcpy.Delete_management("tihuan1.tif") if arcpy.Exists("tihuan2.tif"): arcpy.Delete_management("tihuan2.tif") if arcpy.Exists("tihuan3.tif"): arcpy.Delete_management("tihuan3.tif") if arcpy.Exists("tihuan4.tif"): arcpy.Delete_management("tihuan4.tif") #################################### RasterTableToTxtAndExcel.write2excel(OUTPUTPATH + OUTPUTNAME + ".tif", OUTPUTPATH, OUTPUTNAME) if IN_XZQQ != "99999": StaticticsByXZQ.StatisticBYXZQ(OUTPUTPATH + OUTPUTNAME + ".tif", IN_XZQQ, OUTPUTPATH, OUTPUTNAME + "_XZQ") arcpy.AddColormap_management(OUTPUTPATH + OUTPUTNAME + ".tif", "#", "C:/yz_spj/clr/Month4_nong_tu_zai_5J.clr") ################################ arcpy.CheckInExtension("3D") arcpy.CheckInExtension("Spatial")
if a == 1: return u"好" elif a == 2: return u"较好" elif a == 3: return u"一般" elif a == 4: return u"较差" elif a == 5: return u"差" """ arcpy.CalculateField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "fbl", FBLL, "PYTHON_9.3") arcpy.CalculateField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "dengji", expression, "PYTHON_9.3", codeblock) arcpy.CalculateField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "mj", "(!fbl!)*(!COUNT!)", "PYTHON_9.3") arcpy.DeleteField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "fbl") arcpy.DeleteField_management(IN_XZQ, "ysdj") arcpy.Delete_management('xzq.tif') ##################################### RasterTableToTxtAndExcel.write2excel(OUTPUTPATH + OUTPUTNAME + ".tif", OUTPUTPATH, OUTPUTNAME) if IN_XZQQ != "99999": StaticticsByXZQ.StatisticBYXZQ(OUTPUTPATH + OUTPUTNAME + ".tif", IN_XZQQ, OUTPUTPATH, OUTPUTNAME + "_XZQ") arcpy.AddColormap_management(OUTPUTPATH + OUTPUTNAME + ".tif", "#", "C:\\yz_spj\\clr\\Month4_nong_cheng_shui_5J.clr") arcpy.CheckInExtension("Spatial") arcpy.CheckInExtension("3D")
def Guidos_Post(city, inDir, workFld): import traceback, time, arcpy, os, subprocess from arcpy import env arcpy.CheckOutExtension('Spatial') #-------- DIRECTORY SETUP ------------------------------------------------ """ Working Directory """ if arcpy.Exists(str(workFld) + '/' + city + '_GUIDOS.gdb') == False: arcpy.CreateFileGDB_management(str(workFld), str(city) + '_GUIDOS.gdb') else: pass workDir = str(workFld) + '/' + city + '_GUIDOS.gdb' arcpy.env.workspace = workDir """ Report File Directory """ reportfileDir = str(workFld) + '/Logs' """ Frequent Directory """ freqDir = str(workFld) + '/' + city +'_Freq.gdb' """ Final Geodatabase """ finalDir = str(workFld) + '/' + city + '_Final.gdb' """ Projection File Directory """ prjDir = str(inDir) + '/Prj' """ Split Raster Directory """ if os.path.isdir(str(workFld) + '/' + city + '_Split') == True: pass else: os.makedirs(str(workFld) + '/' + city + '_Split') splitDir = str(workFld) + '/' + city + '_Split' """ Set Workspace Environments """ arcpy.env.workspace = workDir arcpy.env.scratch = str(inDir) + '/Scratch.gdb' arcpy.env.overwriteOutput = True #----------------------------------------------------------------------------- # BEGIN ANALYSIS #----------------------------------------------------------------------------- try: #-------- LOGFILE CREATION --------------------------------------------- """ Create report file for each metric """ ## try: loglist = sorted(f for f in os.listdir(reportfileDir) if f.startswith(str(city) + '_Conn')) tmpName = loglist[-1] ## except: ## tmpName = city + '_Conn_' + time.strftime('%Y%m%d_%H-%M') + '.txt' reportfileName = reportfileDir + '/' + tmpName try: reportFile = open(reportfileName, 'a') except: reportFile = open(reportfileName, 'w') print 'No log for GUIDOS_Prep' try: loglist = sorted (f for f in os.listdir(reportfileDir) if f.startswith(str(city) + '_Reuse')) tmpName = loglist[-1] except: tmpName = city + '_Reuse_' + time.strftime('%Y%m%d_%H-%M') + '.txt' reportfileName = reportfileDir + '/' + tmpName try: ReuseRF = open(reportfileName, 'a') except: ReuseRF = open(reportfileName, 'w') print 'Creating Reuse Log' print 'Connectivity Start Time: ' + time.asctime() reportFile.write("For each piece, convert the raster from a tiled TIFF to a striped TIFF.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n') #-------- PROCESSING LAYERS ---------------------------------------------- """ Set Environments """ #Figure out the correct UTM Zone prjNumb = arcpy.Describe(str(freqDir) + '/LC').spatialReference.name prjNumb = prjNumb[-3:] prjfileUTM = prjDir + '/NAD 1983 UTM Zone ' + prjNumb + '.prj' AllRast = 'yes' """ -------- RUN GUIDOS ---------------------------------------------- """ arcpy.env.workspace = splitDir guidlist = arcpy.ListRasters('S_FWW*') """ For each raster piece, run GUIDOS """ for r in guidlist: guidexe = str(inDir) + '/mspa_win64.exe' inrast = str(splitDir) + '/' + str(r) outrast = 'G_' + str(r) outdir = str(splitDir) + '/' argu = (guidexe, '-i', inrast, '-o', outrast, '-eew', '30', '-internal', '0', '-odir', outdir, '-transition', '0') subprocess.call(argu) """ If GUIDOS worked, Reproject the rasters """ if arcpy.Exists(outrast) == True: # Project the output raster oLeft = arcpy.GetRasterProperties_management(r, "LEFT").getOutput(0) oBottom = arcpy.GetRasterProperties_management(r, "BOTTOM").getOutput(0) nBottom = arcpy.GetRasterProperties_management(outrast, 'BOTTOM').getOutput(0) xMove = float(oLeft) + 0.5 yMove = float(oBottom) - float(nBottom) arcpy.Shift_management(outrast, 'Sh_' + str(r), xMove, yMove, r) numb = r.replace('S_FWW_WB_', '') arcpy.env.extent = "MAXOF" arcpy.env.snapRaster = str(splitDir) + '/' + str(r) descLC = arcpy.Describe(str(freqDir) + '/LC') arcpy.ProjectRaster_management('Sh_' + str(r), 'Conn_' + str(numb), descLC.spatialReference, '', '', '', '', descLC.spatialReference) else: """ If GUIDOS didn't work, quit after loop """ AllRast = 'no' print str(outrast) + ' not run properly' reportFile.write("For each piece, run the GUIDOS (Graphical User Interface for the Description of image Objects and their Shapes) v2.1 MSPA (Morphological Spatial Pattern Analysis) Standalone Tool (http://forest.jrc.ec.europa.eu/download/software/guidos) using 8 neighbor connectivity, 30 pixel edge, transition off, and intext off.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n') reportFile.write("Project each GUIDOS piece into UTM, shifting to the location of the original piece.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n') """-------- If all the GUIDOS Rasters worked, Post-Process ------------ """ if AllRast == 'yes': """-------- Split the Raster As Needs, Process Each Piece ----------------- """ """ Check if the raster should be split """ columns = arcpy.GetRasterProperties_management(splitDir + '/FWW_WB.tif', 'COLUMNCOUNT').getOutput(0) xsplit = int(float(columns) / 8000) + 1 rows = arcpy.GetRasterProperties_management(splitDir + '/FWW_WB.tif', 'ROWCOUNT').getOutput(0) ysplit = int (float(rows) / 8000) + 1 """-------- If no split, run the analysis --------------------------------- """ if xsplit*ysplit == 1: """ Copy Raster """ arcpy.CopyRaster_management(splitDir + '/Conn.TIF', workDir + '/Conn') reportFile.write("Copy Tiff into Working GDB.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n') """-------- If split, run the analysis on each piece and recombine --------- """ else: """ Set Environments """ arcpy.env.extent = 'FWW_WB.tif' arcpy.env.snapRaster = 'FWW_WB.tif' """ Split the Raster """ arcpy.SplitRaster_management('FWW_WB.tif', splitDir, 'NoO_WB_', 'NUMBER_OF_TILES', 'TIFF', '', str(xsplit) + ' ' + str(ysplit), '', '', '') reportFile.write("Split the reclassified land cover into the same pieces as previous but with no overlap.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n') """ Clip the overlap off the tiles """ pieces = int(xsplit) * int(ysplit) for tiles in range(int(pieces)): if arcpy.Exists('NoO_WB_' + str(tiles) + '.TIF') == True: """ Set Environments """ arcpy.env.extent = 'NoO_WB_' + str(tiles) + '.TIF' arcpy.env.snapRaster = 'NoO_WB_' + str(tiles) + '.TIF' """ Extract the Area of Interest """ EbM = arcpy.sa.ExtractByMask('Conn_' + str(tiles) + '.TIF', 'NoO_WB_' + str(tiles) + '.TIF') EbM.save(workDir + '/Conn_' + str(tiles)) else: pass reportFile.write("Clip each GUIDOS output to the corresponding piece of the second raster split to eliminate overlap.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n') """ Set Environments """ arcpy.env.extent = workDir + '/FWW_WB' arcpy.env.snapRaster = workDir + '/FWW_WB' arcpy.env.workspace = workDir """ Mosaic tiles together """ RastList = arcpy.ListRasters('Conn_*') arcpy.MosaicToNewRaster_management(RastList, workDir, 'Conn', '', '8_BIT_UNSIGNED', 1, 1, '', '') reportFile.write("Mosaic all of the clipped GUIDOS output tiles into one raster.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n') """ Burn water into the Output Raster """ watercon = arcpy.sa.Con(freqDir + '/LC', 10, 'Conn', 'value = 10') watercon.save('Conn_WithWat') reportFile.write("Using the original land cover, burn water pixels into raster using a conditional statement if Land Cover Value = 10; for true: 10; for false: GUIDOS raster.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n') """--------- Clip the EA Boundaries to the County Lines, if necessary ----- """ if arcpy.Exists(str(freqDir) + '/Bnd_Cty') == False: """ Copy Counties to Frequent and Project """ arcpy.MakeFeatureLayer_management(str(inDir) + '/Input.gdb/Counties_Alb', 'Cty') arcpy.SelectLayerByLocation_management('Cty', 'CONTAINS', 'BG_Alb', '', 'NEW_SELECTION') arcpy.FeatureClassToFeatureClass_conversion(str(inDir) + '/Input.gdb/Counties_Alb', str(freqDir), 'Counties_Alb') arcpy.SelectLayerByAttribute_management('Cty', 'CLEAR_SELECTION') descLC = arcpy.Describe(str(freqDir) + '/LC') arcpy.Project_management('Counties_Alb', 'Counties', descLC.spatialReference) """ Clip Boundary to County Lines """ arcpy.Clip_analysis(str(freqDir) + '/Bnd', str(freqDir) + '/Counties', str(freqDir) + '/Bnd_Cty') reportFile.write("Clip the EnviroAtlas Community Boundary to the county lines for the community to limit the output to land area.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n') ReuseRF.write("Bnd_Cty--" + time.strftime('%Y%m%d--%H%M%S') + '--\n') else: reportFile.write("Clip the EnviroAtlas Community Boundary to the county lines for the community to limit the output to land area.--Bnd_Cty" + '--\n') """-------- Check that the Analysis Area is covered by the LC -------------- """ """ Create a Polygon Version of the LC """ if arcpy.Exists(freqDir + '/LC_Poly') == False: arcpy.env.snapRaster = str(freqDir) + '/LC' arcpy.env.extent = str(freqDir) + '/LC' ReC = arcpy.sa.Reclassify(str(freqDir) + '/LC', 'Value', arcpy.sa.RemapValue([[0,0],[10,1],[20,1],[21,1],[22,1],[30,1],[40,1],[52,1],[70,1],[80,1],[82,1],[91,1],[92,1]])) ReC.save(str(freqDir) + '/AreaIO') arcpy.RasterToPolygon_conversion(str(freqDir) + '/AreaIO', str(freqDir) + '/LC_Poly', 'SIMPLIFY') arcpy.env.extent = workDir + '/FWW_WB' arcpy.env.snapRaster = workDir + '/FWW_WB' """ Buffer the LC Polygon by -500m """ if arcpy.Exists(freqDir + '/Bnd_Cty_500m') == False: arcpy.Buffer_analysis(str(freqDir) + '/Bnd_Cty', str(freqDir) + '/Bnd_Cty_500m', '500 meters') arcpy.EliminatePolygonPart_management(str(freqDir) + '/Bnd_Cty_500m', str(freqDir) + '/Bnd_Cty_500m_EP', 'PERCENT', '', '30', 'CONTAINED_ONLY') arcpy.Delete_management(str(freqDir) + '/Bnd_Cty_500m') arcpy.Rename_management(str(freqDir) + '/Bnd_Cty_500m_EP', str(freqDir) + '/Bnd_Cty_500m') """ Identify whether LC is large enough """ arcpy.MakeFeatureLayer_management(str(freqDir) + '/LC_Poly', 'LClyr') arcpy.MakeFeatureLayer_management(str(freqDir) + '/Bnd_Cty_500m', 'BC_500lyr') arcpy.SelectLayerByLocation_management('BC_500lyr', 'COMPLETELY_WITHIN', 'LClyr', '', 'NEW_SELECTION') bigEnough = float(arcpy.GetCount_management('BC_500lyr').getOutput(0)) arcpy.SelectLayerByAttribute_management('BC_500lyr', 'CLEAR_SELECTION') """ If the LC isn't large enough, edit erroneous BGS """ if bigEnough == 0: arcpy.Clip_analysis(freqDir + '/Bnd_Cty', freqDir + '/LC_Poly', 'Bnd_Cty_LC') reportFile.write("Because the community boundary extends beyond the Land Cover, clip the boundary to the land cover.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n') """ Clip the Raster to Bnd_Cty """ try: EbM = arcpy.sa.ExtractByMask('Conn_WithWat', 'Bnd_Cty_LC') except: EbM = arcpy.sa.ExtractByMask('Conn_WithWat', freqDir + '/Bnd_Cty') EbM.save('Conn_Bnd') reportFile.write("Extract by Mask the area of the projected raster that is within the clipped EnviroAtlas Community Boundary.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n') """ Add Colormap """ arcpy.AddColormap_management('Conn_Bnd', '', str(inDir) + '/Templates/GUIDOS2.clr') """ Convert to TIFF for sharing """ arcpy.CopyRaster_management('Conn_Bnd', splitDir + '/' + str(city) + '_Conn.tif') reportFile.write("Add a default GUIDOS colormap to the final raster from any of the original GUIDOS output tiles.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n') """ Convert to Web Mercator """ prjfileWM = prjDir + '/WGS 1984 Web Mercator (auxiliary sphere).prj' if arcpy.Exists(freqDir + '/Bnd_WM') == False: arcpy.Project_management(freqDir + '/Bnd', freqDir + '/Bnd_WM', prjfileWM) arcpy.env.extent = freqDir + '/Bnd_WM' arcpy.ProjectRaster_management('Conn_Bnd', 'Conn_WM', prjfileWM) reportFile.write("Convert raster into TIFF format for distribution.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n') """ Copy to Final Directory """ arcpy.CopyRaster_management('Conn_WM', finalDir + '/' + str(city) + '_Conn') ## reportFile.write("Step 15--Copy to Final GDB--" + time.strftime('%Y%m%d--%H%M%S') + '--\n') print 'GUIDOS End Time: ' + time.asctime() else: print 'Some MSPA functions did not complete. Please run manually.' #------------------------------------------------------------------------- #-------- COMPELETE LOGFILES --------------------------------------------- reportFile.close() ReuseRF.close() #----------------------------------------------------------------------------- # END ANALYSIS #----------------------------------------------------------------------------- except: """ This part of the script executes if anything went wrong in the main script above """ #-------- PRINT ERRORS --------------------------------------------------- print "\nSomething went wrong.\n\n" print "Python Traceback Message below:" print traceback.format_exc() print "\nArcMap Error Messages below:" print arcpy.GetMessages(2) print "\nArcMap Warning Messages below:" print arcpy.GetMessages(1) #-------- COMPLETE LOGFILE ------------------------------------------------ reportFile.write("\nSomething went wrong.\n\n") reportFile.write("Pyton Traceback Message below:") reportFile.write(traceback.format_exc()) reportFile.write("\nArcMap Error Messages below:") reportFile.write(arcpy.GetMessages(2)) reportFile.write("\nArcMap Warning Messages below:") reportFile.write(arcpy.GetMessages(1)) reportFile.write( "\n\nEnded at " + time.asctime() + '\n') reportFile.write("\n---End of Log File---\n") if reportFile: reportFile.close()
import arcpy import general as gen arcpy.env.workspace = 'D:\\projects\\usxp\\deliverables\\s35\\s35.gdb' in_raster = 's35_mtr' clr = 'C:\\Users\\Bougie\\Desktop\\misc\\colormaps\\mtr.clr' arcpy.AddColormap_management(in_raster=in_raster, input_CLR_file=clr) # gen.buildPyramids(in_raster)
arcpy.Delete_management("qxshp.shp") arcpy.Delete_management("qhtdshui.shp") arcpy.Delete_management("xzshp.shp") arcpy.Delete_management("hjshp.shp") arcpy.Delete_management("stshp.shp") arcpy.Delete_management("zhshp.shp") arcpy.Delete_management("zhfshp.shp") arcpy.Delete_management("jg.tif") if arcpy.Exists("tihuan.tif"): arcpy.Delete_management("tihuan.tif") if arcpy.Exists("tihuan1.tif"): arcpy.Delete_management("tihuan1.tif") if arcpy.Exists("tihuan2.tif"): arcpy.Delete_management("tihuan2.tif") if arcpy.Exists("tihuan3.tif"): arcpy.Delete_management("tihuan3.tif") if arcpy.Exists("tihuan4.tif"): arcpy.Delete_management("tihuan4.tif") if arcpy.Exists("tihuan5.tif"): arcpy.Delete_management("tihuan5.tif") ################################## RasterTableToTxtAndExcel.write2excel(OUTPUTPATH + OUTPUTNAME + ".tif", OUTPUTPATH, OUTPUTNAME) if IN_XZQQ != "99999": StaticticsByXZQ.StatisticBYXZQ(OUTPUTPATH + OUTPUTNAME + ".tif", IN_XZQQ, OUTPUTPATH, OUTPUTNAME + "_XZQ") arcpy.AddColormap_management(OUTPUTPATH + OUTPUTNAME + ".tif", "#", "C:/yz_spj/clr/Month7_shiyixing_3J.clr") ######################################## arcpy.CheckOutExtension("3D") arcpy.CheckOutExtension("Spatial")
arcpy.AddField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "dengji", "STRING", "", "", "") arcpy.AddField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "mj", "DOUBLE", "", "", "") arcpy.AddField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "fbl", "DOUBLE", "", "", "") expression = "getClass(!VALUE!)" codeblock = """def getClass(a): if a == 1: return u"土地资源约束下城镇建设的最大规模" """ arcpy.CalculateField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "fbl", FBLL, "PYTHON_9.3") arcpy.CalculateField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "dengji", expression, "PYTHON_9.3", codeblock) arcpy.CalculateField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "mj", "(!fbl!)*(!COUNT!)", "PYTHON_9.3") arcpy.DeleteField_management(OUTPUTPATH + OUTPUTNAME + ".tif", "fbl") arcpy.Delete_management('jg.tif') ################################## RasterTableToTxtAndExcel.write2excel(OUTPUTPATH + OUTPUTNAME + ".tif", OUTPUTPATH, OUTPUTNAME) if IN_XZQQ != "99999": StaticticsByXZQ.StatisticBYXZQ(OUTPUTPATH + OUTPUTNAME + ".tif", IN_XZQQ, OUTPUTPATH, OUTPUTNAME + "_XZQ") arcpy.AddColormap_management(OUTPUTPATH + OUTPUTNAME + ".tif", "#", "C:\\yz_spj\\clr\\Month4_jianshe_1J.clr") arcpy.CheckInExtension("Spatial") arcpy.CheckInExtension("3D")
arcpy.Delete_management("shp3.shp") arcpy.Delete_management("shp4.shp") arcpy.Delete_management("jg.tif") if arcpy.Exists("tihuan.tif"): arcpy.Delete_management("tihuan.tif") if arcpy.Exists("tihuan1.tif"): arcpy.Delete_management("tihuan1.tif") if arcpy.Exists("tihuan2.tif"): arcpy.Delete_management("tihuan2.tif") if arcpy.Exists("tihuan3.tif"): arcpy.Delete_management("tihuan3.tif") if arcpy.Exists("tihuan4.tif"): arcpy.Delete_management("tihuan4.tif") if arcpy.Exists("tihuan5.tif"): arcpy.Delete_management("tihuan5.tif") if arcpy.Exists("tihuan6.tif"): arcpy.Delete_management("tihuan6.tif") if arcpy.Exists("tihuan7.tif"): arcpy.Delete_management("tihuan7.tif") ############################## RasterTableToTxtAndExcel.write2excel(OUTPUTPATH + OUTPUTNAME + ".tif", OUTPUTPATH, OUTPUTNAME) if IN_XZQQ != "99999": StaticticsByXZQ.StatisticBYXZQ(OUTPUTPATH + OUTPUTNAME + ".tif", IN_XZQQ, OUTPUTPATH, OUTPUTNAME + "_XZQ") arcpy.AddColormap_management(OUTPUTPATH + OUTPUTNAME + ".tif", "#", "C:\\yz_spj\\clr\\Month7_cheng_ji_3J.clr") ######################## arcpy.CheckInExtension("3D") arcpy.CheckInExtension("Spatial")
def CreateRasters( LocPts, RLoc, num, outFc, Tfolder, Ofolder, Ifolder, Index, Var, PreName, minstr, Spref, Conv, ConvFormula, ConvU, CFolder, CName ): ##### this function will be executed in GWRFunction to create Rasters and Conversion Raster if needed once the Predicted Output shapefile is created. arcpy.env.workspace = Ofolder FIDToXYLocation = {} rows = arcpy.da.SearchCursor(LocPts, ["FID", "X", "Y"]) for row in rows: FIDToXYLocation[row[0]] = [row[1], row[2]] ufdbnamask = arcpy.Raster(RLoc) masklowerleft = arcpy.Point(ufdbnamask.extent.XMin, ufdbnamask.extent.YMin) maskcellsize = ufdbnamask.meanCellWidth npmask = arcpy.RasterToNumPyArray(ufdbnamask) sendrasters = [] convsendrasters = [] sendKML = [] convsendKML = [] npmask.shape newarr = np.full(npmask.shape, 0.0, dtype=np.dtype('Float64')) maskcopy = np.copy(npmask) print "shape" print maskcopy.shape thesefields = arcpy.ListFields(outFc) print "Fields" IDField = "FID" for afield in thesefields: print afield.name if afield.name == "ObjectID": IDField = "ObjectID" with arcpy.da.SearchCursor(outFc, [IDField, "Predicted"]) as rows: # print FIDToXYLocation.keys() for row in rows: # print row[0] # print FIDToXYLocation[row[0]] # print FIDToXYLocation[row[0]][0] X = FIDToXYLocation[row[0]][0] Y = FIDToXYLocation[row[0]][1] newarr[Y, X] = row[1] newras = arcpy.NumPyArrayToRaster(in_array=newarr, lower_left_corner=masklowerleft, x_cell_size=maskcellsize, y_cell_size=maskcellsize, value_to_nodata=0.0) newras.save(Tfolder + "\\outr" + str(num) + ".tif") arcpy.Resample_management(Tfolder + "\\outr" + str(num) + ".tif", Tfolder + "\\outz" + str(num) + ".tif", ".008", "BILINEAR") outCon = Con(IsNull(Tfolder + "\\outz" + str(num) + ".tif"), 0, Tfolder + "\\outz" + str(num) + ".tif") outCon.save(Tfolder + "\\outcon" + str(num) + ".tif") arcpy.DefineProjection_management(Tfolder + "\\outcon" + str(num) + ".tif", coor_system=Spref) opdt = dt.datetime.utcnow() rcraster = arcpy.sa.ReclassByTable( Tfolder + "\\outcon" + str(num) + ".tif", Ifolder + "\\NearTerm.gdb\\RCValTable" + Var, "LowValue", "HighValue", "AssignValue", "NODATA") # rcraster = arcpy.sa.SetNull(rcraster, rcraster, "Value = 0") TifSave = Ofolder + "\\outrrr" + str(Index) + ".tif" rcraster.save(TifSave) ptdt("reclass") ImgSave = Ofolder + "\\outrrr" + str(Index) + ".img" rcraster.save(ImgSave) ptdt("reclass") # 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: "outrrr0.tif" arcpy.SetRasterProperties_management(in_raster=Ofolder + "\\outrrr" + str(Index) + ".tif", data_type="", statistics="", stats_file="", nodata="1 0", key_properties="") arcpy.AddColormap_management(TifSave, "#", Ifolder + "\\" + Var + ".clr") arcpy.AddColormap_management(ImgSave, "#", Ifolder + "\\" + Var + ".clr") outfilename = Ofolder + "\\" + minstr + "_" + str(Index).zfill( 3) + ".tif" outfilenamewithprefixandsuffix = PreName + "_" + minstr + "_" + str( Index).zfill(3) + ".tif" ptdt(outfilenamewithprefixandsuffix) arcpy.CopyRaster_management(in_raster=TifSave, out_rasterdataset=outfilename, config_keyword="", background_value="", nodata_value=None, onebit_to_eightbit="NONE", colormap_to_RGB="", pixel_type="8_BIT_UNSIGNED", scale_pixel_value="NONE", RGB_to_Colormap="NONE") #####3sendrasters.append([outfilename, outfilenamewithprefixandsuffix]) RasterResult = [outfilename, outfilenamewithprefixandsuffix] TifLyr = PreName + ".lyr" arcpy.MakeRasterLayer_management( outfilename, TifLyr, "", "-179.14732999988 17.675849999878 -49.99532999988 83.123849999878", "") KMLfilename = Ofolder + "\\" + minstr + "_" + str(Index).zfill( 3) + ".kmz" KMLfilenamewithprefixandsuffix = PreName + "_" + minstr + "_" + str( Index).zfill(3) + ".kmz" arcpy.LayerToKML_conversion(TifLyr, KMLfilename, "0", "NO_COMPOSITE", "DEFAULT", "1024", "96") #####sendKML.append([KMLfilename,KMLfilenamewithprefixandsuffix]) KMLResult = [KMLfilename, KMLfilenamewithprefixandsuffix] ##########outfilename = Ofolder + "\\" + minstr + "_" + str(Index).zfill(3) + ".png" ########outfilenamewithprefixandsuffix = PreName + "_" + minstr + "_" + str(Index).zfill(3) + ".png" #########ImgRaster=arcpy.CopyRaster_management(in_raster=TifSave,out_rasterdataset=outfilename,config_keyword="", background_value="", nodata_value=None, onebit_to_eightbit="NONE",colormap_to_RGB="", pixel_type="4_BIT") ###########sendrasters.append([outfilename, outfilenamewithprefixandsuffix]) print "Add Colormap done" # newras.save(out_prediciton_raster) if Conv == "True": rastertoconv = arcpy.Raster(Tfolder + "\\outcon" + str(num) + ".tif") convertedraster = eval( ConvFormula.replace("{raster}", "rastertoconv")) convertedraster.save(Tfolder + "\\outcon" + str(num) + ConvU + ".tif") rcraster = arcpy.sa.ReclassByTable( Tfolder + "\\outcon" + str(num) + ConvU + ".tif", Ifolder + "\\NearTerm.gdb\\RCValTable" + Var + ConvU, "LowValue", "HighValue", "AssignValue", "NODATA") # rcraster = arcpy.sa.SetNull(rcraster, rcraster, "Value = 0") if not os.path.exists(CFolder): os.makedirs(CFolder) CTifSave = CFolder + "\\outrrr" + str(Index) + ConvU + ".tif" rcraster.save(CTifSave) ptdt("reclass") CImgSave = CFolder + "\\outrrr" + str(Index) + ConvU + ".img" rcraster.save(CImgSave) ptdt("reclass") # 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: "outrrr0.tif" arcpy.SetRasterProperties_management(in_raster=CTifSave, data_type="", statistics="", stats_file="", nodata="1 0", key_properties="") arcpy.AddColormap_management(CTifSave, "#", Ifolder + "\\" + Var + ConvU + ".clr") arcpy.AddColormap_management(CImgSave, "#", Ifolder + "\\" + Var + ConvU + ".clr") outfilename = CFolder + "\\" + minstr + "_" + str(Index).zfill( 3) + ".tif" outfilenamewithprefixandsuffix = CName + "_" + minstr + "_" + str( Index).zfill(3) + ".tif" arcpy.CopyRaster_management(in_raster=CTifSave, out_rasterdataset=outfilename, config_keyword="", background_value="", nodata_value=None, onebit_to_eightbit="NONE", colormap_to_RGB="", pixel_type="8_BIT_UNSIGNED", scale_pixel_value="NONE", RGB_to_Colormap="NONE") ######convsendrasters.append([outfilename, outfilenamewithprefixandsuffix]) ConvRasterResult = [outfilename, outfilenamewithprefixandsuffix] CTifLyr = CName + ".lyr" KMLfilename = CFolder + "\\" + minstr + "_" + str(Index).zfill( 3) + ".kmz" KMLfilenamewithprefixandsuffix = CName + "_" + minstr + "_" + str( Index).zfill(3) + ".kmz" arcpy.MakeRasterLayer_management( outfilename, CTifLyr, "", "-179.14732999988 17.675849999878 -49.99532999988 83.123849999878", "") arcpy.LayerToKML_conversion(CTifLyr, KMLfilename, "0", "NO_COMPOSITE", "DEFAULT", "1024", "96") #####convsendKML.append([KMLfilename,KMLfilenamewithprefixandsuffix]) ConvKMLResult = [KMLfilename, KMLfilenamewithprefixandsuffix] ########outfilename = CFolder + "\\" + minstr + "_" + str(Index).zfill(3) + ".png" ########outfilenamewithprefixandsuffix = CName + "_" + minstr + "_" + str(Index).zfill(3) + ".png" ########arcpy.CopyRaster_management(in_raster= CImgSave,out_rasterdataset=outfilename,config_keyword="", background_value="", nodata_value=None, onebit_to_eightbit="NONE",colormap_to_RGB="", pixel_type="4_BIT") #######convsendrasters.append([outfilename, outfilenamewithprefixandsuffix]) else: ConvRasterResult = None ConvKMLResult = None ptdt("No Conversion Requested") return RasterResult, ConvRasterResult, KMLResult, ConvKMLResult