Beispiel #1
0
def createYun():
    StopOrStartService(serviceFolder, "DynamicGSMRasterHW", "stop")
    StopOrStartService(serviceFolder, "DynamicGSMRasterLL", "stop")
    if (arcpy.Exists(CellThiessYunHW)):
        arcpy.Delete_management(CellThiessYunHW)
    if (arcpy.Exists(CellThiessYunLL)):
        arcpy.Delete_management(CellThiessYunLL)
    logging.info("PolygonToRaster_conversion HW")
    print "面转栅格"
    # Process: 面转栅格
    arcpy.PolygonToRaster_conversion(CellThiessFinal, "VOICE_TOTAL_TRAFFIC",
                                     CellThiessYunHW, "CELL_CENTER", "NONE",
                                     ".01")
    logging.info("CalculateStatistics_management HW")
    print "计算统计数据"
    # Process: 计算统计数据
    arcpy.CalculateStatistics_management(CellThiessYunHW, "1", "1", "",
                                         "OVERWRITE", "")
    logging.info("PolygonToRaster_conversion LL")
    arcpy.PolygonToRaster_conversion(CellThiessFinal, "UL_DL_FLOW",
                                     CellThiessYunLL, "CELL_CENTER", "NONE",
                                     ".01")
    logging.info("CalculateStatistics_management LL")
    print "计算统计数据"
    # Process: 计算统计数据
    arcpy.CalculateStatistics_management(CellThiessYunLL, "1", "1", "",
                                         "OVERWRITE", "")
    StopOrStartService(serviceFolder, "DynamicGSMRasterHW", "start")
    StopOrStartService(serviceFolder, "DynamicGSMRasterLL", "start")
Beispiel #2
0
    def set_project_area(self, geofile_name):
        # geofile_name = STR of either project area shapefile or TIF raster (DO NOT PROVIDE ANY FILE ENDING [SHP / TIF])
        self.logger.info("   * looking up project area polygon from " +
                         str(geofile_name) + " ...")

        self.set_env()
        arcpy.env.workspace = self.dir2geo + "Rasters\\"
        raster_list = arcpy.ListRasters()

        project_raster_exists = False
        for ras in raster_list:
            if geofile_name.lower() in str(ras).lower():
                try:
                    self.ras_project = arcpy.Raster(self.dir2geo +
                                                    "Rasters\\" +
                                                    str(ras).lower())
                    project_raster_exists = True
                    self.logger.info("   * found project area Raster: " +
                                     str(ras).lower())
                except:
                    self.logger.info(
                        "ERROR: Could not load existing Raster of the project area."
                    )

        if not project_raster_exists:
            self.logger.info("   * Polygon to Raster conversion required.")
            shp_project = self.dir2geo + "Shapefiles\\" + geofile_name.lower(
            ) + ".shp"
            try:
                self.logger.info(
                    "   * converting project area Polygon (%s) to Raster ... "
                    % shp_project)
                try:
                    arcpy.PolygonToRaster_conversion(
                        shp_project, "gridcode", self.dir2geo + "Rasters\\" +
                        geofile_name.lower() + ".tif")
                except:
                    arcpy.PolygonToRaster_conversion(
                        shp_project, "AreaCode", self.dir2geo + "Rasters\\" +
                        geofile_name.lower() + ".tif")
                self.logger.info("     ok")
            except:
                self.logger.info(
                    "ERROR: Could not create Raster of the project area.")
            try:
                self.ras_project = arcpy.Raster(self.dir2geo + "Rasters\\" +
                                                str(geofile_name) + ".tif")
            except:
                try:
                    self.ras_project = arcpy.Raster(self.dir2geo +
                                                    "Rasters\\" +
                                                    str(geofile_name).lower() +
                                                    ".tif")
                except:
                    self.logger.info(
                        "ERROR: Could not load newly created Raster of the project area."
                    )

        arcpy.env.workspace = self.cache
Beispiel #3
0
def feature2Raster(inFeatureClass, referenceRaster, landslide=False):
    # inRasters must be as dictionary {path:'',valueField:'',name:''}
    refRaster = arcpy.Raster(referenceRaster)
    arcpy.env.extent = refRaster.extent
    arcpy.env.snapRaster = refRaster
    outRaster = r"d:\Personal\Temp\{}".format(inFeatureClass['name'])
    if (landslide):
        colFields = arcpy.ListFields(inFeatureClass['path'])
        if (inFeatureClass['classField'].upper() not in [
                x.name.upper()
                for x in arcpy.ListFields(inFeatureClass['path'])
        ]):
            arcpy.AddField_management(inFeatureClass['path'],
                                      field_name="{}".format(
                                          inFeatureClass['classField']),
                                      field_type="SHORT")

        with arcpy.da.UpdateCursor(
                inFeatureClass['path'],
                field_names=["{}".format(inFeatureClass['classField'])
                             ]) as cursor:
            for row in cursor:
                row[0] = 1
                cursor.updateRow(row)
        arcpy.PolygonToRaster_conversion(inFeatureClass['path'],
                                         value_field="{}".format(
                                             inFeatureClass['classField']),
                                         out_rasterdataset=outRaster,
                                         cellsize=refRaster.meanCellWidth)
        out = {}
        out['noData'] = arcpy.Raster(outRaster).noDataValue
        out['path'] = outRaster
        out['classField'] = inFeatureClass['classField']
        out['name'] = inFeatureClass['name']
        return out
    else:
        try:
            arcpy.PolygonToRaster_conversion(inFeatureClass['path'],
                                             value_field="{}".format(
                                                 inFeatureClass['classField']),
                                             out_rasterdataset=outRaster,
                                             cellsize=refRaster.meanCellWidth)
        except:
            print('Eroare')
            print(arcpy.GetMessages(2))
        out = {}
        out['noData'] = arcpy.Raster(outRaster).noDataValue
        out['path'] = outRaster
        out['classField'] = inFeatureClass['classField']
        out['name'] = inFeatureClass['name']
        # print('NoData: ', arcpy.Raster(outRaster).noDataValue)
        return out
def findFlowAccumulation(flowAccumulation, tempData, cellSize):
    """
    Finds the flow accumulation at the point defined in the findPrecipitation function
    :param flowAccumulation: A raster containing flow accumulation data
    :param tempData: Where we can dump all our intermediary data points
    :param cellSize: The area of each cell
    :return: Flow accumulation at a point
    """
    try:
        arcpy.Buffer_analysis(tempData + "\point.shp",
                              tempData + "\pointBuffer.shp", "20 Meters")
        arcpy.PolygonToRaster_conversion(tempData + "\pointBuffer.shp",
                                         "FID",
                                         tempData + "\pointBufferRaster.tif",
                                         cellsize=sqrt(cellSize))
        maxFlow = arcpy.sa.ZonalStatistics(tempData + "\pointBufferRaster.tif",
                                           "Value", flowAccumulation,
                                           "MAXIMUM")
        arcpy.sa.ExtractValuesToPoints(tempData + "\point.shp", maxFlow,
                                       tempData + "\\flowPoint")
    except:
        return -9999

    searchCursor = arcpy.da.SearchCursor(tempData + "\\flowPoint.shp",
                                         "RASTERVALU")
    row = searchCursor.next()
    flowAccAtPoint = row[0]
    del row
    del searchCursor
    flowAccAtPoint *= cellSize  # gives us the total area of flow accumulation, rather than just the number of cells
    flowAccAtPoint /= 1000000  # converts from square meters to square kilometers
    if flowAccAtPoint < 0:
        flowAccAtPoint = 0

    return flowAccAtPoint
Beispiel #5
0
def convertMapUnitsToRaster(projectGDB, mapUnits, season, cellSize):
    # Select features of specified subtype
    util.ClearSelectedFeatures(mapUnits)
    feature = arcpy.MakeFeatureLayer_management(mapUnits, "lyr")
    fields = ["Winter", "Breed", "Summer"]
    for field in fields:
        where_clause = "NOT {0} IS NULL".format(
                    arcpy.AddFieldDelimiters(feature, field)
                    )
        arcpy.SelectLayerByAttribute_management(feature,
                                                "ADD_TO_SELECTION",
                                                where_clause)
        
    # Count features selected to ensure >0 feature selected
    test = arcpy.GetCount_management(mapUnits)
    count = int(test.getOutput(0))    

    # Convert to raster
    if count > 0:
        in_features = mapUnits
        value_field = season
        out_rasterdataset = os.path.join(
            projectGDB, season + "_Site_Quality")
        cell_assignment = "MAXIMUM_AREA"
        priority_field = season
        
        arcpy.PolygonToRaster_conversion(in_features,
                                         value_field,
                                         out_rasterdataset,
                                         cell_assignment,
                                         priority_field,
                                         cellSize)
        return out_rasterdataset
Beispiel #6
0
def estimate2012pop(popRast2010Path, outGDB, outDir, iso3):

    arcpy.CheckOutExtension("Spatial")
    old_workspace = arcpy.env.workspace
    old_scratchWorkspace = arcpy.env.scratchWorkspace        
    tmpdir = tempfile.mkdtemp()
    arcpy.env.workspace = tmpdir
    arcpy.env.scratchWorkspace = tmpdir

    try:
        # Get raster cell size
        popRast2010 = arcpy.Raster(popRast2010Path)
        cellSize = (popRast2010.meanCellHeight + popRast2010.meanCellWidth) / float(2)

        # Create raster of growth rates from feature class
        arcpy.PolygonToRaster_conversion(outGDB + "/growthRates%s" % iso3,
                                         "Growth20102015",
                                         "growth20102015.tif",
                                         cell_assignment="MAXIMUM_AREA",
                                         cellsize=cellSize)

        pop2012 = popRast2010 * arcpy.sa.Exp(arcpy.Raster("growth20102015.tif") / 100 * 2)
        arcpy.CopyRaster_management(pop2012, os.path.join(outDir, "%s2012unadjustedPop.tif" % iso3), pixel_type="32_BIT_FLOAT")

    finally:
        arcpy.Delete_management("in_memory")
        arcpy.Delete_management(tmpdir)
        arcpy.env.workspace = old_workspace
        arcpy.env.scratchWorkspace = old_scratchWorkspace
        arcpy.CheckInExtension("Spatial")
Beispiel #7
0
def coastaldem(Input_Workspace, grdNamePth, InFeatureClass, OutRaster, seaLevel, version = None):
	'''Sets elevations for water and other areas in digital elevation model.

	Parameters
	----------
	Input_Workspace : str
		Input workspace, output raster will be written to this location.
	grdNamePth : str
		Path to the input DEM grid.
	InFeatureClass : str
		Path to the LandSea feature class.
	OutRaster : str
		Output DEM grid name.
	seaLevel : float
		Elevation at which to make the sea.
	version : str (optional)
		StreamStats Data Preparation Tools version number
	
	Returns
	-------
	OutRaster : raster
		Output raster with coastal areas corrected.

	Notes
	-----
	Outputs are written to the workspace.
	'''
	if version:
		arcpy.AddMessage('StreamStats Data Preparation Tools version: %s'%(version))

	try:
		# set working folder
		arcpy.env.workspace = Input_Workspace
		arcpy.env.scratchWorkspace = arcpy.env.workspace

		arcpy.env.extent = grdNamePth
		arcpy.env.snapRaster = grdNamePth
		arcpy.env.outputCoordinateSystem = grdNamePth
		arcpy.env.cellSize = grdNamePth

		# this is assuming land is 1 and sea is -1
		arcpy.PolygonToRaster_conversion(InFeatureClass, "Land", "mskg")
		
		mskg = Raster("mskg") # load the mask grid
		grdName = Raster(grdNamePth) # load the 
		
		seag = Con(mskg == -1, float(seaLevel))

		landg = Con((mskg == 1) & (grdName <= 0), 1, grdName)

		nochgg = Con(mskg == 0, grdName)

		arcpy.MosaicToNewRaster_management([seag,landg,nochgg],arcpy.env.workspace,OutRaster,None, "32_BIT_SIGNED", None, 1, "FIRST") # mosaic and produce new raster
		
	except:
		e = sys.exc_info()[1]
		print(e.args[0])
		arcpy.AddError(e.args[0])

	return None
Beispiel #8
0
def disthistory(inlayer, distfield, outlayer, fire=False):
    
    # set environment settings
    arcpy.env.snapRaster = "Y:/Tahoe/GISdata/Lattice_Clip30m.gdb/Lattice_Clip30m_ProjBound"
    arcpy.env.extent = "Y:/Tahoe/GISdata/Lattice_Clip30m.gdb/Lattice_Clip30m_ProjBound"
    arcpy.env.workspace = "Y:/Tahoe/GISdata/WorkGDBCreated051214.gdb/"

    arcpy.AddField_management(inlayer, "DisturbanceYear", "LONG", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    arcpy.AddField_management(inlayer, "Age_2010", "LONG", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")

    print "added fields"


    arcpy.CalculateField_management(inlayer, "DisturbanceYear", "".join(["int(!",distfield,"!)"]), "PYTHON", "")
    print "calc field 1 done"
    arcpy.CalculateField_management(inlayer, "Age_2010", "2010 - !DisturbanceYear!", "PYTHON", "")
    print "calc field 2 done"

    if fire:
        rule = "\"BEST_ASSESS\" = 'YES' AND \"BURNSEV\" = 4"
        arcpy.SelectLayerByAttribute_management(inlayer, "NEW_SELECTION", rule)
    
        print "selected layer"

    # Set local variables
    assignmentType = "MAXIMUM_AREA"
    cellSize = "30"
    arcpy.PolygonToRaster_conversion(inlayer, "Age_2010", outlayer, assignmentType, "NONE", cellSize)    

    print "conversion successful"
Beispiel #9
0
def prep_idp_dataset():
    # Local variables
    ipd =  orig_datasets_path + "\\CII\\DVRPC_2016_Indicators_of_Potential_Disadvantage\\DVRPC_2016_Indicators_of_Potential_Disadvantage.shp"
    ipd_clipped = "ipd_clipped"
    ipd_ras = "ipd_ras"
    ipd_score_ras = "ipd_score_ras"

    # Load the feature class into the MXD
    arcpy.MakeFeatureLayer_management(ipd, "idp")
    # NO need to reproject (already in NAD 1983 UTM Zone 18N)
    # Clip to the boundaries of 4_counties_dissolved
    arcpy.SpatialJoin_analysis(ipd, "extent_4_counties", ipd_clipped,
                            "JOIN_ONE_TO_ONE", "KEEP_COMMON", match_option="HAVE_THEIR_CENTER_IN")
    # Convert into a raster
    arcpy.PolygonToRaster_conversion (ipd_clipped, "IPD_Score", ipd_ras)

    # reclassify the raster to 1-to-20 score using the Jenks natural breaks classification
    arcpy.CheckOutExtension("Spatial")
    outslice = arcpy.sa.Slice(ipd_ras, 20, "NATURAL_BREAKS")
    outslice.save(ipd_score_ras)
    # Display the resulting raster (note that the tool demands a slightly different name for the layer)
    arcpy.MakeRasterLayer_management(ipd_score_ras, "ipd_score_ras1")

    # Cleanup
    remove_intermediary_layers(["idp","ipd_clipped", "ipd_ras"])
    def _clip_data(self, dem, intersect):
        """
        Clip input data based on AOI.

        :param str dem: raster DTM name
        :param str intersect: vector intersect feature call name

        :return str dem_clip: output clipped DTM name

        """
        if self.data['points']:
            self.data['points'] = self._clip_points(intersect)

        # set extent from intersect vector map
        arcpy.env.extent = intersect

        # raster description
        dem_desc = arcpy.Describe(dem)

        # output raster coordinate system
        arcpy.env.outputCoordinateSystem = dem_desc.SpatialReference

        # create raster mask based on intersect feature call
        mask = self.storage.output_filepath('inter_mask')
        arcpy.PolygonToRaster_conversion(intersect,
                                         self.storage.primary_key,
                                         mask,
                                         "MAXIMUM_AREA",
                                         cellsize=dem_desc.MeanCellHeight)

        # cropping rasters
        dem_clip = ExtractByMask(dem, mask)
        dem_clip.save(self.storage.output_filepath('dem_inter'))

        return dem_clip
def multi_convert_to_raster(polygon_fc_list, output_workspace):

    for polygon_fc in polygon_fc_list:
        env.extent = polygon_fc
        env.snapRaster = SNAP_RASTER
        short_name = os.path.splitext(os.path.basename(polygon_fc))[0]
        arcpy.AddMessage("Converting {}...".format(short_name))
        output_raster = os.path.join(output_workspace, short_name + '_raster')
        lagoslakeid_field = arcpy.ListFields(polygon_fc,
                                             '*lagoslakeid')[0].name
        zoneid_field = arcpy.ListFields(polygon_fc, '*zoneid')[0].name
        if lagoslakeid_field:
            zone_field = lagoslakeid_field
        else:
            zone_field = zoneid_field
        output_raster = arcpy.PolygonToRaster_conversion(polygon_fc,
                                                         zone_field,
                                                         output_raster,
                                                         'CELL_CENTER',
                                                         cellsize=CELL_SIZE)
        arcpy.BuildPyramids_management(output_raster, SKIP_FIRST=True)
        if lagoslakeid_field:
            arcpy.BuildRasterAttributeTable_management(output_raster, True)
            arcpy.AddField_management(output_raster, 'lagoslakeid', 'LONG')
            arcpy.CalculateField_management(output_raster, 'lagoslakeid',
                                            '!Value!', 'PYTHON_9.3')
    arcpy.AddMessage("Completed.")
Beispiel #12
0
def shp_to_rst(shp, inField, cellsize, outRaster, template=None, snap=None):
    """
    Feature Class to Raster
    """

    if template:
        tempEnvironment0 = arcpy.env.extent
        arcpy.env.extent = template

    if snap:
        tempSnap = arcpy.env.snapRaster
        arcpy.env.snapRaster = snap

    obj_describe = arcpy.Describe(shp)
    geom = obj_describe.ShapeType

    if geom == 'Polygon':
        arcpy.PolygonToRaster_conversion(shp, inField, outRaster,
                                         "CELL_CENTER", "NONE", str(cellsize))

    elif geom == 'Polyline':
        arcpy.PolylineToRaster_conversion(shp, inField, outRaster,
                                          "MAXIMUM_LENGTH", "NONE",
                                          str(cellsize))

    if template:
        arcpy.env.extent = tempEnvironment0

    if snap:
        arcpy.env.snapRaster = tempSnap
Beispiel #13
0
def clip_raster_box(in_raster, clip_feature, out_raster):
    """Clip raster to a feature"""
    in_proj = arcpy.Describe(in_raster).spatialReference
    clip_proj = arcpy.Describe(clip_feature).spatialReference
    tmp = None
    clip_with = clip_feature
    if in_proj.exporttostring() != clip_proj.exporttostring():
        tmp = project(clip_with,
                      arcpy.CreateScratchName(),
                      projection=arcpy.Describe(in_raster).spatialReference)
        # project the clipping features to the input features projection so clip works
        clip_with = tmp
    env_push()
    env_defaults(mask="", extent="", cellSize=in_raster)
    oldSpatial = arcpy.env.outputCoordinateSystem
    arcpy.env.outputCoordinateSystem = arcpy.Describe(
        in_raster).spatialReference
    clipBuffer = calc(
        "ClipBuffer", lambda _: arcpy.PolygonToRaster_conversion(
            clip_with,
            arcpy.ListFields(clip_with)[0].name, _))
    #~ clipBuffer = calc("ClipBuffer", lambda _: CreateConstantRaster(0, extent=clip_with))
    out_raster = calc(out_raster,
                      lambda _: Con(IsNull(clipBuffer), clipBuffer, in_raster))
    arcpy.Delete_management(clipBuffer)
    arcpy.env.outputCoordinateSystem = oldSpatial
    env_pop()
    if tmp:
        # assuming this is simple enough that deleting every time makes sense
        arcpy.Delete_management(tmp)
    return out_raster
Beispiel #14
0
def compute_zonal(MFgrid, DEM, z_conversion_factor=1, outfile=None):

    # Settings
    output_path = os.path.split(MFgrid)[0]
    arcpy.env.workspace = output_path
    arcpy.env.overwriteOutput = True
    arcpy.env.qualifiedFieldNames = False

    # Check out any necessary licenses
    arcpy.CheckOutExtension("spatial")

    #arcpy.AddField_management(MFgrid,"cellnum","LONG") #isn't needed if there is a node column
    print "multipling DEM z-values by %s to convert units..." %(z_conversion_factor)
    DEM2 = arcpy.sa.Raster(DEM)*z_conversion_factor

    print "extracting model top elevations from DEM..."
    # create raster of gridcells based on node (cellnum)
    # run zonal statistics on DEM for each grid cell
    print "\tbuilding raster of model grid cells for sampling DEM..."
    DEMres = arcpy.GetRasterProperties_management(DEM2, "CELLSIZEX")
    DEMres = float(DEMres.getOutput(0)) # cell size of DEM in project units
    arcpy.PolygonToRaster_conversion(MFgrid, "node", os.path.join(output_path, "MFgrid_raster"), "MAXIMUM_AREA", "node", DEMres)

    print "\tbuilding raster attribute table..."
    arcpy.BuildRasterAttributeTable_management(os.path.join(output_path, "MFgrid_raster"))

    print "\trunning zonal statistics... (this step will likely take several minutes or more)"
    arcpy.sa.ZonalStatisticsAsTable(os.path.join(output_path, "MFgrid_raster"), "VALUE", DEM2, os.path.join(output_path, "demzstats.dbf"), "DATA", "ALL")

    print "joining elevations back to model grid cells..."
    arcpy.MakeFeatureLayer_management(MFgrid, "MFgrid")

    if not outfile:
        outfile = os.path.join(output_path, MFgrid[:-4]+'_elevs.shp')
    general_join(outfile, "MFgrid", "node", os.path.join(output_path, "demzstats.dbf"), "VALUE", True)
def polygon_to_raster(infc, outlocation, snapRaster, inlocation):
    start_conversion = datetime.datetime.now()
    # set environmental variables
    arcpy.env.workspace = outlocation
    arcpy.Delete_management("snap")
    arcpy.MakeRasterLayer_management(snapRaster, "snap")
    arcpy.env.snapRaster = "snap"

    # Set local variables
    inFeatures = inlocation + os.sep + infc

    valField = "Zone"
    outRaster = outlocation + os.sep + infc
    assignmentType = "CELL_CENTER"
    cellSize = snapRaster

    print inFeatures
    arcpy.Delete_management("fc_lyr")
    arcpy.MakeFeatureLayer_management(inFeatures, "fc_lyr")


    # Execute PolygonToRaster
    if not arcpy.Exists(outRaster):
        arcpy.PolygonToRaster_conversion("fc_lyr", valField, outRaster, assignmentType, "NONE", cellSize)
        print "\nCompleted conversion of {0} in {1}".format(outRaster, (datetime.datetime.now() - start_conversion))

    else:
        print "\nAlready completed conversion {0}".format(outRaster)
    arcpy.Delete_management("snap")
    def execute(self, parameters, messages):
        '''The source code of the tool.'''
        in_rasterdataset = parameters[0].valueAsText
        in_fc = parameters[1].valueAsText
        in_cellsize = parameters[2].valueAsText
        in_field = parameters[3].valueAsText

        arcpy.env.workspace = in_rasterdataset

        ## check workspace and raster files
        rasterlist = arcpy.ListRasters("*")
        arcpy.PolygonToRaster_conversion(in_features=in_fc,
                                         value_field=in_field,
                                         out_rasterdataset="snap1",
                                         cellsize=in_cellsize)
        snap = "snap1"
        arcpy.AddMessage("Snap Raster Created")

        ## Project, resample, and clip rasters
        for raster in rasterlist:
            Ras = arcpy.Raster(raster)
            arcpy.env.snapRaster = snap
            projrast1 = arcpy.ProjectRaster_management(Ras, "proj1", snap,
                                                       "NEAREST")
            resamprast1 = arcpy.Resample_management(projrast1, "resamp1",
                                                    in_cellsize, "NEAREST")
            cliprast = arcpy.Clip_management(resamprast1, "#",
                                             raster + "_final", in_fc, "0",
                                             "ClippingGeometry")
            arcpy.AddMessage("Snap Raster Created")

        ## Delete temp files
        arcpy.Delete_management("resamp1")
        arcpy.Delete_management("proj1")
Beispiel #17
0
 def Landslides2Raster(self, landslides_feature, reference_raster, mask):
     landslidesOUT = "in_memory\\lSimR"
     arcpy.env.snapRaster = reference_raster
     arcpy.env.extent = reference_raster.extent
     # arcpy.FeatureToRaster_conversion(landslides, "tobia", landslidesOUT, cell_size=referenceRaster.meanCellWidth)
     arcpy.PolygonToRaster_conversion(landslides_feature, "SIM", out_rasterdataset=landslidesOUT, cellsize=reference_raster.meanCellWidth)
     arcpy.SetRasterProperties_management(landslidesOUT, nodata=[[1, 0]])
     return arcpy.Raster(landslidesOUT) * mask
Beispiel #18
0
def main():
    """ DOC STRING """
    # Make Feature Layers
    arcpy.MakeFeatureLayer_management(
        INPUTDATA.MAPPING_METHOD_POLYGON,  # in_features
        MAPPING_METHOD_LAYER_1,  # out_layer
        "\"100Bry_ele\" <> 0",  # where_clause
        "",  # workspace
        FIELD_ARGS)
    arcpy.MakeFeatureLayer_management(INPUTDATA.MAPPING_METHOD_POLYGON,
                                      MAPPING_METHOD_LAYER_2,
                                      "\"VAGut_ele\" <> 0", "", FIELD_ARGS)
    arcpy.MakeFeatureLayer_management(INPUTDATA.MAPPING_METHOD_POLYGON,
                                      MAPPING_METHOD_LAYER_3,
                                      "\"LIMWA_ele\" <> 0", "", FIELD_ARGS)

    # Convert Polygons to Rasters
    arcpy.PolygonToRaster_conversion(MAPPING_METHOD_LAYER_1, "100Bry_ele",
                                     V100_YR_RAS, "CELL_CENTER", "NONE", "25")
    arcpy.PolygonToRaster_conversion(MAPPING_METHOD_LAYER_2, "VAGut_ele",
                                     VA_RAS, "CELL_CENTER", "NONE", "25")
    arcpy.PolygonToRaster_conversion(MAPPING_METHOD_LAYER_3, "LIMWA_ele",
                                     LIMWA_RAS, "CELL_CENTER", "NONE", "25")

    # Convert Rasters to TINs
    arcpy.RasterTin_3d(V100_YR_RAS, V100_YR_TIN, "0.01", "1500000", "1")
    arcpy.RasterTin_3d(VA_RAS, VA_TIN, "0.01", "1500000", "1")
    arcpy.RasterTin_3d(LIMWA_RAS, LIMWA_TIN, "0.01", "1500000", "1")

    # Calculate Surface Difference new TINs vs. TERRAIN
    arcpy.SurfaceDifference_3d(V100_YR_TIN, INPUTDATA.TERRAIN,
                               V100_YR_SURF_DIFF_SHP, "0", "0",
                               OUTPUT_RASTER_1, "10", "", "")
    arcpy.SurfaceDifference_3d(VA_TIN, INPUTDATA.TERRAIN, VA_SURF_DIFF_SHP,
                               "0", "0", OUTPUT_RASTER_2, "10", "", "")
    arcpy.SurfaceDifference_3d(LIMWA_TIN, INPUTDATA.TERRAIN,
                               LIMWA_SURF_DIFF_SHP, "0", "0", OUTPUT_RASTER_3,
                               "10", "", "")

    # Process: Polygon To Line
    arcpy.PolygonToLine_management(V100_YR_SURF_DIFF_SHP,
                                   V100_YR_RUNUP_BDY_SHP, "IDENTIFY_NEIGHBORS")
    arcpy.PolygonToLine_management(VA_SURF_DIFF_SHP, VA_BDY_SHP,
                                   "IDENTIFY_NEIGHBORS")
    arcpy.PolygonToLine_management(LIMWA_SURF_DIFF_SHP, LIMWA_BDY_SHP,
                                   "IDENTIFY_NEIGHBORS")
Beispiel #19
0
def Polygon2Raster(plg, cellsize, extent, raster, isprint):
    #GRIDCODE=1
    arcpy.env.extent = extent
    arcpy.env.snapRaster = extent
    arcpy.PolygonToRaster_conversion(plg, "GRIDCODE", raster, "CELL_CENTER",
                                     "NONE", cellsize)
    if isprint:
        print('Polygon2Raster is finished....')
def land_use(nlcd_layer, search_area, excluded_types, tiger_lines,
             census_places, crs, workspace):
    arcpy.CheckOutExtension("spatial")

    geoprocessing_log.info("Extracting NLCD raster to search area")
    nlcd_in_area = arcpy.sa.ExtractByMask(nlcd_layer, search_area)
    avoid_types = [exclude.value for exclude in excluded_types]

    thresholded_raster = nlcd_in_area
    for avoid in avoid_types:  # this is inefficient, but I couldn't get it to work with a "not in" and I need something that works for n number of values
        thresholded_raster = arcpy.sa.Con(thresholded_raster != avoid,
                                          thresholded_raster, 0)

    scratch_raster = generate_gdb_filename("temp_raster", scratch=True)
    thresholded_raster.save(
        scratch_raster)  # save it so we can use it for environment variables

    stored_environments = store_environments(
        ('cellSize', 'mask', 'extent', 'snapRaster')
    )  # cache the env vars so we can reset them at the end of this function
    arcpy.env.cellSize = scratch_raster
    arcpy.env.mask = scratch_raster
    arcpy.env.extent = scratch_raster
    arcpy.env.snapRaster = scratch_raster

    roads_mask = make_road_mask(tiger_lines,
                                census_places=census_places,
                                search_area=search_area)
    roads_raster = generate_gdb_filename("roads_raster")
    geoprocessing_log.info("Converting roads mask to raster")
    try:
        arcpy.PolygonToRaster_conversion(roads_mask, "OBJECTID", roads_raster)
        #arcpy.CalculateStatistics_management(roads_raster)  # crashes for invalid statistics unless we run this after the conversion
    except:
        geoprocessing_log.error(
            "Error creating raster: {0:s} - from roads mask: {1:s}".format(
                roads_raster, roads_mask))
        raise

    # Raster Calculations
    final_nlcd = arcpy.sa.Con(arcpy.sa.IsNull(arcpy.sa.Raster(roads_raster)),
                              thresholded_raster, 1)
    intermediate_raster = generate_gdb_filename("intermediate_nlcd_mask")
    projected_raster = generate_gdb_filename("projected_nlcd_mask",
                                             gdb=workspace)
    final_nlcd.save(intermediate_raster)

    reset_environments(stored_environments)

    geoprocessing_log.info("Reprojecting final raster")
    arcpy.ProjectRaster_management(intermediate_raster,
                                   projected_raster,
                                   out_coor_system=crs)

    filtered_nlcd_poly = filter_patches.convert_and_filter_by_code(
        projected_raster, filter_value=0)

    return filtered_nlcd_poly
def ShpToRaster(fileRoot, item, timeItem, type):
    arcpy.PolygonToRaster_conversion(
        fileRoot + '\\' + 'shapefile' + '_' + str(resolution) + '\\' + type +
        '_' + timeItem + '_' + str(resolution) + '\\' + item,
        "FID",
        fileRoot + '\\' + 'raster' + '_' + str(resolution) + '\\' + type +
        '_' + timeItem + '_' + str(resolution) + '\\' + item.split('.')[0] +
        '.tif',
        cellsize=0.00054)
def getRelevantRaster(inDir, bufferSize, outAllR, DEM):
    #print "time %s - computing relevant raster" % (time.strftime("%m%d_%H%M%S"))
    zdrojDir = config.zdrojDir
    SA = config.getSA(DEM)
    sourceDEM = config.getSourceDEM(DEM)
    rasterDEM = zdrojDir + SA + "\\" + sourceDEM + "\\" + DEM
    tempWS = config.temp
    demDirs = [tempWS]
    createDEMdirs(inDir, demDirs)
    cellSize = bufferSize
    # list of rasters to merge
    tiffNames = []
    # for each lineaments according to DEM
    shp_listDir = os.listdir(inDir)
    for shpName in shp_listDir:
        if shpName[-4:] == ".shp":
            inSHP = inDir + shpName
            angleStart = shpName.find("_") + 1
            angleEnd = shpName.find("_", angleStart)
            rotateAngle = shpName[shpName.rfind("_") + 1:-4]
            outLineName = shpName[0:angleEnd] + "_" + rotateAngle
            outLineR = "in_memory\\" + outLineName
            outLineB = "in_memory\\" + outLineName + "B"
            # buffer inSHP
            lineSHPBuffName = shpName[:-4] + "_buff%d" % bufferSize
            lineSHPBuff = "in_memory\\" + lineSHPBuffName
            if not os.path.exists(lineSHPBuff):
                arcpy.Buffer_analysis(inSHP, lineSHPBuff,
                                      "%d Meters" % bufferSize, "FULL",
                                      "ROUND", "NONE", "#")
            if not os.path.exists(outLineB):
                # create filed, fill with 1 in order to convert vector to raster
                myField = "binary"
                myValue = 1
                # COMPUTING WITH BUFFER instead of line
                inSHP = lineSHPBuff
                arcpy.AddField_management(inSHP, myField, "SHORT", 2, "", "",
                                          "", "NULLABLE", "NON_REQUIRED")
                arcpy.CalculateField_management(inSHP, myField, myValue,
                                                "PYTHON_9.3", "#")
                # polyline to raster, use this field
                if not os.path.exists(outLineR):
                    desc = arcpy.Describe(rasterDEM)
                    arcpy.env.extent = desc.extent
                    arcpy.PolygonToRaster_conversion(inSHP, myField, outLineR,
                                                     "CELL_CENTER", "NONE",
                                                     cellSize)
                    arcpy.env.extent = "default"
                try:
                    # reclassify NoData to 0 !
                    arcpy.gp.Reclassify_sa(outLineR, "VALUE", "1 1;NODATA 0",
                                           outLineB, "DATA")
                    tiffNames.append(outLineB)
                except Exception, e:
                    print e
            arcpy.Delete_management(outLineR)
            arcpy.Delete_management(lineSHPBuff)
def convert_polygon_to_raster(workspace_gdb, in_feature, value,
                              out_raster_name):
    print("executing convert polygon to raster...")
    output_path = os.path.join(workspace_gdb, out_raster_name)
    output_raster = arcpy.PolygonToRaster_conversion(in_feature, value,
                                                     output_path).getOutput(0)
    print("created output raster at {0}".format(output_raster))
    print("finished processing conversion")
    return output_raster
Beispiel #24
0
 def convert_shp2raster(self, shapefile):
     cov_raster = "cov_ras.tif"  # name of the temporarily used cover raster
     try:
         arcpy.PolygonToRaster_conversion(shapefile, "cover", self.cache + cov_raster,
                                          cell_assignment="CELL_CENTER", priority_field="NONE", cellsize=1)
     except:
         self.logger.info(
             "ERROR: Could not perform polygon to raster conversion for: (" + shapefile + ").")
     return arcpy.Raster(self.cache + cov_raster)
Beispiel #25
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
 def create_patches(self):
     """Creates a patch for each separate stranding pool"""
     # reclassify q_disc ras to ints
     self.logger.info("Creating rating curve fit patches...")
     int_ras = Reclassify(self.q_disc_ras, 'Value', RemapValue(list(zip(self.discharges, range(len(self.discharges))))))
     # convert to polygon
     patch_poly = os.path.join(self.cache, 'patches.shp')
     arcpy.RasterToPolygon_conversion(int_ras, patch_poly, 'NO_SIMPLIFY')
     # convert back to raster, with unique val for each patch
     self.patch_ras = os.path.join(self.cache, 'patches.tif')
     arcpy.PolygonToRaster_conversion(patch_poly, 'FID', self.patch_ras)
Beispiel #27
0
def execute_BridgeCorrection(r_dem,
                             str_bridges,
                             str_result,
                             messages,
                             language="FR"):

    with arcpy.EnvManager(snapRaster=r_dem):
        with arcpy.EnvManager(extent=r_dem):

            linebridges = arcpy.CreateScratchName(
                "lines",
                data_type="FeatureClass",
                workspace=arcpy.env.scratchWorkspace)
            arcpy.PolygonToLine_management(str_bridges, linebridges,
                                           "IGNORE_NEIGHBORS")

            r_linebridges = arcpy.CreateScratchName(
                "rlines",
                data_type="RasterDataset",
                workspace=arcpy.env.scratchWorkspace)
            arcpy.PolylineToRaster_conversion(linebridges,
                                              "ORIG_FID",
                                              r_linebridges,
                                              cellsize=r_dem)

            r_polybridges = arcpy.CreateScratchName(
                "rpoly",
                data_type="RasterDataset",
                workspace=arcpy.env.scratchWorkspace)
            arcpy.PolygonToRaster_conversion(
                str_bridges,
                arcpy.Describe(str_bridges).OIDFieldName,
                r_polybridges,
                cellsize=r_dem)

            r_bridges = arcpy.sa.Con(
                arcpy.sa.IsNull(r_polybridges) == 1, r_linebridges,
                r_polybridges)

            z_bridges = arcpy.sa.ZonalStatistics(r_bridges, "VALUE", r_dem,
                                                 "MINIMUM")

            temp_isnull = arcpy.sa.IsNull(z_bridges)

            temp_dem = arcpy.sa.Con(temp_isnull, z_bridges, r_dem, "VALUE = 0")
            temp_fill = arcpy.sa.Fill(temp_dem)
            result = arcpy.sa.Con(temp_isnull, temp_fill, r_dem, "VALUE = 0")
            result.save(str_result)

            arcpy.Delete_management(linebridges)
            arcpy.Delete_management(r_linebridges)
Beispiel #28
0
def convert_ras(in_huc, in_bf, in_strm):
    if in_bf:
        arcpy.AddMessage("Preparing the stream network...")
        arcpy.MakeFeatureLayer_management(in_strm, r"in_strm_lyr")
        arcpy.MakeFeatureLayer_management(in_bf, r"in_bf_lyr")
        arcpy.Clip_analysis("in_strm_lyr", in_huc, r"in_memory\strm_clip")
        arcpy.Clip_analysis("in_bf_lyr", in_huc, r"in_memory\bf_clip")
        arcpy.MakeFeatureLayer_management(r"in_memory\strm_clip",
                                          "strm_clip_lyr")
        arcpy.MakeFeatureLayer_management(r"in_memory\bf_clip", "bf_clip_lyr")

        cellSize = arcpy.env.cellSize

        # convert streams to a raster format
        arcpy.AddField_management("strm_clip_lyr", "VAL", "SHORT")
        arcpy.CalculateField_management("strm_clip_lyr", "VAL", "1",
                                        "PYTHON_9.3")
        arcpy.PolylineToRaster_conversion("strm_clip_lyr", "VAL",
                                          r"in_memory\strm_ras", "", "",
                                          cellSize)

        # convert bankful polygon
        arcpy.AddField_management("bf_clip_lyr", "VAL", "SHORT")
        arcpy.CalculateField_management("bf_clip_lyr", "VAL", "1",
                                        "PYTHON_9.3")
        arcpy.PolygonToRaster_conversion("bf_clip_lyr", "VAL",
                                         r"in_memory\bf_ras", "CELL_CENTER",
                                         "", cellSize)

        # Mosaic stream and bankful rasters
        strm_final = arcpy.MosaicToNewRaster_management(
            r"in_memory\bf_ras;in_memory\strm_ras", "in_memory", "strmMSC", "",
            "8_BIT_UNSIGNED", cellSize, 1, "LAST", "")
        return strm_final
    else:
        arcpy.AddMessage("Preparing the stream network...")
        arcpy.MakeFeatureLayer_management(in_strm, r"in_strm_lyr")
        arcpy.Clip_analysis("in_strm_lyr", in_huc, r"in_memory\strm_clip")
        arcpy.MakeFeatureLayer_management(r"in_memory\strm_clip",
                                          "strm_clip_lyr")

        #cellSize = arcpy.env.cellSize

        # convert streams to a raster format
        arcpy.AddField_management("strm_clip_lyr", "VAL", "SHORT")
        arcpy.CalculateField_management("strm_clip_lyr", "VAL", "1",
                                        "PYTHON_9.3")
        strm_final = arcpy.PolylineToRaster_conversion(
            "strm_clip_lyr", "VAL", r"in_memory\strm_final")
        return strm_final
Beispiel #29
0
def calcConiferPost(coniferTreatmentArea, Conifer_Cover):
    arcpy.AddMessage("Calculating post-project conifer modifier")
    # Add field Conifer to use when converting to raster
    inTable = coniferTreatmentArea
    fieldName = "Conifer"
    fieldType = "SHORT"
    expression = 0
    arcpy.AddField_management(inTable, fieldName, fieldType)
    arcpy.CalculateField_management(inTable, fieldName, expression,
                                    "PYTHON_9.3", "")

    # Convert to raster
    in_features = coniferTreatmentArea
    value_field = "Conifer"
    out_rasterdataset = "Proposed_Conifer_Cover"
    cell_assignment = "MAXIMUM_AREA"
    priority_field = "Conifer"
    cellSize = 30

    coniferRaster = arcpy.PolygonToRaster_conversion(in_features,
                                                     value_field,
                                                     out_rasterdataset,
                                                     cell_assignment,
                                                     priority_field,
                                                     cellSize)

    # Mask existing conifer cover
    coniferPost = Con(IsNull(coniferRaster), Conifer_Cover, coniferRaster)
    coniferPost.save("Post_Conifer_Cover")

    # Calculate neighborhood statistics
    in_raster = coniferPost
    radius = 400
    neighborhood = NbrCircle(radius, "MAP")
    statistics_type = "MEAN"

    coniferCover400 = FocalStatistics(in_raster, neighborhood, statistics_type)

    # Reclassify to get Post_Conifer_Modifier
    in_raster = coniferCover400
    reclass_field = "VALUE"
    remapTable = [[0, 1, 100], [1, 2, 28], [2, 3, 14], [3, 4, 9], [4, 5, 6],
                  [5, 7, 3], [7, 8, 2], [8, 9, 1], [9, 100, 0]]
    coniferModifierPost100 = Reclassify(in_raster, reclass_field,
                                        RemapRange(remapTable))
    coniferModifierPost = Float(coniferModifierPost100) / 100

    return coniferModifierPost
Beispiel #30
0
def buildPointGrids(inFeature, tempRaster, cell_size, outShapefile):
    # Convert from polygon to raster and raster to point to create point grid
    arcpy.PolygonToRaster_conversion(inFeature, "OBJECTID", tempRaster, "CELL_CENTER", "NONE", cell_size)
    # Determine if raster contains only NoData values
    noData = int(arcpy.GetRasterProperties_management(tempRaster, 'ALLNODATA')[0])
    if noData == 0:
        # Convert raster to point grid
        arcpy.RasterToPoint_conversion(tempRaster, outShapefile, "VALUE")
        # Add XY Coordinates to feature class in the NAD_1983_Alaska_Albers projection
        arcpy.AddXY_management(outShapefile)
        # Delete intermediate files
        arcpy.Delete_management(tempRaster)
    elif noData == 1:
        arcpy.AddMessage("All values for this watershed are nodata...")
        # Delete intermediate files
        arcpy.Delete_management(tempRaster)