VoronoiPositionGenerator.cpp 17.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
/*
 * VoronoiPositionGenerator.cpp
 *
 *  Created on: Sep 2, 2015
 *      Author: gsp1502
 */

#include "VoronoiPositionGenerator.h"
//check if all includes are necessary
#include "../pedestrian/AgentsSourcesManager.h"
#include "../pedestrian/Pedestrian.h"
Mohcine Chraibi's avatar
Mohcine Chraibi committed
12 13 14 15 16
//#include "../pedestrian/StartDistribution.h"
//#include "../pedestrian/PedDistributor.h"
//#include "../pedestrian/AgentsSource.h"
//#include "../geometry/Building.h"
//#include "../geometry/Point.h"
17 18

//#include "../mpi/LCGrid.h"
Mohcine Chraibi's avatar
Mohcine Chraibi committed
19
//#include <iostream>
20
#include <thread>
Mohcine Chraibi's avatar
Mohcine Chraibi committed
21
//#include <chrono>
22 23


Mohcine Chraibi's avatar
Mohcine Chraibi committed
24 25 26 27 28
//#include "../geometry/SubRoom.h"
//#include <stdlib.h>
//#include <time.h>
//#include <string>
//#include <random>
29

Mohcine Chraibi's avatar
Mohcine Chraibi committed
30
#include "boost/polygon/voronoi.hpp"
31 32 33 34 35 36 37 38
using boost::polygon::voronoi_builder;
using boost::polygon::voronoi_diagram;
using boost::polygon::x;
using boost::polygon::y;
using boost::polygon::low;
using boost::polygon::high;


39
//wrapping the boost objects (just the point object)
Mohcine Chraibi's avatar
Mohcine Chraibi committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
namespace boost {
namespace polygon {
template <>
struct geometry_concept<Point> {
     typedef point_concept type;
};

template <>
struct point_traits<Point> {
     typedef int coordinate_type;

     static inline coordinate_type get(
               const Point& point, orientation_2d orient) {
          return (orient == HORIZONTAL) ? point._x : point._y;
     }
};
}  // polygon
}  // boost
58 59 60 61 62 63


using namespace std;


//functions
64
//TODO: refactor the function
65
bool IsEnoughInSubroom( SubRoom* subroom, Point& pt, double radius )
66
{
67 68 69 70
     for (const auto& wall: subroom->GetAllWalls())
          if(wall.DistTo(pt)<radius)
               return false;

71
     for(const auto& trans: subroom->GetAllTransitions() )
72
    	 if ( trans->DistTo(pt) < radius + 0.1 )
73 74 75
    		 return false;

     for( const auto& cross: subroom->GetAllCrossings() )
76
    	 if( cross->DistTo(pt) < radius + 0.1 )
77
    		 return false;
78 79

     return true;
80 81
}

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
bool ComputeBestPositionVoronoiBoost(AgentsSource* src, std::vector<Pedestrian*>& peds,
         Building* building)
{
    bool return_value = true;
    auto dist = src->GetStartDistribution();
    int roomID = dist->GetRoomId();
    int subroomID = dist->GetSubroomID();
    std::string caption = (building->GetRoom( roomID ))->GetCaption();

    std::vector<Pedestrian*> existing_peds;
    std::vector<Pedestrian*> peds_without_place;
    building->GetPedestrians(roomID, subroomID, existing_peds);

    double radius = 0.3; //radius of a person, 0.3 is just some number(needed for the fake_peds bellow), will be changed afterwards

    SubRoom* subroom = building->GetRoom( roomID )->GetSubRoom(subroomID);

    double factor = 100;  //factor for conversion to integer for the boost voronoi

    std::vector<Point> fake_peds;
    Point temp(0,0);
    //fake_peds will be the positions of "fake" pedestrians, multiplied by factor and converted to int
    for (auto vert: subroom->GetPolygon() ) //room vertices
    {
   	     const Point& center_pos = subroom->GetCentroid();
   	     temp._x = ( center_pos._x-vert._x );
		temp._y = ( center_pos._y-vert._y );
		temp = temp/sqrt(temp.NormSquare());
		temp = temp*(radius*1.4);  //now the norm of the vector is ~r*sqrt(2), pointing to the center
		temp = temp + vert;
		temp._x = (int)(temp._x*factor);
		temp._y = (int)(temp._y*factor);
		fake_peds.push_back( temp );
    }

    std::vector<Pedestrian*>::iterator iter_ped;
    for (iter_ped = peds.begin(); iter_ped != peds.end(); )
    {
         Pedestrian* ped = (*iter_ped);
         radius = ped->GetEllipse().GetBmax(); //max radius of the current pedestrian

         if(existing_peds.size() == 0 )
         {
       	   const Point& center_pos = subroom->GetCentroid();

              double x_coor = 3 * ( (double)rand() / (double)RAND_MAX ) - 1.5;
              double y_coor = 3 * ( (double)rand() / (double)RAND_MAX ) - 1.5;
              Point random_pos(x_coor, y_coor);
              Point new_pos = center_pos + random_pos;
              //this could be better, but needs to work with any polygon - random point inside a polygon?
              if ( subroom->IsInSubRoom( new_pos ) )
              {
                   if( IsEnoughInSubroom(subroom, new_pos, radius ) )
                   {
                        ped->SetPos(center_pos + random_pos, true);
                        Point v;
                        if (ped->GetExitLine()) {
                             v = (ped->GetExitLine()->ShortestPoint(ped->GetPos())- ped->GetPos()).Normalized();
                        } else {
                             v = Point(0., 0.);
                        }
                        //double speed=ped->GetV0Norm();
                        double speed = ped->GetEllipse().GetV0(); //@todo: some peds do not have a navline. This should not be accepted.
                        v=v*speed;
                        ped->SetV(v);
                   }
                   else
                   {
                        ped->SetPos(center_pos, true);
                        Point v;
                        if (ped->GetExitLine()) {
                             v = (ped->GetExitLine()->ShortestPoint(ped->GetPos())- ped->GetPos()).Normalized();
                        } else {
                             v = Point(0., 0.);
                        }
                        double speed=ped->GetV0Norm();
                        v=v*speed;
                        ped->SetV(v);
                   }
              }
              else
              {
                   ped->SetPos(center_pos, true);
                   Point v;
                   if (ped->GetExitLine()) {
                             v = (ped->GetExitLine()->ShortestPoint(ped->GetPos())- ped->GetPos()).Normalized();
                   } else {
                             v = Point(0., 0.);
                   }
                   double speed=ped->GetV0Norm();
                   v=v*speed;
                   ped->SetV(v);
              }

              existing_peds.push_back(ped);


         }//0

         else //more than one pedestrian
         {
       	   //it would be better to maybe have a mapping between discrete_positions and pointers to the pedestrians
       	   //then there would be no need to remember the velocities_vector and goal_vector
     	       std::vector<Point> discrete_positions;
              std::vector<Point> velocities_vector;
              std::vector<int> goal_vector;
              Point tmp(0,0);
              Point v(0,0);
              double no = 0;

              //points from double to integer
              for (const auto& eped: existing_peds)
              {
                   const Point& pos = eped->GetPos();
                   tmp._x = (int)( pos._x*factor );
                   tmp._y = (int)( pos._y*factor );
                   discrete_positions.push_back( tmp );
                   velocities_vector.push_back( eped->GetV() );
                   goal_vector.push_back( eped->GetFinalDestination() );

                   //calculating the mean, using it for the fake pedestrians
                   v = v + eped->GetV();
                   no++;
              }

              //TODO: dividing by 0 when existing_peds is empty
              // -------> existing_peds is not empty because of the if statement
              // sum up the weighted velocity in the loop
              v = v/no; //this is the mean of all velocities

              //adding fake people to the vector for constructing voronoi diagram
              for (unsigned int i=0; i<subroom->GetPolygon().size(); i++ )
              {
                   discrete_positions.push_back( fake_peds[i] );
                   velocities_vector.push_back( v );
                   goal_vector.push_back( -10 );
              }

              //constructing the diagram
              voronoi_diagram<double> vd;
              construct_voronoi(discrete_positions.begin(), discrete_positions.end(), &vd);

              voronoi_diagram<double>::const_vertex_iterator chosen_it = vd.vertices().begin();
              double dis = 0;
              VoronoiBestVertexRandMax(discrete_positions, vd, subroom, factor, chosen_it, dis, radius );

              if( dis > 4*radius*factor*radius*factor)// be careful with the factor!! radius*factor, 2,3,4?
              {
                   Point pos( chosen_it->x()/factor, chosen_it->y()/factor ); //check!
                   ped->SetPos(pos , true);
                   VoronoiAdjustVelocityNeighbour(chosen_it, ped, velocities_vector, goal_vector);

                   // proceed to the next pedestrian
                   existing_peds.push_back(ped);
                   ++iter_ped;

              }
              else
              {
                   //reject the pedestrian:
                   return_value = false;
                   peds_without_place.push_back(*iter_ped); //Put in a different queue, they will be put back in the source.
                   iter_ped=peds.erase(iter_ped); // remove from the initial vector since it should only contain the pedestrians that could find a place
              }

              /*else //try with the maximum distance, don't need this if already using the VoronoiBestVertexMax function
				{
					VoronoiBestVertexMax(discrete_positions, vd, subroom, factor, chosen_it, dis );
					if( dis > radius*factor*radius*factor)// be careful with the factor!! radius*factor
					{
						Point pos( chosen_it->x()/factor, chosen_it->y()/factor ); //check!
						ped->SetPos(pos , true);
						VoronoiAdjustVelocityNeighbour( vd, chosen_it, ped, velocities_vector );
					}
					else
					{
						return_value = false;
						//reject the pedestrian
					}
				}*/
         }// >0


    }//for loop


    //maybe not all pedestrians could find a place, requeue them in the source
    if(peds_without_place.size()>0)
         src->AddAgentsToPool(peds_without_place);

    return return_value;
}
274 275

//gives an agent the mean velocity of his voronoi-neighbors
Mohcine Chraibi's avatar
Mohcine Chraibi committed
276 277
void VoronoiAdjustVelocityNeighbour(voronoi_diagram<double>::const_vertex_iterator& chosen_it, Pedestrian* ped,
        const std::vector<Point>& velocities_vector, const std::vector<int>& goal_vector)
278
{
279 280 281
     //finding the neighbors (nearest pedestrians) of the chosen vertex
     const voronoi_diagram<double>::vertex_type &vertex = *chosen_it;
     const voronoi_diagram<double>::edge_type *edge = vertex.incident_edge();
282 283
     double no1=0,no2=0;
     double backup_speed = 0;
284
     std::size_t index;
Mohcine Chraibi's avatar
Mohcine Chraibi committed
285 286 287 288 289 290 291 292
     Point v(0,0);
     if(ped->GetExitLine() != nullptr)
          v = (ped->GetExitLine()->ShortestPoint(ped->GetPos())- ped->GetPos()).Normalized(); //the direction
     else
     {
          int gotRoute = ped->FindRoute();
          if(gotRoute < 0) printf("\nWARNING: source agent %d can not get exit\n", ped->GetID());
     }
293
     double speed = 0;
294 295 296
     do
     {
          index = ( edge->cell() )->source_index();
297 298 299 300 301 302 303 304 305 306
          if( ped->GetFinalDestination() == goal_vector[index]  )
          {
        	  no1++;
        	  speed += velocities_vector[index].Norm();
          }
          else
          {
        	  no2++;
        	  backup_speed += velocities_vector[index].Norm();
          }
307 308 309
          edge = edge->rot_next();
     } while (edge != vertex.incident_edge());

310 311 312 313 314
     if(no1)
    	 speed = speed/no1;
     else
    	 speed = backup_speed/(no2*3.0); //just some small speed

315
     v = v*speed;
316
     ped->SetV(v);
317 318 319

}

320

321
//gives the voronoi vertex with max distance
Mohcine Chraibi's avatar
Mohcine Chraibi committed
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
//void VoronoiBestVertexMax(const std::vector<Point>& discrete_positions, const voronoi_diagram<double>& vd,
//        SubRoom* subroom, double factor, voronoi_diagram<double>::const_vertex_iterator& max_it, double& max_dis,
//        double radius)
//{
//     double dis = 0;
//     double score;
//     double max_score = -100; //calculated using distance and considering the goal
//
//
//
//     for (auto it = vd.vertices().begin(); it != vd.vertices().end(); ++it)
//     {
//          Point vert_pos( it->x()/factor, it->y()/factor );
//          if( subroom->IsInSubRoom(vert_pos) )
//               if( IsEnoughInSubroom( subroom, vert_pos, radius ) )
//               {
//                    const voronoi_diagram<double>::vertex_type &vertex = *it;
//                    const voronoi_diagram<double>::edge_type *edge = vertex.incident_edge();
//
//                    std::size_t index = ( edge->cell() )->source_index();
//                    Point p = discrete_positions[index];
//
//                    dis = ( p._x - it->x() )*( p._x - it->x() )  + ( p._y - it->y() )*( p._y - it->y() )  ;
//
//                    score = dis;
//
//
//                    //constructing the checking line
///*
//                    Point p2 = (ped->GetExitLine()->ShortestPoint(vert_pos)-vert_pos).Normalized(); //problem: ped does not have a position
//                    p2 = p2 + p2; //looking 2m in front
//                    Line check_line(vert_pos, vert_pos + p2);  //this is the first 2m of exit line
//
//                    do
//                    {
//                    	//do something
//                    	if( goal_vector[index]!=-3 &&  goal_vector[index]!=ped->GetFinalDestination() ) //
//                    		if( check_line.IntersectionWithCircle(p,1.0) )    //0.7 because the radius is around 0.3
//                    		{
//                    			score -= 100;
//                    			break;
//                    		}
//
//
//                    	//change edge
//                    	edge = edge->rot_next();
//                    	index = ( edge->cell() )->source_index();
//                    	p = discrete_positions[index]/factor;
//
//                    } while( edge != vertex.incident_edge() );
//*/
//                    if(score > max_score)
//                    {
//                         max_score =score;
//                    	 max_dis = dis;
//                         max_it = it;
//                    }
//               }
//     }
//     //at the end, max_it is the choosen vertex, or the first vertex - max_dis=0 assures that this position will not be taken
//}
383

384 385
//gives random voronoi vertex but with weights proportional to distances^2
//in case you want proportional to distance^4 just change two lines commented as HERE
386
void VoronoiBestVertexRandMax (const std::vector<Point>& discrete_positions, const voronoi_diagram<double>& vd, SubRoom* subroom,
387
          double factor, voronoi_diagram<double>::const_vertex_iterator& chosen_it, double& dis	, double radius)
388
{
389 390
     std::vector< voronoi_diagram<double>::const_vertex_iterator > possible_vertices;
     vector<double> partial_sums;
Mohcine Chraibi's avatar
Mohcine Chraibi committed
391
     unsigned long size=0;
392

393
     for (auto it = vd.vertices().begin(); it != vd.vertices().end(); ++it)
394 395 396
     {
          Point vert_pos = Point( it->x()/factor, it->y()/factor );
          if( subroom->IsInSubRoom( vert_pos ) )
397
               if( IsEnoughInSubroom(subroom, vert_pos,radius) )
398 399 400 401 402 403 404
               {
                    const voronoi_diagram<double>::vertex_type &vertex = *it;
                    const voronoi_diagram<double>::edge_type *edge = vertex.incident_edge();

                    std::size_t index = ( edge->cell() )->source_index();
                    Point p = discrete_positions[index];

Oliver Schmidts's avatar
Oliver Schmidts committed
405
                    dis = ( p._x - it->x() )*( p._x - it->x() )   + ( p._y - it->y() )*( p._y - it->y() )  ;
406 407

                    possible_vertices.push_back( it );
408
                    partial_sums.push_back( dis ); // HERE
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436

                    size = partial_sums.size();
                    if( size > 1 )
                    {
                         partial_sums[ size - 1 ] += partial_sums[ size - 2 ];
                    }
               }
     }
     //now we have the vector of possible vertices and weights and we can choose one randomly

     double lower_bound = 0;
     double upper_bound = partial_sums[size-1];
     std::uniform_real_distribution<double> unif(lower_bound,upper_bound);
     std::default_random_engine re;
     double a_random_double = unif(re);

     for (unsigned int i=0; i<size; i++)
     {
          if ( partial_sums[i] >= a_random_double )
          {
               //this is the chosen index
               chosen_it = possible_vertices[i];
               dis = partial_sums[i];
               if( i > 1 )
                    dis -= partial_sums[i-1];
               break;
          }
     }
437
     //dis = sqrt(dis); //HERE
438 439 440
}

//gives a random voronoi vertex
Mohcine Chraibi's avatar
Mohcine Chraibi committed
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
//void VoronoiBestVertexRand (const std::vector<Point>& discrete_positions, const voronoi_diagram<double>& vd, SubRoom* subroom,
//          double factor, voronoi_diagram<double>::const_vertex_iterator& chosen_it, double& dis, double radius	)
//{
//     std::vector< voronoi_diagram<double>::const_vertex_iterator > possible_vertices;
//     std::vector<double> distances;
//
//     for (auto it = vd.vertices().begin(); it != vd.vertices().end(); ++it)
//     {
//          Point vert_pos = Point( it->x()/factor, it->y()/factor );
//          if( subroom->IsInSubRoom(vert_pos) )
//               if( IsEnoughInSubroom(subroom, vert_pos, radius) )
//               {
//                    const voronoi_diagram<double>::vertex_type &vertex = *it;
//                    const voronoi_diagram<double>::edge_type *edge = vertex.incident_edge();
//
//                    std::size_t index = ( edge->cell() )->source_index();
//                    Point p = discrete_positions[index];
//
//                    dis = ( p._x - it->x() )*( p._x - it->x() )   + ( p._y - it->y() )*( p._y - it->y() )  ;
//
//                    possible_vertices.push_back( it );
//                    distances.push_back( dis );
//               }
//     }
//     //now we have all the possible vertices and their distances and we can choose one randomly
//     //TODO: get the seed from the simulation/argumentparser
//     //srand (time(NULL));
//     unsigned int i = rand() % possible_vertices.size();
//     chosen_it = possible_vertices[i];
//     dis = distances[i];
//
//}
473 474