Пример #1
0
def centroid_feature_to_point(feature, as_file=False, id_field=None):
    """
	for internal use only

	:param feature: str feature class
	:param as_file: boolean indicates whether to return the arcpy file instead of returning the point array
	:param id_field: when included, means to pull ids into a tuple with the centroid from the specified field - can't return ids
	:return: list containing arcpy.Point objects
	"""
    if as_file:
        t_name = generate_gdb_filename(
            "feature_to_point"
        )  # we don't want a memory file if we are returning the filename
    else:
        t_name = generate_gdb_filename("feature_to_point", gdb="in_memory")

    arcpy.FeatureToPoint_management(feature, t_name, "CENTROID")

    if as_file:  # if asfile, return the filename, otherwise, make and return the point_array
        return t_name

    curs = arcpy.SearchCursor(t_name)  # open up the output

    points = []
    for record in curs:
        shape = record.shape.getPart()

        if id_field:
            shape_id = record.getValue(id_field)  # get the shape's point
            item = (shape, shape_id)
        else:
            item = shape

        points.append(item)

    arcpy.Delete_management(t_name)  # clean up the in_memory workspace
    del curs

    return points
Пример #2
0
def lightningDensity(clip_feature, grid_feature, cell_size):
    # if arcpy.Exists("lightningDensity.tif"):
    #   return
    intersect_feature = ''.join(["intersect", str(cell_size)])
    arcpy.Intersect_analysis([clip_feature, grid_feature], intersect_feature)

    frequency_table = ''.join(["intersect", str(cell_size), "_frequency"])
    field_frequency = ''.join(["FID_GRID", str(cell_size)])
    arcpy.Frequency_analysis(intersect_feature, frequency_table,
                             field_frequency)

    layer = ''.join(["GRID", str(cell_size)])
    arcpy.MakeFeatureLayer_management(grid_feature, layer)

    field_join = ''.join(["FID_GRID", str(cell_size)])
    arcpy.AddJoin_management(layer, "OID", frequency_table, field_join)

    density_points = "densityPoints"
    arcpy.FeatureToPoint_management(layer, density_points)
    lightning_density_raster = Spline(density_points, "FREQUENCY")

    lightning_density_raster.save("lightningDensity")
Пример #3
0
    def polygon(self):
        inFeatures1 = os.path.join(workspce, cad, cad_use[0])
        outFeatureClass = os.path.join(workspce, creat_gdb, self.polygon_name)
        arcpy.FeatureToPolygon_management(inFeatures1, outFeatureClass)
    
        inFeatures2 = os.path.join(workspce, cad, cad_use[1])
        outFeatureClass = os.path.join(workspce, creat_gdb, self.point_name)
        arcpy.FeatureToPoint_management(inFeatures2, outFeatureClass)
    
        where_clause = " RefName LIKE '5%' OR RefName LIKE '3%'"
        # 筛选符合要求的编号,其都以5和3开头
        select_fc = os.path.join(workspce, creat_gdb, self.select_anno)
        arcpy.Select_analysis(os.path.join(workspce, creat_gdb, self.point_name), select_fc , where_clause)

        outFeatureClass = os.path.join(workspce, creat_gdb, self.sp_fc)
        arcpy.SpatialJoin_analysis(os.path.join(workspce, creat_gdb, self.polygon_name), 
                                   os.path.join(workspce, creat_gdb, self.select_anno), 
                                   outFeatureClass)
        
        arcpy.MakeFeatureLayer_management(os.path.join(workspce, creat_gdb, self.sp_fc), "lyr")
        arcpy.SelectLayerByLocation_management ("lyr", select_features = area_fc)
        arcpy.CopyFeatures_management("lyr", os.path.join(workspce, creat_gdb, self.final_fc))
Пример #4
0
    def create_temporal_accuracy(self):
        """creates the temporal accuracy"""
        try:
            arcpy.AddMessage("Getting change detection statsitics")

            fc = self.change_detection_features
            self.get_change_detection_statistics(fc)

            arcpy.AddMessage('Running Feature To Point')
            arcpy.FeatureToPoint_management(self.change_detection_features,
                                            self.change_detection_as_points,
                                            "INSIDE")

            arcpy.AddMessage('Running Spatial Join')
            arcpy.SpatialJoin_analysis(self.currency_features,
                                       self.change_detection_as_points,
                                       self.temporal_accuracy_features, "JOIN_ONE_TO_ONE",
                                       "KEEP_ALL", "#", "INTERSECT")

            arcpy.AddMessage("Adding fields that will be populated")
            self.append_fields_to_year_list()

            arcpy.AddMessage("Adding fields to temporal accuracy")
            self.add_fields()

            #Calculate the temporal accuracy
            arcpy.AddMessage("Running temporal accuracy algorithm")
            self.get_temporal_accuracy()

        except:
            line, filename, synerror = trace()
            raise FunctionError({
                "function": "create_temporal_accuracy",
                "line": line,
                "filename": __file__,
                "synerror": synerror,
                "arc" : str(arcpy.GetMessages(2))
            })
Пример #5
0
def determine_banks(fcInputStreamLineNetwork, fcChannelBankPolygons,
                    scratchWorkspace):
    '''
        Description:
            Takes  the stream network, buffers out to the left by 1 meter, extracts centroid and
            uses that to select left channel bank (a layer with two polygons l/r), and sets bankside to LEFT
            then inverts selection and set that to RIGHT writing this back to fcChannelBankPolygons.

        Update: 24/8/18 - DDH -Added error trapping
    '''
    try:
        fcChannelBankSideBuffer = gis_tools.newGISDataset(
            scratchWorkspace, "BankSide_Buffer")
        fcChannelBankSidePoints = gis_tools.newGISDataset(
            scratchWorkspace, "BankSidePoints")
        arcpy.Buffer_analysis(fcInputStreamLineNetwork,
                              fcChannelBankSideBuffer, "1 Meter", "LEFT",
                              "FLAT", "NONE")
        arcpy.FeatureToPoint_management(fcChannelBankSideBuffer,
                                        fcChannelBankSidePoints, "INSIDE")
        arcpy.AddField_management(fcChannelBankPolygons, "BankSide", "TEXT",
                                  "10")
        lyrChannelBanks = gis_tools.newGISDataset("Layer", "lyrChannelBanks")
        arcpy.MakeFeatureLayer_management(fcChannelBankPolygons,
                                          lyrChannelBanks)
        arcpy.SelectLayerByLocation_management(lyrChannelBanks,
                                               "INTERSECT",
                                               fcChannelBankSidePoints,
                                               selection_type="NEW_SELECTION")
        arcpy.CalculateField_management(lyrChannelBanks, "BankSide", "'LEFT'",
                                        "PYTHON")
        arcpy.SelectLayerByAttribute_management(lyrChannelBanks,
                                                "SWITCH_SELECTION")
        arcpy.CalculateField_management(lyrChannelBanks, "BankSide", "'RIGHT'",
                                        "PYTHON")
        return
    except Exception as e:
        arcpy.AddError("Error in determine_banks function: " + str(e))
    def valore_precipitation_centroid(self):

        file_amministrativo = self.dirOut + self.admin + ".shp"
        file_centroide = self.dirOut + self.admin + "_ctrd.shp"
        #print file_centroide
        adm2_centroid = arcpy.FeatureToPoint_management(
            file_amministrativo, file_centroide, "CENTROID")
        coords = arcpy.da.SearchCursor(adm2_centroid, ["SHAPE@XY"])
        for polyg in coords:
            x, y = polyg[0]

        os.chdir(self.monthly_precipitation_dir)
        lista_raster = glob.glob("*.tif")

        valori_mensili = {}
        for raster_mese in lista_raster:
            result = arcpy.GetCellValue_management(raster_mese,
                                                   str(x) + " " + str(y))
            valori_mensili[raster_mese] = int(result[0])

        #print valori_mensili

        global dizionario_in
        dizionario_in = self.build_value_list(valori_mensili)
        with open(self.dirOut + self.admin + "_prec.csv", 'wb') as csvfile:
            csvwriter = csv.writer(csvfile,
                                   delimiter=',',
                                   quotechar='"',
                                   quoting=csv.QUOTE_MINIMAL)
            for linea in dizionario_in.iteritems():
                csvwriter.writerow(linea)

        #print dizionario_in
        #global ritornati_somma
        #ritornati_somma = sum(dizionario_in.values())

        return "Monthly Probability Function calculated....\n"
Пример #7
0
    def execute(self, params, messages):
        source_features = params[0].valueAsText
        output_sf = params[1].valueAsText
        sf_list = source_features.split(';')

        if len(sf_list) == 1:
            output_features = ["a"]
        elif len(sf_list) == 2:
            output_features = ["a", "b"]
        elif len(sf_list) == 3:
            output_features = ["a", "b", "c"]

        merge_features = []
        for sf, output in zip(sf_list, output_features):
            out = os.path.join("in_memory", output)
            # create centroids for all biotics source features
            output = arcpy.FeatureToPoint_management(sf, out, "INSIDE")
            # add path of temporary centroid feature classes to merge_features list
            merge_features.append(output)

        # merge centroid feature classes into one Biotics source feature centroid feature class
        arcpy.Merge_management(merge_features, output_sf)

        return
def get_timber_licences(tfl_poly, input_gdb, BCGW_Connection):
    """Used only when change is replacement. Takes the TFL Poly and finds all
       Timber Licenses that are within. Adds the list of licenses to the email
       message text so that FADM staff can confirm with FTB if they should be
       included in the TFL"""
    timber_licences = []
    bcgw_timber_licence = BCGW_Connection + '\\WHSE_FOREST_TENURE.FTEN_TIMBER_LICENCE_POLY_SVW'
    arcpy.env.workspace = input_gdb
    #make a point layer from the timber licenses to check within
    temp_points = arcpy.FeatureToPoint_management(bcgw_timber_licence,
                                                  'Temp_TL_Points', "INSIDE")
    #make a feature layer of the points to allow a selection
    temp_points_fl = arcpy.MakeFeatureLayer_management(temp_points,
                                                       'temp_points_fl')
    #make a feature layer of the active timber licences - we will select into this layer after using points to intersect (avoids intersect on edges)
    timber_licence_fl = arcpy.MakeFeatureLayer_management(
        bcgw_timber_licence, 'timber_licence_fl',
        "LIFE_CYCLE_STATUS_CODE = 'ACTIVE'")
    arcpy.SelectLayerByLocation_management(temp_points_fl, 'INTERSECT',
                                           tfl_poly)
    #then select the timber licences that intersect these points
    arcpy.SelectLayerByLocation_management(timber_licence_fl, 'INTERSECT',
                                           temp_points_fl)
    #delete if the timber licences exists, then create
    if arcpy.Exists(input_gdb + os.sep + 'Timber_Licence'):
        arcpy.Delete_management(input_gdb + os.sep + 'Timber_Licence')
    arcpy.CopyFeatures_management(timber_licence_fl,
                                  input_gdb + os.sep + 'Timber_Licence')

    with arcpy.da.SearchCursor(temp_points_fl, ['FOREST_FILE_ID']) as cursor:
        for row in cursor:
            arcpy.AddMessage('found forest file ID : ' + row[0])

    arcpy.Delete_management(temp_points)
    arcpy.Delete_management(temp_points_fl)
    arcpy.Delete_management(timber_licence_fl)
Пример #9
0
    arcpy.Delete_management("BuildingP_buffer_" + str(n), "")
    arcpy.Delete_management("Building_buffer_" + str(n), "")
    arcpy.Delete_management("Building_bfed_" + str(n), "")
    arcpy.Delete_management("Obs_buffer_" + str(n), "")
    arcpy.Delete_management("LiDAR_bufferclip_" + str(n), "")
    arcpy.Delete_management("LiDAR_obsclip_" + str(n), "")
    arcpy.Delete_management("LiDAR_buildingclip_" + str(n), "")
    #arcpy.Delete_management("Buildingsub_"+str(n),"")
    #arcpy.Delete_management("New_VSRas_"+str(n),"")

    # Select one feature
    arcpy.SelectLayerByAttribute_management("lyr0", "New_SELECTION",
                                            '"fid" = ' + str(n))

    # Process: Feature To Point
    arcpy.FeatureToPoint_management("lyr0", "Building_P_" + str(n), "CENTROID")

    # Creat a 5feet buffer of the building footprint, so that the process is robust to errors (the remnant outline) from 5by5 cell segmentation
    arcpy.Buffer_analysis("lyr0", "Building_buffer_" + str(n), "5 Feet",
                          "FULL", "ROUND", "NONE", "", "GEODESIC")

    #Creat union of the 5ft buffer and the building footprint
    arcpy.Union_analysis(["lyr0", "Building_buffer_" + str(n)],
                         "Building_bfed_" + str(n), "", 0.0003)

    # Process: Buffer-mimic the entire region within 1 mile
    arcpy.Buffer_analysis("Building_P_" + str(n), "BuildingP_buffer_" + str(n),
                          "1 Miles", "FULL", "ROUND", "NONE", "", "GEODESIC")

    # Process: Buffer-creat an observer-a 4 ft(about 5/sqrt(2)) radius pillar-actually one cell of the raster
    arcpy.Buffer_analysis("Building_P_" + str(n), "Obs_buffer_" + str(n),
file11.close()

#Append all the "underlying_level_polygons" files to output shape
os.system ("dir "+org_GIS+"*_underlying_level_polygons.shp /s/d/b >"+org_GIS+"underlying_level_polygons.txt")

file12 = open(org_GIS+'underlying_level_polygons.txt', 'r')
lines = file12.readlines()

for line in lines:
	arcpy.env.workspace = loc_output+'OUTPUT'
	arcpy.Append_management ([line[:-1]],loc_output+'OUTPUT/BH_underlying_level_polygons.shp')
	print (line)

file12.close()

#Perform dissolve and create centroids for every locus (making them unique for spatial analysis)

BH_locus = loc_output+"OUTPUT/BH_locus.shp"
BH_locus_diss = loc_output+"OUTPUT/BH_locus_diss.shp"
BH_locus_point = loc_output+"OUTPUT/BH_locus_points.shp"

# Process: Dissolve
arcpy.Dissolve_management(BH_locus, BH_locus_diss, "Trench;Locus;joinfld", "", "MULTI_PART", "DISSOLVE_LINES")

# Process: Feature To Point
arcpy.FeatureToPoint_management(BH_locus_diss, BH_locus_point, "CENTROID")

print "The script was successful!!! Press ENTER to close"
raw_input ()
Пример #11
0
# get parcel layer
cpar = cparcel[0]
# make layer from SQL statement
arcpy.MakeFeatureLayer_management(cpar,
                                  "selpar",
                                  where_clause=whereClause,
                                  workspace="#",
                                  field_info="#")
# remove output centroid if already exists

# remove centroid if already exists
for filename in glob.glob(outpath + "/centroid*"):
    silentremove(filename)

centroid = arcpy.FeatureToPoint_management("selpar",
                                           outpath + "/centroid.shp",
                                           point_location="INSIDE")

# for dfelement in arcpy.mapping.ListLayoutElements(mapdoc,'DATAFRAME_ELEMENT',df.name)
for df in listdf:
    # access parcel for each df to join with centroid
    mapdoc.activeview = 'PAGE_LAYOUT'
    arcpy.RefreshActiveView()
    parcel = arcpy.mapping.ListLayers(mapdoc, "*Parcel*", df)
    par = parcel[0]
    arcpy.SelectLayerByLocation_management(par, "intersect", centroid)
    df_pdf = outpath + '/' + df.name + ".pdf"
    silentremove(df_pdf)
    par.showLabels = True
    df.zoomToSelectedFeatures()
    arcpy.RefreshActiveView()
Пример #12
0
def main(infc, Width, outfc, radius):

    if 'shp' in outfc:
        arcpy.AddError('Output parameter must be saved in a geodatabase')
        sys.exit()

    extent = arcpy.Describe(infc).extent
    orig = "%s %s" % (extent.XMin, extent.YMin)
    add = extent.YMin * 0.00001

    if extent.YMin < 0:
        yaxis = "%s %s" % (extent.XMin, extent.YMin - add)
    else:
        yaxis = "%s %s " % (extent.XMin, extent.YMin + add)

    arcpy.CreateFishnet_management("in_memory\\fishnet", orig, yaxis, Width,
                                   Width, "", "", "", "", infc, "POLYGON")

    arcpy.MakeFeatureLayer_management("in_memory\\fishnet", "in_memory\\layer")
    arcpy.SelectLayerByLocation_management("in_memory\\layer",
                                           "COMPLETELY_WITHIN", infc)
    arcpy.CopyFeatures_management("in_memory\\layer", outfc)

    if radius:

        fields = ['Area', 'Circumfere']
        arcpy.AddField_management(outfc, 'Area', "DOUBLE")
        arcpy.AddField_management(outfc, 'Circumfere', "DOUBLE", "", "", "",
                                  "Circumference")

        arcpy.AddField_management(outfc, 'S_Radius', "TEXT")
        arcpy.FeatureToPoint_management(outfc, "in_memory\\fishnet_points")
        arcpy.Buffer_analysis("in_memory\\fishnet_points", "in_memory\\buffer",
                              radius, "FULL", "ROUND")

        radius_v = radius.split(' ')

        data = {}

        cursorm = [
            m_data for m_data in arcpy.da.SearchCursor(infc, ['SHAPE@'])
        ]

        count = arcpy.GetCount_management("in_memory\\buffer").getOutput(0)
        arcpy.SetProgressor("step", "Reading Buffer Parameters", 0,
                            eval(count), 1)

        R1 = 1

        with arcpy.da.SearchCursor("in_memory\\buffer",
                                   ['OID@', 'SHAPE@']) as cursor:
            for row in cursor:
                for m in cursorm:
                    inter = row[1].intersect(m[0], 4)
                    if inter.length != 0.0:
                        data[row[0]] = (inter.getLength('PLANAR', radius_v[1]),
                                        inter.getArea('PLANAR', radius_v[1]))
                        break
                arcpy.SetProgressorPosition()

        with arcpy.da.SearchCursor(outfc, ['OID@']) as cursor:
            for row in cursor:
                if row[0] < R1:
                    R1 = row[0]

        fields.extend(['S_Radius', 'OID@'])

        with arcpy.da.UpdateCursor(outfc, fields) as cursor:
            for row in cursor:
                values = data[row[-1] + (1 - R1)]
                row[0] = values[1]
                row[1] = values[0]
                row[2] = radius
                cursor.updateRow(row)
Пример #13
0
addMsgAndPrint('  Making layer view of CAF without concealed lines')
sqlQuery = arcpy.AddFieldDelimiters(fds,'IsConcealed') + " NOT IN ('Y','y')"
testAndDelete(cafLayer)
arcpy.MakeFeatureLayer_management(caf,cafLayer,sqlQuery)

#make temporaryPolys from layer view
addMsgAndPrint('  Making '+temporaryPolys)
testAndDelete(temporaryPolys)
arcpy.FeatureToPolygon_management(cafLayer,temporaryPolys)
if debug:
    addMsgAndPrint('temporaryPolys fields are '+str(fieldNameList(temporaryPolys)))

#make center points (within) from temporarypolys
addMsgAndPrint('  Making '+centerPoints)
testAndDelete(centerPoints)               
arcpy.FeatureToPoint_management(temporaryPolys, centerPoints, "INSIDE")
if debug:
    addMsgAndPrint('centerPoints fields are '+str(fieldNameList(centerPoints)))
# get rid of ORIG_FID field
arcpy.DeleteField_management(centerPoints,'ORIG_FID')

#identity center points with inpolys
testAndDelete(centerPoints2)
arcpy.Identity_analysis(centerPoints, inPolys, centerPoints2, 'NO_FID')
# delete points with MapUnit = ''
## first, make layer view
addMsgAndPrint("    Deleting centerPoints2 MapUnit = '' ")
sqlQuery = arcpy.AddFieldDelimiters(fds,'MapUnit') + "= '' "
testAndDelete('cP2Layer')
arcpy.MakeFeatureLayer_management(centerPoints2,'cP2Layer',sqlQuery)
## then delete features
Пример #14
0
    for field in fieldObjList:
        if not field.required and field.name not in {
                "OBJECTID", "PARCELID", "LRSN", "CONSIDERATION", "PROP_CLASS",
                "TRANSFER_DATE", "PVA_NEIGHBOR"
        }:
            fieldNameList.append(field.name)

    arcpy.DeleteField_management("ParcelDBF_Join", fieldNameList)

    arcpy.FeatureClassToFeatureClass_conversion("ParcelDBF_Join",
                                                r'J:\common\PVA_SALES.gdb',
                                                'RECENT_SALES')
    arcpy.DeleteField_management(r'J:\common\PVA_SALES.gdb\RECENT_SALES',
                                 ["Parcel_SHAPE_Length", "Parcel_SHAPE_Area"])
    arcpy.FeatureToPoint_management(
        r'J:\common\PVA_SALES.gdb\RECENT_SALES',
        r'J:\common\PVA_SALES.gdb\RECENT_SALES_POINTS')
    arcpy.DeleteField_management(
        r'J:\common\PVA_SALES.gdb\RECENT_SALES_POINTS', ["ORIG_FID"])

except:
    tb = sys.exc_info()[2]
    tbinfo = traceback.format_tb(tb)[0]
    pymsg = "PYTHON ERRORS:\n  Traceback Info:\n{0}\n  Error Info:\n    {1}: {2}\n".format(
        tbinfo, str(sys.exc_type), str(sys.exc_value))
    gpmsg = "ARCPY ERRORS:\n{0}\n".format(arcpy.GetMessages(2))
    tmRun = time.strftime("%X", time.localtime())
    endTime = time.time()
    prodInfo = "\tScript errored after running for {0} seconds.".format(
        str(round((endTime - startTime))))
    msgTxt += "\n\n\tScript error at: {0}\n{1}\n\n{2}{3}".format(
Пример #15
0
                                           "NOT_INVERT")
    arcpy.CopyFeatures_management("segmented_roads", cad_proximal_roads)

    step3_endTime = bk_logger.currentSecondsTime()
    bk_logger.showPyMessage(
        " -- Step 3 done. Took {}".format(
            bk_logger.timeTaken(step3_startTime, step3_endTime)), logger)

    #Step 4: Convert bin collection road strips into bin collection points
    bk_logger.showPyMessage(
        "Step 4: Convert bin collection road strips into bin collection points ",
        logger)
    step4_startTime = bk_logger.currentSecondsTime()

    rough_bin_collection_points = intermediate_layers + "/rough_bin_collection_points.shp"
    arcpy.FeatureToPoint_management(cad_proximal_roads,
                                    rough_bin_collection_points, "INSIDE")

    step4_endTime = bk_logger.currentSecondsTime()
    bk_logger.showPyMessage(
        " -- Step 4 done. Took {}".format(
            bk_logger.timeTaken(step4_startTime, step4_endTime)), logger)

    #Step 5: Assign service points to their closest bin collection point
    bk_logger.showPyMessage(
        "Step 5: Assign service points to their closest bin collection point ",
        logger)
    step5_startTime = bk_logger.currentSecondsTime()

    bin_collection_points = working_directory + "/bin_collection_points.shp"
    arcpy.SpatialJoin_analysis(rough_bin_collection_points, service_points,
                               bin_collection_points, "JOIN_ONE_TO_MANY",
Пример #16
0
# Import arcpy module
import arcpy

# Local variables:
a2003_001_dbf = "C:\\Users\\ekloog\\Documents\\$Doc\\3.PostDoc\\3.1.Projetcs\\3.1.3.TEMP_MODELS\\3.1.1.4.Work\\2.Gather_data\\daily_stmp\\a2003_001.dbf"
a2003_001_Layer = "a2003_001_Layer"
a2003_001_shp = "C:\\Users\\ekloog\\Documents\\$Doc\\3.PostDoc\\3.1.Projetcs\\3.1.3.TEMP_MODELS\\3.1.1.4.Work\\2.Gather_data\\metdbf_shp\\a2003_001.shp"
a2003_001_Project = "C:\\Users\\ekloog\\Documents\\$Doc\\3.PostDoc\\3.1.Projetcs\\3.1.3.TEMP_MODELS\\3.1.1.4.Work\\2.Gather_data\\metshp_utm_proj\\a2003_001.shp"

# Process: Make XY Event Layer
arcpy.MakeXYEventLayer_management(a2003_001_dbf, "X", "y", a2003_001_Layer, "GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]];-400 -400 1000000000;-100000 10000;-100000 10000;8.98315284119522E-09;0.001;0.001;IsHighPrecision", "")

# Process: Feature To Point
arcpy.FeatureToPoint_management(a2003_001_Layer, a2003_001_shp, "CENTROID")

# Process: Project
arcpy.Project_management(a2003_001_shp, a2003_001_Project, "PROJCS['WGS_1984_UTM_Zone_19N',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-69.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]", "", "PROJCS['WGS_1984_UTM_Zone_19N',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-69.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]")
                expression = expression + " or " + slopeClipOIDFieldName + " = " + str(
                    i)

        arcpy.AddMessage(
            str(tileNum) +
            "     Copying random polys from slope categories...")
        # copy the random polys to a new feature class
        randomPoly = os.path.join(scratch, "randomPoly")
        arcpy.FeatureClassToFeatureClass_conversion(
            slopeClip, os.path.dirname(randomPoly),
            os.path.basename(randomPoly), expression)
        deleteme.append(randomPoly)

        # generate points within 'selected' polygons -- ARCINFO ONLY!!!!!
        randomPoint = os.path.join(scratch, "randomPoint")
        arcpy.FeatureToPoint_management(randomPoly, randomPoint, "INSIDE")
        deleteme.append(randomPoint)

        # generate diagonals for each point
        arcpy.AddMessage(str(tileNum) + "     Building diagonals...")
        diagonals = os.path.join(scratch, "diagonals")
        arcpy.CreateFeatureclass_management(
            os.path.dirname(diagonals), os.path.basename(diagonals),
            "POLYLINE", "#", "#", "#",
            arcpy.Describe(slopePoly).SpatialReference, "#", "#", "#", "#")
        arcpy.AddField_management(diagonals, "RNDID", "LONG")
        deleteme.append(diagonals)
        rows = arcpy.da.SearchCursor(randomPoint, ["OID@", "SHAPE@XY"])
        insert = arcpy.da.InsertCursor(diagonals, ["SHAPE@", "RNDID"])
        offset = 500.0  # 1/2 km offsets
        for row in rows:
Пример #18
0
    #Setting the size of the enviroment
    arcpy.env.cellSize = pixelsize

    CELL_FLO = float(CELL)

    #FLOW DEPTH CALCULATION--------------------------------------------------------------------

    #Determining the extension of the calculation
    arcpy.Buffer_analysis(WS, BUFF, CELL_FLO, "FULL")  #Buffer of the WSE
    arcpy.FeatureToRaster_conversion(
        BUFF, "Var", EXT,
        CELL_FLO)  #Rasterization of the buffer as coputational domain
    arcpy.env.extent = EXT
    arcpy.env.mask = EXT

    arcpy.FeatureToPoint_management(WS, WSPOINTS,
                                    "CENTROID")  #Extraction of the centroids

    #Kriging application for WLI
    outKriging = Kriging(WSPOINTS, "Var", "SPHERICAL", pixelsize)
    outKriging.save(AUX)
    outExtractByMask = ExtractByMask(AUX, EXT)
    outExtractByMask.save(KRIG)

    #subtracion WS-DEM
    outM = Raster(KRIG) - Raster(DEM)
    outM.save(DIFF)
    outSN = SetNull(DIFF, DIFF, "VALUE < 0")
    outSN.save(FLDEP)

    #Deleting auxiliary files
    arcpy.Delete_management(AUX)
Пример #19
0
        arcpy.AddMessage("# of points extracted from this gully is " +
                         str(count2))
        Notification = "The margin of Gully whose ID is " + str(
            j
        ) + " doesn't provide correct points pair for each point extracted from corresponding gully"
        arcpy.AddMessage(Notification)
        arcpy.AddMessage(
            "Please EDIT the corresponding margin polyline feature")
        # Remove that Gully ID from the list
        Gully_ID_list.remove(j)
        # Remove the Gully Margin points with problems
        arcpy.DeleteRows_management(out_view1)

#Convert a multipoint feature class into a point feature class
fc_point = fc + '_point'
arcpy.FeatureToPoint_management(fc, fc_point)

## Extract Points With Elevation with the raster data ######

ExtractValuesToPoints(fc_point, DEMRasterDir, GullyMarginPointsDir, "",
                      "VALUE_ONLY")

## Add fields
arcpy.AddField_management(GullyPointsDir, "Width", "DOUBLE")
arcpy.AddField_management(GullyPointsDir, "Depth", "DOUBLE")

#Calculation

Point_OBJECTID_list = [
    row[0]
    for row in arcpy.da.SearchCursor(GullyMarginPointsDir, ("Point_OBJECTID"))
Пример #20
0
 for srow in srows:
     count += 1
     end = layer + str(count)
     name = srow.getValue(field)
     query = '"' + str(field) + '" =' + "'" + str(name) + "'"
     temp_feat = "temp"
     new_lyr = end + "_lyr"
     sel_lyr = end + "_lyr2"
     o_point = "point" + str(count)
     d_point = "d_point" + str(count)
     distance = "NEAR_DIST"
     desc = arcpy.Describe(layer)
     arcpy.SelectLayerByAttribute_management(layer, "NEW_SELECTION", query)
     arcpy.CopyFeatures_management(layer, temp_feat)
     arcpy.MakeFeatureLayer_management(temp_feat, new_lyr)
     arcpy.FeatureToPoint_management(new_lyr, o_point)
     arcpy.SelectLayerByLocation_management(layer,
                                            "SHARE_A_LINE_SEGMENT_WITH",
                                            new_lyr)
     arcpy.CopyFeatures_management(layer, sel_lyr)
     arcpy.FeatureToPoint_management(sel_lyr, d_point)
     arcpy.Near_analysis(d_point, o_point)
     f.write("," + name + "," + "\n")
     f.write("Neighbors,")
     arcpy.SetProgressorPosition()
     arcpy.SetProgressorLabel("Calculating Neighbors...")
     lrows = arcpy.SearchCursor(sel_lyr)
     for lrow in lrows:
         name2 = lrow.getValue(field)
         f.write(name2 + ",")
     f.write("\n")
Пример #21
0
arcpy.env.Extent = aExtent

# Select buildable portions of undeveloped parcels...

arcpy.AddMessage("Identifying undeveloped parcels...")
arcpy.SelectLayerByLocation_management(parcelLayer, "CONTAINS",
                                       existStructures, "", "NEW_SELECTION")
arcpy.SelectLayerByAttribute_management(parcelLayer, "SWITCH_SELECTION")
arcpy.MakeFeatureLayer_management(parcelLayer, "pLayer")
arcpy.AddMessage("Identifying buildable areas with undeveloped parcels...")
arcpy.Clip_analysis("pLayer", constraintLayer, clippedParcels)
arcpy.SelectLayerByAttribute_management(parcelLayer, "CLEAR_SELECTION")

# Generate future structures...
arcpy.AddMessage("Generating structures on undeveloped parcels...")
arcpy.FeatureToPoint_management(clippedParcels, newStructures, "INSIDE")

if arcpy.env.Extent == "MINOF":
    arcpy.env.Extent = arcpy.Describe(newStructures).extent
arcpy.AddMessage("Merging new structures with existing structures...")
arcpy.MakeFeatureLayer_management(existStructures, "existStructures")
arcpy.AddField_management("existStructures", "SIM_STRUCT", "SHORT")
arcpy.CalculateField_management("existStructures", "SIM_STRUCT", "0")
arcpy.MakeFeatureLayer_management(newStructures, "newStructures")
arcpy.AddField_management("newStructures", "SIM_STRUCT", "SHORT")
arcpy.CalculateField_management("newStructures", "SIM_STRUCT", "1")
arcpy.Merge_management("existStructures;newStructures", outStructures)
#arcpy.Merge_management (existStructures + ";" + newStructures, outStructures)

#Simulate future roads...
rdcst = CreateRoadCost(inDEM, "", existRoads, tWorkspace)
Пример #22
0
            if count >= 1:
                arcpy.AddMessage("  .. " + str(count) + " line features will " \
                + "be processed.")
                arcpy.AddMessage("  .. Converting line geometry to point.")

                # --- Handle multi-part geometries ---
                # Explode into single part features
                arcpy.MultipartToSinglepart_management("RevLine",
                                                       LineShapeSingle)

                # Run repair geometry incase any bad geometry created.
                arcpy.RepairGeometry_management(LineShapeSingle)

                # Create a point for each part
                arcpy.FeatureToPoint_management(LineShapeSingle, LineShape,
                                                "INSIDE")

                # Dissolve the points into a multi-part point using the LinkGUID
                # field
                arcpy.Dissolve_management(LineShape, LineShapeDissolve,
                                          "LINKGUID", "", "MULTI_PART",
                                          "DISSOLVE_LINES")

                TotalErrors = TotalErrors + count

                arcpy.Append_management(LineShapeDissolve, TempFC, "NO_TEST",
                                        "")

            else:
                arcpy.AddMessage("  .. No line errors exist in selected " \
                + "session.")
Пример #23
0
                          "\"Shape_Area\" >= \"TDP_Minimum_Area\"")

    # Process: Buffer
    arcpy.Buffer_analysis(HLZ_Grid_Small_Areas_Eliminated, Buffered_Areas,
                          "TDP_Interior_Buffer", "FULL", "ROUND", "NONE", "")

    # Process: Select to eliminate small areas
    arcpy.Select_analysis(Buffered_Areas, HLZ_Raw_Area_Grid_,
                          "\"Shape_Area\" >= \"TDP_Minimum_Area\"")

    # Process: Split Buffer Polygons
    arcpy.MultipartToSinglepart_management(HLZ_Raw_Area_Grid_,
                                           Final_HLZ_Area_Grid)

    # Process: Feature To Point
    arcpy.FeatureToPoint_management(Final_HLZ_Area_Grid, TDP_Centerpoints,
                                    "INSIDE")

    # Process: Add TDP Radius
    arcpy.AddField_management(TDP_Centerpoints, "Desired_TDP_Radius", "DOUBLE",
                              "", "", "", "", "NULLABLE", "NON_REQUIRED", "")

    # Process: Calculate TDP Radius
    arcpy.CalculateField_management(TDP_with_Radius_Field,
                                    "Desired_TDP_Radius", "%TDP_Diameter%/2",
                                    "VB", "")

    # Process: Create TDP Circle
    arcpy.Buffer_analysis(TDP_with_Radius, TDP_Circles, "Desired_TDP_Radius",
                          "FULL", "ROUND", "NONE", "")

    # Process: Create Feature Dataset
Пример #24
0
import arcpy

arcpy.env.workspace = r"E:/Park_Ivnt"

arcpy.MakeXYEventLayer_management(
    table="E:/Park_Ivnt/2018_PI_Final_Single.csv",
    in_x_field="POINT_X",
    in_y_field="POINT_Y",
    out_layer="2018_pi_Merged_Points",
    spatial_reference="4326")

arcpy.FeatureToPoint_management(
    in_features="2018_pi_Merged_Points",
    out_feature_class="E:/Park_Ivnt/2018_pi_Merged_Points.shp",
    point_location="CENTROID")
Пример #25
0
    if combine == 'true':
        tagList = ','.join([str(v) for v in devDict.values()])
        c1 = ''.join(['tag_id IN (', tagList, ')'])
        sqlSelect = '{0} AND {1}{2}'.format(c0,c1,c2)
        layerName = 'q_tags'
        # View uses fid as a "sacrificial" key for Arcmap to ingest
        q_layer = arcpy.MakeQueryLayer_management("Database Connections/wtg_gdb.sde",
                                                    layerName,
                                                    sqlSelect,
                                                    "fid",
                                                    "POINT",
                                                    "4326",
                                                    sr)
        # Persist to feature class
        out_name = 'a'+layerName[1:7]
        f_layer = arcpy.FeatureToPoint_management (layerName, out_name)
    else:
        for ptt, devID in devDict.iteritems():
            c1 = ''.join(['tag_id = ', str(devID)])
            layerName = 'q_' + str(ptt).zfill(5)
            sqlSelect = '{0} AND {1}{2}'.format(c0,c1,c2)
            q_layer = arcpy.MakeQueryLayer_management("Database Connections/wtg_gdb.sde",
                                                    layerName,
                                                    sqlSelect,
                                                    "fid",
                                                    "POINT",
                                                    "4326",
                                                    sr)
            out_name = 'a'+layerName[1:7]
            f_layer = arcpy.FeatureToPoint_management (layerName, out_name)
Пример #26
0
        number_rows="",
        number_columns="",
        corner_coord="14.6999999999993 13.9000000038595",
        labels="NO_LABELS",
        template=template,
        geometry_type="POLYGON")
    arcpy.AddField_management(outFishnet, 'UBID', 'LONG')
    arcpy.CalculateField_management(
        outFishnet, 'UBID', '!OID!',
        'PYTHON')  ## Added a uniqueID to the fishnet
    print('      0 - Fishnet created')

# Add GPW population estimates to fishnet
fishPoints = os.path.join(fishnetGDB, 'NGA_fishnet_points')
if not arcpy.Exists(fishPoints):
    arcpy.FeatureToPoint_management(outFishnet, fishPoints, "CENTROID")
    print('      0 - Turned fishnet into points')

# Extract raster cell values to fishnet points
for r in rList:
    gpwPoints = os.path.join(fishnetGDB, os.path.basename(r) + '_points')
    if not arcpy.Exists(gpwPoints):
        arcpy.gp.ExtractValuesToPoints_sa(fishPoints, r, gpwPoints, "", "ALL")
        print('      0 - Extracted raster values to point for ' +
              os.path.basename(r))

        arcpy.AddField_management(outFishnet, os.path.basename(r), 'DOUBLE')
        arcpy.MakeFeatureLayer_management(outFishnet,
                                          os.path.basename(r) + '_lyr')
        arcpy.AddJoin_management(
            os.path.basename(r) + '_lyr', 'UBID', gpwPoints, 'UBID')
Пример #27
0
# Process: Calculate Field
print "calculating cell areas"
arcpy.CalculateField_management(cell05cyl, "area",
                                "!SHAPE.AREA@SQUAREKILOMETERS!", "PYTHON_9.3",
                                "")

# Process: Project
print "projecting cells back to WGS84"
arcpy.Project_management(cell05cyl, cell05, wgs84)

# b) adding coordinates

# Process: Feature to Point
print "Finding cell centroids"
arcpy.FeatureToPoint_management(cell05, cell05cent, "INSIDE")

# Process: Add XY Coordinates
print "Adding latitude (POINT_Y) and longitude (POINT_X) to cell centroids"
arcpy.AddXY_management(cell05cent)

# c) getting water area

# Process: Intersect
print "Intersect cells with lakes"
list_intersect = [cell05, lakes]
arcpy.Intersect_analysis(list_intersect, celllakes, "ALL", "", "INPUT")

# Process: Project
print "projecting cells / lakes to world cylindrical equal area"
arcpy.Project_management(celllakes, celllakescyl, wcea)
Пример #28
0
        if lyr.name == "censusBlocksCut":
            arcpy.mapping.RemoveLayer(df, lyr)
    arcpy.Delete_management("censusBlocksCut.shp")

    #Calculate the allocated population for the smaller cut census blocks.
    arcpy.AddField_management("censusBlocksCutWpop.shp", "PopCut", "DOUBLE",
                              "", "", "", "", "", "")
    expression = '!%s!*(!AcresCut! / !AcresOrig!)' % popField
    arcpy.CalculateField_management("censusBlocksCutWpop.shp", "PopCut",
                                    expression, "PYTHON_9.3", "")

    #Step 8: Sum Population into Fishnet Squares w/ Spatial Join.

    #Convert all Census Blocks into Points so that they can be joined and summed into the cells w/o double counting.

    arcpy.FeatureToPoint_management("censusBlocksCutWpop.shp",
                                    "tempCensusPopPoints.shp", "INSIDE")

    ################################################################################################################

    #In here i need to add a section to calculate the area of the cut census block, and then
    #Add area to field map so that I can sum the census block area into the final grid.
    #      (this will give a better area for calculating pop density)

    ################################################################################################################

    # In order to merge and sum the population, you have to go through all of this field mapping first.
    in_file = "tempCensusPopPoints.shp"
    out_file = 'fishnetWithPopulationJoin'
    #Field mapping.
    fm = arcpy.FieldMap()
    fms = arcpy.FieldMappings()
env.workspace = "M:\Data\Global\DHS\Statcompiler_Processing\Shapefiles"

RECALCULATE_CENTROIDS = False

DHS_Regions = "DHS_Regions.shp"
DHS_Regions_Centroids = "DHS_Regions_Centroids.shp"
if arcpy.Exists(DHS_Regions_Centroids) and not RECALCULATE_CENTROIDS:
    print "Centroids file already exists - will not be recreated"
else:
    print "Calculate centroids %s"%DHS_Regions
    if arcpy.Exists(DHS_Regions_Centroids):
        print "\tDelete %s"%DHS_Regions_Centroids
        arcpy.Delete_management(DHS_Regions_Centroids)
    print "\tNow calculating centroids %s"%DHS_Regions
    arcpy.FeatureToPoint_management(DHS_Regions, DHS_Regions_Centroids, "INSIDE")

near_features_list = ["WWF_Priority_Places.shp", "CI_Hotspots_Areas.shp", "WDPA_INTpol2010.shp", "WDPA_NATpol2010.shp"]
near_fields_list = [["WWFNrName", "WWFNrkm"], ["CINrName", "CINrkm"], \
        ["WDPAIName","WDPAIkm"], ["WDPANName","WDPANkm"]]
for near_features, near_fields in zip(near_features_list, near_fields_list):
    print "Processing %s"%near_features
    print "\tDrop old near fields"
    dropFields = ["NEAR_FID", "NEAR_DIST"]
    arcpy.DeleteField_management(DHS_Regions_Centroids, dropFields)
    # After running the near script, the distance to the nearest zone is stored
    # in the "NEAR_DIST" and the FID of the near feature is stored in
    # "NEAR_FID". Need to rename these fields to CI or WWF as appropriate, and
    # also join the CI or WWF feature class to convert the NEAR_FID into
    # CI_Near_Name (or WWF) with the name of the nearest zone.
    print "\tRun near script"
Пример #30
0
                                           '', "SUBSET_SELECTION")

except:
    pass
arcpy.CopyFeatures_management(waterbody_lyr,
                              os.path.join(outfolder, "fourha.shp"))
fourha = os.path.join(outfolder, "fourha.shp")
arcpy.MakeFeatureLayer_management(fourha, os.path.join(outfolder,
                                                       "fourha.lyr"))
fourha_lyr = os.path.join(outfolder, "fourha.lyr")
arcpy.SelectLayerByAttribute_management(fourha_lyr, "NEW_SELECTION",
                                        '''"AreaSqKm">=0.1''')
arcpy.CopyFeatures_management(fourha_lyr, os.path.join(outfolder, "tenha.shp"))
tenha = os.path.join(outfolder, "tenha.shp")
arcpy.FeatureToPoint_management(tenha,
                                os.path.join(outfolder, "tenhacenter.shp"),
                                "INSIDE")
tenhacenter = os.path.join(outfolder, "tenhacenter.shp")

# Make shapefiles of junctions that intersect one hectare and ten hectare lakes.
arcpy.MakeFeatureLayer_management(junction,
                                  os.path.join(outfolder, "junction.lyr"))
junction_lyr = os.path.join(outfolder, "junction.lyr")
arcpy.SelectLayerByLocation_management(junction_lyr, "INTERSECT", fourha, '',
                                       "NEW_SELECTION")
arcpy.CopyFeatures_management(junction_lyr,
                              os.path.join(outfolder, "fourhajunction.shp"))
fourhajunction = os.path.join(outfolder, "fourhajunction.shp")
arcpy.SelectLayerByLocation_management(junction_lyr, "INTERSECT", tenha, '',
                                       "NEW_SELECTION")
arcpy.CopyFeatures_management(junction_lyr,