common.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. ##################################################################
  4. #
  5. # Copyright (c) 2023 CICV, Inc. All Rights Reserved
  6. #
  7. ##################################################################
  8. """
  9. @Authors: yangzihao(yangzihao@china-icv.cn)
  10. @Data: 2023/07/24
  11. @Last Modified: 2023/07/24
  12. @Summary: Evaluateion functions
  13. """
  14. import sys
  15. sys.path.append('../common')
  16. sys.path.append('../modules')
  17. import os
  18. import time
  19. import json
  20. import math
  21. import pandas as pd
  22. import numpy as np
  23. import zipfile
  24. import importlib
  25. import matplotlib.pyplot as plt
  26. def _cal_max_min_avg(num_list):
  27. maxx = round(max(num_list), 3) if len(num_list)>0 else "-"
  28. minn = round(min(num_list), 3) if len(num_list)>0 else "-"
  29. avg = round(sum(num_list) / len(num_list), 3) if len(num_list)>0 else "-"
  30. result = {
  31. "max": maxx,
  32. "min": minn,
  33. "avg": avg
  34. }
  35. return result
  36. def save_line_chart(list1, list2, save_path):
  37. plt.plot(list1, label='列表1')
  38. plt.plot(list2, label='列表2')
  39. plt.xlabel('索引')
  40. plt.ylabel('值')
  41. plt.title('折线图')
  42. plt.legend()
  43. plt.savefig(save_path)
  44. plt.close()
  45. def import_class(path, file):
  46. sys.path.append(path) # 将path添加到Python的搜索路径中
  47. # module_name = file[:-3] # 去掉文件名的".py"后缀
  48. module = __import__(file, fromlist=['ScoreModel'])
  49. class_instance = module.ScoreModel
  50. return class_instance
  51. def import_class_lib(path, file):
  52. sys.path.append(path) # 将path添加到Python的搜索路径中
  53. module = importlib.import_module(file)
  54. class_name = "ScoreModel"
  55. class_instance = getattr(module, class_name)
  56. return class_instance
  57. def score_over_100(score):
  58. if score > 100:
  59. return 100
  60. return score
  61. def normalize_dict_values(dictionary):
  62. # 计算字典中键的数量
  63. n = len(dictionary)
  64. # 初始化总和为0
  65. total_sum = 0
  66. # 遍历字典,对每个值进行赋值,并累加总和
  67. for key, value in dictionary.items():
  68. # 计算当前值,除了最后一个值外都四舍五入到两位小数
  69. if key != list(dictionary.keys())[-1]:
  70. new_value = round(1 / n, 2)
  71. else:
  72. # 最后一个值的计算:1减去之前所有值的和
  73. new_value = round(1 - total_sum, 2)
  74. # 更新字典的值
  75. dictionary[key] = new_value
  76. # 累加当前值到总和
  77. total_sum += new_value
  78. return dictionary
  79. def cal_velocity(lat_v, lon_v):
  80. """
  81. The function can calculate the velocity with lateral velocity and longitudinal velocity.
  82. Args:
  83. lat_v: lateral velocity, m/s
  84. lon_v: longitudinal velocity, m/s
  85. Returns:
  86. v: the resultant velocity, km/h
  87. """
  88. v = (lat_v ** 2 + lon_v ** 2) ** 0.5
  89. return v
  90. def json2dict(json_file):
  91. with open(json_file, 'r', encoding='utf-8') as f:
  92. json_dict = json.load(f)
  93. return json_dict
  94. def get_subfolders_name(path):
  95. return [name for name in os.listdir(path) if os.path.isdir(os.path.join(path, name))]
  96. def zip_dir(dir_path, zip_file_path):
  97. """
  98. This function can zip the files in dir_path as a zipfile.
  99. Arguments:
  100. dir_path: A str of the path of the files to be ziped.
  101. zip_file_path: A str of the path of the zipfile to be stored.
  102. Returns:
  103. None
  104. """
  105. with zipfile.ZipFile(zip_file_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
  106. for root, dirs, files in os.walk(dir_path):
  107. for file in files:
  108. file_path = os.path.join(root, file)
  109. zipf.write(file_path)
  110. def score_grade(score):
  111. """
  112. Returns the corresponding grade based on the input score.
  113. Arguments:
  114. score: An integer or float representing the score.
  115. Returns:
  116. grade: A string representing the grade.
  117. """
  118. if score >= 90:
  119. grade = '优秀'
  120. elif score >= 80:
  121. grade = '良好'
  122. elif score > 60:
  123. grade = '一般'
  124. else:
  125. grade = '较差'
  126. return grade
  127. def mileage_format(mileage):
  128. if mileage < 1000:
  129. return f"{mileage:.2f}米"
  130. else:
  131. mileage = mileage / 1000
  132. return f"{mileage:.2f}公里"
  133. def duration_format(duration):
  134. if duration < 60:
  135. return f"{duration:.2f}秒"
  136. elif duration < 3600:
  137. minute = int(duration / 60)
  138. second = int(duration % 60)
  139. return f"{minute}分{second}秒" if second != 0 else f"{minute}分"
  140. else:
  141. hour = int(duration / 3600)
  142. minute = int((duration % 3600) / 60)
  143. second = int(duration % 60)
  144. ans = f"{hour:d}时"
  145. ans = ans + f"{minute}分" if minute != 0 else ans
  146. ans = ans + f"{second}秒" if second != 0 else ans
  147. return ans
  148. def continuous_group(df):
  149. time_list = df['simTime'].values.tolist()
  150. frame_list = df['simFrame'].values.tolist()
  151. group_time = []
  152. group_frame = []
  153. sub_group_time = []
  154. sub_group_frame = []
  155. for i in range(len(frame_list)):
  156. if not sub_group_time or frame_list[i] - frame_list[i - 1] <= 1:
  157. sub_group_time.append(time_list[i])
  158. sub_group_frame.append(frame_list[i])
  159. else:
  160. group_time.append(sub_group_time)
  161. group_frame.append(sub_group_frame)
  162. sub_group_time = [time_list[i]]
  163. sub_group_frame = [frame_list[i]]
  164. group_time.append(sub_group_time)
  165. group_frame.append(sub_group_frame)
  166. group_time = [g for g in group_time if len(g) >= 2]
  167. group_frame = [g for g in group_frame if len(g) >= 2]
  168. # 输出图表值
  169. time = [[g[0], g[-1]] for g in group_time]
  170. frame = [[g[0], g[-1]] for g in group_frame]
  171. time_df = pd.DataFrame(time, columns=['start_time', 'end_time'])
  172. frame_df = pd.DataFrame(frame, columns=['start_frame', 'end_frame'])
  173. result_df = pd.concat([time_df, frame_df], axis=1)
  174. return result_df
  175. def continuous_group_old(df):
  176. time_list = df['simTime'].values.tolist()
  177. frame_list = df['simFrame'].values.tolist()
  178. group = []
  179. sub_group = []
  180. for i in range(len(frame_list)):
  181. if not sub_group or frame_list[i] - frame_list[i - 1] <= 1:
  182. sub_group.append(time_list[i])
  183. else:
  184. group.append(sub_group)
  185. sub_group = [time_list[i]]
  186. group.append(sub_group)
  187. group = [g for g in group if len(g) >= 2]
  188. # 输出图表值
  189. time = [[g[0], g[-1]] for g in group]
  190. unsafe_df = pd.DataFrame(time, columns=['start_time', 'end_time'])
  191. return unsafe_df
  192. def get_frame_with_time(df1, df2):
  193. # 将dataframe1按照start_time与simTime进行合并
  194. df1_start = df1.merge(df2[['simTime', 'simFrame']], left_on='start_time', right_on='simTime')
  195. df1_start = df1_start[['start_time', 'simFrame']].copy()
  196. df1_start.rename(columns={'simFrame': 'start_frame'}, inplace=True)
  197. # 将dataframe1按照end_time与simTime进行合并
  198. df1_end = df1.merge(df2[['simTime', 'simFrame']], left_on='end_time', right_on='simTime')
  199. df1_end = df1_end[['end_time', 'simFrame']].copy()
  200. df1_end.rename(columns={'simFrame': 'end_frame'}, inplace=True)
  201. # 将两个合并后的数据框按照行索引进行拼接
  202. result = pd.concat([df1_start, df1_end], axis=1)
  203. return result
  204. def string_concatenate(str_list):
  205. """
  206. This function concatenates the input string list to generate a new string.
  207. If str_list is empty, an empty string is returned.
  208. If str_list has only one element, return that element.
  209. If str_list has multiple elements, concatenate all the elements except the last element with ', ', and then concatenate the resulting string with the last element with 'and'.
  210. Arguments:
  211. str_list: A list of strings.
  212. Returns:
  213. ans_str: A concatenated string.
  214. """
  215. if not str_list:
  216. return ""
  217. ans_str = '、'.join(str_list[:-1])
  218. ans_str = ans_str + "和" + str_list[-1] if len(str_list) > 1 else ans_str + str_list[-1]
  219. return ans_str
  220. def zip_time_pairs(time_list, zip_list, upper_limit=9999):
  221. zip_time_pairs = zip(time_list, zip_list)
  222. zip_vs_time = [[x, upper_limit if y > upper_limit else y] for x, y in zip_time_pairs if not math.isnan(y)]
  223. return zip_vs_time
  224. def replace_key_with_value(input_string, replacement_dict):
  225. """
  226. 替换字符串中的关键字为给定的字典中的值。
  227. :param input_string: 需要进行替换的字符串
  228. :param replacement_dict: 替换规则,格式为 {key: value}
  229. :return: 替换后的字符串
  230. """
  231. # 遍历字典中的键值对,并用值替换字符串中的键
  232. for key, value in replacement_dict.items():
  233. if key in input_string:
  234. input_string = input_string.replace(key, value)
  235. return input_string
  236. def continous_judge(frame_list):
  237. if not frame_list:
  238. return 0
  239. cnt = 1
  240. for i in range(1, len(frame_list)):
  241. if frame_list[i] - frame_list[i - 1] <= 3:
  242. continue
  243. cnt += 1
  244. return cnt
  245. def get_interpolation(x, point1, point2):
  246. """
  247. According to the two extreme value points, the equation of one variable is determined,
  248. and the solution of the equation is obtained in the domain of definition.
  249. Arguments:
  250. x: A float number of the independent variable.
  251. point1: A set of the coordinate extreme point.
  252. point2: A set of the other coordinate extreme point.
  253. Returns:
  254. y: A float number of the dependent variable.
  255. """
  256. try:
  257. k = (point1[1] - point2[1]) / (point1[0] - point2[0])
  258. b = (point1[0] * point2[1] - point1[1] * point2[0]) / (point1[0] - point2[0])
  259. y = x * k + b
  260. return y
  261. except Exception as e:
  262. return f"Error: {str(e)}"
  263. def statistic_analysis(data_list):
  264. sorted_data_list = sorted(data_list)
  265. maxx = sorted_data_list[-1]
  266. minn = sorted_data_list[0]
  267. meann = sum(sorted_data_list) / len(sorted_data_list)
  268. percentile_99 = np.percentile(sorted_data_list, 99)
  269. ans_list = [maxx, minn, meann, percentile_99]
  270. return ans_list