· 6 years ago · Aug 14, 2019, 07:56 PM
1import arcpy, os, sys, shutil
2
3
4class Toolbox(object):
5 def __init__(self):
6 """Define the toolbox (the name of the toolbox is the name of the .pyt file)."""
7 self.label = "polyNTool"
8 self.alias = ""
9
10 # List of tool classes associated with this toolbox
11 self.tools = [polyNTool]
12
13
14def polyProcess(src, target):
15 user_profile_path = os.environ['USERPROFILE']
16 gdb = r"{}/AppData/Local/Temp/PolyChecker/PolyCheck.gdb".format(user_profile_path)
17
18 # GDB already exists, delete it
19
20 # if arcpy.Exists(gdb):
21 # shutil.rmtree(r"{}/AppData/Local/Temp/PolyChecker".format(user_profile_path))
22
23 # Create fresh GDB path
24 # os.makedirs(os.path.dirname(gdb))
25
26 # Create GDB
27 if not arcpy.Exists(gdb):
28 if not arcpy.Exists(os.path.dirname(gdb)):
29 os.makedirs(os.path.dirname(gdb))
30 arcpy.CreateFileGDB_management(os.path.dirname(gdb), os.path.basename(gdb))
31
32 arcpy.AddMessage('xxx' + str(arcpy.Exists(gdb)) + ' ' + os.path.dirname(gdb))
33 arcpy.env.workspace = gdb
34 arcpy.env.overwriteOutput = True
35
36 # Script arguments
37 MapUnitPolys = src
38 if MapUnitPolys == '#' or not MapUnitPolys:
39 MapUnitPolys = "MapUnitPolys" # provide a default value if unspecified
40
41 MapUnitPolys_CopyFeatures = target
42
43 # Set Geoprocessing environments
44 MapUnitPolys = MapUnitPolys
45
46 # Validate that all Polygons have a map unit
47
48 invalid_polygon_found = False
49
50 with arcpy.da.SearchCursor(MapUnitPolys, ['SHAPE@', 'MapUnit', 'OBJECTID']) as cursor:
51 for row in cursor:
52 # arcpy.AddMessage(str(row[1]))
53 # Does this Polygon have a map unit
54 if row[1] == "" or row[1] == "<Null>" or row[1] is None or row[1] is 0:
55 invalid_polygon_found = True
56 arcpy.AddMessage('Polygon OBJECT ID:{} is missing map unit... exiting.'.format(row[2]))
57
58 # Invalid polygons were found, terminate
59 if (invalid_polygon_found):
60 sys.exit(1)
61
62 Polygon_Neighbors = "{}/polytest".format(gdb)
63 Polygon_Neighbors = r"POLYTABLE"
64 PolygonNeighbor_TableSelect = "{}/PolygonNeighbor_TableSelect".format(gdb)
65
66 inFeatures_lyr = "{}/inFeatures_1yr".format(gdb)
67 inFeatures_lyr = r"inFeatures_1yr"
68
69 # Process: Polygon Neighbors
70 arcpy.PolygonNeighbors_analysis(MapUnitPolys, Polygon_Neighbors, "OBJECTID;MapUnit", "NO_AREA_OVERLAP",
71 "BOTH_SIDES",
72 "", "METERS", "SQUARE_METERS")
73
74 mxd = arcpy.mapping.MapDocument("CURRENT")
75
76 df = arcpy.mapping.ListDataFrames(mxd)[0]
77 arcpy.AddMessage('current ' + mxd.title + ' ' + df.name + ' ' + Polygon_Neighbors)
78 pn = arcpy.mapping.TableView(Polygon_Neighbors)
79 arcpy.mapping.AddTableView(df, pn)
80 # for lyr in arcpy.mapping.ListLayers(mxd):
81 # arcpy.AddMessage('Map Layer: '+lyr.name)
82
83 # Process: Select Layer By Attribute
84 arcpy.SelectLayerByAttribute_management(Polygon_Neighbors, "NEW_SELECTION", "src_MapUnit = nbr_MapUnit")
85
86 # Process: Table Select
87 arcpy.TableSelect_analysis(Polygon_Neighbors, PolygonNeighbor_TableSelect, "src_MapUnit = nbr_MapUnit")
88
89 arcpy.GetCount_management(PolygonNeighbor_TableSelect)
90
91 arcpy.AddMessage(arcpy.GetMessages())
92
93 if int(arcpy.GetCount_management(PolygonNeighbor_TableSelect)[0]) > 0:
94 arcpy.MakeFeatureLayer_management(MapUnitPolys, inFeatures_lyr)
95 else:
96 print ("done")
97
98 # Process: Add Join
99 arcpy.AddJoin_management(inFeatures_lyr, "OBJECTID", PolygonNeighbor_TableSelect, "src_OBJECTID", "KEEP_COMMON")
100
101 # Process: Copy Features
102 arcpy.CopyFeatures_management(inFeatures_lyr, MapUnitPolys_CopyFeatures, "", "0", "0", "0")
103
104 # Add to Map
105 ws = arcpy.env.workspace
106 lyrNew = ws + "/" + MapUnitPolys_CopyFeatures
107 arcpy.AddMessage('Copy layer ' + df.name + ' Path ' + lyrNew)
108 addLayer = arcpy.mapping.Layer(lyrNew)
109 arcpy.mapping.AddLayer(df, addLayer)
110
111 # Process: Remove Join
112 arcpy.RemoveJoin_management(inFeatures_lyr, "")
113
114 # Execute Delete
115 arcpy.Delete_management(PolygonNeighbor_TableSelect)
116 arcpy.Delete_management(Polygon_Neighbors)
117
118 arcpy.AddMessage('All done! Check Polygons')
119
120 return
121
122
123class polyNTool(object):
124 def __init__(self):
125 """Define the tool (tool name is the name of the class)."""
126 self.label = "polyNTool"
127 self.description = ""
128 self.canRunInBackground = False
129
130 def getParameterInfo(self):
131 """Define parameter definitions"""
132
133 param0 = arcpy.Parameter(
134 displayName="Source Layer",
135 name="sourceLayer",
136 datatype="Feature Class",
137 parameterType="Required",
138 direction="Input")
139
140 param1 = arcpy.Parameter(
141 displayName="Target Layer",
142 name="targetLayer",
143 datatype="String",
144 parameterType="Required",
145 direction="Input")
146
147 params = [param0, param1]
148 return params
149
150 def isLicensed(self):
151 """Set whether tool is licensed to execute."""
152 return True
153
154 def updateParameters(self, parameters):
155 """Modify the values and properties of parameters before internal
156 validation is performed. This method is called whenever a parameter
157 has been changed."""
158 return
159
160 def updateMessages(self, parameters):
161 """Modify the messages created by internal validation for each tool
162 parameter. This method is called after internal validation."""
163 return
164
165 def execute(self, parameters, messages):
166 """The source code of the tool."""
167 arcpy.ResetEnvironments()
168 arcpy.env.overwriteOutput = True
169 src = parameters[0].valueAsText
170
171 target = parameters[1].valueAsText
172 arcpy.AddMessage('params ' + src + ' ' + target)
173 # arcpy.env.workspace = cws
174 status = True
175
176 if arcpy.Exists(src):
177 ps = "Found WS " + src
178 else:
179 ps = "Missing WS" + src
180 status = False
181
182 if status == False:
183 arcpy.AddMessage(ps)
184 try:
185 sys.exit(0)
186 except SystemExit:
187 pass
188 else:
189 arcpy.AddMessage("Validated input ...")
190 polyProcess(src, target)
191
192 return