代码-step1:
import sys
import os from collections import defaultdict def read_nodes_and_elements(input_file): """ 读取 txt 文件,提取节点和单元信息。 """ nodes = [] elements = [] node_dict = {} # 用于快速查找节点 try: with open(input_file, 'r') as file: current_section = None for line in file: line = line.strip() if line.startswith('*'): current_section = line continue if current_section == '*NODE': parts = line.split(',') node_id = parts[0].strip() x, y, z = map(float, parts[1:]) nodes.append((node_id, x, y, z)) node_dict[node_id] = (x, y, z) elif current_section and current_section.startswith('*ELEMENT'): parts = line.split(',') element_id = parts[0].strip() element_type = current_section.split(',')[1].split('=')[1] elset = current_section.split(',')[2].split('=')[1] node_ids = [part.strip() for part in parts[1:]] elements.append((element_id, element_type, elset, node_ids)) print(f"成功读取 {len(nodes)} 个节点和 {len(elements)} 个单元。") return nodes, elements, node_dict except Exception as e: print(f"读取文件时发生错误: {e}") return [], [], {} def count_node_occurrences(elements): """ 统计每个节点在单元中出现的次数。 """ node_occurrences = defaultdict(int) for _, _, _, node_ids in elements: for node_id in node_ids: node_occurrences[node_id] += 1 return node_occurrences def generate_new_nodes(nodes, node_occurrences, node_dict): """ 生成新节点。 """ new_nodes = [] new_node_map = defaultdict(list) for node_id, count in node_occurrences.items(): if count >= 2: base_id = int(node_id) for i in range(count): new_node_id = str(base_id + (i + 1) * 100000) # 生成唯一的新节点编号 if node_id in node_dict: x, y, z = node_dict[node_id] new_nodes.append((new_node_id, x, y, z)) new_node_map[node_id].append(new_node_id) else: print(f"警告: 节点 ID {node_id} 未找到。") print(f"成功生成 {len(new_nodes)} 个新节点。") new_nodes.sort(key=lambda x: int(x[0])) # 按节点编号排序 return new_nodes, new_node_map def update_elements_with_new_nodes(elements, new_node_map): """ 更新单元中的节点编号。 """ updated_elements = [] used_new_nodes = defaultdict(set) for element in elements: element_id, element_type, elset, node_ids = element updated_node_ids = [] for node_id in node_ids: if node_id in new_node_map: available_new_nodes = [new_node for new_node in new_node_map[node_id] if new_node not in used_new_nodes[node_id]] if available_new_nodes: new_node_id = available_new_nodes[0] used_new_nodes[node_id].add(new_node_id) updated_node_ids.append(new_node_id) else: updated_node_ids.append(node_id) else: updated_node_ids.append(node_id) updated_elements.append((element_id, element_type, elset, updated_node_ids)) return updated_elements def write_output_to_file(input_file, nodes, new_nodes, updated_elements): """ 将结果写入到以“输入文件名_mid”为名称的 txt 文件中,保存在与输入文件相同的目录中。 """ input_dir = os.path.dirname(input_file) input_base = os.path.basename(input_file) output_file = os.path.join(input_dir, f"{os.path.splitext(input_base)[0]}_mid.txt") try: with open(output_file, 'w') as file: file.write("*Node\n") for node in nodes + new_nodes: file.write(f"{node[0]}, {node[1]}, {node[2]}, {node[3]}\n") if updated_elements: element_type = updated_elements[0][1] file.write(f"*Element,Type={element_type}\n") for element in updated_elements: file.write(f"{element[0]}, {', '.join(element[3])}\n") else: file.write("\n*Element\n") print(f"结果已成功写入文件: {output_file}") return True except Exception as e: print(f"写入文件时发生错误: {e}") return False def main(input_file): # 检查文件是否存在 if not os.path.exists(input_file): print("错误: 文件不存在,请检查路径是否正确。") return # 读取节点和单元信息 nodes, elements, node_dict = read_nodes_and_elements(input_file) if not nodes or not elements: return # 统计节点在单元中出现的次数 node_counts = count_node_occurrences(elements) # 生成新节点 new_nodes, new_node_map = generate_new_nodes(nodes, node_counts, node_dict) # 更新单元中的节点编号 updated_elements = update_elements_with_new_nodes(elements, new_node_map) # 写入输出文件 if write_output_to_file(input_file, nodes, new_nodes, updated_elements): print("程序执行成功。") if __name__ == "__main__": if len(sys.argv) != 2: print("用法: python step1.py <输入文件>") else: main(sys.argv[1])

代码-step2:
import sys
import os from itertools import combinations from collections import defaultdict def read_nodes_and_elements(input_file): """ 读取 INP 文件,提取节点和单元信息。 """ nodes = [] elements = [] node_dict = {} # 用于快速查找节点 element_lines = [] # 保存 *Element 行及其后续行 current_element_type = None # 当前 *Element 类型 try: with open(input_file, 'r') as file: for line in file: line = line.strip() if line.startswith('*'): if line.startswith('*Element'): current_element_type = line.split('=')[1].split(',')[0] element_lines.append(f"*Element,Type={current_element_type}") continue if line.startswith('*Node'): continue if current_element_type: parts = line.split(',') element_id = parts[0].strip() node_ids = [part.strip() for part in parts[1:]] elements.append((element_id, current_element_type, node_ids)) element_lines.append(f"{element_id}, {', '.join(node_ids)}") else: parts = line.split(',') node_id = parts[0].strip() x, y, z = map(float, parts[1:]) nodes.append((node_id, x, y, z)) node_dict[node_id] = (x, y, z) print(f"成功读取 {len(nodes)} 个节点和 {len(elements)} 个单元。") return nodes, elements, node_dict, element_lines except Exception as e: print(f"读取文件时发生错误: {e}") return [], [], {}, [] def get_element_faces(element_type, node_ids): """ 根据单元类型返回单元面。 """ if element_type in ['C3D8R', 'C3D8']: # 6面体的面 faces = [ (node_ids[0], node_ids[1], node_ids[2], node_ids[3]), # 底面 (node_ids[4], node_ids[5], node_ids[6], node_ids[7]), # 顶面 (node_ids[0], node_ids[1], node_ids[5], node_ids[4]), # 前面 (node_ids[2], node_ids[3], node_ids[7], node_ids[6]), # 后面 (node_ids[0], node_ids[3], node_ids[7], node_ids[4]), # 左面 (node_ids[1], node_ids[2], node_ids[6], node_ids[5]) # 右面 ] elif element_type == 'C3D4': # 4面体的面 faces = [ (node_ids[0], node_ids[1], node_ids[2]), (node_ids[0], node_ids[2], node_ids[3]), (node_ids[0], node_ids[3], node_ids[1]), (node_ids[1], node_ids[3], node_ids[2]) ] else: raise ValueError(f"不支持的单元类型: {element_type}") return faces def find_adjacent_elements(elements, node_dict): """ 找出相邻的单元面。 """ adjacent_faces = [] element_faces = {} for element in elements: element_id, element_type, node_ids = element faces = get_element_faces(element_type, node_ids) element_faces[element_id] = faces for (id1, id2) in combinations(element_faces.keys(), 2): faces1 = element_faces[id1] faces2 = element_faces[id2] for face1 in faces1: for face2 in faces2: coords1 = [node_dict[node_id] for node_id in face1] coords2 = [node_dict[node_id] for node_id in face2] if set(coords1) == set(coords2): adjacent_faces.append((id1, id2, face1, face2)) print(f"找到 {len(adjacent_faces)} 对相邻单元面。") return adjacent_faces def write_output_to_file(input_file, nodes, adjacent_faces, element_lines): """ 将结果写入到以“输入文件名_cohesive”为名称的 inp 文件中,保存在与输入文件相同的目录中。 """ input_dir = os.path.dirname(input_file) input_base = os.path.basename(input_file) output_file = os.path.join(input_dir, f"{os.path.splitext(input_base)[0]}_cohesive.inp") try: with open(output_file, 'w') as file: file.write("*Node\n") for node in nodes: file.write(f"{node[0]}, {node[1]}, {node[2]}, {node[3]}\n") for line in element_lines: file.write(line + '\n') cohesive_start_id = len(element_lines) + 1 file.write("*Element,Type=COH3D8\n" if len(adjacent_faces[0][2]) == 4 else "*Element,Type=COH3D6\n") for face in adjacent_faces: element_id1, element_id2, face1, face2 = face cohesive_start_id += 1 file.write(f"{cohesive_start_id}, {', '.join(face1 + face2)}\n") file.write("*Elset, elset=SET_COHESIVE, generate\n") file.write(f"{len(element_lines) + 1}, {cohesive_start_id}, 1\n") print(f"结果已成功写入文件: {output_file}") return True except Exception as e: print(f"写入文件时发生错误: {e}") return False def main(input_file): # 检查文件是否存在 if not os.path.exists(input_file): print("错误: 文件不存在,请检查路径是否正确。") return # 读取节点和单元信息 nodes, elements, node_dict, element_lines = read_nodes_and_elements(input_file) if not nodes or not elements: return # 找出相邻的单元面 adjacent_faces = find_adjacent_elements(elements, node_dict) # 写入输出文件 if write_output_to_file(input_file, nodes, adjacent_faces, element_lines): print("程序执行成功。") if __name__ == "__main__": if len(sys.argv) != 2: print("用法: python step2.py <mid_file>") else: main(sys.argv[1]) --------over
免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删