AgentsSourcesManager.cpp 13.4 KB
Newer Older
1 2
/*
 * AgentsSourcesManager.cpp
3
 *
4 5 6
 *  Created on: 14.04.2015
 *      Author: piccolo
 */
7 8 9

#include "AgentsSourcesManager.h"
#include "Pedestrian.h"
10 11
#include "StartDistribution.h"
#include "PedDistributor.h"
12
#include "AgentsSource.h"
13
#include "../voronoi/VoronoiDiagramGenerator.h"
14
#include "../geometry/Building.h"
15 16
#include "../geometry/Point.h"

17

18
#include "../mpi/LCGrid.h"
19 20 21
#include <iostream>
#include <thread>
#include <chrono>
22
#include "AgentsQueue.h"
23 24 25

using namespace std;

26
bool AgentsSourcesManager::_isCompleted=false;
27

28 29 30 31 32 33 34 35
AgentsSourcesManager::AgentsSourcesManager()
{
}

AgentsSourcesManager::~AgentsSourcesManager()
{
}

36
void AgentsSourcesManager::operator()()
37
{
38
     Run();
39
}
40

41 42 43 44
void AgentsSourcesManager::Run()
{
     Log->Write("INFO:\tStarting agent manager thread");

45

46 47 48 49 50
     //Generate all agents required for the complete simulation
     //It might be more efficient to generate at each frequency step
     for (const auto& src : _sources)
     {
          src->GenerateAgentsAndAddToPool(src->GetMaxAgents(), _building);
51
          cout<<"generation: "<<src->GetPoolSize()<<endl;
52 53 54 55 56 57 58 59 60
     }

     //first call ignoring the return value
     ProcessAllSources();

     //the loop is updated each x second.
     //it might be better to use a timer
     _isCompleted = false;
     bool finished = false;
61
     long updateFrequency = 5;     // 1 second
62 63 64 65
     do
     {
          int current_time = Pedestrian::GetGlobalTime();

66 67 68 69 70 71
          //first step
          //if(current_time==0){
          //finished=ProcessAllSources();
          //     ProcessAllSources();
          //     //cout<<"here:"<<endl; exit(0);
          //}
72 73 74
          if ((current_time != _lastUpdateTime)
                    && ((current_time % updateFrequency) == 0))
          {
75
               //cout<<"TIME:"<<current_time<<endl;
76 77
               finished=ProcessAllSources();
               _lastUpdateTime = current_time;
78
               cout << "source size: " << _sources.size() << endl;
79 80
          }
          //wait some time
81 82
          //cout<<"sleepinp..."<<endl;
          //std::this_thread::sleep_for(std::chrono::milliseconds(1));
83 84
     } while (!finished);
     Log->Write("INFO:\tTerminating agent manager thread");
85
     _isCompleted = true;//exit(0);
86 87 88
}

bool AgentsSourcesManager::ProcessAllSources() const
89 90
{
     bool empty=true;
91
     //cout<<"src size: "<<_sources.size()<<endl;
92 93
     for (const auto& src : _sources)
     {
94
          //cout<<"size: "<<src->GetPoolSize()<<endl;//exit(0);
95 96
          if (src->GetPoolSize())
          {
97
               vector<Pedestrian*> peds;
98
               src->RemoveAgentsFromPool(peds,src->GetFrequency());
99

100
               ComputeBestPositionRandom(src.get(), peds);
101
               //todo: compute the optimal position for insertion using voronoi
102 103 104 105 106
               //for (auto&& ped : peds)
               //{
               //ComputeBestPositionVoronoi(src.get(), ped);
               //ped->Dump(ped->GetID());
               //}
107
               AgentsQueueIn::Add(peds);
108 109 110 111 112
               empty = false;
          }
          //src->Dump();//exit(0);
     }
     return empty;
113
}
114

115
void AgentsSourcesManager::ComputeBestPositionVoronoi(AgentsSource* src,
116
          Pedestrian* agent) const
117
{
118 119 120 121 122
     auto dist = src->GetStartDistribution();
     double bounds[4];
     dist->Getbounds(bounds);
     int roomID = dist->GetRoomId();
     int subroomID = dist->GetSubroomID();
123 124 125

     //Get all pedestrians in that location
     vector<Pedestrian*> peds;
126
     _building->GetPedestrians(roomID, subroomID, peds);
127

128
     //filter the points that are not within the boundaries
129 130 131 132 133 134 135
     for (auto&& iter = peds.begin(); iter != peds.end();)
     {
          const Point& pos = (*iter)->GetPos();
          if ((bounds[0] <= pos._x && pos._x <= bounds[1])
                    && (bounds[1] <= pos._y && pos._y <= bounds[2]))
          {
               iter = peds.erase(iter);
136
               cout << "removing..." << endl;
137
               exit(0);
138
          } else
139 140 141 142 143 144 145 146
          {
               ++iter;
          }
     }

     //special case with 1, 2 or only three pedestrians in the area
     if (peds.size() < 3)
     {
147 148
          //TODO/random position in the area
          return;
149 150

     }
151
     // compute the cells and cut with the bounds
152
     const int count = peds.size();
153 154
     float* xValues = new float[count];
     float* yValues = new float[count];
155 156
     //float xValues[count];
     //float yValues[count];
157

158
     for (int i = 0; i < count; i++)
159
     {
160 161
          xValues[i] = peds[i]->GetPos()._x;
          yValues[i] = peds[i]->GetPos()._y;
162 163 164
     }

     VoronoiDiagramGenerator vdg;
165 166
     vdg.generateVoronoi(xValues, yValues, count, bounds[0], bounds[1],
               bounds[2], bounds[3], 3);
167 168 169 170
     vdg.resetIterator();
     vdg.resetVerticesIterator();

     printf("\n------vertices---------\n");
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
     //collect the positions
     vector<Point> positions;
     float x1, y1;
     while (vdg.getNextVertex(x1, y1))
     {
          printf("GOT Point (%f,%f)\n", x1, y1);
          positions.push_back(Point(x1, y1));
     }

     //look for the biggest spot
     map<double, Point> map_dist_to_position;

     for (auto&& pos : positions)
     {
          double min_dist = FLT_MAX;

          for (auto&& ped : peds)
          {
189 190
               double distance = (pos - ped->GetPos()).NormSquare();
               if (distance < min_dist)
191
               {
192
                    min_dist = distance;
193 194 195 196 197 198 199
               }
          }
          map_dist_to_position[min_dist] = pos;
     }

     //list the result
     for (auto&& mp : map_dist_to_position)
200
     {
201
          cout << "dist: " << mp.first << " pos: " << mp.second.toString()
202
                                        << endl;
203
          //agent->SetPos(mp.second, true);
204 205
     }

206 207 208 209 210 211 212
     //the elements are ordered.
     // so the last one has the largest distance
     if (!map_dist_to_position.empty())
     {
          agent->SetPos(map_dist_to_position.rbegin()->second, true);
          cout << "position:" << agent->GetPos().toString() << endl;
          //exit(0);
213

214
     } else
215 216 217
     {
          cout << "position not set:" << endl;
          cout << "size: " << map_dist_to_position.size() << endl;
218
          cout << " for " << peds.size() << " pedestrians" << endl;
219 220
          exit(0);
     }
221 222 223 224 225 226 227 228
     //exit(0);
     // float x1,y1,x2,y2;
     //while(vdg.getNext(x1,y1,x2,y2))
     //{
     //     printf("GOT Line (%f,%f)->(%f,%f)\n",x1,y1,x2, y2);
     //
     //}
     //compute the best position
229
     //exit(0);
230 231
}

232
void AgentsSourcesManager::ComputeBestPositionRandom(AgentsSource* src,
233
          std::vector<Pedestrian*>& peds) const
234 235 236
{

     //generate the agents with default positions
237 238 239 240 241
     auto dist = src->GetStartDistribution();
     auto subroom = _building->GetRoom(dist->GetRoomId())->GetSubRoom(
               dist->GetSubroomID());
     vector<Point> positions = PedDistributor::PossiblePositions(*subroom);
     double bounds[4] = { 0, 0, 0, 0 };
242 243
     dist->Getbounds(bounds);

244 245
     vector<Point> extra_positions;

246
     for (auto& ped : peds)
247
     {
248 249 250
          //need to be called at each iteration
          SortPositionByDensity(positions, extra_positions);

251 252 253
          int index = -1;

          //in the case a range was specified
254
          //just take the first element
255
          for (unsigned int a = 0; a < positions.size(); a++)
256
          {
257 258 259
               Point pos = positions[a];
               if ((bounds[0] <= pos._x) && (pos._x <= bounds[1])
                         && (bounds[2] <= pos._y) && (pos._y < bounds[3]))
260
               {
261 262
                    index = a;
                    break;
263 264
               }
          }
265
          if (index == -1)
266
          {
267
               if (positions.size())
268
               {
269
                    Log->Write(
270
                              "ERROR:\t AgentSourceManager Cannot distribute pedestrians in the mentioned area [%0.2f,%0.2f,%0.2f,%0.2f]",
271
                              bounds[0], bounds[1], bounds[2], bounds[3]);
272
                    Log->Write("ERROR:\t Specifying a subroom_id might help");
273
               }
274
          }
275
          else
276 277
          {
               const Point& pos = positions[index];
278 279 280
               extra_positions.push_back(pos);
               ped->SetPos(pos, true); //true for the initial position
               positions.erase(positions.begin() + index);
281

282 283 284 285
               //at this point we have a position
               //so we can adjust the velocity
               //AdjustVelocityUsingWeidmann(ped);
               AdjustVelocityByNeighbour(ped);
286 287 288
          }
     }
}
289

290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
void AgentsSourcesManager::AdjustVelocityByNeighbour(Pedestrian* ped) const
{
     //get the density
     vector<Pedestrian*> neighbours;
     _building->GetGrid()->GetNeighbourhood(ped,neighbours);

     double speed=0.0;
     double radius_square=0.56*0.56;//corresponding to an area of 1m3
     int count=0;

     for(const auto& p: neighbours)
     {
          //only pedes in a sepcific rance
          if( (ped->GetPos()-p->GetPos()).NormSquare()<=radius_square)
          {
               //only peds with the same destination
               if(ped->GetExitIndex()==p->GetExitIndex())
               {
                    double dist1=ped->GetDistanceToNextTarget();
                    double dist2=p->GetDistanceToNextTarget();
                    //only peds in front of me
                    if(dist2<dist1)
                    {
                         speed+=p->GetV().Norm();
                         count++;
                    }
               }
          }

     }
     //mean speed
     if(count==0)
     {
323 324
          //speed=ped->GetV0Norm();
          speed=ped->GetEllipse().GetV0(); //bad fix for: peds without navline (ar.graf)
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
     }
     else
     {
          speed=speed/count;
     }

     if(ped->FindRoute()!=-1)
     {
          //get the next destination point
          Point v =(ped->GetExitLine()->ShortestPoint(ped->GetPos())- ped->GetPos()).Normalized();
          v=v*speed;
          ped->SetV(v);
     }
     else
     {
          Log->Write("ERROR:\t no route could be found for agent [%d] going to [%d]",ped->GetID(),ped->GetFinalDestination());
          //that will be most probably be fixed in the next computation step.
          // so do not abort
     }

}

347 348 349 350 351 352
void AgentsSourcesManager::AdjustVelocityUsingWeidmann(Pedestrian* ped) const
{
     //get the density
     vector<Pedestrian*> neighbours;
     _building->GetGrid()->GetNeighbourhood(ped,neighbours);

353
     //density in pers per m2
354 355
     double density = 1.0;
     //radius corresponding to a surface of 1m2
356
     //double radius_square=0.564*0.564;
357
     double radius_square=1.0;
358

359 360
     for(const auto& p: neighbours)
     {
361
          if( (ped->GetPos()-p->GetPos()).NormSquare()<=radius_square)
362 363
               density+=1.0;
     }
364 365
     density=density/(radius_square*M_PI);

366 367
     //get the velocity
     double density_max=5.4;
368

369 370 371 372 373 374
     //speed from taken from weidmann FD
     double speed=1.34*(1-exp(-1.913*(1.0/density-1.0/density_max)));
     if(speed>=ped->GetV0Norm())
     {
          speed=ped->GetV0Norm();
     }
375

376 377
     //set the velocity vector
     if(ped->FindRoute()!=-1)
378 379 380 381 382
     {
          //get the next destination point
          Point v =(ped->GetExitLine()->ShortestPoint(ped->GetPos())- ped->GetPos()).Normalized();
          v=v*speed;
          ped->SetV(v);
383
          //cout<<"density: "<<density<<endl;
384 385 386 387
     }
     else
     {
          Log->Write("ERROR:\t no route could be found for agent [%d] going to [%d]",ped->GetID(),ped->GetFinalDestination());
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
          //that will be most probably be fixed in the next computation step.
          // so do not abort
     }

}

void AgentsSourcesManager::SortPositionByDensity(std::vector<Point>& positions, std::vector<Point>& extra_positions) const
{
     std::multimap<double,Point> density2pt;
     //std::map<double,Point> density2pt;

     for(auto&& pt:positions)
     {
          vector<Pedestrian*> neighbours;
          _building->GetGrid()->GetNeighbourhood(pt,neighbours);
          //density in pers per m2
          double density = 0.0;
405
          //double radius_square=0.56*0.56;
406 407 408 409
          double radius_square=0.40*0.40;

          for(const auto& p: neighbours)
          {
410
               if( (pt-p->GetPos()).NormSquare()<=radius_square)
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
                    density+=1.0;
          }

          //consider the extra positions
          for(const auto& ptx: extra_positions)
          {
               if( (ptx-pt).NormSquare()<=radius_square)
                    density+=1.0;
          }
          density=density/(radius_square*M_PI);

          density2pt.insert(std::pair<double,Point>(density,pt));

     }

     //cout<<"------------------"<<positions.size()<<"-------"<<endl;
     positions.clear();
     for(auto&& d: density2pt)
     {
          positions.push_back(d.second);
          //     printf("density [%lf, %s]\n",d.first, d.second.toString().c_str());
432
     }
433 434

}
435 436 437 438 439 440 441 442 443 444 445


void AgentsSourcesManager::GenerateAgents()
{

     for (const auto& src : _sources)
     {
          src->GenerateAgentsAndAddToPool(src->GetMaxAgents(), _building);
     }
}

446 447 448 449 450 451 452 453 454
void AgentsSourcesManager::AddSource(std::shared_ptr<AgentsSource> src)
{
     _sources.push_back(src);
}

const std::vector<std::shared_ptr<AgentsSource> >& AgentsSourcesManager::GetSources() const
{
     return _sources;
}
455 456 457

void AgentsSourcesManager::SetBuilding(Building* building)
{
458
     _building = building;
459
}
460 461 462

bool AgentsSourcesManager::IsCompleted() const
{
463
     return _isCompleted;
464
}
465 466 467 468 469 470


Building* AgentsSourcesManager::GetBuilding() const
{
     return _building;
}
471 472 473 474 475 476 477 478 479 480

long AgentsSourcesManager::GetMaxAgentNumber() const
{
     long pop=0;
     for (const auto& src : _sources)
     {
          pop+=src->GetMaxAgents();
     }
     return pop;
}