[英]python concatenation in cycle partitioning
我知道我只能連接相似類型的東西,但是對於以下為什么是不同類型,我確實感到困惑。
這是我的代碼的一部分:
import sys
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import gurobipy as GRB
def solveOptCyclePartition(diGraph):
# Create the Optimization Model
try:
m = GRB.Model("ctrlModel")
linkWeights = {}
for (u,v) in sorted(diGraph.edges(data=False)):
linkWeights[(u,v)] = diGraph[u][v]['weight']
#Create variables
e = m.addVars(sorted(diGraph.edges(data=False)),lb=0.0,ub=1.0,
obj=linkWeights , name="e")
# Add the objective function
m.setObjective( (e.prod(linkWeights)), GRB.MAXIMIZE)
#Add Constraint: One output edge from each node
m.addConstrs( (e.sum(i,'*') == 1 for i in nx.nodes(diGraph)), "outDegree")
#Add Constraint: One input edge from each node
m.addConstrs( (e.sum('*',i) == 1 for i in nx.nodes(diGraph)), "inDegree")
# Compute optimal solution
m.optimize()
# Print solution
if m.status == GRB.Status.OPTIMAL:
objOptimalVal = m.getAttr('objVal')
solution = m.getAttr('x', e)
for (u,v) in sorted(diGraph.edges(data=False)):
if solution[u,v] > 0:
print('%s -> %s: %g' % (u, v, solution[u,v]))
return objOptimalVal , solution
except:
print('Error reported')
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
#def main():
# Network Adjacency Matrix
A = np.matrix([[0,0,0],
[1,0,0],
[1,0,1]])
G = nx.DiGraph()
G = nx.from_numpy_matrix(A)
# Check to see if connected
if nx.is_connected(G) == False:
print('The graph is not connected and has unaccessible nodes')
sys.exit(0)
# Nodes and Edge Lists
nodes = nx.nodes(G)
N = len(nodes)
edgeList = nx.to_edgelist(G)
# M Actuator nodes are selected randomly fron N nodes
M = 1;
augNodes = range(N,N+M)
actuatorNodes = sorted(list(np.random.permutation(np.arange(N))[:M]))
actuatorEdges = [(i,actuatorNodes[N-i],{'weight':1}) for i in augNodes ]
# Augmented edges lists and augmented graph
augEdgeList = (edgeList + actuatorEdges +
[(i,j,{'weight':0}) for i in nodes for j in augNodes] +
[(i,i,{'weight':0}) for i in nodes+augNodes if (i,i,{'weight':1}) not in edgeList])
Gprim = nx.DiGraph()
Gprim = nx.from_edgelist(augEdgeList,Gprim)
# Poljak Algorithm: Perform maximum weight cycle partitioning on
# augmented graph and return the optimal solution
objOptimalVal, solution = solveOptCyclePartition(Gprim)
plt.draw()
# Evaluate the solution
#if __name__ == '__main__':
# main()
我正在嘗試解決循環分區問題,以便在所有分區中找到一個包含單位重量最大邊緣數並滿足以下約束的分區。 但我得到這個錯誤:
*** TypeError: can only concatenate list (not "range") to list
如果沒有完整的堆棧跟蹤,很難確切地確定此錯誤發生的位置,但是我相信它是在以下行中發生的:
[(i,i,{'weight':0}) for i in nodes+augNodes if (i,i,{'weight':1}) not in edgeList])
要注意的特定部分是nodes+augNodes
。
的nodes
變量包含從調用的返回值networkx.nodes()
根據文檔返回的列表。 augNodes
,將augNodes
設置為以下行中的范圍:
augNodes = range(N,N+M)
由於您不能將范圍附加到列表中,因此您將看到所看到的TypeError
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.