如何优化Abaqus Python创建近距节点集的代码以提升效率?
问题:Abaqus批量查找最近节点效率低下
需要读取坐标文本文件,在Abaqus中创建最近节点集,但当前循环处理单个点耗时约1秒,效率极低。现有代码如下:
file_hole_path = 'I:/Worktem/hole_shape_xyz_nocracks_scale.txt' def read_xyz_file(file_hole_path): # Read hole edge shape XYZ points coordinates = [] with open(file_hole_path, 'r') as file: for line in file: parts = line.strip().split() coordinates.append( (float(parts[0]), float(parts[1]), float(parts[2]))) return tuple(coordinates) rootAsse = mdb.models['Model1'].rootAssembly Instance = rootAsse.instances['plate-1'] allNodes = Instance.nodes Path_xyz = read_xyz_file(file_hole_path) cor_nodes_label = [] previous_value = None # Initialize a variable to store the previous value # general cal start_time = time.time() for i_k in range(0, len(Path_xyz)): cor_nodes = allNodes.getClosest(Path_xyz[i_k]).label if cor_nodes != previous_value: # Check if the current value is different from the previous value cor_nodes_label.append(cor_nodes) # Append the value to the tuple y previous_value = cor_nodes # Update the previous value # print total_time = time.time() - start_time print("Step {}/{}; Total time elapsed: {:.2f} seconds".format(i_k + 1, len(Path_xyz), total_time)) cor_nodes_label = tuple(cor_nodes_label) rootAsse.Set(name='Set-hole', nodes=allNodes.sequenceFromLabels((cor_nodes_label),))
优化方案
1. 使用批量查找函数getClosestMultiple
Abaqus的NodeArray提供了getClosestMultiple方法,支持一次性传入多个坐标点批量查找最近节点,大幅减少Python与Abaqus内核的交互次数(这是原代码效率低下的核心原因)。
2. 优化去重逻辑
批量获取节点后,直接用集合或有序字典去重,比循环逐个判断效率更高;用dict.fromkeys可以保留节点标签首次出现的顺序。
3. 减少冗余IO操作
原代码每步循环都打印耗时,频繁IO会拖慢速度,改为循环结束后打印总耗时,或每N步打印一次进度。
优化后完整代码
import time file_hole_path = 'I:/Worktem/hole_shape_xyz_nocracks_scale.txt' def read_xyz_file(file_hole_path): # Read hole edge shape XYZ points coordinates = [] with open(file_hole_path, 'r') as file: for line in file: parts = line.strip().split() coordinates.append( (float(parts[0]), float(parts[1]), float(parts[2]))) return coordinates # 返回列表即可,无需转元组 rootAsse = mdb.models['Model1'].rootAssembly Instance = rootAsse.instances['plate-1'] allNodes = Instance.nodes Path_xyz = read_xyz_file(file_hole_path) start_time = time.time() # 批量查找最近节点 closest_nodes = allNodes.getClosestMultiple(coordinates=Path_xyz) # 提取节点标签并有序去重 cor_nodes_label = list(dict.fromkeys(node.label for node in closest_nodes)) total_time = time.time() - start_time print(f"Total time elapsed: {total_time:.2f} seconds") # 创建节点集 rootAsse.Set(name='Set-hole', nodes=allNodes.sequenceFromLabels(cor_nodes_label))
额外优化提示
- 如果坐标文件体积极大,可以分块读取并分批次批量处理,避免一次性加载过多数据占用内存。
- 确保
Instance.nodes的引用已提前缓存,避免重复获取节点集合。
内容的提问来源于stack exchange,提问作者Elliot
相关产品推荐
相关产品推荐

