def site_exposure(raw_aspect, raw_slope, exposure_output): """ Description: calculates 32-bit float site exposure Inputs: 'raw_aspect' -- an input raw aspect raster 'raw_slope' -- an input raster digital elevation model 'exposure_output' -- an output exposure raster Returned Value: Returns a raster dataset on disk Preconditions: requires an input aspect and slope raster """ # Import packages import arcpy from arcpy.sa import Cos from arcpy.sa import Divide from arcpy.sa import Minus from arcpy.sa import Raster from arcpy.sa import Times # Set overwrite option arcpy.env.overwriteOutput = True # Calculate cosine of modified aspect print('\t\tCalculating cosine of modified aspect...') cosine = Cos(Divide(Times(3.142, Minus(Raster(raw_aspect), 180)), 180)) # Calculate site exposure index and save output print('\t\tCalculating site exposure index...') out_raster = Times(Raster(raw_slope), cosine) out_raster.save(exposure_output)
def main(bpi_raster=None, out_raster=None): arcpy.env.compression = "LZW" try: # Get raster properties message = ("Calculating properties of the Bathymetric " "Position Index (BPI) raster...") utils.msg(message) utils.msg(" input raster: {}\n output: {}".format( bpi_raster, out_raster)) # convert to a path desc = arcpy.Describe(bpi_raster) bpi_raster_path = desc.catalogPath bpi_mean = utils.raster_properties(bpi_raster_path, "MEAN") utils.msg("BPI raster mean: {}.".format(bpi_mean)) bpi_std_dev = utils.raster_properties(bpi_raster_path, "STD") utils.msg("BPI raster standard deviation: {}.".format(bpi_std_dev)) # Create the standardized Bathymetric Position Index (BPI) raster std_msg = "Standardizing the Bathymetric Position Index (BPI) raster..." utils.msg(std_msg) arcpy.env.rasterStatistics = "STATISTICS" outRaster = Int(Plus(Times(Divide( Minus(bpi_raster_path, bpi_mean), bpi_std_dev), 100), 0.5)) out_raster = utils.validate_path(out_raster) arcpy.CopyRaster_management(outRaster, out_raster) except Exception as e: utils.msg(e, mtype='error')
def compound_topographic(elevation_input, flow_accumulation, raw_slope, cti_output): """ Description: calculates 32-bit float compound topographic index Inputs: 'elevation_input' -- an input raster digital elevation model 'flow_accumulation' -- an input flow accumulation raster with the same spatial reference as the elevation raster 'raw_slope' -- an input raw slope raster in degrees with the same spatial reference as the elevation raster 'cti_output' -- an output compound topographic index raster Returned Value: Returns a raster dataset on disk Preconditions: requires input elevation, flow accumulation, and raw slope raster """ # Import packages import arcpy from arcpy.sa import Con from arcpy.sa import Divide from arcpy.sa import Ln from arcpy.sa import Plus from arcpy.sa import Raster from arcpy.sa import Times from arcpy.sa import Tan # Set overwrite option arcpy.env.overwriteOutput = True # Get spatial properties for the input elevation raster description = arcpy.Describe(elevation_input) cell_size = description.meanCellHeight # Convert degree slope to radian slope print('\t\tConverting degree slope to radians...') slope_radian = Divide(Times(Raster(raw_slope), 1.570796), 90) # Calculate slope tangent print('\t\tCalculating slope tangent...') slope_tangent = Con(slope_radian > 0, Tan(slope_radian), 0.001) # Correct flow accumulation print('\t\tModifying flow accumulation...') accumulation_corrected = Times(Plus(Raster(flow_accumulation), 1), cell_size) # Calculate compound topographic index as natural log of corrected flow accumulation divided by slope tangent print('\t\tCalculating compound topographic index...') out_raster = Ln(Divide(accumulation_corrected, slope_tangent)) out_raster.save(cti_output)
def calculate_LST(source_dir): dir_name = os.path.dirname(source_dir) basename = os.path.basename(source_dir) print(dir_name, basename) workspace = create_dir(basename + ".gdb") print workspace env.workspace = workspace env.overwriteOutput = True Band4 = "{}/{}_B4.tif".format(source_dir, basename) Band5 = "{}/{}_B5.tif".format(source_dir, basename) Band10 = "{}/{}_B10.tif".format(source_dir, basename) Band4_R = Raster(Band4) Band5_R = Raster(Band5) Band5_R.save("{}/{}_bands".format(workspace, basename)) Band4 = Float(Band4_R) Band5 = Float(Band5_R) Band10 = Float(Raster(Band10)) NDVI = Divide((Band5 - Band4), (Band5 + Band4)) NDVI_path = "{}/{}_ndvi".format(workspace, basename) print NDVI_path NDVI.save(NDVI_path) NDVI_max = GetRasterProperties_management( NDVI_path, property_type="MAXIMUM").getOutput(0) NDVI_min = GetRasterProperties_management( NDVI_path, property_type="MINIMUM").getOutput(0) a = Minus(NDVI, -1) b = float(NDVI_max) - float(NDVI_min) c = Divide(a, b) PV = Square(c) E = 0.004 * PV + 0.986 E.save("{}/{}_E".format(workspace, basename)) TOA = 0.0003342 * Band10 + 0.1 BT = 1321.08 / Ln((774.89 / TOA) + 1) - 273.15 d = 1 + (0.00115 * BT / 1.4388) + Ln(E) LST = Divide(BT, d) print LST, type(LST) LST_Path = "{}/{}_LST".format(workspace, basename) LST.save(LST_Path) print(LST_Path)
def mp_land_temperature(file): path_thermal = file + "\\" + file[-40:] + "_B10.tif" location = file[-30:-24] date = file[-24:-15] name = date + "_" + location print(name) arcpy.env.scratchWorkspace = os.path.join( arcpy.env.workspace, name) # r'C:\Users\yourname\PSU_LiDAR\f'+raster.replace(".img","") if not os.path.exists(arcpy.env.scratchWorkspace): os.makedirs(arcpy.env.scratchWorkspace) path_thermal = file + "\\" + file[-40:] + "_B10.tif" thermal_band = Raster(path_thermal) print thermal_band print "band condirmed" Rfloat = Float(thermal_band) top_temperature = Rfloat * RADIANCE_MULT_BAND + RADIANCE_ADD - Oi temp_tif = "temp{}.tif".format(name) top_temperature.save(temp_tif) top_temperature = Raster(temp_tif) top_temperature = Float(top_temperature) divide1 = Divide(K1_CONSTANT_BAND_10, (top_temperature + 1)) ln1 = Ln(divide1) surface_temp = Divide(K2_CONSTANT_BAND_10, ln1) - 273.15 location = file[-30:-24] date = file[-24:-15] name = date + "_" + location print name path = "surface_temp" + name + ".tif" print path surface_temp.save(path)
def Calculate(self, parameters, messages): try: messages.addMessage("Starting categorical membership calculation") cat_evidence = parameters[0].valueAsText reclassification = parameters[1].valueAsText rescale_constant = parameters[2].value fmcat = parameters[3].valueAsText if fmcat == '#' or not fmcat: fmcat = "%Workspace%/FMCat" # provide a default value if unspecified reclass_cat_evidence = ReclassByTable(cat_evidence, reclassification, "VALUE", "VALUE", "FMx100", "NODATA") float_reclass_cat_evidence = Float(reclass_cat_evidence) result_raster = Divide(float_reclass_cat_evidence, rescale_constant) rasterLayerName = os.path.split(fmcat)[1] addToDisplay(result_raster, rasterLayerName, "BOTTOM") except: tb = sys.exc_info()[2] errors = traceback.format_exc() arcpy.AddError(errors)
def Calculate(self, parameters, messages): try: messages.addMessage("Starting categorical reclass calculation") cat_evidence = parameters[0].valueAsText reclass_field = parameters[1].valueAsText reclassification = parameters[2].value fm_categorical = parameters[3].valueAsText divisor = parameters[4].value reclassified = Reclassify(cat_evidence, reclass_field, reclassification, "DATA") float_reclassified = Float(reclassified) result_raster = Divide(float_reclassified, divisor) arcpy.MakeRasterLayer_management(result_raster, fm_categorical) arcpy.SetParameterAsText(3, fm_categorical) rasterLayerName = os.path.split(fm_categorical)[1] addToDisplay(result_raster, rasterLayerName, "BOTTOM") except: tb = sys.exc_info()[2] errors = traceback.format_exc() arcpy.AddError(errors)
def Calculate(self, parameters, messages): try: messages.addMessage("Starting toc fuzzification calculation"); input_raster = parameters[0].valueAsText reclass_field = parameters[1].valueAsText remap = parameters[2].valueAsText classes = parameters[3].value fmtoc = parameters[4].valueAsText if fmtoc == '#' or not fmtoc: fmtoc = "%Workspace%/FMTOC" # provide a default value if unspecified rasterLayerName = os.path.split(fmtoc)[1] min_class_number = 1 reclassified = Reclassify(input_raster, reclass_field, remap, "DATA") float_reclass = Float(reclassified) minus_float1 = Minus(float_reclass, min_class_number) denominator = Minus(classes, min_class_number) fmtoc = Divide(minus_float1, denominator) addToDisplay(fmtoc, rasterLayerName, "BOTTOM") except: tb = sys.exc_info()[2] errors = traceback.format_exc() arcpy.AddError(errors)
def Calculate(self, parameters, messages): try: messages.addMessage("Starting categorical membership calculation") cat_evidence = parameters[0].valueAsText reclassification = parameters[1].valueAsText rescale_constant = parameters[2].value fmcat = parameters[3].valueAsText if fmcat == '#' or not fmcat: fmcat = "%Workspace%/FMCat" # provide a default value if unspecified #Next row doesn't work with Reclassification table from Categorical & Reclass / Arto Laiho, Geological survey of Finland #reclass_cat_evidence = ReclassByTable(cat_evidence, reclassification, "VALUE", "VALUE", "FMx100", "NODATA") product = arcpy.GetInstallInfo()['ProductName'] if "Desktop" in product: reclass_cat_evidence = ReclassByTable(cat_evidence, reclassification, "FROM", "TO", "OUT", "NODATA") #AL 290420 else: reclass_cat_evidence = ReclassByTable(cat_evidence, reclassification, "FROM_", "TO", "OUT", "NODATA") #AL 290420 float_reclass_cat_evidence = Float(reclass_cat_evidence) result_raster = Divide(float_reclass_cat_evidence, rescale_constant) rasterLayerName = os.path.split(fmcat)[1] addToDisplay(result_raster, rasterLayerName, "BOTTOM") except: tb = sys.exc_info()[2] errors = traceback.format_exc() arcpy.AddError(errors)
def main(in_raster=None, out_raster=None, acr_correction=True, area_raster=None): """ A calculation of rugosity, based on the difference between surface area and planar area, as described in Jenness, J. 2002. Surface Areas and Ratios from Elevation Grid (surfgrids.avx) extension for ArcView 3.x, v. 1.2. Jenness Enterprises. NOTE: the VRM method implemented in ruggeddness is generally considered superior to this method. """ # sanitize acr input if isinstance(acr_correction, unicode) and acr_correction.lower() == 'false': acr_correction = False out_workspace = os.path.dirname(out_raster) # make sure workspace exists utils.workspace_exists(out_workspace) utils.msg("Set scratch workspace to {}...".format(out_workspace)) # force temporary stats to be computed in our output workspace arcpy.env.scratchWorkspace = out_workspace arcpy.env.workspace = out_workspace pyramid_orig = arcpy.env.pyramid arcpy.env.pyramid = "NONE" # TODO: currently set to automatically overwrite, expose this as option arcpy.env.overwriteOutput = True bathy = Raster(in_raster) # get the cell size of the input raster; use same calculation as was # performed in BTM v1: (mean_x + mean_y) / 2 cell_size = (bathy.meanCellWidth + bathy.meanCellHeight) / 2.0 corner_dist = math.sqrt(2 * cell_size ** 2) flat_area = cell_size ** 2 utils.msg("Cell size: {}\nFlat area: {}".format(cell_size, flat_area)) try: # Create a set of shifted grids, with offets n from the origin X: # 8 | 7 | 6 # --|---|--- # 5 | X | 4 # --|---|--- # 3 | 2 | 1 positions = [(1, -1), (0, -1), (-1, -1), (1, 0), (-1, 0), (1, 1), (0, 1), (-1, 1)] corners = (1, 3, 6, 8) # dist * sqrt(2), as set in corner_dist orthogonals = (2, 4, 5, 7) # von Neumann neighbors, straight dist shift_rasts = [None] # offset to align numbers temp_rasts = [] for (n, pos) in enumerate(positions, start=1): utils.msg("Creating Shift Grid {} of 8...".format(n)) # scale shift grid by cell size (x_shift, y_shift) = map(lambda(n): n * cell_size, pos) # set explicit path on shift rasters, otherwise suffer # inexplicable 999999 errors. shift_out = os.path.join(out_workspace, "shift_{}.tif".format(n)) shift_out = utils.validate_path(shift_out) temp_rasts.append(shift_out) arcpy.Shift_management(bathy, shift_out, x_shift, y_shift) shift_rasts.append(arcpy.sa.Raster(shift_out)) edge_rasts = [None] # calculate triangle length grids # edges 1-8: pairs of bathy:shift[n] for (n, shift) in enumerate(shift_rasts[1:], start=1): utils.msg("Calculating Triangle Edge {} of 16...".format(n)) # adjust for corners being sqrt(2) from center if n in corners: dist = corner_dist else: dist = cell_size edge_out = os.path.join(out_workspace, "edge_{}.tif".format(n)) edge_out = utils.validate_path(edge_out) temp_rasts.append(edge_out) edge = compute_edge(bathy, shift, dist) edge.save(edge_out) edge_rasts.append(arcpy.sa.Raster(edge_out)) # edges 9-16: pairs of adjacent shift grids [see layout above] # in BTM_v1, these are labeled A-H adjacent_shift = [(1, 2), (2, 3), (1, 4), (3, 5), (6, 4), (5, 8), (6, 7), (7, 8)] for (n, pair) in enumerate(adjacent_shift, start=9): utils.msg("Calculating Triangle Edge {} of 16...".format(n)) # the two shift rasters for this iteration (i, j) = pair edge_out = os.path.join(out_workspace, "edge_{}.tif".format(n)) edge_out = utils.validate_path(edge_out) temp_rasts.append(edge_out) edge = compute_edge(shift_rasts[i], shift_rasts[j], cell_size) edge.save(edge_out) edge_rasts.append(arcpy.sa.Raster(edge_out)) # areas of each triangle areas = [] for (n, pair) in enumerate(adjacent_shift, start=1): utils.msg("Calculating Triangle Area {} of 8...".format(n)) # the two shift rasters; n has the third side (i, j) = pair area_out = os.path.join(out_workspace, "area_{}.tif".format(n)) area_out = utils.validate_path(area_out) temp_rasts.append(area_out) area = triangle_area(edge_rasts[i], edge_rasts[j], edge_rasts[n+8]) area.save(area_out) areas.append(arcpy.sa.Raster(area_out)) utils.msg("Summing Triangle Area...") arcpy.env.pyramid = pyramid_orig arcpy.env.rasterStatistics = "STATISTICS" total_area = (areas[0] + areas[1] + areas[2] + areas[3] + areas[4] + areas[5] + areas[6] + areas[7]) if area_raster: save_msg = "Saving Surface Area Raster to " + \ "{}.".format(area_raster) utils.msg(save_msg) total_area.save(area_raster) if not acr_correction: utils.msg("Calculating ratio with uncorrected planar area.") area_ratio = total_area / cell_size**2 else: utils.msg("Calculating ratio with slope-corrected planar area.") slope_raster = arcpy.sa.Slope(in_raster, "DEGREE", "1") planar_area = Divide(float(cell_size**2), Cos(Times(slope_raster, 0.01745))) area_ratio = Divide(total_area, planar_area) out_raster = utils.validate_path(out_raster) save_msg = "Saving Surface Area to Planar Area ratio to " + \ "{}.".format(out_raster) utils.msg(save_msg) area_ratio.save(out_raster) except Exception as e: utils.msg(e, mtype='error') try: # Delete all intermediate raster data sets utils.msg("Deleting intermediate data...") for path in temp_rasts: arcpy.Delete_management(path) except Exception as e: utils.msg(e, mtype='error')
def main(in_raster=None, out_raster=None, acr_correction=True, area_raster=None): """ A calculation of rugosity, based on the difference between surface area and planar area, as described in Jenness, J. 2002. Surface Areas and Ratios from Elevation Grid (surfgrids.avx) extension for ArcView 3.x, v. 1.2. Jenness Enterprises. NOTE: the VRM method implemented in ruggeddness is generally considered superior to this method. """ # sanitize acr input if isinstance(acr_correction, str) and acr_correction.lower() == 'false': acr_correction = False w = utils.Workspace() if w.exists: out_workspace = w.path else: out_workspace = os.path.dirname(out_raster) # make sure workspace exists utils.workspace_exists(out_workspace) utils.msg("Set scratch workspace to {}...".format(out_workspace)) # force temporary stats to be computed in our output workspace arcpy.env.scratchWorkspace = out_workspace arcpy.env.workspace = out_workspace pyramid_orig = arcpy.env.pyramid arcpy.env.pyramid = "NONE" # TODO: currently set to automatically overwrite, expose this as option arcpy.env.overwriteOutput = True bathy = Raster(in_raster) # get the cell size of the input raster; use same calculation as was # performed in BTM v1: (mean_x + mean_y) / 2 cell_size = (bathy.meanCellWidth + bathy.meanCellHeight) / 2.0 corner_dist = math.sqrt(2 * cell_size ** 2) flat_area = cell_size ** 2 utils.msg("Cell size: {}\nFlat area: {}".format(cell_size, flat_area)) try: # Create a set of shifted grids, with offets n from the origin X: # 8 | 7 | 6 # --|---|--- # 5 | X | 4 # --|---|--- # 3 | 2 | 1 positions = [(1, -1), (0, -1), (-1, -1), (1, 0), (-1, 0), (1, 1), (0, 1), (-1, 1)] corners = (1, 3, 6, 8) # dist * sqrt(2), as set in corner_dist orthogonals = (2, 4, 5, 7) # von Neumann neighbors, straight dist shift_rasts = [None] # offset to align numbers temp_rasts = [] for (n, pos) in enumerate(positions, start=1): utils.msg("Creating Shift Grid {} of 8...".format(n)) # scale shift grid by cell size (x_shift, y_shift) = map(lambda n: n * cell_size, pos) # set explicit path on shift rasters, otherwise suffer # inexplicable 999999 errors. shift_out = os.path.join(out_workspace, "shift_{}.tif".format(n)) shift_out = utils.validate_path(shift_out) temp_rasts.append(shift_out) arcpy.Shift_management(bathy, shift_out, x_shift, y_shift) shift_rasts.append(arcpy.sa.Raster(shift_out)) edge_rasts = [None] # calculate triangle length grids # edges 1-8: pairs of bathy:shift[n] for (n, shift) in enumerate(shift_rasts[1:], start=1): utils.msg("Calculating Triangle Edge {} of 16...".format(n)) # adjust for corners being sqrt(2) from center if n in corners: dist = corner_dist else: dist = cell_size edge_out = os.path.join(out_workspace, "edge_{}.tif".format(n)) edge_out = utils.validate_path(edge_out) temp_rasts.append(edge_out) edge = compute_edge(bathy, shift, dist) edge.save(edge_out) edge_rasts.append(arcpy.sa.Raster(edge_out)) # edges 9-16: pairs of adjacent shift grids [see layout above] # in BTM_v1, these are labeled A-H adjacent_shift = [(1, 2), (2, 3), (1, 4), (3, 5), (6, 4), (5, 8), (6, 7), (7, 8)] for (n, pair) in enumerate(adjacent_shift, start=9): utils.msg("Calculating Triangle Edge {} of 16...".format(n)) # the two shift rasters for this iteration (i, j) = pair edge_out = os.path.join(out_workspace, "edge_{}.tif".format(n)) edge_out = utils.validate_path(edge_out) temp_rasts.append(edge_out) edge = compute_edge(shift_rasts[i], shift_rasts[j], cell_size) edge.save(edge_out) edge_rasts.append(arcpy.sa.Raster(edge_out)) # areas of each triangle areas = [] for (n, pair) in enumerate(adjacent_shift, start=1): utils.msg("Calculating Triangle Area {} of 8...".format(n)) # the two shift rasters; n has the third side (i, j) = pair area_out = os.path.join(out_workspace, "area_{}.tif".format(n)) area_out = utils.validate_path(area_out) temp_rasts.append(area_out) area = triangle_area(edge_rasts[i], edge_rasts[j], edge_rasts[n+8]) area.save(area_out) areas.append(arcpy.sa.Raster(area_out)) utils.msg("Summing Triangle Area...") arcpy.env.pyramid = pyramid_orig arcpy.env.rasterStatistics = "STATISTICS" arcpy.env.compression = "LZW" total_area = (areas[0] + areas[1] + areas[2] + areas[3] + areas[4] + areas[5] + areas[6] + areas[7]) if area_raster: save_msg = "Saving Surface Area Raster to " + \ "{}.".format(area_raster) utils.msg(save_msg) arcpy.CopyRaster_management(total_area, area_raster) if not acr_correction: utils.msg("Calculating ratio with uncorrected planar area.") area_ratio = total_area / cell_size**2 else: utils.msg("Calculating ratio with slope-corrected planar area.") slope_raster = arcpy.sa.Slope(in_raster, "DEGREE", "1") planar_area = Divide(float(cell_size**2), Cos(Times(slope_raster, 0.01745))) area_ratio = Divide(total_area, planar_area) out_raster = utils.validate_path(out_raster) save_msg = "Saving Surface Area to Planar Area ratio to " + \ "{}.".format(out_raster) utils.msg(save_msg) arcpy.CopyRaster_management(area_ratio, out_raster) except Exception as e: utils.msg(e, mtype='error') try: # Delete all intermediate raster data sets utils.msg("Deleting intermediate data...") for path in temp_rasts: arcpy.Delete_management(path) except Exception as e: utils.msg(e, mtype='error')