AgentsSourcesManager.cpp 28.3 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 "../voronoi/VoronoiDiagramGenerator.h"
36
#include "../geometry/Building.h"
37 38
#include "../geometry/Point.h"

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

45

46 47 48 49 50 51 52
//a.brkic begin
#include "../geometry/SubRoom.h"
#include <stdlib.h>
#include <time.h>
#include <string>
#include <random>

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
#include "boost/polygon/voronoi.hpp"
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;


//wrapping the boost objects
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

82
//a.brkic end
83

84 85
using namespace std;

86
bool AgentsSourcesManager::_isCompleted=true;
87

88 89 90 91 92 93 94 95
AgentsSourcesManager::AgentsSourcesManager()
{
}

AgentsSourcesManager::~AgentsSourcesManager()
{
}

96
void AgentsSourcesManager::operator()()
97
{
98
     Run();
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
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;
     long updateFrequency = 5;     // 1 second
     do
     {
          int current_time = Pedestrian::GetGlobalTime();

          if ((current_time != _lastUpdateTime)
                    && ((current_time % updateFrequency) == 0))
          {
               finished=ProcessAllSources();
               _lastUpdateTime = current_time;
          }
          //wait some time
131
         // std::this_thread::sleep_for(std::chrono::milliseconds(1));
132 133
     } while (!finished);
     Log->Write("INFO:\tTerminating agent manager thread");
134
     _isCompleted = true;
135 136 137
}

bool AgentsSourcesManager::ProcessAllSources() const
138 139 140 141
{
     bool empty=true;
     for (const auto& src : _sources)
     {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
142

143 144 145
          if (src->GetPoolSize())
          {
               vector<Pedestrian*> peds;
146
               src->RemoveAgentsFromPool(peds,src->GetFrequency());
Ulrich Kemloh's avatar
Ulrich Kemloh committed
147
               Log->Write("INFO:\tSource %d generating %d agents (%d remaining)",src->GetId(),peds.size(),src->GetPoolSize());
148

149
               //ComputeBestPositionRandom(src.get(), peds);
150
               //todo: compute the optimal position for insertion using voronoi
151 152 153 154 155 156
               ComputeBestPositionVoronoiBoost2(src.get(), peds);
               /*for (auto&& ped : peds)
               {
               ComputeBestPositionVoronoiBoost(src.get(), ped);
               //ped->Dump(ped->GetID(),0);
               }*/
157
               AgentsQueueIn::Add(peds);
158 159 160 161 162
               empty = false;
          }
          //src->Dump();//exit(0);
     }
     return empty;
163
}
164
/*
165
void AgentsSourcesManager::ComputeBestPositionVoronoi(AgentsSource* src,
166
          Pedestrian* agent) const
167
{
168 169 170 171 172
     auto dist = src->GetStartDistribution();
     double bounds[4];
     dist->Getbounds(bounds);
     int roomID = dist->GetRoomId();
     int subroomID = dist->GetSubroomID();
173 174 175

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

178
     //filter the points that are not within the boundaries
179 180 181 182 183 184 185
     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
186
               cout << "removing (testing only)..." << endl;
187
               exit(0);
188
          } else
189 190 191 192 193 194 195 196
          {
               ++iter;
          }
     }

     //special case with 1, 2 or only three pedestrians in the area
     if (peds.size() < 3)
     {
197 198
          //TODO/random position in the area
          return;
199 200

     }
201
     // compute the cells and cut with the bounds
202
     const int count = peds.size();
203 204
     float* xValues = new float[count];
     float* yValues = new float[count];
205 206
     //float xValues[count];
     //float yValues[count];
207

208
     for (int i = 0; i < count; i++)
209
     {
210 211
          xValues[i] = peds[i]->GetPos()._x;
          yValues[i] = peds[i]->GetPos()._y;
212 213 214
     }

     VoronoiDiagramGenerator vdg;
215 216
     vdg.generateVoronoi(xValues, yValues, count, bounds[0], bounds[1],
               bounds[2], bounds[3], 3);
217 218 219 220
     vdg.resetIterator();
     vdg.resetVerticesIterator();

     printf("\n------vertices---------\n");
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
     //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)
250
     {
251
          cout << "dist: " << mp.first << " pos: " << mp.second.toString()
252
                                        << endl;
253
          //agent->SetPos(mp.second, true);
254 255
     }

256 257 258 259 260 261 262
     //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);
263

264
     } else
265 266 267
     {
          cout << "position not set:" << endl;
          cout << "size: " << map_dist_to_position.size() << endl;
268
          cout << " for " << peds.size() << " pedestrians" << endl;
269 270
          exit(0);
     }
271 272 273 274 275 276 277 278
     //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
279
     //exit(0);
280
}
281 282 283 284 285 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 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 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
*/

void AgentsSourcesManager::ComputeBestPositionVoronoiBoost2(AgentsSource* src,
		std::vector<Pedestrian*>& peds) const
{
	auto dist = src->GetStartDistribution();
	int roomID = dist->GetRoomId();
	int subroomID = dist->GetSubroomID();
	std::string caption = (_building->GetRoom( roomID ))->GetCaption();
	double radius = 0.4; //DO: change! radius of a person

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

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

	for(auto&& ped : peds)
	{
		if(existing_peds.size() == 0 )
		{
			Log->Write("INFO:\tenter case 0");
			Point new_pos = subroom->GetCentroid();
			ped->SetPos(new_pos, true);
			Point v =(ped->GetExitLine()->ShortestPoint(ped->GetPos())- ped->GetPos()).Normalized();
			double speed=ped->GetV0Norm();
			v=v*speed;
			ped->SetV(v);
		}

		else if(existing_peds.size() == 1 )
		{
			Log->Write("INFO:\tenter case 1");

			Point p = existing_peds[0]->GetPos();
			vector<Point> room_vertices = subroom->GetPolygon();

			srand (time(NULL));
			unsigned int i = rand() % room_vertices.size();
			double dis = ( p.GetX() - room_vertices[i].GetX() ) * ( p.GetX() - room_vertices[i].GetX() )
					+ ( p.GetY() - room_vertices[i].GetY() ) * ( p.GetY() - room_vertices[i].GetY() );
			if( dis > radius*radius)
			{
				Point new_pos( p.GetX()/2.0  + room_vertices[i].GetX()/2.0,  p.GetY()/2.0 + room_vertices[i].GetY()/2.0  );
				ped->SetPos( new_pos, true );
				Point v =(ped->GetExitLine()->ShortestPoint(ped->GetPos())- ped->GetPos()).Normalized();
				double speed=ped->GetV0Norm();
				v=v*speed;
				ped->SetV(v);
			}
		}

		else if(existing_peds.size() == 2)
		{
			Log->Write("INFO:\tenter case 2");
			Point p1 = existing_peds[0]->GetPos();
			Point p2 = existing_peds[1]->GetPos();
			double x1 = p1.GetX(); double y1 = p1.GetY();
			double x2 = p2.GetX(); double y2 = p2.GetY();
			Point t1( (x1+x2)/2.0 + 1.1*(y1-y2), (y1+y2)/2.0 + 1.1*(x2-x1) );
			Point t2( (x1+x2)/2.0 + 1.1*(y2-y1), (y1+y2)/2.0 + 1.1*(x1-x2) );

			for (double alpha = 1.0; alpha>0 ; alpha-=0.1)
				if( subroom->IsInsideOfPolygon(t1) )
				{
					ped->SetPos(t1, true );
					Point new_velo(-1,0);
					ped->SetV( new_velo );
					break;
				}
				else if( subroom->IsInsideOfPolygon(t1) )
				{
					ped->SetPos(t2, true );
					Point new_velo(-1,0);
					ped->SetV( new_velo );
					break;
				}
				else
				{
					t1.SetX( (x1+x2)/2.0 + alpha*(y1-y2) );
					t1.SetY( (y1+y2)/2.0 + alpha*(x2-x1) );
					t2.SetX( (x1+x2)/2.0 + alpha*(y2-y1) );
					t2.SetY( (y1+y2)/2.0 + alpha*(x1-x2) );
				}
			//in case it didn't work
			for (double alpha = 1.0; alpha<3 ; alpha+=0.2)
				if( subroom->IsInsideOfPolygon(t1) )
				{
					ped->SetPos(t1, true );
					ped->SetV( ped->GetV0() );
					break;
				}
				else if( subroom->IsInsideOfPolygon(t1) )
				{
					ped->SetPos(t2, true );
					ped->SetV( ped->GetV0() );
					break;
				}
				else
				{
					t1.SetX( (x1+x2)/2.0 + alpha*(y1-y2) );
					t1.SetY( (y1+y2)/2.0 + alpha*(x2-x1) );
					t2.SetX( (x1+x2)/2.0 + alpha*(y2-y1) );
					t2.SetY( (y1+y2)/2.0 + alpha*(x1-x2) );
				}
		}

		else
		{
			Log->Write("INFO:\tenter case 3");
			double factor = 100;  //factor for conversion to integer
			std::vector<Point> discrete_positions;
			std::vector<Point> velocities_vector;

			Point temp(0,0);
			//points from double to integer
			for (auto&& iter = existing_peds.begin(); iter != existing_peds.end(); ++iter)
			{
				const Point& pos = (*iter)->GetPos();
				temp.SetX( (int)( pos.GetX()*factor ) );
				temp.SetY( (int)( pos.GetY()*factor ) );
				discrete_positions.push_back( temp );
				velocities_vector.push_back( (*iter)->GetV() );
			}

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

			voronoi_diagram<double>::const_vertex_iterator max_it=vd.vertices().begin();
			double max_dis=0;

412
			VoronoiBestVertexRandMax(discrete_positions, vd, subroom, factor, max_it, max_dis	);
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

			Point pos( max_it->x()/factor, max_it->y()/factor ); //check!
			if(max_dis> radius*factor*radius*factor)// be careful with the factor!! radius*factor
			{
				ped->SetPos(pos , true);

				//finding the neighbors (nearest pedestrians) of the chosen vertex
				const voronoi_diagram<double>::vertex_type &vertex = *max_it;
				const voronoi_diagram<double>::edge_type *edge = vertex.incident_edge();
				double sum_x=0, sum_y=0;
				int no=0;
				std::size_t index;

				do
				{
					no++;
					index = ( edge->cell() )->source_index();
					const Point& v = velocities_vector[index];
					sum_x += v.GetX();
					sum_y += v.GetY();
					edge = edge->rot_next();
				} while (edge != vertex.incident_edge());

				Point v(sum_x/no, sum_y/no);
				ped->SetV(v);
			}
		}
		existing_peds.push_back(ped);
	}
}

//gives the voronoi vertex with max distance
445
void AgentsSourcesManager::VoronoiBestVertexMax (const std::vector<Point>& discrete_positions, const voronoi_diagram<double>& vd, SubRoom* subroom, int factor,
446 447 448 449 450 451 452 453 454 455 456 457 458 459
		voronoi_diagram<double>::const_vertex_iterator& max_it, double& max_dis	) const
{
	double dis = 0;
	for (voronoi_diagram<double>::const_vertex_iterator it = vd.vertices().begin(); it != vd.vertices().end(); ++it)
	{
		Point vert_pos = Point( it->x()/factor, it->y()/factor );
		if( subroom->IsInsideOfPolygon(vert_pos) ) //wrote this function by myself
		{
			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];

460
			dis = ( p.GetX() - it->x() )*( p.GetX() - it->x() )   + ( p.GetY() - it->y() )*( p.GetY() - it->y() )  ;
461 462 463 464 465 466 467 468 469
			if(dis>max_dis)
			{
				max_dis = dis;
				max_it = it;
			}
		}
	}
}

470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524

//gives random voronoi vertex but with weights proportional to squared distances
void AgentsSourcesManager::VoronoiBestVertexRandMax (const std::vector<Point>& discrete_positions, const voronoi_diagram<double>& vd, SubRoom* subroom, int factor,
		voronoi_diagram<double>::const_vertex_iterator& chosen_it, double& dis	) const
{
	std::vector< voronoi_diagram<double>::const_vertex_iterator > possible_vertices;
	vector<double> partial_sums;
	unsigned int size;

	for (voronoi_diagram<double>::const_vertex_iterator it = vd.vertices().begin(); it != vd.vertices().end(); ++it)
	{
		Point vert_pos = Point( it->x()/factor, it->y()/factor );
		if( subroom->IsInsideOfPolygon(vert_pos) ) //wrote this function by myself
		{
			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.GetX() - it->x() )*( p.GetX() - it->x() )   + ( p.GetY() - it->y() )*( p.GetY() - it->y() )  ;

			possible_vertices.push_back( it );
			partial_sums.push_back( dis );

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

}

525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
//not working, use the version 2
void AgentsSourcesManager::ComputeBestPositionVoronoiBoost(AgentsSource* src,
          Pedestrian* ped) const
{
	auto dist = src->GetStartDistribution();
	int roomID = dist->GetRoomId();
	int subroomID = dist->GetSubroomID();
	std::string caption = (_building->GetRoom( roomID ))->GetCaption();
	double radius = 0.4; //DO: change! radius of a person

	//Positions of pedestrians
	std::vector<Pedestrian*> peds;
	_building->GetPedestrians(roomID, subroomID, peds);  //do I need only pedestrians in the subroom?
	Log->Write("INFO:\tpedsize=%d", peds.size());
	//getting the geometry of the room, needed for checking if the voronoi vertex is inside of a room
	SubRoom* subroom=(_building->GetRoom( roomID ))->GetSubRoom(subroomID);
	//Room* GetRoom(int index) const;

	if( peds.size() == 0 )
	{
		//puts the person in the center
		Point new_pos = subroom->GetCentroid();
		ped->SetPos(new_pos, true);


		Point v =(ped->GetExitLine()->ShortestPoint(ped->GetPos())- ped->GetPos()).Normalized();
		double speed=ped->GetV0Norm();
		v=v*speed;
		ped->SetV(v);
		//ped->SetRoomID(roomID, caption);
		//ped->SetSubRoomID(subroomID);

		Log->Write("INFO:\texit case 0");

	}
	else if( peds.size() == 1 )
	{
		Point p = peds[0]->GetPos();
		vector<Point> room_vertices = subroom->GetPolygon();

		for (unsigned int i=0 ; i < room_vertices.size() ; i++ )
		{
			double dis = ( p.GetX() - room_vertices[i].GetX() ) * ( p.GetX() - room_vertices[i].GetX() )
					+ ( p.GetY() - room_vertices[i].GetY() ) * ( p.GetY() - room_vertices[i].GetY() );
			if( dis > radius*radius)
			{
				Point new_pos( p.GetX()/2.0  + room_vertices[i].GetX()/2.0,  p.GetY()/2.0 + room_vertices[i].GetY()/2.0  );
				ped->SetPos( new_pos, true );
				Point new_velo(-1,0);
				ped->SetV( new_velo );
				break;
			}
		}


		Point new_pos(10.2,6.4);
		ped->SetPos( new_pos, true );
		Point new_velo(-1,0);
		ped->SetV( new_velo );
		Log->Write("INFO:\texit case 1");
	}
	else if( peds.size() == 2 )
	{
		Point p1 = peds[0]->GetPos();
		Point p2 = peds[1]->GetPos();
		double x1 = p1.GetX(); double y1 = p1.GetY();
		double x2 = p2.GetX(); double y2 = p2.GetY();
		Point t1( (x1+x2)/2.0 + 1.1*(y1-y2), (y1+y2)/2.0 + 1.1*(x2-x1) );
		Point t2( (x1+x2)/2.0 + 1.1*(y2-y1), (y1+y2)/2.0 + 1.1*(x1-x2) );

		for (double alpha = 1.0; alpha>0 ; alpha-=0.1)
			if( subroom->IsInsideOfPolygon(t1) )
			{
				ped->SetPos(t1, true );
				Point new_velo(-1,0);
				ped->SetV( new_velo );
				break;
			}
			else if( subroom->IsInsideOfPolygon(t1) )
			{
				ped->SetPos(t2, true );
				Point new_velo(-1,0);
				ped->SetV( new_velo );
				break;
			}
			else
			{
				t1.SetX( (x1+x2)/2.0 + alpha*(y1-y2) );
				t1.SetY( (y1+y2)/2.0 + alpha*(x2-x1) );
				t2.SetX( (x1+x2)/2.0 + alpha*(y2-y1) );
				t2.SetY( (y1+y2)/2.0 + alpha*(x1-x2) );
			}
		//in case it didn't work
		for (double alpha = 1.0; alpha<3 ; alpha+=0.2)
			if( subroom->IsInsideOfPolygon(t1) )
			{
				ped->SetPos(t1, true );
				ped->SetV( ped->GetV0() );
				break;
			}
			else if( subroom->IsInsideOfPolygon(t1) )
			{
				ped->SetPos(t2, true );
				ped->SetV( ped->GetV0() );
				break;
			}
			else
			{
				t1.SetX( (x1+x2)/2.0 + alpha*(y1-y2) );
				t1.SetY( (y1+y2)/2.0 + alpha*(x2-x1) );
				t2.SetX( (x1+x2)/2.0 + alpha*(y2-y1) );
				t2.SetY( (y1+y2)/2.0 + alpha*(x1-x2) );
			}

		Log->Write("INFO:\texit case 2");
	}
	else
	{
		double factor = 100;  //factor for conversion to int
		std::vector<Point> discrete_positions;
		std::vector<Point> velocities_vector;

		Point temp(0,0);
		//points from double to int
		for (auto&& iter = peds.begin(); iter != peds.end();++iter)
		{
			const Point& pos = (*iter)->GetPos();
			temp.SetX( (int)( pos.GetX()*factor ) );
			temp.SetY( (int)( pos.GetY()*factor ) );
			discrete_positions.push_back( temp );
			velocities_vector.push_back( (*iter)->GetV() );
		}

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

		voronoi_diagram<double>::const_vertex_iterator max_it=vd.vertices().begin();
		double max_dis=0;
		double dis=0;

		//finding the best position - DO: make different functions for calculating the best position
		for (voronoi_diagram<double>::const_vertex_iterator it = vd.vertices().begin(); it != vd.vertices().end(); ++it)
			{
				//making the surroundings,  bool IsPartOfPolygon(const Point& pt);
				Point vert_pos = Point( it->x()/factor,it->y()/factor );
				if( subroom->IsInsideOfPolygon(vert_pos) ) //wrote this function by myself
				{
					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.GetX() - it->x() )*( p.GetX() - it->x() )   + ( p.GetY() - it->y() )*( p.GetY() - it->y() )  ;
					if(dis>max_dis)
					{
						max_dis = dis;
						max_it = it;
					}
				}
			}
		//best position is max_it->x(), max_it->y() - give it to the neighbor
		Point pos( max_it->x()/factor, max_it->y()/factor ); //check!
		//SetPos(const Point& pos, bool initial=false);
		//if(max_dis> radius*factor*radius*factor), be careful with the factor!! radius*factor
		ped->SetPos(pos , true);

		//finding the neighbors (nearest pedestrians) of the chosen vertex
		const voronoi_diagram<double>::vertex_type &vertex = *max_it;
		const voronoi_diagram<double>::edge_type *edge = vertex.incident_edge();
		double sum_x=0, sum_y=0;
		int no=0;
		std::size_t index;

		do
		{
			no++;
			index = ( edge->cell() )->source_index();
			const Point& v = velocities_vector[index];
			sum_x += v.GetX();
			sum_y += v.GetY();
			edge = edge->rot_next();
		} while (edge != vertex.incident_edge());

		Point v(sum_x/no, sum_y/no);
		ped->SetV(v);

		//const Point& GetV() const;
		//void SetV(const Point& v);
		Log->Write("INFO:\texit case 3");
	} //ELSE
	return;
}

720

721
void AgentsSourcesManager::ComputeBestPositionRandom(AgentsSource* src,
722
          std::vector<Pedestrian*>& peds) const
723 724 725
{

     //generate the agents with default positions
726 727 728 729 730
     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 };
731 732
     dist->Getbounds(bounds);

733 734
     vector<Point> extra_positions;

735
     for (auto& ped : peds)
736
     {
737 738 739
          //need to be called at each iteration
          SortPositionByDensity(positions, extra_positions);

740 741 742
          int index = -1;

          //in the case a range was specified
743
          //just take the first element
744
          for (unsigned int a = 0; a < positions.size(); a++)
745
          {
746
               Point pos = positions[a];
747
               //cout<<"checking: "<<pos.toString()<<endl;
748 749
               if ((bounds[0] <= pos._x) && (pos._x <= bounds[1])
                         && (bounds[2] <= pos._y) && (pos._y < bounds[3]))
750
               {
751
                    index = a;
752 753 754
                    break;
               }
          }
755
          if (index == -1)
756
          {
757
               if (positions.size())
758
               {
759
                    Log->Write(
760
                              "ERROR:\t AgentSourceManager Cannot distribute pedestrians in the mentioned area [%0.2f,%0.2f,%0.2f,%0.2f]",
761
                              bounds[0], bounds[1], bounds[2], bounds[3]);
762 763 764
                    Log->Write("     \t Specifying a subroom_id might help");
                    Log->Write("     \t %d positions were available",positions.size());
                    exit(EXIT_FAILURE);
765
               }
766 767
          }
          else
768 769
          {
               const Point& pos = positions[index];
770
               extra_positions.push_back(pos);
771
               ped->SetPos(pos, true); //true for the initial position
772 773
               positions.erase(positions.begin() + index);

774
               //at this point we have a position
775 776 777
               //so we can adjust the velocity
               //AdjustVelocityUsingWeidmann(ped);
               AdjustVelocityByNeighbour(ped);
778 779 780
          }
     }
}
781

782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
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
     }

}

838 839 840 841 842 843
void AgentsSourcesManager::AdjustVelocityUsingWeidmann(Pedestrian* ped) const
{
     //get the density
     vector<Pedestrian*> neighbours;
     _building->GetGrid()->GetNeighbourhood(ped,neighbours);

844
     //density in pers per m2
845 846
     double density = 1.0;
     //radius corresponding to a surface of 1m2
847
     //double radius_square=0.564*0.564;
848
     double radius_square=1.0;
849

850 851
     for(const auto& p: neighbours)
     {
852
          if( (ped->GetPos()-p->GetPos()).NormSquare()<=radius_square)
853 854
               density+=1.0;
     }
855 856
     density=density/(radius_square*M_PI);

857 858
     //get the velocity
     double density_max=5.4;
859

860 861 862 863 864 865
     //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();
     }
866

867 868
     //set the velocity vector
     if(ped->FindRoute()!=-1)
869 870 871 872 873
     {
          //get the next destination point
          Point v =(ped->GetExitLine()->ShortestPoint(ped->GetPos())- ped->GetPos()).Normalized();
          v=v*speed;
          ped->SetV(v);
874
          //cout<<"density: "<<density<<endl;
875 876 877 878
     }
     else
     {
          Log->Write("ERROR:\t no route could be found for agent [%d] going to [%d]",ped->GetID(),ped->GetFinalDestination());
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
          //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)
          {
               if( (pt-p->GetPos()).NormSquare()<=radius_square)
                    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());
922
     }
923 924

}
925 926 927 928 929 930 931 932 933 934 935


void AgentsSourcesManager::GenerateAgents()
{

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

936 937 938
void AgentsSourcesManager::AddSource(std::shared_ptr<AgentsSource> src)
{
     _sources.push_back(src);
939
     _isCompleted=false;//at least one source was provided
940 941 942 943 944 945
}

const std::vector<std::shared_ptr<AgentsSource> >& AgentsSourcesManager::GetSources() const
{
     return _sources;
}
946 947 948

void AgentsSourcesManager::SetBuilding(Building* building)
{
949
     _building = building;
950
}
951 952 953

bool AgentsSourcesManager::IsCompleted() const
{
954
     return _isCompleted;
955
}
956 957 958 959 960 961


Building* AgentsSourcesManager::GetBuilding() const
{
     return _building;
}
962 963 964 965 966 967 968 969 970 971

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