Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import arcpy, traceback, os, sys,time
- import itertools as itt
- scriptsPath=os.path.dirname(os.path.realpath(__file__))
- os.chdir(scriptsPath)
- import COMMON
- sys.path.append(r'C:Usersfelix_pertzigerAppDataRoamingPythonPython27site-packages')
- import networkx as nx
- RATIO = int(arcpy.GetParameterAsText(0))
- try:
- def showPyMessage():
- arcpy.AddMessage(str(time.ctime()) + " - " + message)
- mxd = arcpy.mapping.MapDocument("CURRENT")
- theT=COMMON.getTable(mxd)
- theNodesLayer = COMMON.getInfoFromTable(theT,1)
- theNodesLayer = COMMON.isLayerExist(mxd,theNodesLayer)
- theLinksLayer = COMMON.getInfoFromTable(theT,9)
- theLinksLayer = COMMON.isLayerExist(mxd,theLinksLayer)
- arcpy.SelectLayerByAttribute_management(theLinksLayer, "CLEAR_SELECTION")
- linksFromI=COMMON.getInfoFromTable(theT,14)
- linksToI=COMMON.getInfoFromTable(theT,13)
- G=nx.Graph()
- arcpy.AddMessage("Adding links to graph")
- with arcpy.da.SearchCursor(theLinksLayer, (linksFromI,linksToI,"Times")) as cursor:
- for row in cursor:
- (f,t,c)=row
- G.add_edge(f,t,weight=c)
- del row, cursor
- pops=[]
- pops=arcpy.da.TableToNumPyArray(theNodesLayer,("P2013"))
- length0=nx.all_pairs_shortest_path_length(G)
- nNodes=len(pops)
- aBmNodes=[]
- aBig=xrange(nNodes)
- host=[-1]*nNodes
- while True:
- RATIO+=-1
- if RATIO==0:
- break
- aBig = filter(lambda x: x not in aBmNodes, aBig)
- p=itt.combinations(aBig, 2)
- pMin=1000000
- small=[]
- for a in p:
- S0,S1=0,0
- for i in aBig:
- p=pops[i][0]
- p0=length0[a[0]][i]
- p1=length0[a[1]][i]
- if p0<p1:
- S0+=p
- else:
- S1+=p
- if S0!=0 and S1!=0:
- sMin=min(S0,S1)
- sMax=max(S0,S1)
- df=abs(float(sMax)/sMin-RATIO)
- if df<pMin:
- pMin=df
- aBest=a[:]
- arcpy.AddMessage('%s %i %i' %(aBest,sMax,sMin))
- if df<0.005:
- break
- lSmall,lBig,S0,S1=[],[],0,0
- arcpy.AddMessage ('Ratio %i' %RATIO)
- for i in aBig:
- p0=length0[aBest[0]][i]
- p1=length0[aBest[1]][i]
- if p0<p1:
- lSmall.append(i)
- S0+=p0
- else:
- lBig.append(i)
- S1+=p1
- if S0<S1:
- aBmNodes=lSmall[:]
- for i in aBmNodes:
- host[i]=aBest[0]
- for i in lBig:
- host[i]=aBest[1]
- else:
- aBmNodes=lBig[:]
- for i in aBmNodes:
- host[i]=aBest[1]
- for i in lSmall:
- host[i]=aBest[0]
- with arcpy.da.UpdateCursor(theNodesLayer, "rcvnode") as cursor:
- i=0
- for row in cursor:
- row[0]=host[i]
- cursor.updateRow(row)
- i+=1
- del row, cursor
- except:
- message = "n*** PYTHON ERRORS *** "; showPyMessage()
- message = "Python Traceback Info: " + traceback.format_tb(sys.exc_info()[2])[0]; showPyMessage()
- message = "Python Error Info: " + str(sys.exc_type)+ ": " + str(sys.exc_value) + "n"; showPyMessage()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement