R语言带约束的飞机运力分配线性规划lp函数问题排查
问题修正与优化代码实现
原代码核心问题分析
- 约束矩阵维度与逻辑错误
- 机型约束:原代码直接使用
block_hours_available作为约束行,但该矩阵仅4个元素,而决策变量共20个(5航线×4机型),维度不匹配;且约束逻辑应为汇总同一机型在所有航线上的使用时长,而非直接复用可用时长数值。 - 航线约束:原代码错误使用
profits矩阵作为约束行,正确逻辑应为汇总同一航线各机型的使用时长,使其等于指定的刚性值。
- 机型约束:原代码直接使用
- 变量类型错误
all.bin = TRUE将变量设为二进制,但实际需求是非负连续的block小时数,二进制变量不符合业务逻辑。
- 求解调用错误
lp()函数返回的对象无需调用solve(),直接访问$solution属性即可获取最优解。
修正后的完整代码
# 输入矩阵定义 profits <- matrix(c(10, 15, 20, 25, 30, 12, 16, 18, 22, 28, 8, 12, 16, 20, 24, 9, 11, 13, 15, 19), ncol = 4, byrow = TRUE, dimnames = list(paste0("Route", 1:5), paste0("Plane", 1:4))) block_hours_available <- matrix(c(50, 40, 60, 45), nrow = 1, ncol = 4) colnames(block_hours_available) <- paste0("Plane", 1:4) block_hours_per_route <- matrix(c(20, 30, 25, 35, 15), nrow = 5, ncol = 1) rownames(block_hours_per_route) <- paste0("Route", 1:5) n_routes <- nrow(profits) n_planes <- ncol(profits) n_vars <- n_routes * n_planes # 总决策变量数:20 # 1. 构造目标函数系数(按列展开profits矩阵,对应变量顺序:Route1-Plane1, Route2-Plane1,...Route5-Plane4) objective <- as.vector(profits) # 2. 构造约束矩阵 ## 约束1:各机型总使用时长不超过可用上限(4行约束) plane_constraints <- matrix(0, nrow = n_planes, ncol = n_vars) for (j in 1:n_planes) { # 每个机型j对应的变量位置是:(j-1)*n_routes + 1 到 j*n_routes plane_constraints[j, (j-1)*n_routes + 1:n_routes] <- 1 } ## 约束2:每条航线总block小时等于指定值(5行约束) route_constraints <- matrix(0, nrow = n_routes, ncol = n_vars) for (i in 1:n_routes) { # 每个航线i对应的变量位置是:i, i+n_routes, i+2*n_routes, i+3*n_routes route_constraints[i, seq(from = i, by = n_routes, length.out = n_planes)] <- 1 } ## 合并所有约束矩阵 const_mat <- rbind(plane_constraints, route_constraints) # 3. 约束方向与右端项 const_dir <- c(rep("<=", n_planes), rep("==", n_routes)) const_rhs <- c(as.vector(block_hours_available), as.vector(block_hours_per_route)) # 4. 求解线性规划问题 lprec <- lp(direction = "max", objective.in = objective, const.mat = const_mat, const.dir = const_dir, const.rhs = const_rhs, all.pos = TRUE) # 确保变量非负 # 输出最优解与总利润 cat("最优分配方案(按变量顺序:Route1-Plane1, Route2-Plane1,...Route5-Plane4):\n") print(lprec$solution) cat("\n最大总利润:", lprec$objval, "\n") # 将结果整理为矩阵格式(更易读) solution_matrix <- matrix(lprec$solution, nrow = n_routes, ncol = n_planes, byrow = FALSE) rownames(solution_matrix) <- paste0("Route", 1:5) colnames(solution_matrix) <- paste0("Plane", 1:4) cat("\n最优分配矩阵(行:航线,列:机型):\n") print(solution_matrix)
代码说明
- 决策变量:共20个,对应每条航线与机型的组合,变量顺序为
Route1-Plane1、Route2-Plane1…Route5-Plane4。 - 约束构造:通过循环分别生成机型总时长约束和航线总时长约束的矩阵,确保维度匹配且逻辑正确。
- 变量非负:设置
all.pos = TRUE保证block小时数为非负值,符合业务实际。
内容的提问来源于stack exchange,提问作者Sarah
相关产品推荐
相关产品推荐

