jmartinezot commited on
Commit
a7d6c33
·
1 Parent(s): fd843fb

Adding distortions

Browse files
Files changed (3) hide show
  1. GenerarSinteticos_3coord_denak.py +88 -0
  2. aaaaa.py +13 -2
  3. app.py +43 -14
GenerarSinteticos_3coord_denak.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ from scipy.stats import multivariate_normal
4
+ import matplotlib.pyplot as plt
5
+ from mpl_toolkits.mplot3d import Axes3D
6
+ import aaaaa
7
+
8
+ # checked; it is ok
9
+ # To generate distorsed covariance matrixes
10
+ def genS(sds, R, distor=1):
11
+ # sds: standard deviations
12
+ # R: correlation matrix
13
+ # distor: level of distorsion
14
+ sdsdis = sds * distor
15
+ S = R * np.outer(sdsdis, sdsdis)
16
+ np.fill_diagonal(S, sdsdis ** 2)
17
+ return S
18
+
19
+ original_data_path = "/home/scpmaotj/Github/hcr/reference_data/"
20
+ synthetic_data_path = "/home/scpmaotj/Github/hcr/synthetic_data/"
21
+ plots_path = "/home/scpmaotj/Github/hcr/plots/"
22
+ nkey = 21
23
+
24
+ #Nivel distorsion
25
+ # 1 - Distorsionamos las desviaciones sin distorsionar la estructura de correlacion
26
+ # Funcion genS()
27
+ d = [1, 1.01, 1.05, 1.1, 1.2, 1.5, 1.7, 2]
28
+ # 2 - Distorsionamos las desviaciones y la estrucctura de correlacion
29
+ # Funcion???
30
+
31
+ # Intento sacar una mano al azar de una normal multivariante.
32
+ # Sacaremos m=100 observaciones
33
+ m = 100
34
+ #gesto <- 1
35
+
36
+ #for gesto in range(1, 43):
37
+ for gesto in range(1, 2):
38
+ print(gesto)
39
+ datXYZ = aaaaa.get_datXYZ(gesto, original_data_path)
40
+ # Hacemos un grafico con ndib= 16 lecturas, no las 16 primeras sino desplazadas pos=4 posiciones
41
+ ndib = 16
42
+ pos = 4
43
+ hands = datXYZ[pos:pos+ndib].reshape(ndib, nkey, 3)
44
+ fig, axes = plt.subplots(4, 4, subplot_kw={'projection': '3d'})
45
+ for i, ax in enumerate(axes.flat):
46
+ ax.scatter(hands[i, :, 0], hands[i, :, 1], hands[i, :, 2], c='b', marker='o')
47
+ ax.set_title(f"Original {i+pos}")
48
+ plt.savefig(plots_path + f"{gesto}orig.pdf")
49
+ plt.close()
50
+
51
+ obsmean = np.mean(datXYZ, axis=0)
52
+ obssd = np.std(datXYZ, axis=0)
53
+ R = np.corrcoef(datXYZ, rowvar=False)
54
+
55
+ id = len(d)
56
+ np.random.seed(3663)
57
+
58
+ for i in range(id):
59
+ Sberria = genS(obssd, R, distor=d[i])
60
+ z = multivariate_normal.rvs(mean=obsmean, cov=Sberria, size=m)
61
+ np.savetxt(synthetic_data_path + f"gesto{gesto}d{i-1}.csv", z, delimiter=',', fmt='%.6f')
62
+ simhands = z[pos:pos+ndib].reshape(ndib, nkey, 3).transpose(0, 2, 1)
63
+ fig, axes = plt.subplots(4, 4, subplot_kw={'projection': '3d'})
64
+ for j, ax in enumerate(axes.flat):
65
+ ax.scatter(simhands[j, 0, :], simhands[j, 1, :], simhands[j, 2, :], c='b', marker='o')
66
+ ax.set_title(f"Simulated, d={i-1}, It. {j+4}")
67
+ plt.savefig(plots_path + f"gesto{gesto}_3coord_d{i-1}.pdf")
68
+ plt.close()
69
+
70
+ # Selecciono un gesto, y miro algunas configuraciones simuladas segun grado de distorsion
71
+ gesto = 4
72
+ gd = 0
73
+ mirar = synthetic_data_path + f"gesto{gesto}d{gd}.csv"
74
+ z = np.loadtxt(mirar, delimiter=',')
75
+ m = z.shape[0]
76
+ simhands = np.zeros((nkey, 3, m))
77
+ for i in range(m):
78
+ simhands[:, :, i] = z[i].reshape(nkey, 3)
79
+ simhands = simhands.transpose(2, 0, 1)
80
+ simhands = np.swapaxes(simhands, 1, 2)
81
+ fig, axes = plt.subplots(4, 4, subplot_kw={'projection': '3d'})
82
+ for i, ax in enumerate(axes.flat):
83
+ ax.scatter(simhands[i, 0, :], simhands[i, 1, :], simhands[i, 2, :], c='b', marker='o')
84
+ ax.set_title(str(i+1))
85
+ plt.show()
86
+
87
+
88
+
aaaaa.py CHANGED
@@ -2,6 +2,16 @@ import csv
2
  import numpy as np
3
  import plotly.graph_objects as go
4
 
 
 
 
 
 
 
 
 
 
 
5
  def get_datXYZ(gesto, data_path):
6
  file_path = data_path + f"config{gesto}.csv"
7
  with open(file_path, 'r') as file:
@@ -15,7 +25,7 @@ def get_datXYZ(gesto, data_path):
15
  coordinates[i, j] = [x, y, z]
16
  return coordinates
17
 
18
- def plot_3d_points(points_21_3d):
19
  # Create a scatter plot
20
  colors = ['red', 'green', 'yellow', 'orange', 'blue']
21
  colors = ["purple"]
@@ -55,6 +65,7 @@ def plot_3d_points(points_21_3d):
55
  z=[start_point[2], end_point[2]],
56
  mode='lines',
57
  line=dict(color='black', width=2),
 
58
  showlegend=False
59
  )
60
 
@@ -68,7 +79,7 @@ def plot_3d_points(points_21_3d):
68
  zaxis=dict(title='Z')
69
  ),
70
  dragmode = 'orbit',
71
- title='3D Random Points'
72
  )
73
 
74
  # Return the figure
 
2
  import numpy as np
3
  import plotly.graph_objects as go
4
 
5
+ # To generate distorsed covariance matrixes
6
+ def genS(sds, R, distor=1):
7
+ # sds: standard deviations
8
+ # R: correlation matrix
9
+ # distor: level of distorsion
10
+ sdsdis = sds * distor
11
+ S = R * np.outer(sdsdis, sdsdis)
12
+ np.fill_diagonal(S, sdsdis ** 2)
13
+ return S
14
+
15
  def get_datXYZ(gesto, data_path):
16
  file_path = data_path + f"config{gesto}.csv"
17
  with open(file_path, 'r') as file:
 
25
  coordinates[i, j] = [x, y, z]
26
  return coordinates
27
 
28
+ def plot_3d_points(points_21_3d, title):
29
  # Create a scatter plot
30
  colors = ['red', 'green', 'yellow', 'orange', 'blue']
31
  colors = ["purple"]
 
65
  z=[start_point[2], end_point[2]],
66
  mode='lines',
67
  line=dict(color='black', width=2),
68
+ name ="",
69
  showlegend=False
70
  )
71
 
 
79
  zaxis=dict(title='Z')
80
  ),
81
  dragmode = 'orbit',
82
+ title=title
83
  )
84
 
85
  # Return the figure
app.py CHANGED
@@ -5,36 +5,65 @@ import matplotlib.pyplot as plt
5
  from mpl_toolkits.mplot3d import Axes3D
6
  from gradio.components import Slider, Number, Image, Dataframe, Textbox, Checkbox, Radio, Label, Plot
7
  import plotly.graph_objects as go
8
- import csv
9
- from aaaaa import get_datXYZ, plot_3d_points
10
  import PIL.Image
11
 
12
  data_path = "reference_data/"
13
  image_path = "images_configs/"
14
 
15
- def show_hand_3d(gesto, data_path, image_path):
 
 
 
 
 
 
 
 
 
 
16
  datXYZ = get_datXYZ(gesto, data_path)
17
  print(datXYZ.shape)
18
- print(datXYZ)
19
- first_row = datXYZ[0] # Extract the first row of the array
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  reshaped_array = first_row[:63].reshape(21, 3) # Reshape the first row to (21, 3)
21
- hand_plot = plot_3d_points(reshaped_array)
 
 
 
 
 
 
22
  image_filename = image_path + str(int(gesto)) + ".png"
23
  print(image_filename)
24
  image = PIL.Image.open(image_filename)
25
- width, height = image.size
26
- newsize = (width // 2, height // 2)
27
- image = image.resize(newsize)
28
  # image = Image(image_filename) # Load the corresponding image
29
- return image, hand_plot
30
 
31
  inputs = [
32
- Number(value=42, precision=0, label="Number of Hand Configuration"),
33
- Textbox(label="Data Path", value="reference_data/"),
34
- Textbox(label="Image Path", value="images_configs/")
 
 
35
  ]
36
 
37
- outputs = [Image(type="pil", shape=(50,50)), Plot()]
38
 
39
  title = "Hand 3D Visualization"
40
  description = "Enter the gesture number (gesto) and the data path (data_path) to visualize the hand in 3D."
 
5
  from mpl_toolkits.mplot3d import Axes3D
6
  from gradio.components import Slider, Number, Image, Dataframe, Textbox, Checkbox, Radio, Label, Plot
7
  import plotly.graph_objects as go
8
+ from aaaaa import get_datXYZ, plot_3d_points, genS
9
+ from scipy.stats import multivariate_normal
10
  import PIL.Image
11
 
12
  data_path = "reference_data/"
13
  image_path = "images_configs/"
14
 
15
+ # To generate distorsed covariance matrixes
16
+ def genS(sds, R, distor=1):
17
+ # sds: standard deviations
18
+ # R: correlation matrix
19
+ # distor: level of distorsion
20
+ sdsdis = sds * distor
21
+ S = R * np.outer(sdsdis, sdsdis)
22
+ np.fill_diagonal(S, sdsdis ** 2)
23
+ return S
24
+
25
+ def show_hand_3d(gesto, attempt, distortion, mean, std):
26
  datXYZ = get_datXYZ(gesto, data_path)
27
  print(datXYZ.shape)
28
+ # print(datXYZ)
29
+ obsmean = np.mean(datXYZ, axis=0)
30
+ print(obsmean.shape)
31
+ # change to 63 shape
32
+ obsmean = obsmean.reshape(63)
33
+ obssd = np.std(datXYZ, axis=0)
34
+ print(obssd.shape)
35
+ obssd = obssd.reshape(63)
36
+ datXYZ_reshaped = datXYZ.reshape(datXYZ.shape[0], -1)
37
+ R = np.corrcoef(datXYZ_reshaped, rowvar=False)
38
+ Sberria = genS(obssd, R, distor=distortion)
39
+ z = multivariate_normal.rvs(mean=obsmean, cov=Sberria, size=1)
40
+ print(z.shape)
41
+ # print(z)
42
+ # add here the code to transform z into an array eith the same shape as datXYZ
43
+ first_row = datXYZ[attempt] # Extract the attempt row of the array
44
  reshaped_array = first_row[:63].reshape(21, 3) # Reshape the first row to (21, 3)
45
+ # create noise from mean and std
46
+ noise = np.random.normal(mean, std, reshaped_array.shape)
47
+ reshaped_array_with_noise = reshaped_array + noise
48
+ distorted_hand = z.reshape(reshaped_array.shape)
49
+ hand_plot = plot_3d_points(reshaped_array, "Recorded Hand Configuration")
50
+ distorted_hand_plot = plot_3d_points(distorted_hand, "Distorted Hand Configuration (global)")
51
+ reshaped_array_with_noise_plot = plot_3d_points(reshaped_array_with_noise, "Distorted Hand Configuration (individual))")
52
  image_filename = image_path + str(int(gesto)) + ".png"
53
  print(image_filename)
54
  image = PIL.Image.open(image_filename)
 
 
 
55
  # image = Image(image_filename) # Load the corresponding image
56
+ return image, hand_plot, distorted_hand_plot, reshaped_array_with_noise_plot
57
 
58
  inputs = [
59
+ Number(value=42, precision=0, label="Number of Kind of Hand Configuration"),
60
+ Number(value=0, precision=0, label="Number of Concrete Hand Attempt"),
61
+ Number(value=1.0, label="Distortion Level"),
62
+ Number(value=0.0, label="Mean Distortion Level (one hand)"),
63
+ Number(value=0.006, label="Standard Deviation Distortion Level (one hand)")
64
  ]
65
 
66
+ outputs = [Image(type="pil"), Plot(), Plot(), Plot()]
67
 
68
  title = "Hand 3D Visualization"
69
  description = "Enter the gesture number (gesto) and the data path (data_path) to visualize the hand in 3D."