x2XcarleX2x commited on
Commit
cb02dd8
·
verified ·
1 Parent(s): bb43153

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -38
app.py CHANGED
@@ -2,21 +2,31 @@ import gradio as gr
2
  import numpy as np
3
  import matplotlib.pyplot as plt
4
  from mpl_toolkits.mplot3d import Axes3D
 
 
5
  import math
6
  from scipy.special import comb
7
  import time
8
 
9
- # --- Funções Matemáticas ---
 
 
 
 
10
 
11
  def bernstein_poly(i, n, t):
12
  return comb(n, i) * (t**(i)) * ((1 - t)**(n - i))
13
 
14
- def bezier_curve_3d(points, n_times=20): # 20 vetores para alta velocidade
15
  n_points = len(points)
16
- x_points, y_points, z_points = np.array([p[0] for p in points]), np.array([p[1] for p in points]), np.array([p[2] for p in points])
 
 
17
  t = np.linspace(0.0, 1.0, n_times)
18
  polynomial_array = np.array([bernstein_poly(i, n_points - 1, t) for i in range(n_points)])
19
- x_vals, y_vals, z_vals = np.dot(x_points, polynomial_array), np.dot(y_points, polynomial_array), np.dot(z_points, polynomial_array)
 
 
20
  return x_vals, y_vals, z_vals
21
 
22
  def aprender_com_o_eco_3d(pontos_do_eco: list):
@@ -24,25 +34,27 @@ def aprender_com_o_eco_3d(pontos_do_eco: list):
24
  p1, p2 = np.array(pontos_do_eco[0]), np.array(pontos_do_eco[-1])
25
  return {"velocity_vector": p2 - p1}
26
 
27
- # --- Função Principal do Gradio (Motor Hyperdrive com Ambiente Fixo) ---
28
 
29
  def motor_da_simulacao_infinita(angulo_camera: int):
30
- """
31
- Motor da simulação que roda em um loop infinito, com um universo compacto,
32
- velocidade extrema e um AMBIENTE FIXO.
33
- """
34
- ponto_a = np.array([0., 0., 0.])
35
- vetor_inercia = np.array([12., 12., 12.])
36
  historico_rastro = [ponto_a.tolist()]
37
 
38
  fig = plt.figure(figsize=(8, 8)); ax = fig.add_subplot(111, projection='3d')
39
  cor_fundo = '#0a0a0a'; fig.patch.set_facecolor(cor_fundo); ax.set_facecolor(cor_fundo)
 
 
 
 
 
40
 
41
  ciclo_num = 0
42
  while True:
43
  ciclo_num += 1
44
 
45
- ponto_b = np.random.rand(3) * 60 - 24 # Universo compacto
 
46
 
47
  ponto_controle = ponto_a + vetor_inercia
48
  pontos_curva = [ponto_a, ponto_controle, ponto_b]
@@ -50,59 +62,71 @@ def motor_da_simulacao_infinita(angulo_camera: int):
50
 
51
  novos_pontos_rastro = list(zip(x_ciclo, y_ciclo, z_ciclo))
52
  historico_rastro.extend(novos_pontos_rastro)
53
- max_rastro = 8
54
  historico_rastro = historico_rastro[-max_rastro:]
55
 
56
- tamanho_eco = 8
57
- pontos_eco = list(zip(x_ciclo[-tamanho_eco:], y_ciclo[-tamanho_eco:], z_ciclo[-tamanho_eco:]))
58
  vetor_inercia = aprender_com_o_eco_3d(pontos_eco)["velocity_vector"]
59
-
60
- rastro_np = np.array(historico_rastro)
61
 
62
  for frame in range(len(x_ciclo)):
63
  ax.cla()
64
  ax.xaxis.pane.fill = False; ax.yaxis.pane.fill = False; ax.zaxis.pane.fill = False
65
  ax.grid(color='#222222', linestyle='--')
66
-
67
- # --- A MUDANÇA PRINCIPAL: AMBIENTE FIXO ---
68
- # A câmera não gira mais com base no frame. Ela usa o ângulo fixo da UI.
69
- ax.view_init(elev=32., azim=angulo_camera)
70
- # ------------------------------------------
71
-
72
- ax.set_xlim(-32, 32); ax.set_ylim(-32, 32); ax.set_zlim(-32, 32)
73
  ax.set_xticklabels([]); ax.set_yticklabels([]); ax.set_zticklabels([])
74
 
75
- ax.scatter(*ponto_a, s=320, c='lime', alpha=0.4)
76
- ax.scatter(*ponto_b, s=320, c='red', marker='X', alpha=0.8)
77
 
 
 
78
  indice_global_frame = len(historico_rastro) - len(x_ciclo) + frame
79
- ax.plot(rastro_np[:indice_global_frame+1, 0], rastro_np[:indice_global_frame+1, 1], rastro_np[:indice_global_frame+1, 2], '-', color='#ff4500', linewidth=4, alpha=0.6)
 
 
80
 
81
- ax.plot([x_ciclo[frame]], [y_ciclo[frame]], [z_ciclo[frame]], 'o', color='#ff4500', markersize=8, markeredgecolor='white')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
- info_texto = f"Ciclo: {ciclo_num}\nAlvo: {np.round(ponto_b, 1)}"
84
- ax.text2D(0.04, 0.88, info_texto, transform=ax.transAxes, color='white', fontsize=12)
85
 
86
  yield fig
87
- time.sleep(0.008)
88
 
89
  ponto_a = ponto_b
90
 
91
  plt.close(fig)
92
 
93
- # --- Interface Gradio ---
94
- with gr.Blocks(theme=gr.themes.Base(primary_hue="teal", secondary_hue="green")) as demo:
95
  gr.Markdown(
96
  """
97
- # Simulador Autônomo 3D (Hyperdrive Estático)
98
- Defina um ângulo para a câmera e clique em "Iniciar". O agente (bola) irá navegar em
99
- **velocidade extrema** por um universo compacto com um **ponto de vista fixo**.
100
  """
101
  )
102
  with gr.Row():
103
  with gr.Column(scale=1):
104
- angulo_camera_slider = gr.Slider(-180, 180, value=45, label="Ângulo da Câmera (Fixo)")
105
- start_btn = gr.Button("🚀 Iniciar Simulação (Ambiente Fixo)", variant="primary")
106
  with gr.Column(scale=2):
107
  plot_output = gr.Plot(label="Visualização em Tempo Real")
108
 
 
2
  import numpy as np
3
  import matplotlib.pyplot as plt
4
  from mpl_toolkits.mplot3d import Axes3D
5
+ from matplotlib.collections import LineCollection
6
+ from matplotlib.colors import LinearSegmentedColormap
7
  import math
8
  from scipy.special import comb
9
  import time
10
 
11
+ # --- Funções Matemáticas e Utilitários ---
12
+
13
+ def quantizar(valor, multiplo=4):
14
+ """Arredonda um valor para o múltiplo mais próximo."""
15
+ return multiplo * round(valor / multiplo)
16
 
17
  def bernstein_poly(i, n, t):
18
  return comb(n, i) * (t**(i)) * ((1 - t)**(n - i))
19
 
20
+ def bezier_curve_3d(points, n_times=20):
21
  n_points = len(points)
22
+ # Quantiza os pontos de controle
23
+ points_q = [np.array([quantizar(p[0]), quantizar(p[1]), quantizar(p[2])]) for p in points]
24
+ x_points, y_points, z_points = np.array([p[0] for p in points_q]), np.array([p[1] for p in points_q]), np.array([p[2] for p in points_q])
25
  t = np.linspace(0.0, 1.0, n_times)
26
  polynomial_array = np.array([bernstein_poly(i, n_points - 1, t) for i in range(n_points)])
27
+ x_vals = np.dot(x_points, polynomial_array)
28
+ y_vals = np.dot(y_points, polynomial_array)
29
+ z_vals = np.dot(z_points, polynomial_array)
30
  return x_vals, y_vals, z_vals
31
 
32
  def aprender_com_o_eco_3d(pontos_do_eco: list):
 
34
  p1, p2 = np.array(pontos_do_eco[0]), np.array(pontos_do_eco[-1])
35
  return {"velocity_vector": p2 - p1}
36
 
37
+ # --- Função Principal do Gradio (O Motor Elegante) ---
38
 
39
  def motor_da_simulacao_infinita(angulo_camera: int):
40
+ ponto_a = np.array([quantizar(v) for v in [-40., 20., 10.]])
41
+ vetor_inercia = np.array([quantizar(v) for v in [30., 10., -20.]])
 
 
 
 
42
  historico_rastro = [ponto_a.tolist()]
43
 
44
  fig = plt.figure(figsize=(8, 8)); ax = fig.add_subplot(111, projection='3d')
45
  cor_fundo = '#0a0a0a'; fig.patch.set_facecolor(cor_fundo); ax.set_facecolor(cor_fundo)
46
+
47
+ # --- NOVO: Setup para o Rastro em Degradê ---
48
+ cor_rastro = '#ff4500'
49
+ cmap = LinearSegmentedColormap.from_list("rastro_cmap", [(0, 0, 0, 0), cor_rastro], N=256)
50
+ # ---------------------------------------------
51
 
52
  ciclo_num = 0
53
  while True:
54
  ciclo_num += 1
55
 
56
+ ponto_b_raw = np.random.rand(3) * 50 - 25
57
+ ponto_b = np.array([quantizar(v) for v in ponto_b_raw])
58
 
59
  ponto_controle = ponto_a + vetor_inercia
60
  pontos_curva = [ponto_a, ponto_controle, ponto_b]
 
62
 
63
  novos_pontos_rastro = list(zip(x_ciclo, y_ciclo, z_ciclo))
64
  historico_rastro.extend(novos_pontos_rastro)
65
+ max_rastro = 150
66
  historico_rastro = historico_rastro[-max_rastro:]
67
 
68
+ tamanho_eco = 10
69
+ pontos_eco = historico_rastro[-tamanho_eco:]
70
  vetor_inercia = aprender_com_o_eco_3d(pontos_eco)["velocity_vector"]
 
 
71
 
72
  for frame in range(len(x_ciclo)):
73
  ax.cla()
74
  ax.xaxis.pane.fill = False; ax.yaxis.pane.fill = False; ax.zaxis.pane.fill = False
75
  ax.grid(color='#222222', linestyle='--')
76
+ ax.view_init(elev=30., azim=angulo_camera)
77
+ ax.set_xlim(-30, 30); ax.set_ylim(-30, 30); ax.set_zlim(-30, 30)
 
 
 
 
 
78
  ax.set_xticklabels([]); ax.set_yticklabels([]); ax.set_zticklabels([])
79
 
80
+ ax.scatter(*ponto_a, s=150, c='lime', alpha=0.7)
81
+ ax.scatter(*ponto_b, s=150, c='red', marker='X', alpha=0.9)
82
 
83
+ # --- LÓGICA DO RASTRO EM DEGRADÊ ---
84
+ tamanho_rastro_fixo = 12
85
  indice_global_frame = len(historico_rastro) - len(x_ciclo) + frame
86
+ start_index = max(0, indice_global_frame - tamanho_rastro_fixo)
87
+
88
+ rastro_atual = np.array(historico_rastro[start_index:indice_global_frame+1])
89
 
90
+ if len(rastro_atual) > 1:
91
+ pontos = rastro_atual.reshape(-1, 1, 3)
92
+ segmentos = np.concatenate([pontos[:-1], pontos[1:]], axis=1)
93
+
94
+ # Cria um array de cores com transparência crescente
95
+ alphas = np.linspace(0.0, 0.8, len(segmentos))
96
+ cores = cmap(np.arange(256))
97
+ cores[:,-1] = np.linspace(0, 1, 256)
98
+ grad_cmap = LinearSegmentedColormap.from_list('custom_alpha', cores)
99
+
100
+ lc = LineCollection(segmentos, cmap=grad_cmap, linewidth=4)
101
+ lc.set_array(np.linspace(0, 1, len(segmentos)))
102
+ ax.add_collection3d(lc, zs=rastro_atual[:, 2], zdir='z')
103
+
104
+ # ------------------------------------
105
+
106
+ ax.plot([x_ciclo[frame]], [y_ciclo[frame]], [z_ciclo[frame]], 'o', color=cor_rastro, markersize=8, markeredgecolor='white')
107
 
108
+ info_texto = f"Ciclo: {ciclo_num}\nAlvo: {np.round(ponto_b)}"
109
+ ax.text2D(0.05, 0.95, info_texto, transform=ax.transAxes, color='white', fontsize=10)
110
 
111
  yield fig
112
+ time.sleep(0.01)
113
 
114
  ponto_a = ponto_b
115
 
116
  plt.close(fig)
117
 
118
+ # --- Interface Gradio (Inalterada) ---
119
+ with gr.Blocks(theme=gr.themes.Base(primary_hue="purple", secondary_hue="orange")) as demo:
120
  gr.Markdown(
121
  """
122
+ # Simulador Elegante 3D de Convergência
123
+ Uma simulação autônoma com física "quantizada" e um rastro de 12 vetores em degradê.
 
124
  """
125
  )
126
  with gr.Row():
127
  with gr.Column(scale=1):
128
+ angulo_camera_slider = gr.Slider(-180, 180, value=25, label="Ângulo da Câmera (Fixo)")
129
+ start_btn = gr.Button("🚀 Iniciar Simulação Elegante", variant="primary")
130
  with gr.Column(scale=2):
131
  plot_output = gr.Plot(label="Visualização em Tempo Real")
132