66from  tqdm  import  tqdm 
77from  pathlib  import  Path 
88import  math 
9+ from  scipy .optimize  import  minimize 
910
1011from  copy  import  deepcopy  as  dc 
1112from  sklearn .mixture  import  GaussianMixture 
1213
1314ROBOTS_NUM  =  6 
1415ROBOT_RANGE  =  5.0 
15- TARGETS_NUM  =  1 
16+ TARGETS_NUM  =  2 
1617COMPONENTS_NUM  =  1 
1718PARTICLES_NUM  =  500 
1819AREA_W  =  20.0 
1920vmax  =  1.5 
2021SAFETY_DIST  =  2.0 
2122EPISODES  =  100 
22- 
23+ NUM_OBSTACLES  =  4 
24+ USE_CBF  =  True 
25+ GAMMA  =  0.5 
2326
2427path  =  Path ().resolve ()
25- path  =  (path  /  'dataset_3ch /' )
28+ path  =  (path  /  'dataset_3ch_obs /' )
2629
2730
2831def  plot_occgrid (x , y , z , save = False , name = "occgrid" , ax = None ):
@@ -90,6 +93,12 @@ def gmm_pdf(x, y, means, covariances, weights):
9093
9194  return  prob 
9295
96+ def  objective_function (u ):
97+   return  np .linalg .norm (u )** 2 
98+ 
99+ def  safety_constraint (u , A , b ):
100+   return  - np .dot (A ,u ) +  b 
101+ 
93102
94103
95104for  episode  in  range (EPISODES ):
@@ -115,7 +124,7 @@ def gmm_pdf(x, y, means, covariances, weights):
115124  # Fit GMM 
116125  samples  =  samples .reshape ((TARGETS_NUM * PARTICLES_NUM , 2 ))
117126  print (samples .shape )
118-   gmm  =  GaussianMixture (n_components = COMPONENTS_NUM , covariance_type = 'full' , max_iter = 1000 )
127+   gmm  =  GaussianMixture (n_components = TARGETS_NUM , covariance_type = 'full' , max_iter = 1000 )
119128  gmm .fit (samples )
120129
121130  means  =  gmm .means_ 
@@ -142,6 +151,12 @@ def gmm_pdf(x, y, means, covariances, weights):
142151  Zmax  =  np .max (Z )
143152  Z  =  Z  /  Zmax 
144153
154+   fig , [ax , ax2 ] =  plt .subplots (1 , 2 , figsize = (12 ,6 ))
155+   plot_occgrid (Xg , Yg , Z , ax = ax )
156+   plot_occgrid (Xg , Yg , Z , ax = ax2 )
157+       
158+   
159+ 
145160
146161  # Simulate episode 
147162  # ROBOTS_NUM = np.random.randint(6, ROBOTS_MAX) 
@@ -157,6 +172,18 @@ def gmm_pdf(x, y, means, covariances, weights):
157172  imgs  =  np .zeros ((1 , ROBOTS_NUM , NUM_CHANNELS , GRID_STEPS , GRID_STEPS ))
158173  vels  =  np .zeros ((1 , ROBOTS_NUM , 2 ))
159174
175+ 
176+   # obstacles 
177+   obstacles  =  np .zeros ((NUM_OBSTACLES , 2 ))
178+   for  i  in  range (NUM_OBSTACLES ):
179+     done  =  False 
180+     while  not  done :
181+       obstacles [i , :] =  - 0.5 * AREA_W  +  AREA_W * np .random .rand (1 , 2 )
182+       obs_rel  =  points  -  obstacles [i ]
183+       norm  =  np .linalg .norm (obs_rel , axis = 1 )
184+       if  (norm  >  3.0 ).all ():
185+         done  =  True    
186+ 
160187  r_step  =  2  *  ROBOT_RANGE  /  GRID_STEPS 
161188  for  s  in  range (1 , NUM_STEPS + 1 ):
162189    row  =  0 
@@ -188,6 +215,8 @@ def gmm_pdf(x, y, means, covariances, weights):
188215      Zmax_i  =  np .max (Z_i )
189216      Z_i  =  Z_i  /  Zmax_i 
190217
218+      
219+ 
191220      img_s [idx , 0 , :, :] =  Z_i  *  255 
192221
193222      neighs  =  np .delete (vor .points [:ROBOTS_NUM ], idx , 0 )
@@ -216,6 +245,11 @@ def gmm_pdf(x, y, means, covariances, weights):
216245          p_w  =  p_ij  +  p_i 
217246          if  p_w [0 ] <  - 0.5 * AREA_W  or  p_w [0 ] >  0.5 * AREA_W  or  p_w [1 ] <  - 0.5 * AREA_W  or  p_w [1 ] >  0.5 * AREA_W :
218247            img_obs [i , j ] =  1.0 
248+           
249+           # check obstacles 
250+           for  obs  in  obstacles :
251+             if  p_w [0 ] >  obs [0 ]- 1  and  p_w [0 ] <  obs [0 ]+ 1  and  p_w [1 ] >  obs [1 ]- 1  and  p_w [1 ] <  obs [1 ]+ 1 :
252+               img_obs [i , j ] =  1.0 
219253
220254      img_s [idx , 1 , :, :] =  img_neighs  *  255 
221255      img_s [idx , 2 , :, :] =  img_obs  *  255 
@@ -282,8 +316,36 @@ def gmm_pdf(x, y, means, covariances, weights):
282316      vel  =  0.8  *  (centr  -  robot )
283317      vel [0 , 0 ] =  max (- vmax , min (vmax , vel [0 ,0 ]))
284318      vel [0 , 1 ] =  max (- vmax , min (vmax , vel [0 ,1 ]))
319+       vel_i  =  vel [0 ]
320+       
321+       # CBF 
322+       if  USE_CBF :
323+         local_pts  =  neighs  -  p_i 
324+         constraints  =  []
325+         # for n in local_pts: 
326+         #   h = np.linalg.norm(n)**2 - SAFETY_DIST**2 
327+         #   A_cbf = 2*n 
328+         #   b_cbf = GAMMA * h 
329+         #   constraints.append({'type': 'ineq', 'fun': lambda u: safety_constraint(u, A_cbf, b_cbf)}) 
330+         
331+         local_obs  =  obstacles  -  p_i 
332+         for  obs  in  local_obs :
333+           h  =  np .linalg .norm (obs )** 2  -  (2 * SAFETY_DIST )** 2 
334+           A_cbf  =  2 * obs 
335+           b_cbf  =  GAMMA  *  h 
336+           constraints .append ({'type' : 'ineq' , 'fun' : lambda  u : safety_constraint (u , A_cbf , b_cbf )})
337+         # print("vdes: ", vel_i) 
338+         # print("Acbf: ", A_cbf) 
339+         # print("b_cbf: ", b_cbf) 
340+         # print("h: ", h) 
341+         obj  =  lambda  u : objective_function (u - vel_i )
342+         res  =  minimize (obj , vel_i , constraints = constraints , bounds = [(- vmax , vmax ), (- vmax , vmax )])
343+         vel  =  res .x 
344+       
285345      vel_s [idx , :] =  vel 
286346
347+ 
348+ 
287349      points [idx , :] =  robot  +  vel 
288350      if  dist  >  0.1 :
289351        conv  =  False 
@@ -305,8 +367,21 @@ def gmm_pdf(x, y, means, covariances, weights):
305367  imgs  =  imgs [1 :]
306368  vels  =  vels [1 :]
307369
370+   """ 
371+   for i in range(ROBOTS_NUM): 
372+     ax.plot(robots_hist[:, i, 0], robots_hist[:, i, 1]) 
373+     ax.scatter(robots_hist[-1, i, 0], robots_hist[-1, i, 1]) 
374+ 
375+   for obs in obstacles: 
376+     o_x = np.array([obs[0]-1, obs[0]+1, obs[0]+1, obs[0]-1, obs[0]-1]) 
377+     o_y = np.array([obs[1]-1, obs[1]-1, obs[1]+1, obs[1]+1, obs[1]-1]) 
378+     ax.plot(o_x, o_y, c='r', linewidth=3) 
308379
380+   for i in range(ROBOTS_NUM): 
381+     ax2.scatter(robots_hist[-1, i, 0], robots_hist[-1, i, 1]) 
309382
383+   plt.show() 
384+   """ 
310385
311386  with  open (str (path / f"test{ episode }  .npy" ), 'wb' ) as  f :
312387    np .save (f , imgs )
0 commit comments