Guest User

Untitled

a guest
Mar 7th, 2023
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. import networkx as nx
  2. import gurobipy as gp
  3. from gurobipy import GRB
  4.  
  5.  
  6. def callback(model, where):
  7. if where == GRB.Callback.MIPSOL:
  8.  
  9. G2 = nx.DiGraph()
  10.  
  11. x, offsets, G = model._vars
  12.  
  13. vals = model.cbGetSolution(x)
  14.  
  15. for fr, to in x.keys():
  16. if vals[fr, to] > 0.5:
  17. G2.add_edge(fr, to, weight=G[fr][to]["weight"])
  18.  
  19. for cycle in nx.simple_cycles(G2):
  20.  
  21. print(cycle)
  22.  
  23. weight = sum(G2[fr][to]["weight"]
  24. for fr, to in zip(cycle, cycle[1:] + [cycle[0]]))
  25.  
  26. weight_single = weight / len(cycle)
  27.  
  28. for fr, to in zip(cycle, cycle[1:] + [cycle[0]]):
  29. model.cbLazy(
  30. offsets[fr, to] <= -weight_single
  31. )
  32.  
  33. print((fr, to), "<=", -weight_single)
  34.  
  35.  
  36. def augment_graph_lp(G):
  37.  
  38. m = gp.Model("augment")
  39.  
  40. x = m.addVars(G.edges(), vtype=GRB.BINARY, name="x")
  41. offsets = m.addVars(G.edges(), vtype=GRB.CONTINUOUS, name="offsets")
  42.  
  43. for fr, to in G.edges():
  44. m.addConstr(offsets[fr, to] <= 0)
  45.  
  46. # add deg 2 constraints
  47.  
  48. m.addConstrs(
  49. x.sum(fr, "*") == x.sum("*", fr)
  50. for fr in G.nodes()
  51. )
  52.  
  53. m.addConstrs(
  54. x.sum(fr, "*") <= 1 for fr in G.nodes()
  55. )
  56.  
  57. m.addConstrs(
  58. x.sum("*", to) <= 1 for to in G.nodes()
  59. )
  60.  
  61. obj = gp.quicksum(x[fr, to] * G[fr][to]["weight"] + offsets[fr, to] * x[fr, to]
  62. for fr, to in G.edges())
  63.  
  64. m.setObjective(obj, GRB.MAXIMIZE)
  65.  
  66. m._vars = x, offsets, G
  67. m.params.LazyConstraints = 1
  68. m.params.OutputFlag = 0
  69. m.optimize(callback)
  70.  
  71. print("Optimal value:", m.objVal)
  72.  
  73. for offset in offsets.values():
  74. print(offset.x)
  75.  
  76.  
  77. def main():
  78. G = nx.DiGraph()
  79.  
  80. G.add_edge("USD", "ETH", weight=-1)
  81. G.add_edge("ETH", "BNB", weight=-1)
  82. G.add_edge("BNB", "BTC", weight=1)
  83. G.add_edge("BTC", "EUR", weight=-1)
  84. G.add_edge("EUR", "ETH", weight=2)
  85.  
  86. # print(nx.negative_edge_cycle(G))
  87.  
  88. # print(get_best_sol(G))
  89.  
  90. # G2, offset = augment_graph(G)
  91.  
  92. # print(offset)
  93.  
  94. augment_graph_lp(G)
  95.  
  96.  
  97. if __name__ == "__main__":
  98. main()
  99.  
Advertisement
Add Comment
Please, Sign In to add comment