2021年4月12日 星期一

如何快速讀取兩個Q3D Matrix CSV並計算及輸出偏差值圖及CSV表

 

"""
Created on Thu Apr 8 11:16:35 2021
Output deviation of 2 Q3D matrix
@author: mlin
"""
# -------------------------------User Input-------------------------------------
path = 'd:/demo'
f_pair = [('case1.csv', 'case2.csv'), ]

# ---------------------------Don't Revise Code Below----------------------------
import os, math
import matplotlib.pyplot as plt

matrix_type = ['Capacitance Matrix',
'Conductance Matrix',
'DC Inductance Matrix',
'DC Resistance Matrix',
'AC Inductance Matrix',
'AC Resistance Matrix', ]


def getDiagonal(x):
N = int(math.sqrt(len(x)))
result = [x[i * N + i] for i in range(N)]
return result


def readQ3Dcsv(csv_path):
data = {i: [] for i in matrix_type}
name = {i: [] for i in matrix_type}

with open(csv_path) as f:
for line in f:
if line.strip() in matrix_type:
mtype = line.strip()
continue
else:
for i in line.strip().split(','):
try:
data[mtype].append(float(i))
continue
except:
...

try:
if i.strip() != '':
name[mtype].append(i)
except:
...

result = {i: getDiagonal(data[i]) for i in data}
return result, name


for f1, f2 in f_pair:
label = '{} - {}'.format(f1.split('.')[0], f2.split('.')[0])

f1 = os.path.join(path, f1)
f2 = os.path.join(path, f2)
data1, name1 = readQ3Dcsv(f1)
data2, name2 = readQ3Dcsv(f2)

with open(os.path.join(path, label + '.csv'), 'w') as f:
for mtype in data1:
result = []
f.writelines(f'\n[{mtype}]\n')
png_name = f'{label} [{mtype}]'
title = f'{label}\n[{mtype}]'
try:
for name, v1, v2 in zip(name1[mtype], data1[mtype], data2[mtype]):
deviation = (v2 - v1) * 100 / v1
result.append(deviation)
f.writelines(f'{name:36}{v2:12}{v1:12}{deviation:12.3f}%\n')
plt.plot(result, linewidth=1, color='b')
plt.title(title)
plt.ylim(-2, 2)
plt.grid()
plt.ylabel('deviation(%)')
plt.savefig(os.path.join(path, png_name + '.png'))
plt.show()
except:
print(f'Failed: {label}, {mtype}')

(圖一)差異圖

(圖二)差異表



沒有留言:

張貼留言