with open('poscars.txt', 'r') as f: poscars = f.readlines(),更改两行代码,不用pymatgen,使得代码能读取目录下所有POSCAR结构文件
时间: 2024-01-11 20:02:21 浏览: 164
Python实现读取目录所有文件的文件名并保存到txt文件代码
5星 · 资源好评率100%
好的,下面是修改后的代码,它使用Python内置的open函数读取目录下的所有POSCAR文件,然后解析文件内容计算C原子的分布规律,并使用KMeans算法进行聚类。
```python
import os
import numpy as np
# 获取目录下所有POSCAR文件的路径
poscars = [os.path.join(root, file) for root, dirs, files in os.walk('.') for file in files if file.endswith('.POSCAR')]
# 计算每个文件中C原子的分布规律
c_coords = []
for poscar in poscars:
with open(poscar, 'r') as f:
lines = f.readlines()
lattice = np.array([list(map(float, line.split())) for line in lines[2:5]])
positions = np.array([list(map(float, line.split()[:3])) for line in lines[8:]])
c_indices = [i for i, line in enumerate(lines[8:]) if 'C' in line]
c_positions = positions[c_indices]
c_coords.append([len([j for j, pos in enumerate(c_positions) if np.linalg.norm(pos - c_positions[i]) < 2]) for i in range(len(c_positions))])
# 将C原子分布规律转换为numpy数组
c_coords = np.array(c_coords)
# 定义KMeans算法
def kmeans(X, k):
centroids = X[np.random.choice(range(len(X)), k, replace=False)]
while True:
clusters = [[] for i in range(k)]
for x in X:
distances = np.linalg.norm(x - centroids, axis=1)
cluster = np.argmin(distances)
clusters[cluster].append(x)
new_centroids = [np.mean(cluster, axis=0) for cluster in clusters]
if np.array_equal(new_centroids, centroids):
break
centroids = new_centroids
return clusters
# 使用KMeans算法进行聚类
clusters = kmeans(c_coords, 3)
# 输出每个簇中的文件名
for i, cluster in enumerate(clusters):
print('Cluster {}:'.format(i))
for j in range(len(poscars)):
with open(poscars[j], 'r') as f:
lines = f.readlines()
lattice = np.array([list(map(float, line.split())) for line in lines[2:5]])
positions = np.array([list(map(float, line.split()[:3])) for line in lines[8:]])
c_indices = [i for i, line in enumerate(lines[8:]) if 'C' in line]
c_positions = positions[c_indices]
c_counts = [len([j for j, pos in enumerate(c_positions) if np.linalg.norm(pos - c_positions[i]) < 2]) for i in range(len(c_positions))]
if c_counts in cluster:
print(poscars[j])
print()
```
这里使用了Python内置的open函数读取POSCAR文件,然后解析文件内容计算C原子的分布规律。其余部分与前面的代码相同。
阅读全文