I'm creating a model, using ArcGIS ModelBuilder, and want to use SelectRandombyPercent from Randomly subsetting X% of selected features using ArcPy? to randomly select points from a feature class. The selected features will be an intermediate data set for use as a source for a Network Analyst OD Cost Matrix layer destinations. The script works perfectly from the Python shell in ArcMap.
I've added a Script in my toolbox utilizing the script from the shell. When executed, I'm prompted for parameters, get the tool executing message, and get a Succeeded (green check) result. However it doesn't actually make a selection.
What do I need to modify to have the script (run in ModelBuilder) make a selection that I can use?
It appears that the major problem with moving from Shell to Script/Tool was the function definition line (probably a rookie mistake, but definitely not easily discoverable).
FINAL WORKING CODE (verified in both toolbox and ModelBuilder):
import arcpy
import random
inLayer = arcpy.GetParameterAsText(0)
inPercent = arcpy.GetParameterAsText(1)
arcpy.AddMessage(inPercent+"% random sample")
if float(inPercent) > 100:
arcpy.AddError ("Error: Percent is greater than 100")
sys.exit()
if float(inPercent) <= 0:
arcpy.AddError ("Error: Percent is less than zero")
sys.exit()
fc = arcpy.Describe (inLayer).catalogPath
featureCount = float (arcpy.GetCount_management (fc).getOutput (0))
count = int (featureCount * float (inPercent) / float (100))
if not count:
arcpy.SelectLayerByAttribute_management (inLayer, "CLEAR_SELECTION")
oids = [oid for oid, in arcpy.da.SearchCursor (fc, "OID@")]
oidFldName = arcpy.Describe (inLayer).OIDFieldName
delimOidFld = arcpy.AddFieldDelimiters (inLayer, oidFldName)
randOids = random.sample (oids, count)
oidsStr = ", ".join (map (str, randOids))
sql = "{0} IN ({1})".format (delimOidFld, oidsStr)
arcpy.SelectLayerByAttribute_management (inLayer, "", sql)
arcpy.MakeFeatureLayer_management(inLayer,outLayer)
I made five major changes from the source:
- Deletion of the DEF line.
- Addition of FLOAT for the percent comparison in the IF lines.
- Addition of message with the calculated percentage (for quick reference).
- Addition of an error message and function stop in the IF lines.
- Addition of MakeFeatureLayer parameter and output.