I have this code:
import arcpy
# Get the active map in the current project
active_map = arcpy.mp.ArcGISProject("CURRENT").activeMap
# Get the currently selected layer in tcrhe Contents pane
current_layer = active_map.listLayers()[0] # Assumes the first layer; adjust as needed
# Define the desired new name
new_layer_name = "HZ004"
# Check if the layer was found
if current_layer:
# Update the layer's name in the Contents pane
current_layer.name = new_layer_name
# Select and unselect the layer to trigger a refresh in the TOC
current_layer.visible = False
current_layer.visible = True
print(f"The layer name in the Contents pane has been successfully changed to {new_layer_name}.")
else:
print(f"No layer found in the project.")
# begin of required paramters
# name of the Lot layer that will be sampled
Polygon_Layer = "HZ004"
# sampling percentage
Sampling_Percent = 0.04
# the cell width and height for fishnet
# determine the size of each cell
cellSizeWidth = '25'
cellSizeHeight = '25'
#task Id and Lot Parameter
taskId = "NPA_CL_SY01_001"
lotNum = "LOT01"
Fishnet_Layer = "Fishnet004"
labels = 'NO_LABELS'
# end of required paramters
#begin of optional parameter - no need to change
# Number of rows and columns for fishnet if we don't determin width and height of cell
numRows = '0'
numColumns = '0'
# Create a point label feature class for the fishnet
#labels = 'NO_LABELS'
# name of fishnet layer
# Fishnet_Layer = "Fishnet004"
# end of optional parameter
import arcpy
# Get the current project
project = arcpy.mp.ArcGISProject("CURRENT")
# Get a list of all the layers in the project
layers = []
for map in project.listMaps():
layers.extend(map.listLayers())
# Find the feature class you want to use as the clip feature
clip_feature = None
for layer in layers:
if layer.isFeatureLayer:
if layer.name == Polygon_Layer :
clip_feature = layer
break
extent = project.activeView.camera.getExtent()
# fishnet options and creation
# Set the latitude and longitude coordinates for fishnet
latitude = extent.XMin
longitude = extent.YMin
maxLongitude = extent.YMax
maxLatitude = extent.XMax
originCoordinate = "%f %f" % (latitude,longitude)
yAxisCoordinate = "%f %f" % (latitude,maxLongitude)
conrnerCoordinate = "%f %f" % (maxLatitude,maxLongitude)
arcpy.CreateFishnet_management(Fishnet_Layer, originCoordinate,yAxisCoordinate , cellSizeWidth, cellSizeHeight, numRows, numColumns, conrnerCoordinate, labels, '', 'POLYGON')
arcpy.management.DefineProjection(Fishnet_Layer, arcpy.SpatialReference(arcpy.mp.ArcGISProject("CURRENT").activeMap.spatialReference.name))
# end of fishnet creation
arcpy.management.SelectLayerByLocation(Fishnet_Layer, "INTERSECT", Polygon_Layer, None, "NEW_SELECTION", "NOT_INVERT")
arcpy.management.AddField(Fishnet_Layer, "Box_Number", "TEXT", None, None, 15, "Box_Number", "NULLABLE", "NON_REQUIRED", '')
arcpy.management.CalculateField(Fishnet_Layer, "Box_Number", "SequentialNumber()", "PYTHON3", """# Calculates a sequential number
# More calculator examples at esriurl.com/CalculatorExamples
rec=0
def SequentialNumber():
global rec
pStart = 1
pInterval = 1
if (rec == 0):
rec = pStart
else:
rec = rec + pInterval
return rec""", "TEXT", "NO_ENFORCE_DOMAINS")
# Get the full path of the clip feature
clip_feature_path = clip_feature.dataSource
# Set the output feature class
output_fc = "Sampling_Polygon"
# Perform the clip
arcpy.analysis.Clip(Fishnet_Layer, clip_feature_path, output_fc)
import arcpy
import random
import string
# Set the workspace to the current workspace
arcpy.env.workspace = arcpy.mp.ArcGISProject("CURRENT").defaultGeodatabase
# Generate a random domain name starting with "Random_Status"
domain_name = "Sampling_Status_" + ''.join(random.choices(string.ascii_uppercase + string.digits, k=3))
# Check if the domain already exists and delete it if it does
if arcpy.Exists(domain_name):
arcpy.management.DeleteDomain(arcpy.env.workspace, domain_name)
# Create the domain
arcpy.management.CreateDomain(arcpy.env.workspace, domain_name, "Sampling Domain Status", "TEXT", "CODED")
arcpy.management.AddCodedValueToDomain(arcpy.env.workspace, domain_name, "Random Pending", "Random Pending")
arcpy.management.AddCodedValueToDomain(arcpy.env.workspace, domain_name, "Random Passed", "Random Passed")
arcpy.management.AddCodedValueToDomain(arcpy.env.workspace, domain_name, "Random Failed", "Random Failed")
arcpy.management.AddCodedValueToDomain(arcpy.env.workspace, domain_name, "Random Replaced", "Random Replaced")
arcpy.management.AddCodedValueToDomain(arcpy.env.workspace, domain_name, "Targeted Pending", "Targeted Pending")
arcpy.management.AddCodedValueToDomain(arcpy.env.workspace, domain_name, "Targeted Passed", "Targeted Passed")
arcpy.management.AddCodedValueToDomain(arcpy.env.workspace, domain_name, "Targeted Failed", "Targeted Failed")
# Get the "Sampling_Polygon" feature layer
sampling_polygon_layer = arcpy.mp.ArcGISProject("CURRENT").listMaps()[0].listLayers("Sampling_Polygon")[0]
# Check if the "Random_Status" field already exists and delete it if it does
if "Sampling_Status" in [f.name for f in arcpy.ListFields(sampling_polygon_layer)]:
arcpy.management.DeleteField(sampling_polygon_layer, "Sampling_Status")
# Add the "Random_Status" field to the layer
arcpy.management.AddField(sampling_polygon_layer, "Sampling_Status", "TEXT", field_length=50)
# Assign the random domain to the "Random_Status" field in the layer
arcpy.management.AssignDomainToField(sampling_polygon_layer, "Sampling_Status", domain_name)
arcpy.management.AddField("Sampling_Polygon", "X", "TEXT", None, None, None, "X", "NULLABLE", "NON_REQUIRED", '')
arcpy.management.AddField("Sampling_Polygon", "Y", "TEXT", None, None, None, "Y", "NULLABLE", "NON_REQUIRED", '')
arcpy.management.CalculateGeometryAttributes("Sampling_Polygon", "X INSIDE_X;Y INSIDE_Y", '', '', None, "SAME_AS_INPUT")
arcpy.management.AddField("Sampling_Polygon", "TaskID", "TEXT", None, None, None, "TaskID", "NULLABLE", "NON_REQUIRED", '')
# Use an update cursor to update the field
with arcpy.da.UpdateCursor("Sampling_Polygon", "TaskID") as cursor:
for row in cursor:
row[0] = taskId
cursor.updateRow(row)
# Clean up the cursor
del cursor
arcpy.management.AddField("Sampling_Polygon", "Lot_Number", "TEXT", None, None, None, "Lot_Number", "NULLABLE", "NON_REQUIRED", '')
# Use an update cursor to update the field
with arcpy.da.UpdateCursor("Sampling_Polygon", "Lot_Number") as cursor:
for row in cursor:
row[0] = lotNum
cursor.updateRow(row)
# Clean up the cursor
del cursor
import arcpy
import random
# Get the "Sampling_Polygon" feature layer
sampling_polygon_layer = arcpy.mp.ArcGISProject("CURRENT").listMaps()[0].listLayers("Sampling_Polygon")[0]
# Define the feature layer and field names
feature_layer = "Sampling_Polygon"
area_field = "SHAPE@AREA"
oid_field = arcpy.Describe(feature_layer).OIDFieldName
# Calculate the area threshold for selecting records
total_area = sum(row[0] for row in arcpy.da.SearchCursor(feature_layer, area_field))
area_threshold = total_area * Sampling_Percent # Sampling_Percent% of the total area
# Select a random box to start with
selected_boxes = []
selected_area = 0
with arcpy.da.SearchCursor(feature_layer, [area_field, oid_field, "SHAPE@"]) as cursor:
row = random.choice([row for row in cursor])
selected_boxes.append((row[1], row[2]))
selected_area += row[0]
# Determine the minimum distance between selected boxes
min_distance = max([box[1].length / 100 for box in selected_boxes])
# Exclude boxes that are within the minimum distance from the selected boxes
excluded_boxes = set()
while selected_area < area_threshold:
# Get the distance between the selected boxes and all other boxes
distances = {}
with arcpy.da.SearchCursor(feature_layer, [oid_field, "SHAPE@"]) as cursor:
for row in cursor:
if row[0] not in excluded_boxes:
distance = min([box[1].distanceTo(row[1]) for box in selected_boxes])
distances[row[0]] = distance
# Select the box with the maximum distance from the selected boxes
if not distances:
break
max_distance_oid = max(distances, key=distances.get)
if distances[max_distance_oid] >= min_distance:
excluded_boxes.add(max_distance_oid)
with arcpy.da.SearchCursor(feature_layer, [area_field, oid_field, "SHAPE@"], "{0} = {1}".format(oid_field, max_distance_oid)) as cursor:
row = next(cursor)
selected_boxes.append((row[1], row[2]))
selected_area += row[0]
# Update the minimum distance between selected boxes
min_distance = max([box[1].length / 100 for box in selected_boxes])
else:
# If no box can be selected, reduce the min_distance and try again
min_distance *= 0.9
# Select the randomly selected boxes by their ObjectIDs
selected_oids = [box[0] for box in selected_boxes]
where_clause = "{0} IN ({1})".format(oid_field, ','.join(str(oid) for oid in selected_oids))
arcpy.SelectLayerByAttribute_management(feature_layer, "NEW_SELECTION", where_clause)
arcpy.management.CalculateField("Sampling_Polygon", "Sampling_Status", "'Random Pending'", "PYTHON3", "", "TEXT", "NO_ENFORCE_DOMAINS")
# Set the workspace to the current workspace
arcpy.env.workspace = arcpy.mp.ArcGISProject("CURRENT").defaultGeodatabase
# Delete the "Fishnet_Sampling_Polygon" layer if it exists
if arcpy.Exists(Fishnet_Layer):
arcpy.management.Delete(Fishnet_Layer)
# Delete the "Exported_Polygon" layer if it exists
if arcpy.Exists(Polygon_Layer 😞
arcpy.management.Delete(Polygon_Layer )
import arcpy
# Get the active map in the current project
active_map = arcpy.mp.ArcGISProject("CURRENT").activeMap
# Get the currently selected layer in the Contents pane
current_layer = active_map.listLayers()[0] # Assumes the first layer; adjust as needed
# Check if a layer is selected
if current_layer:
# Get the layer name
polygon_layer_name = current_layer.name
# Set the output point feature class name
output_points_fc = f"{polygon_layer_name}_Vertices_Points"
# Use the Feature Vertices to Points tool
arcpy.management.FeatureVerticesToPoints(polygon_layer_name, output_points_fc, "ALL")
print(f"Points have been created from the vertices of the {polygon_layer_name} layer.")
else:
print("No layer found in the project.")
and its working when I run it in python window.
can any one help me to craete a tool box based on this code