使用scipy的线性优化失败

mjqavswn  于 2023-04-21  发布在  其他
关注(0)|答案(1)|浏览(157)

我需要使用pythonscipy最大化网络的吞吐量

class optimization():
    def __init__(self,nodes=nodes):
        self.nodes = nodes
        self.estimated_throughput_list=[] # list of throughputs
        for i in self.nodes:
            self.estimated_throughput_list.append(i.estimated_throughput) # adding for each node its throughput to the list
        self.d= np.ones_like(self.nodes, dtype=bool) # creating a boolean matrix having the same dimensions of the estimated_throughput_list

    def objective_function(self):
        """
        Objective function to maximize the sum of Di * xi,
        where Di is a binary variable that can take values of 0 or 1.
        x is an array of values for the variables x1, x2, ..., xn,
        and D is an array of values for the binary variables D1, D2, ..., Dn.
        """  
        return  np.dot(self.d, self.estimated_throughput_list)

    def constraint1(self):
        summation=8* 0.5 # erlang
        summation= summation+ np.dot(self.d, self.estimated_throughput_list)
        return summation
    def solution(self):
        return linprog(c=self.nodes,A_ub=self.estimated_throughput_list,b_ub=[8* 0.5],method="revised simplex")

我有一个节点的全局列表,每个节点包含它的估计吞吐量,由estimated_throughput表示
我试图解决的优化问题是由上传的figure:optimzation problem提出的
为简单起见m *h^(-1)[PDR] is replaced by (8*0.5)
在main.py文件中,我只是调用函数:

opt=optimization()
    
 print("obj:",opt.solution())

这是我第一次在python中应用优化,我不知道这是否是解决这类问题的方法。如果有人能在这个问题上进一步指导我,我将不胜感激。
结果是:c = np.array(c, dtype=np.float64, copy=True).squeeze() TypeError: float() argument must be a string or a real number, not 'myNode'

wfypjpf4

wfypjpf41#

error的意思是错误的意思。如果你有一个类myNode,你不能把它作为scipy方法的输入。在你的例子中,这可能发生在c=self.nodes中,它有错误的符号和错误的类型。这很好用:

import numpy as np
import scipy
from numpy.random import default_rng
from scipy.optimize import LinearConstraint

rand = default_rng(seed=0)
n = 12
nodes = rand.uniform(low=0.1, high=2, size=n)

m = 8
h = 2

result = scipy.optimize.milp(
    c=-nodes,  # maximize dot product
    integrality=np.ones_like(nodes, dtype=bool),  # everything integral
    bounds=(0, 1),
    constraints=LinearConstraint(A=nodes, lb=-np.inf, ub=m/h),
)

print('Node throughputs:')
print(nodes)
print()
print(result)
Node throughputs:
[1.31022721 0.61259476 0.1778497  0.13140251 1.64521345 1.8342356
 1.25260797 1.48604347 1.13288748 1.87663761 1.65012175 0.10520315]

        message: Optimization terminated successfully. (HiGHS Status 7: Optimal)
        success: True
         status: 0
            fun: -3.994173190069585
              x: [ 0.000e+00  1.000e+00  1.000e+00  1.000e+00  0.000e+00
                   1.000e+00  0.000e+00  0.000e+00  1.000e+00  0.000e+00
                  -0.000e+00  1.000e+00]
 mip_node_count: 44
 mip_dual_bound: -3.994173190069585
        mip_gap: 0.0

相关问题