【发布时间】:2021-02-05 03:54:11
【问题描述】:
我有一个代码,我想把它放在一个 for 循环中。我想将一些存储为文件的数据输入到我的代码中,并根据每个输入自动生成输出。目前,我的代码仅适用于一个输入文件,因此提供了一个输出。我的输入文件被命名为model000.msh,但事实上我有一系列名称为model000.msh、model001.msh 等的输入文件。在代码中,我正在对导入的文件进行一些计算,最后将其与另一个 numpy 数组 (ID) 生成的 numpy 数组 (my_data) 进行比较,该数组具有一列和数千行。 ID 数组是我要迭代的第二个变量。 ID 正在通过 np.concatenate 函数生成 my_data。我想使用ID 的每一列来制作my_data (my_data=np.concatenate((ID[:,iterator], gr), axis =1))。所以,我想遍历几个文件,然后从每个文件(extracted)中提取数组,然后按照循环从ID 的每一列生成my_data,并对my_data 和extracted 进行计算最后以动态命名方式(changed_000、changed_001等)导出每次迭代的结果。这是我的一个输入和一个 my_data 数组的代码(由一个只有一列的 ID 创建),但我想更改对多个输入文件和几个 my_data 数组的迭代,最后是几个输出:
from itertools import islice
with open('model000.msh') as lines:
nodes = np.genfromtxt(islice(lines, 0, 1000))
with open('model000.msh', "r") as f:
saved_lines = np.array([line.split() for line in f if len(line.split()) == 9])
saved_lines[saved_lines == ''] = 0.0
elem = saved_lines.astype(np.int)
# following lines extract some data from my file
extracted=np.c_[elem[:,:-4], nodes[elem[:,-4]-1, 1:], nodes[elem[:,-3]-1, 1:],nodes[elem[:,-2]-1, 1:], nodes[elem[:,-1]-1, 1:]]
…
extracted =np.concatenate((extracted, avs), axis =1) # each input file ('model000.msh') will make this numpy array
# another data set, stored as a numpy array is compared to the data extracted from the file
ID= np.array [[… ..., …, …]] # now, it is has one column, but it should have several columns and each iteration, one column will make a my_data array
my_data=np.concatenate((ID, gr), axis =1) # I think it should be something like my_data=np.concatenate((ID[:,iterator], gr), axis =1)
from scipy.spatial import distance
distances=distance.cdist(extracted [:,17:20],my_data[:,1:4])
ind_min_dis=np.argmin(distances, axis=1).reshape(-1,1)
z=np.array([])
for i in ind_min_dis:
u=my_data[i,0]
z=np.array([np.append(z,u)]).reshape(-1,1)
final_merged=np.concatenate((extracted,z), axis =1)
new_vol=final_merged[:,-1].reshape(-1,1)
new_elements=np.concatenate((elements,new_vol), axis =1)
new_elements[:,[4,-1]] = new_elements[:,[-1,4]]
# The next block is output block
chunk_size = 3
buffer = ""
i = 0
relavent_line = 0
with open('changed_00', 'a') as fout:
with open('model000.msh', 'r') as fin:
for line in fin:
if len(line.split()) == 9:
aux_string = ' '.join([str(num) for num in new_elements[relavent_line]])
buffer += '%s\n' % aux_string
relavent_line += 1
else:
buffer += line
i+=1
if i == chunk_size:
fout.write(buffer)
i=0
buffer = ""
if buffer:
fout.write(buffer)
i=0
buffer = ""
感谢您提前提供的任何帮助。
【问题讨论】: