Heatmap_3D.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. import UnityEngine as ue
  2. import pandas as pd
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. import matplotlib.cm as cm
  6. import json
  7. from matplotlib.colors import LinearSegmentedColormap
  8. from sklearn import preprocessing
  9. from mpl_toolkits.mplot3d import Axes3D
  10. WIDTH = int(70)
  11. HEIGHT = int(35)
  12. COND = "0"
  13. INDEX = "1"
  14. POSITION_PATH = ue.Application.dataPath + '/Data_position/'+ COND +'/Walk'+ INDEX +'.csv'
  15. HEATMAP_PATH = 'Assets/Data_image/'+ COND +'/heatmap3D'+ INDEX +'.png'
  16. SAVEFILE = 'Assets/Resources/Json/'+ COND +'/heatmap3D'+ INDEX +'.json'
  17. def get_data_hight(dataset):
  18. dataset_human_on_same_spot = dataset.groupby(["Delta Time", "Position x", "Position z"]).size().reset_index(name='AmountOneSpot')
  19. dataset_human_amount_per_deltaTime = dataset_human_on_same_spot.groupby(['Delta Time']).size().reset_index(name='counts')
  20. solution = np.zeros((HEIGHT, WIDTH))
  21. old = np.zeros((HEIGHT, WIDTH))
  22. current = np.zeros((HEIGHT, WIDTH))
  23. minStart = 0
  24. for i in range(dataset_human_amount_per_deltaTime.shape[0]):
  25. for count in range(minStart, minStart + int(dataset_human_amount_per_deltaTime['counts'][i])):
  26. x = int(dataset_human_on_same_spot['Position x'][count])
  27. y = int(dataset_human_on_same_spot['Position z'][count])
  28. if i == 0:
  29. old[y][x] = dataset_human_on_same_spot['AmountOneSpot'][count]
  30. else :
  31. current[y][x] = dataset_human_on_same_spot['AmountOneSpot'][count]
  32. if i > 0:
  33. solution = solution + np.absolute(old - current)
  34. old = current
  35. current = np.zeros((HEIGHT, WIDTH))
  36. minStart += int(dataset_human_amount_per_deltaTime['counts'][i])
  37. return solution
  38. # 1. Get position data from csv file
  39. data = pd.read_csv(POSITION_PATH, sep=';', usecols=["Delta Time", "Position x", "Position z"], decimal=',', dtype={'Delta Time': float, 'Position x': float, 'Position z': float})
  40. data["Position x"] = data["Position x"].round(0)
  41. data["Position z"] = data["Position z"].round(0)
  42. data["Delta Time"] = data["Delta Time"].round(2)
  43. for i in range(len(data["Position x"].tolist())):
  44. if data["Position x"][i] % 2 != 0:
  45. data["Position x"][i] -= 1
  46. if data["Position z"][i] % 2 != 0:
  47. data["Position z"][i] -= 1
  48. # 2. Group by positions and count appearance
  49. data_count = data.groupby(['Position x', 'Position z']).size().reset_index(name='counts')
  50. # 3.1 Assign x, y, z
  51. x = data_count["Position x"].tolist()
  52. y = data_count["Position z"].tolist()
  53. z = np.zeros_like(len(x))
  54. # 3.2 Assign height of the bars
  55. dz_dynamic = get_data_hight(data)
  56. dz = []
  57. for i in range(len(x)):
  58. dz.append(dz_dynamic[int(y[i])][int(x[i])])
  59. # 4. Create figure and axes
  60. fig = plt.figure()
  61. ax = fig.add_subplot(111, projection='3d')
  62. # 5.1 Create custom colormap Day1, Day2, Day3
  63. cmap = LinearSegmentedColormap.from_list(name='day1', colors=[(0.40,0.76,0.65), (0.11,0.62,0.47)])
  64. # cmap = LinearSegmentedColormap.from_list(name='day2', colors=[(0.99,0.55,0.38), (0.85,0.37,0.01)])
  65. # cmap = LinearSegmentedColormap.from_list(name='day3', colors=[(0.55,0.63,0.80), (0.46,0.44,0.70)])
  66. # 5.2 Initialize array for coloring the bars
  67. dz_array = np.array(data_count['counts'])
  68. fracs = dz_array.astype(float) / dz_array.max()
  69. color_values = cmap(fracs.tolist())
  70. # 5.3 calculate alpha value of the bars
  71. alpha_values = np.array(data_count['counts'])
  72. alpha_values = alpha_values.astype(np.float)
  73. alpha_values = (alpha_values - alpha_values.min()) / (alpha_values.max() - alpha_values.min())
  74. # 6. Create the bars
  75. # for i in range(len(x)):
  76. # img = ax.bar3d(x[i], y[i], z, 1, 1, dz[i], color=color_values[i], shade=False)
  77. img = ax.bar3d(x, y, z, 1, 1, dz, color=color_values, shade=False)
  78. # 7. Create Colorbar
  79. color_intense = data_count['counts'].tolist()
  80. color_map = cm.ScalarMappable(cmap=cmap)
  81. color_map.set_array(color_intense)
  82. fig.colorbar(color_map)
  83. # 8.
  84. ax.set_xlabel('Width')
  85. ax.set_ylabel('Height')
  86. ax.set_zlabel('Human dynamic')
  87. plt.show()
  88. # 10. Save 3D Heatmap
  89. # heatmap.get_figure().savefig(HEATMAP_PATH, transparent=True)
  90. # fig.savefig(HEATMAP_PATH, transparent=True)
  91. # 11. Save the data from the Heatmap to create it in Unity
  92. dz = (np.array(dz)/np.array(dz).max()).tolist()
  93. jsonData = {"x1" : x,
  94. "y1" : y,
  95. "z1" : z.tolist(),
  96. "dz1" : dz,
  97. "alpha_values1" : alpha_values.flatten().tolist(),
  98. "x2" : 0,
  99. "y2" : 0,
  100. "z2" : 0,
  101. "dz2" : 0,
  102. "alpha_values2" : np.zeros_like(alpha_values).tolist(),
  103. "x3" : 0,
  104. "y3" : 0,
  105. "z3" : 0,
  106. "dz3" : 0,
  107. "alpha_values3" : np.zeros_like(alpha_values).tolist()}
  108. with open(SAVEFILE, 'w') as filehandle:
  109. json.dump(jsonData, filehandle)