POST
|
Apologies, I forgot to post my finished script. Here it is for anyone interested. It basically allows an unexperienced ArcGIS user to select by attributes and returns the number of features meeting the specified criteria. It was a fun exercise, but I kind of doubt it will benefit any of you that much. import arcpy
import pythonaddins
class ButtonClass4(object):
"""Implementation for Totals_addin.button (Button)"""
def __init__(self):
self.enabled = True
self.checked = False
def onClick(self):
desc = arcpy.Describe(fc)
if desc.shapeType == "Point":
arcpy.MakeFeatureLayer_management(fc, "pointfeats", '"' + attName + '"' + ' = ' + "'" + valName + "'")
count = arcpy.GetCount_management("pointfeats")
print str(count) + " FEATURES WITH " + str(attName) + " EQUAL TO " + (str(valName)).upper()
arcpy.Delete_management("pointfeats")
elif desc.shapeType == "Polyline":
arcpy.MakeFeatureLayer_management(fc, "linefeats", '"' + attName + '"' + ' = ' + "'" + valName + "'")
lengths = []
curs = arcpy.da.SearchCursor("linefeats", "Shape_Length")
for cur in curs:
lengths.append(cur)
floatLengths = [float(e[0]) for e in lengths]
totalLength = sum(floatLengths)
print str(round(totalLength,2)) + " TOTAL LINEAR FEET"
arcpy.Delete_management("linefeats")
elif desc.shapeType == "Polygon":
arcpy.MakeFeatureLayer_management(fc, "polygonfeats", '"' + attName + '"' + ' = ' + "'" + valName + "'")
areas = []
curs = arcpy.da.SearchCursor("polygonfeats", "SHAPE_Area")
for cur in curs:
areas.append(cur)
floatAreas = [float(e[0]) for e in areas]
totalArea = sum(floatAreas)
print str(round(totalArea,2)) + " TOTAL SQUARE FEET"
arcpy.Delete_management("polygonfeats")
else:
print "Calculation can not be performed"
class ComboBoxClass1(object):
"""Implementation for Totals_addin.combobox (ComboBox)"""
def __init__(self):
self.editable = True
self.enabled = True
self.dropdownWidth = 'WWWWWWWWWWWW'
self.width = 'WWWWWWWWWWWW'
def onFocus(self, focused):
if focused:
self.mxd = arcpy.mapping.MapDocument('current')
layers = arcpy.mapping.ListLayers(self.mxd)
self.items = []
for layer in layers:
self.items.append(layer.name)
def onSelChange(self, selection):
global fc
fc = arcpy.mapping.ListLayers(self.mxd, selection)[0]
class ComboBoxClass2(object):
"""Implementation for Totals_addin.combobox_1 (ComboBox)"""
def __init__(self):
self.editable = True
self.enabled = True
self.dropdownWidth = 'WWWWWWWWWWWW'
self.width = 'WWWWWWWWWWWW'
def onFocus(self, focused):
if focused:
fields = arcpy.ListFields(fc)
self.items = []
for field in fields:
self.items.append(field.name)
def onSelChange(self, selection):
global attName
global attribute
attribute = arcpy.ListFields(fc, selection)[0]
attName = attribute.name
class ComboBoxClass3(object):
"""Implementation for Totals_addin.combobox_2 (ComboBox)"""
def __init__(self):
self.editable = True
self.enabled = True
self.dropdownWidth = 'WWWWWWWWWWWW'
self.width = 'WWWWWWWWWWWW'
def onFocus(self, focused):
if focused:
values = [row[0] for row in arcpy.da.SearchCursor(fc, attName)]
uniqueValues = set(values)
self.items = []
for uniqueValue in uniqueValues:
self.items.append(uniqueValue)
def onSelChange(self, selection):
global valName
val = (self.items, selection)[1]
valName = str(val)
... View more
04-03-2013
04:09 AM
|
0
|
0
|
276
|
POST
|
For anyone interested, I figured out what was going wrong. When declaring a global variable in the second combo box, I declared the object as the variable, rather than the name of the object. Then, when I tried passing that variable into the next combo box, it failed, since it needed a string input. I'm away from my work computer now, but I will post my code tomorrow. Cheers!
... View more
03-20-2013
02:44 PM
|
0
|
0
|
276
|
POST
|
Hello all- I'm working on a custom toolbar that will contain three combo boxes and one button. It will basically allow the user to select the layer (first combo box), the attribute (second combo box), and a specific value (third combo box), and return the total length or area of the features in question (button). I've gotten the first two combo boxes working: the first one populates all the layers in the current mxd, and the second populates all the fields in the first combo box's selection. Where I'm running into trouble is populating the third combo box with all unique values found in the second combo box's selection. I've experimented with using a Search Cursor to add values to a list, then create a set of that list to pare it down to unique values. Below is my working code, I would greatly appreciate any and all feedback. Please disregard the button object, as I have not begun working on it. import arcpy
import pythonaddins
class ButtonClass4(object):
"""Implementation for Totals_addin.button (Button)"""
def __init__(self):
self.enabled = True
self.checked = False
def onClick(self):
pass
class ComboBoxClass1(object):
"""Implementation for Totals_addin.combobox (ComboBox)"""
def __init__(self):
self.editable = True
self.enabled = True
self.dropdownWidth = 'WWWWWWWWWWWW'
self.width = 'WWWWWWWWWWWW'
def onFocus(self, focused):
if focused:
self.mxd = arcpy.mapping.MapDocument('current')
layers = arcpy.mapping.ListLayers(self.mxd)
self.items = []
for layer in layers:
self.items.append(layer.name)
def onSelChange(self, selection):
global fc
fc = arcpy.mapping.ListLayers(self.mxd, selection)[0]
class ComboBoxClass2(object):
"""Implementation for Totals_addin.combobox_1 (ComboBox)"""
def __init__(self):
self.editable = True
self.enabled = True
self.dropdownWidth = 'WWWWWWWWWWWW'
self.width = 'WWWWWWWWWWWW'
def onFocus(self, focused):
if focused:
fields = arcpy.ListFields(fc)
self.items = []
for field in fields:
self.items.append(field.name)
def onSelChange(self, selection):
global attribute
attribute = arcpy.ListFields(self.items, selection)[0]
class ComboBoxClass3(object):
"""Implementation for Totals_addin.combobox_2 (ComboBox)"""
def __init__(self):
self.editable = False
self.enabled = True
self.dropdownWidth = 'WWWWWWWWWWWW'
self.width = 'WWWWWWWWWWWW'
def onFocus(self, focused):
if focused:
values = []
val = arcpy.da.SearchCursor(fc, attribute)
for v in val:
values.append(v)
value_set = set(values)
for value in value_set:
self.items.append(value)
del val
def onSelChange(self, selection):
global value
value = arcpy.ListValues(self.values, selection)[0]
Thanks!
... View more
03-20-2013
08:16 AM
|
0
|
2
|
2585
|
POST
|
I got it working! For anyone interested, the following script will take a point feature class representing sinks in a geometric network, select each one at a time, trace upstream from each, and update a field in an upstream feature class with a unique ID of the sink it traces to. Cheers! import arcpy
arcpy.env.overwriteOutput=True
arcpy.env.workspace = "D:\FacID_Python\SO_CSS_Master_9x_GDB.gdb"
sinkFeatures = "D:\\FacID_Python\\SO_CSS_Master_9x_GDB.gdb\\SO_CSS_Master\\SManhole_Master"
dCatchBasin = "D:\\FacID_Python\\SO_CSS_Master_9x_GDB.gdb\\SO_CSS_Master\\DCatchBasin_Master"
geometricNetwork = "D:\\FacID_Python\\SO_CSS_Master_9x_GDB.gdb\\SO_CSS_Master\\SO_CSS_Master_Net"
mxd = arcpy.mapping.MapDocument("D:\FacID_Python\Working.mxd")
sinkList = []
rows = arcpy.SearchCursor(sinkFeatures)
row = rows.next()
while row:
featureID = row.OBJECTID
if featureID not in sinkList:
sinkList.append(featureID)
row = rows.next()
del rows
print sinkList
sinkCount = len(sinkList)
for each in range(sinkCount):
print "%s of %s" % (each +1, sinkCount)
sinkWhere = '"OBJECTID" = %s' % sinkList[each]
if arcpy.Exists("TempSinkLayer"):
arcpy.Delete_management("TempSinkLayer")
arcpy.MakeFeatureLayer_management(sinkFeatures, "TempSinkLayer", sinkWhere)
cursor = arcpy.SearchCursor("TempSinkLayer")
sink = cursor.next()
while sink:
facID = sink.getValue("FACILITYID")
print facID
sink = cursor.next()
del sink
del cursor
try:
outGroupLayer = str("Trace" + facID)
arcpy.SetFlowDirection_management(geometricNetwork, "WITH_DIGITIZED_DIRECTION")
arcpy.TraceGeometricNetwork_management(geometricNetwork, outGroupLayer, "TempSinkLayer", "TRACE_UPSTREAM", "", "", "", "", "", "", "" ,"", "", "", "", "", "", "")
except:
print "Can't trace"
try:
dCatchLayer = str(facID + "dCatch")
arcpy.SelectData_management(outGroupLayer, "DCatchBasin_Master")
arcpy.MakeFeatureLayer_management("DCatchBasin_Master", dCatchLayer)
result = int(arcpy.GetCount_management(dCatchLayer).getOutput(0))
print result
dCatchs = arcpy.UpdateCursor(dCatchLayer)
dCatch = dCatchs.next()
fieldID = "DnComboFacID"
while dCatch:
dCatch.setValue(fieldID, facID)
dCatchs.updateRow(dCatch)
dCatch = dCatchs.next()
del dCatch
del dCatchs
arcpy.Delete_management(dCatchLayer)
arcpy.Delete_management("DCatchBasin_Master")
arcpy.SelectLayerByAttribute_management("DCatchBasin_Master", "CLEAR_SELECTION")
##for df in arcpy.mapping.ListDataFrames(mxd):
##for lyr in arcpy.mapping.ListLayers(mxd, "", df):
##if lyr.name == "Trace" + facID:
##arcpy.mapping.RemoveLayer(df, lyr)
##else:
##pass
except:
print "not working"
PS- the code works within PyScripter, but for some reason gets wonky results when run within ArcMap.
... View more
11-07-2012
09:40 AM
|
0
|
0
|
401
|
POST
|
I've built a lot upon the above suggestions and currently have a script that will: 1. Add all sink features to a list. 2. Use the list to cycle through the features and select them one at a time. 3. Create feature layer from this selection. 4. Use the feature layer as a sink to trace the geometric network. 5. Update the selected (traced) features in a networked feature class with the FacilityID of the first selected sink. I need for the script to eliminate the selection and start fresh with the next feature in line, trace from there, and update all the upstream selected features. However, as of now it will not produce the intended results. What's confusing is I get different messages/results every time I run it. Could anyone please take a look and see if I'm missing something obvious? Thanks, John import arcpy
arcpy.env.overwriteOutput=True
arcpy.env.workspace = "D:\FacID_Python\SO_CSS_Master_9x_GDB.gdb"
sinkFeatures = "D:\\FacID_Python\\SO_CSS_Master_9x_GDB.gdb\\SO_CSS_Master\\Export_Output"
dCatchBasin = "D:\\FacID_Python\\SO_CSS_Master_9x_GDB.gdb\\SO_CSS_Master\\DCatchBasin_Master"
geometricNetwork = "D:\\FacID_Python\\SO_CSS_Master_9x_GDB.gdb\\SO_CSS_Master\\SO_CSS_Master_Net"
mxd = arcpy.mapping.MapDocument("D:\FacID_Python\Working.mxd")
sinkList = []
rows = arcpy.SearchCursor(sinkFeatures)
row = rows.next()
while row:
featureID = row.OBJECTID
if featureID not in sinkList:
sinkList.append(featureID)
row = rows.next()
del rows
print sinkList
sinkCount = len(sinkList)
for each in range(sinkCount):
print "%s of %s" % (each +1, sinkCount)
sinkWhere = '"OBJECTID" = %s' % sinkList[each]
if arcpy.Exists("TempSinkLayer"):
arcpy.Delete_management("TempSinkLayer")
arcpy.MakeFeatureLayer_management(sinkFeatures, "TempSinkLayer", sinkWhere)
cursor = arcpy.SearchCursor("TempSinkLayer")
sink = cursor.next()
while sink:
facID = sink.getValue("FACILITYID")
print facID
sink = cursor.next()
del sink
del cursor
try:
outGroupLayer = "Trace" + facID
arcpy.SetFlowDirection_management(geometricNetwork, "WITH_DIGITIZED_DIRECTION")
arcpy.TraceGeometricNetwork_management(geometricNetwork, outGroupLayer, "TempSinkLayer", "TRACE_UPSTREAM", "", "", "", "", "", "", "" ,"", "", "", "", "", "", "")
except:
print "Can't trace"
try:
dCatchLayer = facID + "dCatch"
arcpy.SelectData_management(outGroupLayer, "DCatchBasin_Master")
arcpy.MakeFeatureLayer_management("DCatchBasin_Master", dCatchLayer)
result = int(arcpy.GetCount_management(dCatchLayer).getOutput(0))
print result
except:
print "can't make feature layer or access selection"
try:
dCatchs = arcpy.UpdateCursor(dCatchLayer)
dCatch = dCatchs.next()
fieldID = "DnComboFacID"
while dCatch:
dCatch.setValue(fieldID, facID)
dCatchs.updateRow(dCatch)
dCatch = dCatchs.next()
del dCatch
del dCatchs
except:
print "can't update rows"
try:
arcpy.Delete_management(dCatchLayer)
except:
print "can't delete the feature layer"
try:
arcpy.SelectLayerByAttribute_management("DCatchBasin_Master", "CLEAR_SELECTION")
for df in arcpy.mapping.ListDataFrames(mxd):
for lyr in arcpy.mapping.ListLayers(mxd, "", df):
if lyr.name == "Trace" + facID:
arcpy.mapping.RemoveLayer(df, lyr)
else:
pass
except:
print "can't delete the group layer"
... View more
11-06-2012
10:41 AM
|
0
|
0
|
401
|
POST
|
Thanks for the reply! I think this will work. After writing more script, I'm coming across another issue. I'm basically performing a TRACE_UPSTREAM on each feature in the feature class. That will produce a selection set of upstream structures and conveyances. I want to take the unique FacilityID from the selected sink and update the selected upstream structures with that value. I have set up an update cursor to update the records, but I'm getting an error when trying to get the value from the selected sink. I guess once the feature is in a list I can no longer use the getValue command. So should I store this value in the list as well? Thanks again for any input.
... View more
11-02-2012
07:45 AM
|
0
|
0
|
401
|
POST
|
Hello all- I'm having a tough time getting started on what should be a relatively simple script. I have a feature class consisting of sinks in a geometric network. I need my script to initially select the first record, perform some functions, finish those functions, then move to the next record, and repeat until the end. I've set up a search cursor to cycle through the records, but my problem is making a feature layer from the "current" record in the search cursor. Any input on how I could do this? Thanks, John
... View more
11-02-2012
04:36 AM
|
0
|
5
|
3017
|
POST
|
Never mind! It works great! Thanks so much for your help!
... View more
08-01-2012
09:50 AM
|
0
|
0
|
378
|
POST
|
Thanks for the fast response! I made the corrections you suggested and got the following error/message: Executing: Script P:\xxxxxxxxx Start Time: Wed Aug 01 13:28:06 2012 Running script Script... Traceback (most recent call last): File "P:\2012_Projects\12004_Chatt_ST_DBCC\Toolboxes\PhotoExists2.py", line 13, in <module> if os.path.exists(photo_path): File "C:\Python27\ArcGIS10.1\Lib\genericpath.py", line 18, in exists os.stat(path) TypeError: coercing to Unicode: need string or buffer, NoneType found Failed to execute (Script). Failed at Wed Aug 01 13:28:31 2012 (Elapsed Time: 25.00 seconds) Any idea what's wrong?
... View more
08-01-2012
09:34 AM
|
0
|
0
|
378
|
POST
|
Thank you for the suggestions. I've built upon one, creating a standalone script that I've added to a custom toolbox. The body of the script is included below. This script will run and complete with no errors, but it won't produce the result I'm going for. The field "PhotoExists" still only contain null values. Any thoughts? And thanks again! import arcpy
import os
featureClass = arcpy.GetParameterAsText(0)
photo_field = "PhotoHotlink"
results_field = "PhotoExists"
curs = arcpy.UpdateCursor(featureClass, results_field)
row = curs.next()
for row in curs:
photo_path = row.getValue(photo_field)
if os.path.exists(photo_path):
row.setValue(results_field, "Y")
else:
row.setValue(results_field, "N")
curs.updateRow(row)
row = curs.next()
del curs, row
... View more
08-01-2012
09:12 AM
|
0
|
0
|
378
|
POST
|
We have a feature class consisting of manholes. Each manhole has a corresponding photo. All the photos reside on the server. The photo file names equate to the manholes' unique ID number. There is a field in the feature class that is calculated to the file path to each manhole's photo. I need a bit of code that I can use in Field Calculator to check if there is indeed a photo at the end of each path. Any ideas?
... View more
07-31-2012
10:41 AM
|
0
|
6
|
994
|
POST
|
Alright, I seem to have solved the issue, and boy is it strange. It all seems to be related to the use of multiple displays. On Thursday of last week I connected to a large HDTV to demonstrate the function of my script to my superiors. I dragged the geoprocessing dialog box to the big screen so we could watch it work and return messages. It seems that ArcMap somehow and for some reason remembered the location of the dialog box and tried to project it there even after I was disconnected from the display. So back at my desk, my process was running, and upon finishing it was waiting for a response from me (basically to close the dialog box). But since it was nowhere to be seen on the current display configuration, I had no way of interacting with it. Only by reconnecting to the HDTV in our conference room was I able to see the box and drag it back into my laptop display. It now remembers the location and I can see it when running the script. I'm not sure where the fault lies with this bug, but does anybody else have experience with it?
... View more
04-09-2012
07:14 AM
|
0
|
0
|
146
|
POST
|
I've produced a relatively simple Python script that strings together several geoprocessing tasks in order to calculate the volume of a stormwater detention pond. I've been working on this for a week or so, and just recently I started having trouble running the tool. Whereas before I would see a geoprocessing window after clicking "OK" to begin the process, now nothing pops up. The script tool finishes and produces the results I expect, but then the mxd becomes completely unresponsive. Clicking anywhere inside the mxd just makes a "ding" noise. It's as if the window that formerly was visible is now hidden somewhere and waiting for me to click "OK" in reply to a message that the process completed. I feel like I'm missing something insanely simple, but for the life of me I can't figure it out. Please help! Running Windows 7 64, ArcEditor SP 4
... View more
04-09-2012
06:30 AM
|
0
|
1
|
729
|
POST
|
Hello. I am very new to Python and scripting in general, and would appreciate any assistance with my following problem. I've created an extremely simple Python script that strips away unnecessary characters from fields in a shapefile. The script works within PythonWin and returns no errors. However, when I make a script tool in ArcMap and try to deploy the same function, it crashes ArcMap. Sometimes the data is actually updated, other times no. But every time I try the script tool, ArcMap becomes unresponsive, jumps to 100% of CPU use, and has to be shut down from within Task Manager. Below is my working script. Any comments or suggestions would be welcome. Thank you for your time. import arcpy featureClass = arcpy.GetParameterAsText(0) rows = arcpy.UpdateCursor(featureClass) row = rows.next() while row: subtypeValue = row.SUBTYPE subtypeValueIndex = subtypeValue.split(" ") row.SUBTYPE = subtypeValueIndex[0] materialValue = row.STRMAT strmatValueIndex = materialValue.split("-") row.STRMAT = strmatValueIndex[0] photoynValue = row.PHOTOYN photoynValueIndex = photoynValue.split("-") row.PHOTOYN = photoynValueIndex[0] conditionValue = row.CONDITION conditionValueIndex = conditionValue.split("-") row.CONDITION = conditionValueIndex[0] clidmatValue = row.CLIDMAT clidmatValueIndex = clidmatValue.split("-") row.CLIDMAT = clidmatValueIndex[0] accesstypeValue = row.ACCESSTYPE accesstypeValueIndex = accesstypeValue.split("-") row.ACCESSTYPE = accesstypeValueIndex[0] groundtypeValue = row.GROUNDTYPE groundtypeValueIndex = groundtypeValue.split("-") row.GROUNDTYPE = groundtypeValueIndex[0] stepsValue = row.STEPS stepsValueIndex = stepsValue.split("-") row.STEPS = stepsValueIndex[0] skimmerValue = row.SKIMMER skimmerValueIndex = skimmerValue.split("-") row.SKIMMER = skimmerValueIndex[0] lcyclestatValue = row.LCYCLESTAT lcyclestatValueIndex = lcyclestatValue.split("-") row.LCYCLESTAT = lcyclestatValueIndex[0] collectbyValue = row.COLLECTBY collectbyValueIndex = collectbyValue.split("-") row.COLLECTBY = collectbyValueIndex[0] datasourceValue = row.DATASOURCE datasourceValueIndex = datasourceValue.split("-") row.DATASOURCE = datasourceValueIndex[0] erosionValue = row.EROSION erosionValueIndex = erosionValue.split("-") row.EROSION = erosionValueIndex[0] rows.updateRow(row) row = rows.next() del row, rows
... View more
03-26-2012
11:29 AM
|
0
|
1
|
289
|
Online Status |
Offline
|
Date Last Visited |
11-11-2020
02:23 AM
|