Beispiel #1
0
def macierzeRastrowe(x):

    if x == "wilgObjRaster":

        wilgObjRaster = "wilgObjRaster"
        arcpy.FeatureToRaster_conversion(wydzieleniaShp, wilgObjField,
                                         wilgObjRaster, cellsize)

        return wilgObjRaster

    elif x == "wskInfEfRaster":

        wskInfEfRaster = "wskInfEfRaster"
        arcpy.FeatureToRaster_conversion(wydzieleniaShp, wskInfEfField,
                                         wskInfEfRaster, cellsize)

        return wskInfEfRaster

    elif x == "wspolFiltrRaster":

        wspolFiltrRaster = "wspolFiltrRaster"
        arcpy.FeatureToRaster_conversion(wydzieleniaShp, wspolFiltrField,
                                         wspolFiltrRaster, cellsize)

        return wspolFiltrRaster

    else:

        porowEfekRaster = "porowEfekRaster"
        arcpy.FeatureToRaster_conversion(wydzieleniaShp, porowEfekField,
                                         porowEfekRaster, cellsize)

        return porowEfekRaster
 def exportInventory(self, inventory_raster_out, resolution):
     pp = self.ProgressPrinter.newProcess(inspect.stack()[0][3], 1, 1).start()
     print "\tExporting inventory to raster..."
     arcpy.env.overwriteOutput = True
     classifier_names = self.inventory.getClassifiers()
     fields = {
         "age": self.inventory.getFieldNames()["age"],
         "species": self.inventory.getFieldNames()["species"]
         # "ownership": self.inventory.getFieldNames()["ownership"],
         # "FMLB": self.inventory.getFieldNames()["FMLB"],
         # "THLB": self.inventory.getFieldNames()["THLB"]
     }
     for classifier_name in classifier_names:
         field_name = self.inventory.getClassifierAttr(classifier_name)
         file_path = os.path.join(inventory_raster_out, "{}.tif".format(classifier_name))
         arcpy.FeatureToRaster_conversion("inventory_gridded", field_name, file_path, resolution)
         self.inventory.addRaster(file_path, classifier_name, self.createAttributeTable(
             os.path.join(os.path.dirname(file_path), "{}.tif.vat.dbf".format(classifier_name)), field_name))
         # arcpy.DeleteField_management(file_path, field_name)
     for attr in fields:
         field_name = fields[attr]
         file_path = os.path.join(inventory_raster_out,"{}.tif".format(attr))
         arcpy.FeatureToRaster_conversion("inventory_gridded", field_name, file_path, resolution)
         self.inventory.addRaster(file_path, attr, self.createAttributeTable(
             os.path.join(os.path.dirname(file_path), "{}.tif.vat.dbf".format(attr)), field_name))
         # arcpy.DeleteField_management(file_path, field_name)
     pp.finish()
def exposure(in_property_layer,nearby_properties_layer,ocean_layer):
    print "\t...commencing raster processing..."
    try:
        cellsize = 10
        # remap objects for the reclassifications
        combined_remap = RemapValue([["NODATA", 0],
                                     [-1, 0],
                                     [0, 0],
                                     [10, 10],
                                     [11, 10],
                                     [200, 1]])
        euc_dir_remap = RemapRange([[-1, -1, 0],
                                    [-1, 22.5, 1],
                                    [22.5, 67.5, 2],
                                    [67.5, 112.5, 3],
                                    [112.5, 157.5, 4],
                                    [157.5, 202.5, 5],
                                    [202.5, 247.5, 6],
                                    [247.5, 292.5, 7],
                                    [292.5, 337.5, 8],
                                    [337.5, 360, 1]])

        # generate land_ocean raster
        arcpy.FeatureToRaster_conversion(ocean_layer, "HY_CS_CODE", "_ocean", cellsize)
        land_ocean = Reclassify("_ocean", "VALUE", combined_remap)

        # create surface from nearby property points
        arcpy.FeatureToRaster_conversion(nearby_properties_layer, offset_fieldname,
                                         "point_heights", cellsize)
        vis_surface = Reclassify("point_heights", "VALUE", combined_remap, "DATA")

        # Apparently we have to save the input FC to disk now.
        # This adds a whole second to the processing =\
        arcpy.FeatureClassToFeatureClass_conversion(in_property_layer,
                                                    r"C:\ExposureDetection\scratch", "inprop.shp")

        # Do the viewshed & find visible ocean
        viewshed = Viewshed(vis_surface, r"C:\ExposureDetection\scratch\inprop.shp")
        visible_ocean = (land_ocean == 1) & (viewshed > 0)

        # Euclidean direction & classify into zones
        euc_dir = EucDirection(in_property_layer,analysis_distance)
        euc_zones = Reclassify(euc_dir, "VALUE", euc_dir_remap, "DATA")

        # Do the stats
        print "\t...calculating statistics..."
        ZonalStatisticsAsTable(euc_zones, "VALUE", visible_ocean, "zStats")

        # Now go off and get the deets from that table.
        return getExposureResults("zStats")

    except ExecuteError as e:
        print " Raster processing failed! ".center(79,"=")
        print "Error was:", e

        # Return null values for failed rows.
        return (None, ) * 8
def RastToShp(rastinfile, year_day, flag): 
    """Creates the output extent to be used in the rest of the script. Allows all images to be snapped to
    a constant grid, for direct matrix to matrix comparison"""
    if flag == 'N':
        arcrast = TMP + year_day + "_recasttif.tif"
        tmptif = arcpy.Raster(rastinfile)
        tmptif.save(arcrast) #This step can be necessary for Arc tools to work properly on .tif files
        arcpy.CalculateStatistics_management(arcrast)
    if flag == 'Y':
        arcrast = TMP + year_day + "_recasttif.tif"
        arcpy.CopyRaster_management(rastinfile, arcrast, '', '-9999', '-9999')
    arcpy.env.extent = arcrast
    clipshp_tmp = TMP + year_day + "_clipshp_tmp.shp"
    EXT_data = arcpy.sa.Con(arcrast, 1, 0, '"Value" > 0') #Choose only areas with data
    tmp_ext = TMP + year_day + "_clipshp_con.tif"
    EXT_data.save(tmp_ext)
    del EXT_data
    arcpy.RasterToPolygon_conversion(tmp_ext, clipshp_tmp, "NO_SIMPLIFY", "Value") #Convert to Shpfile
    clipshp = TMP + year_day + "_ext.shp"
    clipshp_tmp2 = TMP + year_day + "_ext_tmp2.shp"
    arcpy.Select_analysis(clipshp_tmp, clipshp_tmp2, '"GRIDCODE" = 1')
    arcpy.Buffer_analysis(clipshp_tmp2, clipshp, "-2 Kilometers") #Negative buffer to remove edge effects

    cliprast = TMP + year_day + '_ext_tif.tif'
    arcpy.FeatureToRaster_conversion(clipshp, "GRIDCODE", cliprast, 30) #Convert back to TIF file to use as output extent
    
    arcpy.Delete_management(clipshp)
    arcpy.Delete_management(clipshp_tmp)
    arcpy.Delete_management(clipshp_tmp2)
    arcpy.Delete_management(tmp_ext)
    
    return cliprast, arcrast
Beispiel #5
0
def rasterize(indir, outdir, season):

    output_data = outdir + "\\" + season + ".tif"
    input_data = indir + '\\' + season + ".shp"
    #Output_variance_of_prediction_raster=""
    #arcpy.gp.Kriging_sa(input_data, "Max_NDVI", output_data, "Spherical 0.000001", "1.0", "VARIABLE 12", Output_variance_of_prediction_raster)
    arcpy.FeatureToRaster_conversion(input_data, "date", output_data, "10.0")
Beispiel #6
0
def runFeatToRast(tracts, projectGDBPath):
    #
    print("\nGenerating cancer rate raster...")

    # Set environment settings
    arcpy.env.workspace = r"C:\Users\rkpalmerjr\Documents\School\WISC\Fall_2019\GEOG_777_Capstone_in_GIS_Development\Project_1\TESTING\Test_1\Scratch"
    dataFolder = r"C:\Users\rkpalmerjr\Documents\School\WISC\Fall_2019\GEOG_777_Capstone_in_GIS_Development\Project_1\GEOG777_Project_1_Nitrate_Cancer\Data"

    # Set local variables for Feature to Raster
    inFeatures = os.path.join(dataFolder, tracts)
    field = "canrate"
    canrateRaster = os.path.join(projectGDBPath, "canrate")
    # cellSize =

    # Execute Feature to Raster
    arcpy.FeatureToRaster_conversion(inFeatures, field, canrateRaster, "")

    # Delete local variables
    del dataFolder, inFeatures, field

    #
    print("\nCancer rate raster generated.")

    # Return canrateRaster to global scope
    return canrateRaster
Beispiel #7
0
def features_to_raster(feature_class,
                       outfile,
                       field,
                       template=None,
                       transform_method=None,
                       where=''):
    '''convert a feature-class to a raster-file
    
    template : str, optional
        full path to template raster, outfput file will get same projection and
        raster size
    '''
    proj_tmp = join(arcpy.env.scratchGDB, 'proj_tmp')
    where_tmp = join(arcpy.env.scratchGDB, 'where_tmp')
    arcpy.Delete_management(where_tmp)
    arcpy.Delete_management(proj_tmp)
    in_features = arcpy.FeatureClassToFeatureClass_conversion(
        feature_class, *split(where_tmp), where_clause=where)
    if template:
        desc = arcpy.Describe(template)
        sr = desc.spatialReference
        in_features = arcpy.Project_management(
            in_features, proj_tmp, sr, transform_method=transform_method)
    arcpy.FeatureToRaster_conversion(in_features,
                                     field,
                                     outfile,
                                     cell_size=template)
    arcpy.Delete_management(where_tmp)
    arcpy.Delete_management(proj_tmp)
    return outfile
Beispiel #8
0
def runFeatToRast(tracts, projectGDBPath):
    #
    arcpy.AddMessage("\nGenerating cancer rate raster...")

    # Set local variables for Feature to Raster
    inFeatures = tracts
    field = "canrate"
    canrateRasterPath = os.path.join(projectGDBPath, "canrateRaster")
    # cellSize =

    # Execute Feature to Raster
    arcpy.FeatureToRaster_conversion(inFeatures, field, canrateRasterPath, "")
    # Get Feature to Raster Messages
    arcpy.AddMessage("\n" + arcpy.GetMessages())

    # Create a raster layer to add to the MXD
    canrateRasterLyr = arcpy.MakeRasterLayer_management(
        canrateRasterPath, "canrateRaster")

    # Add the output to the MXD
    arcpy.SetParameterAsText(6, canrateRasterLyr)

    #
    arcpy.AddMessage("\nCancer rate raster generated:\n" + canrateRasterPath)

    # Delete local variables
    del inFeatures, field, canrateRasterPath

    # Return canrateRaster to global scope
    return canrateRasterLyr
Beispiel #9
0
def create_cost_layer(folder, dem_raster, shapefile, out_raster_file,
                      buffer_m):
    #setup folder for temporary results

    #get cellsize and spatial reference for new raster
    sp = dem_raster.spatialReference
    cellSize = dem_raster.meanCellWidth

    #reproject it to same projection as dem
    vectorFile = os.path.join(folder, shapefile)
    vectorFileProj = os.path.join(temp, "projected_" + shapefile)
    arcpy.Project_management(vectorFile, vectorFileProj, sp)

    #get buffer
    bufferFile = os.path.join(temp, "buffer_" + shapefile)
    arcpy.Buffer_analysis(vectorFileProj, bufferFile,
                          str(buffer_m) + " meters")
    arcpy.AddMessage("buffer done!")

    #feature to raster
    rasterFile = os.path.join(temp,
                              "raster_" + shapefile.strip(".shp") + ".tif")
    arcpy.FeatureToRaster_conversion(bufferFile, "BUFF_DIST", rasterFile,
                                     cellSize)
    arcpy.AddMessage("feature to raster done!")

    #reclassify to a raster with [0, 1]
    raster = arcpy.sa.Raster(rasterFile)
    cost_raster = arcpy.sa.Con(arcpy.sa.IsNull(raster), 0, 1)
    costFile1 = os.path.join(temp, out_raster_file)
    cost_raster.save(costFile1)
    arcpy.AddMessage("reclassify " + shapefile + " done!")
Beispiel #10
0
def shp_to_raster(workspace, excel, shp, c_field, save_path):
    arcpy.env.workspace = workspace
    if arcpy.Exists("temp.shp"):
        arcpy.Delete_management("temp.shp")


    work_book = xlrd.open_workbook(excel)
    sheet = work_book.sheet_by_index(0)
    for x in range(0, sheet.nrows, 3):
        desc = arcpy.Describe(shp)
        spatial_reference = desc.spatialReference
        arcpy.CreateFeatureclass_management(workspace, "temp.shp", "POLYGON", shp, "DISABLED", "DISABLED",
                                            spatial_reference)
        fields = ["FID", "JUDGE_CLAS", "SHAPE@"]
        values = []
        file_name = sheet.cell(x, 4).value

        where_clause = """"file_name" = '""" + file_name.replace("tif", "shp") + "'"
        cursor = arcpy.SearchCursor(shp, where_clause)
        for row in cursor:
            values.append([row.FID, row.JUDGE_CLAS, row.Shape])

        print (file_name)

        insert_cursor = arcpy.da.InsertCursor("temp.shp", fields)
        for insert_row in values:
            insert_cursor.insertRow(insert_row)
        del insert_cursor
        arcpy.FeatureToRaster_conversion("temp.shp", c_field, save_path+"/"+file_name.replace("shp", "tif"), 0.6)
        # update_cursor = arcpy.da.UpdateCursor("temp.shp", fields)
        # for _ in update_cursor:
        #     update_cursor.deleteRow()
        # del update_cursor
        arcpy.Delete_management("temp.shp")
 def featureToRaster(inFeature, outRaster, cellSize, field):
     raster_naturales = arcpy.FeatureToRaster_conversion(
         inFeature,
         field,
         outRaster,
         cellSize,
     )
Beispiel #12
0
def cc_copy_inputs():
    """Clip Climate Linkage Mapper inputs to smallest extent."""
    lm_util.gprint("\nCOPYING LAYERS AND, IF NECESSARY, REDUCING EXTENT")
    ext_poly = "ext_poly"  # Extent polygon
    climate_extent = arcpy.Raster(cc_env.climate_rast).extent

    if cc_env.resist_rast is not None:
        resist_extent = arcpy.Raster(cc_env.resist_rast).extent
        xmin = max(climate_extent.XMin, resist_extent.XMin)
        ymin = max(climate_extent.YMin, resist_extent.YMin)
        xmax = min(climate_extent.XMax, resist_extent.XMax)
        ymax = min(climate_extent.YMax, resist_extent.YMax)

        # Set to minimum extent if resistance raster was given
        arcpy.env.extent = arcpy.Extent(xmin, ymin, xmax, ymax)

        # Want climate and resistance rasters in same spatial ref
        # with same nodata cells
        proj_resist_rast = arcpy.sa.Con(arcpy.sa.IsNull(cc_env.climate_rast),
                                        arcpy.sa.Int(cc_env.climate_rast),
                                        cc_env.resist_rast)
        proj_resist_rast.save(cc_env.prj_resist_rast)
    else:
        xmin = climate_extent.XMin
        ymin = climate_extent.YMin
        xmax = climate_extent.XMax
        ymax = climate_extent.YMax

        ones_resist_rast = arcpy.sa.Con(arcpy.sa.IsNull(cc_env.climate_rast),
                                        arcpy.sa.Int(cc_env.climate_rast), 1)
        ones_resist_rast.save(cc_env.prj_resist_rast)

    arcpy.CopyRaster_management(cc_env.climate_rast, cc_env.prj_climate_rast)

    # Create core raster
    arcpy.env.extent = arcpy.Extent(xmin, ymin, xmax, ymax)
    lm_util.delete_data(cc_env.prj_core_rast)
    arcpy.FeatureToRaster_conversion(
        cc_env.core_fc, cc_env.core_fld, cc_env.prj_core_rast,
        arcpy.Describe(cc_env.climate_rast).MeanCellHeight)
    arcpy.env.extent = None

    # Create array of boundary points
    array = arcpy.Array()
    pnt = arcpy.Point(xmin, ymin)
    array.add(pnt)
    pnt = arcpy.Point(xmax, ymin)
    array.add(pnt)
    pnt = arcpy.Point(xmax, ymax)
    array.add(pnt)
    pnt = arcpy.Point(xmin, ymax)
    array.add(pnt)
    # Add in the first point of the array again to close polygon boundary
    array.add(array.getObject(0))
    # Create a polygon geometry object using the array object
    ext_feat = arcpy.Polygon(array)
    arcpy.CopyFeatures_management(ext_feat, ext_poly)
    # Clip core feature class
    arcpy.Clip_analysis(cc_env.core_fc, ext_poly, cc_env.prj_core_fc)
Beispiel #13
0
def soil_clip_analysis(soil_BNG, Soil_type, DTM_cell_size, buffer_catchment,
                       buffer_extent, river_catchment_BNG, catch_extent):
    # Check the soil type
    desc_soil = arcpy.Describe(soil_BNG)
    soil_raster_feature = desc_soil.datasetType
    arcpy.AddMessage("The soil is a " + soil_raster_feature)

    if soil_raster_feature == 'FeatureClass':

        soil_clip = arcpy.Clip_analysis(soil_BNG, river_catchment_BNG)

        if Soil_type == 'UK HOST':
            arcpy.AddMessage("UK HOST soil data selected")
            soil_clipped = arcpy.FeatureToRaster_conversion(
                soil_clip, "HOST", "Temp7", DTM_cell_size)
            soil_clip_raster = arcpy.Clip_management(soil_clipped,
                                                     catch_extent,
                                                     "MODEL_Soil_HOST",
                                                     river_catchment_BNG, "#",
                                                     "ClippingGeometry")
            #soil_clip_raster = arcpy.gp.ExtractByMask_sa(soil_clipped, river_catchment_BNG, "MODEL_Soil_HOST")

        elif Soil_type == 'FAO':
            arcpy.AddMessage("FAO soil data selected")

            soil_clipped = arcpy.FeatureToRaster_conversion(
                soil_BNG, "SNUM", "Temp8", DTM_cell_size)
            soil_clip_raster = arcpy.gp.ExtractByMask_sa(
                soil_clipped, river_catchment_polygon, "MODEL_Soil_FAO")
            #soil_clip_raster = arcpy.Clip_management(Soil_clip, extent, "MODEL_Soil_FAO", River_catchment_poly, "#", "ClippingGeometry")

    else:
        if Soil_type == 'UK HOST':
            Soil_clip = arcpy.Clip_management(soil_BNG, catch_extent,
                                              "MODEL_Soil_HOST",
                                              river_catchment_BNG, "#",
                                              "ClippingGeometry")

        elif Soil_type == 'FAO':
            Soil_clip = arcpy.Clip_management(soil_BNG, catch_extent,
                                              "MODEL_Soil_FAO",
                                              river_catchment_BNG, "#",
                                              "ClippingGeometry")

    arcpy.AddMessage("Soil clipped to catchment")
    arcpy.AddMessage("-------------------------")
Beispiel #14
0
    def __convert_hydro_to_raster(self, input_features, input_field,
                                  output_raster, cell_size):

        arcpy.AddMessage('Converting hydrography to raster surface...')
        arcpy.FeatureToRaster_conversion(in_features=input_features,
                                         field=input_field,
                                         out_raster=output_raster,
                                         cell_size=cell_size)
        return output_raster
Beispiel #15
0
def convertProposedToRasterDebit(ProposedSurfaceDisturbance, cellSize):
    arcpy.AddMessage("Preparing Proposed Surface Disturbance for processing")

    # Check feature type of provided feature class
    desc = arcpy.Describe(ProposedSurfaceDisturbance)

    # Make feature layer of proposed surface disturbance
    features = arcpy.MakeFeatureLayer_management(ProposedSurfaceDisturbance, "lyr")

    # Generate list of unique subtypes in Proposed_Surface_Disturbance
    uniqueProposedSubtypes = list(set([row[0] for row in arcpy.da.SearchCursor(
        ProposedSurfaceDisturbance, "Subtype")]))
    arcpy.AddMessage("Proposed Surface Disturbance contains "
                     + str(uniqueProposedSubtypes))

    for subtype in uniqueProposedSubtypes:
        # Select features of specified subtype
        field = "Subtype"
        where_clause = """{} = '{}'""".format(arcpy.AddFieldDelimiters
                                              (features, field), subtype)

        arcpy.SelectLayerByAttribute_management(features,
                                                "NEW_SELECTION",
                                                where_clause)

        # Count features selected to ensure >0 feature selected
        test = arcpy.GetCount_management(features)
        count = int(test.getOutput(0))

        # Convert to raster
        if count > 0:
            in_features = features
            value_field = "Weight"
            out_rasterdataset = os.path.join("Proposed_" + subtype)
            cell_assignment = "MAXIMUM_AREA"
            priority_field = "Weight"

            if desc.shapeType == "Polygon":
                arcpy.PolygonToRaster_conversion(in_features,
                                                 value_field,
                                                 out_rasterdataset,
                                                 cell_assignment,
                                                 priority_field,
                                                 cellSize)
            else:  # Consider changing to buffer of ? meters
                arcpy.FeatureToRaster_conversion(in_features,
                                                 value_field,
                                                 out_rasterdataset,
                                                 cellSize)

        # Clear selected features
        arcpy.SelectLayerByAttribute_management(features,
                                                "CLEAR_SELECTION")

    return uniqueProposedSubtypes
Beispiel #16
0
def shp2raster(input_shp, field, snapraster, outpath):
    print("Start " + input_shp)
    arcpy.env.snapRaster = snapraster
    arcpy.env.cellSize = snapraster
    arcpy.env.extent = snapraster
    arcpy.env.outputCoordinateSystem = snapraster

    # Execute FeatureToRaster
    arcpy.FeatureToRaster_conversion(input_shp, field, outpath)
    print(outpath + " had been rasterized!")
    return
Beispiel #17
0
def wall():
    arcpy.env.workspace = nhd
    arcpy.env.compression = "NONE"
    arcpy.env.snapRaster = huc6mosaic
    arcpy.env.cellSize = "10"
    albers = arcpy.SpatialReference()
    albers.factoryCode = 102039
    albers.create()

    NAD83 = arcpy.SpatialReference()
    NAD83.factoryCode = "4269"
    NAD83.create()

    arcpy.env.overwriteOutput = "TRUE"

    # Project HUC12 and Flowlines to USGS Albers then select the local HUC8s
    arcpy.Project_management("WBD_HU8", "huc8albers", albers, "", NAD83)
    arcpy.CopyFeatures_management("NHDFlowline", "Flowline")
    arcpy.Project_management("Flowline", "flowlinealbers", albers, "", NAD83)
    arcpy.AddMessage("Projected HUC8s and Flowlines to Albers.")

    # Select out Subregion's HUC8s to fc "WBD_HU8_Local"
    arcpy.MakeFeatureLayer_management("huc8albers", "huc8", "", nhd)
    arcpy.MakeFeatureLayer_management("flowlinealbers", "flowline_layer", "",
                                      nhd)
    arcpy.SelectLayerByLocation_management("huc8", "INTERSECT",
                                           "flowline_layer")
    arcpy.CopyFeatures_management("huc8", "WBD_HU8_Local")
    arcpy.AddMessage("Selected local HUC8s.")

    # Convert to lines and add a field to local HUC8s for wall height
    arcpy.PolygonToLine_management("WBD_HU8_Local", "WallLines")
    arcpy.AddField_management("WallLines", "WallHeight", "DOUBLE", "", "", "7")
    arcpy.CalculateField_management("WallLines", "WallHeight", hgt, "PYTHON")

    # Convert wall lines to raster
    arcpy.FeatureToRaster_conversion("WallLines", "WallHeight",
                                     outfolder + "\\" + "Walls.tif")
    walls = os.path.join(outfolder, "Walls.tif")
    subregion_number = os.path.basename(nhd)
    nhdsubregion = subregion_number[4:8]

    # Add rasters together
    arcpy.env.workspace = infolder
    rasters = arcpy.ListRasters("NED*")
    for raster in rasters:
        arcpy.env.extent = raster
        wallsObject = Raster(walls)
        elevObject = Raster(raster)
        walled_ned = Con(IsNull(wallsObject), elevObject,
                         (wallsObject + elevObject))
        walled_ned.save(os.path.join(outfolder, os.path.basename(raster)))

    return
def getImperv(inShpPath, inlandUsePath, indexField, weights):
    # Process Path
    if not os.path.exists('Process'):
        os.makedirs('Process')
    processPath = "./Process/"
    # Process Data Path
    outShpTempPath = processPath + "subcaTemp.shp"
    outLandTempPath = processPath + "landTemp.shp"
    outLandRasterPath = processPath + "landUseRaster"
    outTablePath = processPath + "impervTable.dbf"
    # Output Path
    if not os.path.exists('Result'):
        os.makedirs('Result')
    # Output Data Path
    outShpPath = "./Result/subcatchments.shp"
    # Execute CopyFeatures
    arcpy.CopyFeatures_management(inShpPath, outShpTempPath)
    arcpy.CopyFeatures_management(inlandUsePath, outLandTempPath)
    # Check out the ArcGIS Spatial Analyst extension license
    arcpy.CheckExtension("Spatial")
    # Execute AddField
    arcpy.AddField_management(outLandTempPath, "Weight", "DOUBLE", "", "", "",
                              "weight", "NULLABLE", "NON_REQUIRED", "")
    # Calculate Weight
    codeBlock = """
def getWeight(type, weights):
    return weights[type]"""
    expression = "getWeight( !category! ," + json.dumps(weights) + ")"
    arcpy.CalculateField_management(outLandTempPath, "Weight", expression,
                                    "PYTHON", codeBlock)
    # Execute FeatureToRaster
    arcpy.FeatureToRaster_conversion(outLandTempPath, "Weight",
                                     outLandRasterPath, 5)
    # Execute ZonalStatisticsAsTable
    outImperv = ZonalStatisticsAsTable(outShpTempPath, indexField,
                                       outLandRasterPath, outTablePath,
                                       "NODATA", "MEAN")
    # Execute AddField
    arcpy.AddField_management(outShpTempPath, "Imperv", "DOUBLE", "", "", "",
                              "imperv", "NULLABLE", "NON_REQUIRED", "")
    # Create a feature layer
    layerName = "subcaShp"
    arcpy.MakeFeatureLayer_management(outShpTempPath, layerName)
    # Join the feature layer to a table
    arcpy.AddJoin_management(layerName, indexField, outImperv, indexField)
    # Calculate Slope
    arcpy.CalculateField_management(layerName, "Imperv", "!impervTable.MEAN!",
                                    "PYTHON")
    # Remove the join
    arcpy.RemoveJoin_management(layerName, "impervTable")
    # Copy the layer to a new permanent feature class
    arcpy.CopyFeatures_management(layerName, outShpPath)
    return outShpPath
Beispiel #19
0
def shp2raster(year):
    # Set environment settings
    env.workspace = "F:/NEW(1)/Feature"
    indicators = ["IJI", "PAFRAC", "DIVISION", "CONTAG", "SHEI", "SHDI"]
    # Set local variables
    inFeature = year + ".shp"
    for indicator in indicators:
        outRaster = "F:/NEW(1)/GRID/" + indicator + "/" + year + ".tif"
        cellSize = 3000
        field = indicator

        # Execute FeatureToRaster
        arcpy.FeatureToRaster_conversion(inFeature, field, outRaster, cellSize)
Beispiel #20
0
def is_south_building_taller(shape_file, x_coords, y_coords):
    """This method should return true if building south of the building at
    x y coords is taller
    This method converts the shape file to raster and uses a moving window to look
    at the polygon south
    TODO: Method is unfinished
    """
    raster_ext = 'raster.tif'
    if arcpy.Exists(raster_ext):
        arcpy.Delete_management(raster_ext)
        print("WARNING: deleting file " + raster_ext)
    raster_file = arcpy.FeatureToRaster_conversion(shape_file, "elevation",
                                                   raster_ext)
Beispiel #21
0
def convert_afe_to_final_tiles(phyreg_ids):
    '''
    This function converts AFE outputs to final TIFF files.

    phyreg_ids: list of physiographic region IDs to process
    '''
    phyregs_layer = canopy_config.phyregs_layer
    naipqq_layer = canopy_config.naipqq_layer
    naipqq_phyregs_field = canopy_config.naipqq_phyregs_field
    snaprast_path = canopy_config.snaprast_path
    results_path = canopy_config.results_path

    arcpy.env.addOutputsToMap = False
    arcpy.env.snapRaster = snaprast_path

    arcpy.SelectLayerByAttribute_management(phyregs_layer,
            where_clause='PHYSIO_ID in (%s)' % ','.join(map(str, phyreg_ids)))
    with arcpy.da.SearchCursor(phyregs_layer, ['NAME', 'PHYSIO_ID']) as cur:
        for row in cur:
            name = row[0]
            print(name)
            # CreateRandomPoints cannot create a shapefile with - in its
            # filename
            name = name.replace(' ', '_').replace('-', '_')
            phyreg_id = row[1]
            outdir_path = '%s/%s/Outputs' % (results_path, name)
            if len(os.listdir(outdir_path)) == 0:
                continue
            arcpy.SelectLayerByAttribute_management(naipqq_layer,
                    where_clause="%s like '%%,%d,%%'" % (naipqq_phyregs_field,
                        phyreg_id))
            with arcpy.da.SearchCursor(naipqq_layer, ['FileName']) as cur2:
                for row2 in sorted(cur2):
                    filename = row2[0][:-13]
                    rshpfile_path = '%s/r%s.shp' % (outdir_path, filename)
                    rtiffile_path = '%s/r%s.tif' % (outdir_path, filename)
                    frtiffile_path = '%s/fr%s.tif' % (outdir_path, filename)
                    if os.path.exists(frtiffile_path):
                        continue
                    if os.path.exists(rshpfile_path):
                        arcpy.FeatureToRaster_conversion(rshpfile_path,
                                'CLASS_ID', frtiffile_path, 1)
                    elif os.path.exists(rtiffile_path):
                        arcpy.Reclassify_3d(rtiffile_path, 'Value', '1 0;2 1',
                                frtiffile_path)

    # clear selection
    arcpy.SelectLayerByAttribute_management(phyregs_layer, 'CLEAR_SELECTION')
    arcpy.SelectLayerByAttribute_management(naipqq_layer, 'CLEAR_SELECTION')

    print('Completed')
Beispiel #22
0
    def feature2raster(input_features, shp_workspace, images_workspace,
                       field_name, resolution, proj):
        arcpy.env.overwriteOutput = True
        arcpy.env.workspace = shp_workspace

        # define projection
        sr = arcpy.SpatialReference(proj)
        arcpy.DefineProjection_management(input_features, sr)

        raster_name = os.path.join(images_workspace,
                                   input_features[:-4] + ".tif")
        out = arcpy.FeatureToRaster_conversion(input_features, field_name,
                                               raster_name, resolution)
        print(out)
Beispiel #23
0
def wall(nhd_gdb,
         rasters_list,
         outfolder,
         height='500',
         projection=arcpy.SpatialReference(102039)):
    """For one or more HU8s within the same subregion (nhd_gdb variable),
    adds walls at the boundaries to force flow direction that do not cross
    the boundary."""
    env.workspace = 'in_memory'
    env.outputCoordinateSystem = projection
    env.compression = "NONE"
    env.snapRaster = rasters_list[0]  # they all have the same snap
    env.cellSize = '10'
    env.pyramids = "PYRAMIDS -1 SKIP_FIRST"
    arcpy.CheckOutExtension("Spatial")

    # HU8 layer
    huc8_fc = os.path.join(nhd_gdb, "WBD_HU8")
    arcpy.MakeFeatureLayer_management(huc8_fc, "huc8_layer")

    # create output folder with HUC4 in the name
    huc4_code = re.search('\d{4}', os.path.basename(nhd_gdb)).group()
    walled_dir = os.path.join(outfolder, 'walled' + huc4_code)
    if not os.path.exists(walled_dir):
        os.mkdir(walled_dir)

    # make the walls raster
    arcpy.PolygonToLine_management(huc8_fc, 'wall_lines')
    arcpy.AddField_management('wall_lines', "height", "DOUBLE")
    arcpy.CalculateField_management('wall_lines', "height", '500', "PYTHON")
    arcpy.FeatureToRaster_conversion('wall_lines', "height", 'wall_raster')
    wallsObject = Raster('wall_raster')

    for raster in rasters_list:
        out_name = os.path.join(
            walled_dir,
            os.path.basename(raster).replace('fel.tif', '_wfel.tif'))
        cu.multi_msg('Creating output {0}'.format(out_name))
        env.extent = raster
        elevObject = Raster(raster)
        walled_ned = Con(IsNull(wallsObject), elevObject,
                         (wallsObject + elevObject))

        walled_ned.save(out_name)

    for item in ['huc8_layer', 'wall_lines', 'wall_raster']:
        arcpy.Delete_management(item)
    arcpy.ResetEnvironments()
    arcpy.CheckInExtension("Spatial")
Beispiel #24
0
def main(datadir, pointfile, refraster, outfile):
    """ coverts feature to raster"""

    # Set environment settings
    env.workspace = datadir

    # Local variables:
    dp_file = os.path.join(env.workspace, pointfile)
    wt_tif = os.path.join(env.workspace, outfile)
    arcpy.env.extent = os.path.join(env.workspace, refraster)
    arcpy.env.outputCoordinateSystem = os.path.join(env.workspace, refraster)
    cellsize = 30

    # Process: Feature to Raster
    arcpy.FeatureToRaster_conversion(dp_file, "Gval", wt_tif, cellsize)
def streamBurning(DEM_orig, scratch_gdb, seg_network_a, home, home_name):
    print("stream burning process")
    arcpy.CalculateStatistics_management(DEM_orig)

    dem_orig_b = Con(IsNull(DEM_orig), 0, DEM_orig)
    dem_orig_b.save(scratch_gdb + "/DEM_square")

    # set up river network raster
    network_raster = scratch_gdb + "/network_raster"

    arcpy.env.extent = dem_orig_b
    arcpy.env.cellsize = dem_orig_b
    arcpy.env.snapRaster = dem_orig_b
    arcpy.env.outputCoordinateSystem = dem_orig_b

    print('convert network to raster')
    net_fields = [f.name for f in arcpy.ListFields(seg_network_a)]
    if "burn_val" in net_fields:
        arcpy.DeleteField_management(seg_network_a, "burn_val")
    del net_fields
    arcpy.AddField_management(seg_network_a, "burn_val", "SHORT")
    arcpy.CalculateField_management(seg_network_a, "burn_val", "10")  #

    arcpy.FeatureToRaster_conversion(
        seg_network_a, "burn_val", network_raster,
        dem_orig_b)  # THINK IT IS WORTH CHANGING THE ATTRIBUTE VALUE

    network_raster_a = Con(
        IsNull(network_raster), 0,
        30)  # changed to 30 to see if it improves stream ordering
    network_raster_a.save(scratch_gdb + "/net_ras_fin")
    arcpy.ResetEnvironments()

    # This is just a map algebra thing to replace the stuff above that uses numpy (the numpy stuff works but is
    # limited in terms of how much it can process.
    print("stream burning DEM")
    rivers_ting = Raster(scratch_gdb + "/net_ras_fin")
    dem_ting = Raster(scratch_gdb + "/DEM_square")

    stream_burn_dem_a = dem_ting - rivers_ting
    stream_burn_dem_a.save(scratch_gdb + "/raster_burn")

    sb_DEM = os.path.join(home, "{0}strBurndDEm.tif".format(home_name))

    arcpy.CopyRaster_management(scratch_gdb + "/raster_burn", sb_DEM)

    print("stream burning complete")
    return stream_burn_dem_a, network_raster, sb_DEM
Beispiel #26
0
def Burn(Buildings, DEM, DEMfinal, locationtemp1, DEM_extent, gv):
    # Create a raster with all the buildings
    Outraster = locationtemp1 + '\\' + 'AllRaster'
    arcpy.env.extent = DEM_extent  # These coordinates are extracted from the environment settings/once the DEM raster is selected directly in ArcGIS,
    arcpy.FeatureToRaster_conversion(
        Buildings, 'height_ag', Outraster,
        '0.5')  # creating raster of the footprints of the buildings

    # Clear non values and add all the Buildings to the DEM
    OutNullRas = arcpy.sa.IsNull(Outraster)  # identify noData Locations
    Output = arcpy.sa.Con(OutNullRas == 1, 0, Outraster)
    RadiationDEM = arcpy.sa.Raster(DEM) + Output
    RadiationDEM.save(DEMfinal)
    gv.log('complete burning buildings into raster')

    return arcpy.GetMessages()
Beispiel #27
0
def getCountryClipRaster(country_name, scratch_workspace_basepath):
    AddMsgAndPrint('Getting Clip Features')
    try:

        #in_features = "FILE PATH"\TRMM Tools\\SampleGauls\\SimpleGauls.shp"
        #in_features = "FILE PATH"\\SERVIR\\ReferenceNode\\GPServices\\TRMM Tools\\SampleGauls\\SimpleGauls.shp"
                      
        #out_feature_class = os.path.join(scratch_workspace_basepath, "temp_fc")
        out_feature_class = scratch_fgdb_fullpath+"\\temp_fc"
        arcpy.Select_analysis(inClipFeatures, out_feature_class, "\"ADM0_NAME\" = \'"+country_name+"\'")
        
        clip_raster = out_feature_class+"_ras"
        arcpy.FeatureToRaster_conversion(out_feature_class+".shp", 'value', clip_raster, 0.25)
        
        return clip_raster
    except Exception as e:
            AddMsgAndPrint(e.message)
            arcpy.AddError(e.message)
Beispiel #28
0
def wall(nhd_gdb,
         rasters_list,
         outfolder,
         height='500',
         projection=arcpy.SpatialReference(102039)):
    """For one or more HU8s within the same subregion (nhd_gdb variable),
    adds walls at the boundaries to force flow direction that do not cross
    the boundary."""
    env.workspace = 'in_memory'
    env.outputCoordinateSystem = projection
    env.compression = "NONE"
    env.snapRaster = rasters_list[0]  # they all have the same snap
    env.cellSize = '10'
    env.pyramids = "PYRAMIDS -1 SKIP_FIRST"
    arcpy.CheckOutExtension("Spatial")

    # HU8 layer
    huc12_fc = os.path.join(nhd_gdb, "WBDHU12")
    arcpy.MakeFeatureLayer_management(huc12_fc, "huc12_layer")

    # make the walls raster
    arcpy.PolygonToLine_management(huc12_fc, 'wall_lines')
    arcpy.AddField_management('wall_lines', "height", "DOUBLE")
    arcpy.CalculateField_management('wall_lines', "height", '500000', "PYTHON")
    arcpy.FeatureToRaster_conversion('wall_lines', "height", 'wall_raster')
    wallsObject = Raster('wall_raster')

    for raster in rasters_list:
        out_name = os.path.join(raster.replace('.tif', '_walled.tif'))
        arcpy.AddMessage('Creating output {0}'.format(out_name))
        env.extent = raster
        elevObject = Raster(raster)
        walled_ned = Con(
            IsNull(wallsObject), elevObject,
            Con(LessThan(elevObject, -58000), elevObject, wallsObject))

        walled_ned.save(out_name)

    for item in ['huc8_layer', 'wall_lines', 'wall_raster']:
        arcpy.Delete_management(item)
    arcpy.ResetEnvironments()
    arcpy.CheckInExtension("Spatial")

    return out_name
Beispiel #29
0
def burn_streams(subregion_ned,
                 nhd_gdb,
                 burnt_out,
                 projection=arcpy.SpatialReference(102039)):
    env.snapRaster = subregion_ned
    env.outputCoordinateSystem = projection
    env.compression = "LZ77"  # compress temp tifs for speed
    env.extent = subregion_ned
    env.workspace = 'in_memory'

    flowline = os.path.join(nhd_gdb, 'NHDFlowline')
    # Copy flowlines to shapefile that will inherit environ output coord system
    # just easier to have a copy in the correct projection later
    arcpy.CopyFeatures_management(flowline, 'flowline_proj')
    ##    arcpy.FeatureClassToFeatureClass_conversion("NHDFlowline", "in_memory", flow_line)
    cu.multi_msg("Prepared NHDFlowline for rasterizing.")

    # Feature to Raster- rasterize the NHDFlowline
    # will inherit grid from env.snapRaster
    arcpy.FeatureToRaster_conversion('flowline_proj', "OBJECTID",
                                     'flowline_raster', "10")
    cu.multi_msg("Converted flowlines to raster.")

    # Raster Calculator- burns in streams, beveling in from 500m
    cu.multi_msg(
        "Burning streams into raster, 10m deep and beveling in from 500m out. This may take a while...."
    )
    arcpy.CheckOutExtension("Spatial")
    distance = EucDistance('flowline_proj', cell_size="10")
    streams = Reclassify(
        Raster('flowline_raster') > 0, "Value", "1 1; NoData 0")
    burnt = Raster(subregion_ned) - (10 * streams) - (0.02 * (500 - distance) *
                                                      (distance < 500))

    cu.multi_msg("Saving output raster...")
    burnt.save(burnt_out)

    # Delete intermediate rasters and shapefiles
    for item in ['flowline_proj', 'flowline_raster']:
        arcpy.Delete_management(item)
    arcpy.CheckInExtension("Spatial")
    cu.multi_msg("Burn process completed")
    arcpy.ResetEnvironments()
Beispiel #30
0
def catchment_preparation(river_catchment, cell_size):
 
    river_catchment_raster = arcpy.FeatureToRaster_conversion(river_catchment, "OBJECTID", "MODEL_river_catchment_ras", cell_size)
    river_catchment_polygon = arcpy.RasterToPolygon_conversion(river_catchment_raster, "MODEL_river_catchment_poly", "NO_SIMPLIFY", "#")

    lst = arcpy.ListFields(river_catchment_polygon)

    SBS_exists = 'false'
    GRID_exists = 'false'

    for f in lst:        
        if f.name == "SBS_CODE":
            SBS_exists = 'true'
            arcpy.AddMessage("SBS_CODE exists")
        elif f.name == "grid_code":
            GRID_exists = 'true'
            arcpy.AddMessage("grid_code exists")

    if SBS_exists == 'false':
        arcpy.AddField_management(river_catchment_polygon, "SBS_CODE", "SHORT")
        arcpy.AddMessage("added SBS_CODE")
    if GRID_exists == 'false':    
        arcpy.AddField_management(river_catchment_polygon, "grid_code", "SHORT")
        arcpy.AddMessage("added grid_code")

            
    # Create update cursor for feature class 
    rows = arcpy.UpdateCursor(river_catchment_polygon) 

    for row in rows:
        row.SBS_CODE = 0
        row.grid_code = 0

        rows.updateRow(row)
        
    # Delete cursor and row objects to remove locks on the data 
    del row 
    del rows 
    arcpy.AddMessage("Corrected catchment")
    arcpy.AddMessage("-------------------------")

    return river_catchment_polygon