AgentsSourcesManager.cpp 17.2 KB
Newer Older
1 2 3
/**
 * \file        AgentsSourcesManager.cpp
 * \date        Apr 14, 2015
4
 * \version     v0.7
5
 * \copyright   <2009-2015> Forschungszentrum J��lich GmbH. All rights reserved.
6
 *
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
 * \section License
 * This file is part of JuPedSim.
 *
 * JuPedSim is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * JuPedSim is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with JuPedSim. If not, see <http://www.gnu.org/licenses/>.
 *
 * \section Description
 * This class is responsible for materialising agent in a given location at a given frequency up to a maximum number.
 * The optimal position where to put the agents is given by various algorithms, for instance
 * the Voronoi algorithm or the Mitchell Best candidate algorithm.
 *
 **/
29 30 31

#include "AgentsSourcesManager.h"
#include "Pedestrian.h"
32 33
#include "StartDistribution.h"
#include "PedDistributor.h"
34
#include "AgentsSource.h"
35
#include "../geometry/Building.h"
36 37
#include "../geometry/Point.h"

38
#include "../mpi/LCGrid.h"
39 40 41
#include <iostream>
#include <thread>
#include <chrono>
42
#include "AgentsQueue.h"
43

44
#include "../voronoi-boost/VoronoiPositionGenerator.h"
45

46 47
using namespace std;

48
bool AgentsSourcesManager::_isCompleted=true;
49

50 51 52 53 54 55 56 57
AgentsSourcesManager::AgentsSourcesManager()
{
}

AgentsSourcesManager::~AgentsSourcesManager()
{
}

58
void AgentsSourcesManager::operator()()
59
{
60
     Run();
61
}
62

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
void AgentsSourcesManager::Run()
{
     Log->Write("INFO:\tStarting agent manager thread");

     //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);
     }

     //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;
81
     long updateFrequency = 2;     // 1 = second
82 83 84 85 86 87 88 89 90 91 92
     do
     {
          int current_time = Pedestrian::GetGlobalTime();

          if ((current_time != _lastUpdateTime)
                    && ((current_time % updateFrequency) == 0))
          {
               finished=ProcessAllSources();
               _lastUpdateTime = current_time;
          }
          //wait some time
93
          // std::this_thread::sleep_for(std::chrono::milliseconds(1));
94 95
     } while (!finished);
     Log->Write("INFO:\tTerminating agent manager thread");
96
     _isCompleted = true;
97 98 99
}

bool AgentsSourcesManager::ProcessAllSources() const
100 101 102 103 104 105
{
     bool empty=true;
     for (const auto& src : _sources)
     {
          if (src->GetPoolSize())
          {
106
               vector<Pedestrian*> peds;
107
               src->RemoveAgentsFromPool(peds,src->GetFrequency());
Ulrich Kemloh's avatar
Ulrich Kemloh committed
108
               Log->Write("INFO:\tSource %d generating %d agents (%d remaining)",src->GetId(),peds.size(),src->GetPoolSize());
109
               Log->Write("                                                                   " + std::to_string(peds[0]->GetExitIndex()));
110

111
               //ComputeBestPositionRandom(src.get(), peds);
112
               //todo: compute the optimal position for insertion using voronoi
113
               if( !ComputeBestPositionVoronoiBoost(src.get(), peds, _building) )
114
                    Log->Write("INFO:\t there was no place for some pedestrians");
115
               //ComputeBestPositionTotalRandom(src.get(), peds );
116
               //ComputeBestPositionDummy( src.get(), peds );
117 118 119 120 121
               /*for (auto&& ped : peds)
               {
               ComputeBestPositionVoronoiBoost(src.get(), ped);
               //ped->Dump(ped->GetID(),0);
               }*/
122
               AgentsQueueIn::Add(peds);
123 124 125 126 127
               empty = false;
          }
          //src->Dump();//exit(0);
     }
     return empty;
128
}
129 130 131 132 133

//4 agents frequency, just for an example
void AgentsSourcesManager::ComputeBestPositionDummy(AgentsSource* src,
          vector<Pedestrian*>& peds)const
{
134 135 136 137
     peds[0]->SetPos( Point(10,5.5) );
     peds[1]->SetPos( Point(10,4.9) );
     peds[2]->SetPos( Point(10,4.3) );
     peds[3]->SetPos( Point(10,3.7) );
138

139
     /*peds[0]->SetPos( Point(10,5.4) );
140 141
	peds[1]->SetPos( Point(10,4.6) );
	peds[2]->SetPos( Point(10,3.8) );*/
142

143 144 145 146 147 148 149
     for(auto&& ped : peds)
     {
          Point v = (ped->GetExitLine()->ShortestPoint(ped->GetPos())- ped->GetPos()).Normalized();
          double speed=ped->GetV0Norm();
          v=v*speed;
          ped->SetV(v);
     }
150
}
151 152

void AgentsSourcesManager::ComputeBestPositionCompleteRandom(AgentsSource* src,
153
          vector<Pedestrian*>& peds)const
154
{
155 156 157 158
     auto dist = src->GetStartDistribution();
     auto subroom = _building->GetRoom(dist->GetRoomId())->GetSubRoom(dist->GetSubroomID());
     vector<Point> positions = PedDistributor::PossiblePositions(*subroom);

Ulrich Kemloh's avatar
Ulrich Kemloh committed
159
     //TODO: get the seed from the simulation
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
     srand (time(NULL));

     for (auto& ped : peds)
     {
          if( positions.size() )
          {
               int index = rand()%positions.size();
               Point new_pos = positions[index];
               positions.erase(positions.begin() + index);
               ped->SetPos(new_pos, true);
               AdjustVelocityByNeighbour(ped);
          }
          else
          {
               Log->Write("\t No place for a pedestrian");
               break;
          }
     }
178 179 180

}

181
/*
182
void AgentsSourcesManager::ComputeBestPositionVoronoi(AgentsSource* src,
183
          Pedestrian* agent) const
184
{
185 186 187 188 189
     auto dist = src->GetStartDistribution();
     double bounds[4];
     dist->Getbounds(bounds);
     int roomID = dist->GetRoomId();
     int subroomID = dist->GetSubroomID();
190 191 192

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

195
     //filter the points that are not within the boundaries
196 197 198 199 200 201 202
     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);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
203
               cout << "removing (testing only)..." << endl;
204
               exit(0);
205
          } else
206 207 208 209 210 211 212 213
          {
               ++iter;
          }
     }

     //special case with 1, 2 or only three pedestrians in the area
     if (peds.size() < 3)
     {
214 215
          //TODO/random position in the area
          return;
216 217

     }
218
     // compute the cells and cut with the bounds
219
     const int count = peds.size();
220 221
     float* xValues = new float[count];
     float* yValues = new float[count];
222 223
     //float xValues[count];
     //float yValues[count];
224

225
     for (int i = 0; i < count; i++)
226
     {
227 228
          xValues[i] = peds[i]->GetPos()._x;
          yValues[i] = peds[i]->GetPos()._y;
229 230 231
     }

     VoronoiDiagramGenerator vdg;
232 233
     vdg.generateVoronoi(xValues, yValues, count, bounds[0], bounds[1],
               bounds[2], bounds[3], 3);
234 235 236 237
     vdg.resetIterator();
     vdg.resetVerticesIterator();

     printf("\n------vertices---------\n");
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
     //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)
          {
               double dist = (pos - ped->GetPos()).NormSquare();
               if (dist < min_dist)
               {
                    min_dist = dist;
               }
          }
          map_dist_to_position[min_dist] = pos;
     }

     //list the result
     for (auto&& mp : map_dist_to_position)
267
     {
268
          cout << "dist: " << mp.first << " pos: " << mp.second.toString()
269
                                        << endl;
270
          //agent->SetPos(mp.second, true);
271 272
     }

273 274 275 276 277 278 279
     //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);
280

281
     } else
282 283 284
     {
          cout << "position not set:" << endl;
          cout << "size: " << map_dist_to_position.size() << endl;
285
          cout << " for " << peds.size() << " pedestrians" << endl;
286 287
          exit(0);
     }
288 289 290 291 292 293 294 295
     //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
296
     //exit(0);
297
}
298
 */
299

300

301

302
void AgentsSourcesManager::ComputeBestPositionRandom(AgentsSource* src,
303
          std::vector<Pedestrian*>& peds) const
304 305 306
{

     //generate the agents with default positions
307 308 309 310 311
     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 };
312 313
     dist->Getbounds(bounds);

314 315
     std::vector<Pedestrian*> peds_without_place;

316 317
     vector<Point> extra_positions;

318 319
     std::vector<Pedestrian*>::iterator iter_ped;
     for (iter_ped = peds.begin(); iter_ped != peds.end(); )
320
     {
321 322 323
          //need to be called at each iteration
          SortPositionByDensity(positions, extra_positions);

324
          int index = -1;
325
          double radius = ( (*iter_ped)->GetEllipse() ).GetBmax()   ;
326 327

          //in the case a range was specified
328
          //just take the first element
329
          for (unsigned int a = 0; a < positions.size(); a++)
330
          {
331
               Point pos = positions[a];
332
               //cout<<"checking: "<<pos.toString()<<endl;
333
               // for positions inside bounds, check it there is enough space
334 335
               if ((bounds[0] <= pos._x) && (pos._x <= bounds[1])
                         && (bounds[2] <= pos._y) && (pos._y < bounds[3]))
336
               {
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357

            	   bool enough_space = true;

            	   //checking enough space!!
            	   vector<Pedestrian*> neighbours;
            	   _building->GetGrid()->GetNeighbourhood(pos,neighbours);

				   for (const auto& ngh: neighbours)
					   if(  (ngh->GetPos() - pos).NormSquare() < 4*radius*radius )
					   {
							enough_space = false;
							break;
					   }


				   if( enough_space )
				   {
					   index = a;
					   break;
				   }

358 359
               }
          }
360
          if (index == -1)
361
          {
362
               if (positions.size())
363
               {
364
                    Log->Write(
365
                              "ERROR:\t AgentSourceManager Cannot distribute pedestrians in the mentioned area [%0.2f,%0.2f,%0.2f,%0.2f]",
366
                              bounds[0], bounds[1], bounds[2], bounds[3]);
367 368
                    Log->Write("     \t Specifying a subroom_id might help");
                    Log->Write("     \t %d positions were available",positions.size());
369
                    //exit(EXIT_FAILURE);
370
               }
371 372 373
               //dump the pedestrian, move iterator
               peds_without_place.push_back(*iter_ped);
               iter_ped=peds.erase(iter_ped);
374
          }
375
          else //we found a position with enough space
376 377 378
          {
               const Point& pos = positions[index];

379 380 381 382 383 384 385 386 387 388 389
			   extra_positions.push_back(pos);
			   (*iter_ped)->SetPos(pos, true); //true for the initial position
			   positions.erase(positions.begin() + index);

			   //at this point we have a position
			   //so we can adjust the velocity
			   //AdjustVelocityUsingWeidmann(ped);
			   AdjustVelocityByNeighbour( (*iter_ped) );
			   //move iterator
			   iter_ped++;

390
          }
391 392

          //return the pedestrians without place
393
     }
394 395
     if(peds_without_place.size()>0)
         src->AddAgentsToPool(peds_without_place);
396
}
397

398 399 400 401 402 403 404 405 406 407 408 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 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
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)
     {
          speed=ped->GetV0Norm();
     }
     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
     }

}

454 455 456 457 458 459
void AgentsSourcesManager::AdjustVelocityUsingWeidmann(Pedestrian* ped) const
{
     //get the density
     vector<Pedestrian*> neighbours;
     _building->GetGrid()->GetNeighbourhood(ped,neighbours);

460
     //density in pers per m2
461 462
     double density = 1.0;
     //radius corresponding to a surface of 1m2
463
     //double radius_square=0.564*0.564;
464
     double radius_square=1.0;
465

466 467
     for(const auto& p: neighbours)
     {
468
          if( (ped->GetPos()-p->GetPos()).NormSquare()<=radius_square)
469 470
               density+=1.0;
     }
471 472
     density=density/(radius_square*M_PI);

473 474
     //get the velocity
     double density_max=5.4;
475

476 477 478 479 480 481
     //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();
     }
482

483 484
     //set the velocity vector
     if(ped->FindRoute()!=-1)
485 486 487 488 489
     {
          //get the next destination point
          Point v =(ped->GetExitLine()->ShortestPoint(ped->GetPos())- ped->GetPos()).Normalized();
          v=v*speed;
          ped->SetV(v);
490
          //cout<<"density: "<<density<<endl;
491 492 493 494
     }
     else
     {
          Log->Write("ERROR:\t no route could be found for agent [%d] going to [%d]",ped->GetID(),ped->GetFinalDestination());
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
          //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;
          double radius_square=0.40*0.40;

          for(const auto& p: neighbours)
          {
516 517
              //FIXME: p  can be null, if deleted in the main simulation thread.
        	  if( p && (pt-p->GetPos()).NormSquare()<=radius_square)
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
                    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());
539
     }
540 541

}
542 543 544 545 546 547 548 549 550 551 552


void AgentsSourcesManager::GenerateAgents()
{

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

553 554 555
void AgentsSourcesManager::AddSource(std::shared_ptr<AgentsSource> src)
{
     _sources.push_back(src);
556
     _isCompleted=false;//at least one source was provided
557 558 559 560 561 562
}

const std::vector<std::shared_ptr<AgentsSource> >& AgentsSourcesManager::GetSources() const
{
     return _sources;
}
563 564 565

void AgentsSourcesManager::SetBuilding(Building* building)
{
566
     _building = building;
567
}
568 569 570

bool AgentsSourcesManager::IsCompleted() const
{
571
     return _isCompleted;
572
}
573 574 575 576 577 578


Building* AgentsSourcesManager::GetBuilding() const
{
     return _building;
}
579 580 581 582 583 584 585 586 587 588

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