Python 读取文本格式的 golden 和 target 数据对比写出报告

2024-01-09 15:41:48

前言

Python 读取文本格式的 golden 和 target 数据对比并将报告写入到文本文件中

golden 和 target 数据格式

case1 result 0.2
case2 result 0.3
case3 result 0.35
case4 result 0.012

程序


import os
import sys
import math
import argparse
import pprint
from collections import OrderedDict


def CommandParser():
  parser = argparse.ArgumentParser()
  parser.add_argument('--golden', '-g', type=str, required=True, help='given ref(golden) file for analysis')
  parser.add_argument('--target', '-t', type=str, required=True, help='given target file for analysis')
  parser.add_argument('--out', '-o', type=str, required=False, default='anaysis_result.txt', help='output filename, default is "anaysis_result.txt"')
  return parser.parse_args()


def readFile(file_name):

  valMap = OrderedDict()
  f = open(file_name)
  lines = f.readlines()
  for line in lines :
    line = line.strip('\n')
    line = line.split(' ')
    case = line[0]
    value = float(line[2])
    valMap[case] = value

  f.close()
  return valMap


def generate_report(golden, target, file_name):

  f = open(file_name, 'w')
  errors = []
  f.write('{0:<30s} | {1:<8s} {2:<8s} | {3:<8s}\n'.format('case', 'golden', 'target', 'error'))
  for case in golden:
    gol = golden[case]
    if case not in target:
      f.write('{0:<30s} | {1:<8.3f} {2:<8s} | {3:<8s}\n'.format(case, gol, '--', '--'))
    else:
      tar = target[case]
      err = gol/tar - 1.0
      errors.append(err)
      f.write('{0:<30s} | {1:<8.3f} {2:<8.3f} | {3:<8.2%}\n'.format(case, gol, tar, err))
  
  mean = sum(errors)/len(errors)
  var = sum([pow(err-mean, 2) for err in errors]) / len(errors)
  std2 = 2.0*math.sqrt(var)
  max_error = max(errors)
  min_error = min(errors)
  outP5 = sum([1 if err > 0.05 else 0 for err in errors])
  outN5 = sum([1 if err <- 0.05 else 0 for err in errors])

  f.write('\n')
  f.write('mean : {0:8.2%}\n'.format(mean)) 
  f.write('2sigma : {0:8.2%}\n'.format(std2)) 
  f.write('max : {0:8.2%}\n'.format(max_error)) 
  f.write('min : {0:8.2%}\n'.format(min_error

  f.close()



if __name__ == '__main__':

  args = CommandParser()
  if  not os.path.exists(args.golden) : 
    print(args.golden, " is not exit, please check it.")
  if  not os.path.exists(args.target) : 
    print(args.target, " is not exit, please check it.")

  golden = readFile(args.golden)
  target = readFile(args.target)
  #print(golden)
  #print(target)

  generate_report(golden, target, args.out)



文章来源:https://blog.csdn.net/guihunkun/article/details/135479501
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。