首页 > 编程语言 >运筹学练习Python精解——网络计划技术

运筹学练习Python精解——网络计划技术

时间:2024-06-10 09:13:58浏览次数:14  
标签:node weight Python critical time path nodes 精解 运筹学

练习1

某新产品研制项目的各项工序、所需时间及相互关系如下表所示,试画出该项目的网络图,试求出关键路线。

工序 工序代号 所需时间 紧后工序
产品及工艺设计 A 60 B, C, D, E
外购配套件 B 45 K
下料、锻件 C 10 F
工装制造1 D 20 G, H
木模、铸件 E 40 H
机械加工1 F 18 K
工装制造2 G 30 I
机械加工2 H 15 K
机械加工3 I 25 K
装配调试 K 35 -

1.1 绘制网络计划图(数学模型)

1.2 Python求解

#网络计划的最长路算法
import networkx as nx

# Define the edges with the new data structure
edges = {
    'A': {'nodes': ('1', '2'), 'weight': 60},
    'B': {'nodes': ('2', '7'), 'weight': 45},
    'C': {'nodes': ('2', '3'), 'weight': 10},
    'D': {'nodes': ('2', '4'), 'weight': 20},
    'E': {'nodes': ('2', '5'), 'weight': 40},
    'F': {'nodes': ('3', '7'), 'weight': 18},
    'G': {'nodes': ('4', '6'), 'weight': 30},
    'L': {'nodes': ('4', '5'), 'weight': 0},
    'H': {'nodes': ('5', '7'), 'weight': 15},
    'I': {'nodes': ('6', '7'), 'weight': 25},
    'K': {'nodes': ('7', '8'), 'weight': 35}
}

# Initialize a directed graph
G = nx.DiGraph()

# Add edges to the graph using the new data structure
for edge_name, edge_data in edges.items():
    start, end = edge_data['nodes']
    weight = edge_data['weight']
    G.add_edge(start, end, weight=weight, name=edge_name)

# Compute the longest path using the networkx library
length, path = nx.algorithms.dag.dag_longest_path_length(G, weight='weight'), nx.algorithms.dag.dag_longest_path(G, weight='weight')

# Extract the names of the edges in the critical path
critical_path_edges = []
for i in range(len(path) - 1):
    critical_path_edges.append(G[path[i]][path[i + 1]]['name'])

# Format the critical path output
formatted_critical_path = " -> ".join(critical_path_edges) + "."

print(f"Length of the critical path: {length}")
print(f"Critical path nodes: {path}")
print(f"Critical path edges: {formatted_critical_path}")
Length of the critical path: 170
Critical path nodes: ['1', '2', '4', '6', '7', '8']
Critical path edges: A -> D -> G -> I -> K.

练习2

import networkx as nx
import matplotlib.pyplot as plt
from matplotlib import rcParams

# 设置字体
rcParams['font.sans-serif'] = ['Arial']  # 使用Arial字体
rcParams['axes.unicode_minus'] = False  # 解决坐标轴负号显示问题

# 定义任务、紧前任务和任务时间
tasks = {
    'A': {'pre': ['G', 'M'], 'time': 3},
    'B': {'pre': ['H'], 'time': 4},
    'C': {'pre': [], 'time': 7},
    'D': {'pre': ['L'], 'time': 3},
    'E': {'pre': ['C'], 'time': 5},
    'F': {'pre': ['A', 'E'], 'time': 5},
    'G': {'pre': ['B', 'C'], 'time': 2},
    'H': {'pre': [], 'time': 5},
    'I': {'pre': ['A', 'L'], 'time': 2},
    'K': {'pre': ['F', 'L'], 'time': 1},
    'L': {'pre': ['B', 'C'], 'time': 7},
    'M': {'pre': ['C'], 'time': 9}
}

# 构建有向图
G = nx.DiGraph()

# 添加任务节点和时间
for task, details in tasks.items():
    G.add_node(task, time=details['time'])

# 添加任务依赖关系
for task, details in tasks.items():
    for pre in details['pre']:
        G.add_edge(pre, task)

# 计算最早开始时间和最晚完成时间
def calculate_earliest_latest_times(G):
    earliest_start = {}
    latest_finish = {}
    
    for node in nx.topological_sort(G):
        es = max([earliest_start.get(pred, 0) + G.nodes[pred]['time'] for pred in G.predecessors(node)], default=0)
        earliest_start[node] = es
    
    for node in reversed(list(nx.topological_sort(G))):
        lf = min([latest_finish.get(succ, float('inf')) - G.nodes[node]['time'] for succ in G.successors(node)], default=earliest_start[node] + G.nodes[node]['time'])
        latest_finish[node] = lf
    
    return earliest_start, latest_finish

# 计算关键路径
def calculate_critical_path(G, earliest_start, latest_finish):
    critical_path = []
    for node in nx.topological_sort(G):
        if earliest_start[node] == latest_finish[node] - G.nodes[node]['time']:
            critical_path.append(node)
    return critical_path

# 计算并显示结果
earliest_start, latest_finish = calculate_earliest_latest_times(G)
critical_path = calculate_critical_path(G, earliest_start, latest_finish)

print("Earliest Start Times:", earliest_start)
print("Latest Finish Times:", latest_finish)
print("Critical Path:", critical_path)

# 按时间线组织节点布局
pos = {}
layer = 0
for node in nx.topological_sort(G):
    pos[node] = (earliest_start[node], layer)
    layer += 1

plt.figure(figsize=(12, 8))

# 绘制所有节点和边
nx.draw(G, pos, with_labels=True, node_color='lightblue', node_size=2000, font_size=10, font_weight='bold', arrowsize=20, font_family='sans-serif')

# 添加节点标签
node_labels = {node: f"{node}\n{G.nodes[node]['time']} days" for node in G.nodes}
nx.draw_networkx_labels(G, pos, labels=node_labels, font_size=10, font_family='sans-serif')

# 添加边标签
edge_labels = {(pre, succ): f"ES: {earliest_start[succ]}" for pre, succ in G.edges}
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_color='red', font_size=8, font_family='sans-serif')

# 高亮关键路径
critical_edges = [(critical_path[i], critical_path[i + 1]) for i in range(len(critical_path) - 1)]
nx.draw_networkx_edges(G, pos, edgelist=critical_edges, edge_color='r', width=2)

plt.title("Network Diagram")
plt.show()
Length of the critical path: 170
Critical path nodes: ['1', '2', '4', '6', '7', '8']
Critical path edges: A -> D -> G -> I -> K.

标签:node,weight,Python,critical,time,path,nodes,精解,运筹学
From: https://www.cnblogs.com/haohai9309/p/18240022

相关文章

  • python-10-数据处理得学:while+for循环搭配使用,排查数据和除重
    学习内容:《python编程:从入门到实践》第二版知识点:whilefor循环搭配使用,利用while排查数据,删除重复选项练习内容:练习7-8:熟食店创建一个名为sandwich_orders的列表,在其中包含各种三明治的名字,再创建一个名为finished_sandwiches的空列表。遍历列表sandwich_orders,对于其中......
  • python-7-求问,打印嵌套字典中的信息时,出现重复怎么解决?
    ​​​​​​学习内容:《python编程:从入门到实践》知识点:字典、键值对、嵌套#练习6-11:城市创建一个名为cities的字典,将三个城市名用作键。对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。在表示每座城市的字典中,应包含co......
  • python系列:FastAPI系列 10-路由管理APIRouter
    FastAPI系列10-路由管理APIRouterFastAPI系列10-路由管理APIRouter前言一、路由管理APIRouter二、FastAPI主体总结FastAPI系列10-路由管理APIRouter前言在fastapi中也有类似的功能通过APIRouter来管理一、路由管理APIRouter正在开发一个应用程序或We......
  • mac python 包管理工具 pip 的配置
     python3--versionPython3.12.3brewinstallpython@3.12pip3configsetglobal.index-urlhttps://pypi.tuna.tsinghua.edu.cn/simplepip3configsetglobal.break-system-packagestrue pip3installaiohttppython包管理工具pip的配置 近几年来,python的包......
  • python-数据分析-Pandas-2、DataFrame对象
    如果使用pandas做数据分析,那么DataFrame一定是被使用得最多的类型,它可以用来保存和处理异质的二维数据。这里所谓的“异质”是指DataFrame中每个列的数据类型不需要相同,这也是它区别于NumPy二维数组的地方。DataFrame提供了极为丰富的属性和方法,帮助我们实现对数据的重塑、......
  • 1.安装opencv-python失败的解决办法 2.pip 安装失败 3.WARNING:Ignoring invalid distr
    问题:安装opencv-python失败:用:pipinstall-ihttps://pypi.tuna.tsinghua.edu.cn/simpleopencv-python安装会被卡在Buildingwheelforopencv-python(pyproject.toml)...之后便安装失败。使用顺序:先使用方法二,再使用方法一(有可能不会解决问题),用方法三查看问题出......
  • python学习笔记
    (1)help('keywords')控制台内输入关键字 pycharm常用操作: [1]ctrl+y 恢复上一次操作 [2]ctrl+z 撤回上一次操作(2)%常见格式: [1]%s 字符串 [2]%d 整数 [3]%f 小数(浮点数)(3)注释: 单行注释: #________ 多行注释: """______"""(4)运算符号: / 除 // ......
  • Python模拟时钟演示及源代码
     turtle是Python中的一个模块,用于绘图和图形设计。它提供了一个简单的绘图窗口,可以绘制各种形状、线条和颜色等。通过使用turtle模块,我们可以在屏幕上实时地绘制图形,并且可以控制画笔的移动、旋转等操作。 2、使用示例下面是一个简单的使用turtle模块绘制一个正方形的......
  • python gdal 安装使用(Windows, python 3.6.8)
    pythongdal安装使用pythonGDAL有两种安装方式:第一种是利用pipinstallgdal安装如果安装失败,可以采用下面的方法:第二种离线安装步骤:(1)查看python版本;(2)下载gdal的whl文件;(3)利用pipinstall下载的gdal.whl文件;(4)将gdal中的可执行文件所在路径添加到系统环境中;具体操作见......
  • Python-金融编程第二版-GPT-重译--一-
    Python金融编程第二版(GPT重译)(一)原文:annas-archive.org/md5/d2f94efd019a2e2cb5c4fa9f260d63c译者:飞龙协议:CCBY-NC-SA4.0第一部分:Python与金融本部分介绍了Python在金融领域的应用。它包括三章:第一章简要讨论了Python的一般情况,并论述了为什么Python确实非常......