Simulation.cpp 22.6 KB
Newer Older
1
/**
Weichen's avatar
Weichen committed
2 3
 * \file        Simulation.cpp
 * \date        Dec 15, 2010
Mohcine Chraibi's avatar
Mohcine Chraibi committed
4
 * \version     v0.8.1
5
 * \copyright   <2009-2015> Forschungszentrum Jülich GmbH. All rights reserved.
6
 *
Weichen's avatar
Weichen committed
7
 * \section License
8 9 10
 * This file is part of JuPedSim.
 *
 * JuPedSim is free software: you can redistribute it and/or modify
11
 * it under the terms of the GNU Lesser General Public License as published by
12 13 14 15 16 17 18 19
 * 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.
 *
20
 * You should have received a copy of the GNU Lesser General Public License
Weichen's avatar
Weichen committed
21
 * along with JuPedSim. If not, see <http://www.gnu.org/licenses/>.
22
 *
23
 * \section Description
24 25 26 27
 * The Simulation class represents a simulation of pedestrians
 * based on a certain model in a specific scenario. A simulation is defined by
 * various parameters and functions.
 *
Weichen's avatar
Weichen committed
28 29 30
 *
 **/

Ulrich Kemloh's avatar
Ulrich Kemloh committed
31
#include "Simulation.h"
Mohcine Chraibi's avatar
Mohcine Chraibi committed
32
#include "IO/progress_bar.hpp"
33
#include "routing/ff_router/ffRouter.h"
Ulrich Kemloh's avatar
Ulrich Kemloh committed
34 35
#include "math/GCFMModel.h"
#include "math/GompertzModel.h"
Arne Graf's avatar
Arne Graf committed
36
#include "math/GradientModel.h"
37
#include "pedestrian/AgentsQueue.h"
38
#include "pedestrian/AgentsSourcesManager.h"
39
#ifdef _OPENMP
GrgrLmml's avatar
GrgrLmml committed
40

41 42 43 44
#else
#define omp_get_thread_num() 0
#define omp_get_max_threads()  1
#endif
45

Ulrich Kemloh's avatar
Ulrich Kemloh committed
46
using namespace std;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
47

48 49
OutputHandler* Log;

Arne Graf's avatar
Arne Graf committed
50
Simulation::Simulation(Configuration* args)
GrgrLmml's avatar
GrgrLmml committed
51
        :_config(args)
52
{
GrgrLmml's avatar
GrgrLmml committed
53 54 55 56 57 58 59 60 61 62
    _nPeds = 0;
    _seed = 8091983;
    _deltaT = 0;
    _building = nullptr;
    //_direction = NULL;
    _operationalModel = nullptr;
    _solver = nullptr;
    _iod = new IODispatcher();
    _fps = 1;
    _em = nullptr;
Mohcine Chraibi's avatar
Mohcine Chraibi committed
63
    _gotSources = false;
64
    _maxSimTime = 100;
GrgrLmml's avatar
GrgrLmml committed
65
//     _config = args;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
66 67
}

68 69
Simulation::~Simulation()
{
GrgrLmml's avatar
GrgrLmml committed
70 71 72
    delete _solver;
    delete _iod;
    delete _em;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
73 74
}

Oliver Schmidts's avatar
Oliver Schmidts committed
75
long Simulation::GetPedsNumber() const
76
{
GrgrLmml's avatar
GrgrLmml committed
77
    return _nPeds;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
78 79
}

GrgrLmml's avatar
GrgrLmml committed
80
bool Simulation::InitArgs()
81
{
GrgrLmml's avatar
GrgrLmml committed
82 83 84 85
    char tmp[CLENGTH];
    string s = "Parameter:\n";

    switch (_config->GetLog()) {
Mohcine Chraibi's avatar
Mohcine Chraibi committed
86 87
    case 0: {

GrgrLmml's avatar
GrgrLmml committed
88
        break;
Mohcine Chraibi's avatar
Mohcine Chraibi committed
89 90
    }
    case 1: {
GrgrLmml's avatar
GrgrLmml committed
91 92 93 94
        if (Log)
            delete Log;
        Log = new STDIOHandler();
        break;
Mohcine Chraibi's avatar
Mohcine Chraibi committed
95
    }
GrgrLmml's avatar
GrgrLmml committed
96 97
    case 2: {
        char name[CLENGTH] = "";
Mohcine Chraibi's avatar
Mohcine Chraibi committed
98
        sprintf(name, "%s.txt", _config->GetErrorLogFile().c_str());
GrgrLmml's avatar
GrgrLmml committed
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
        if (Log)
            delete Log;
        Log = new FileHandler(name);
    }
        break;
    default:
        printf("Wrong option for Logfile!\n\n");
        return false;
    }

    if (_config->GetPort()!=-1) {
        switch (_config->GetFileFormat()) {
        case FORMAT_XML_PLAIN_WITH_MESH:
        case FORMAT_XML_PLAIN: {
            OutputHandler* travisto = new SocketHandler(_config->GetHostname(),
                    _config->GetPort());
            Trajectories* output = new TrajectoriesJPSV06();
            output->SetOutputHandler(travisto);
            _iod->AddIO(output);
            break;
        }
        case FORMAT_XML_BIN: {
            Log->Write(
                    "INFO: \tFormat xml-bin not yet supported in streaming\n");
            //exit(0);
            break;
        }
        case FORMAT_PLAIN: {
            Log->Write(
                    "INFO: \tFormat plain not yet supported in streaming\n");
            return false;
        }
        case FORMAT_VTK: {
            Log->Write(
                    "INFO: \tFormat vtk not yet supported in streaming\n");
            return false;
        }
        default: {
            return false;
        }
        }

        s.append("\tonline streaming enabled \n");
    }

    if (!_config->GetTrajectoriesFile().empty()) {
        switch (_config->GetFileFormat()) {
        case FORMAT_XML_PLAIN: {
            OutputHandler* tofile = new FileHandler(
                    _config->GetTrajectoriesFile().c_str());
            Trajectories* output = new TrajectoriesJPSV05();
            output->SetOutputHandler(tofile);
            _iod->AddIO(output);
            break;
        }
        case FORMAT_PLAIN: {
            OutputHandler* file = new FileHandler(
                    _config->GetTrajectoriesFile().c_str());
            Trajectories* output = new TrajectoriesFLAT();
            output->SetOutputHandler(file);
            _iod->AddIO(output);
            break;
        }
        case FORMAT_VTK: {
            Log->Write("INFO: \tFormat vtk not yet supported\n");
            OutputHandler* file = new FileHandler(
                    (_config->GetTrajectoriesFile()+".vtk").c_str());
            Trajectories* output = new TrajectoriesVTK();
            output->SetOutputHandler(file);
            _iod->AddIO(output);
            break;
        }

        case FORMAT_XML_PLAIN_WITH_MESH: {
            //OutputHandler* tofile = new FileHandler(args->GetTrajectoriesFile().c_str());
            //if(_iod) delete _iod;
            //_iod = new TrajectoriesXML_MESH();
            //_iod->AddIO(tofile);
            break;
        }
        case FORMAT_XML_BIN: {
            // OutputHandler* travisto = new SocketHandler(args->GetHostname(), args->GetPort());
            // Trajectories* output= new TrajectoriesJPSV06();
            // output->SetOutputHandler(travisto);
            // _iod->AddIO(output);
            break;
        }
        default: {
            break;
        }
        }
    }

    _operationalModel = _config->GetModel();
    s.append(_operationalModel->GetDescription());

    // ODE solver which is never used!
    auto solver = _config->GetSolver();
    sprintf(tmp, "\tODE Solver: %d\n", solver);
    s.append(tmp);

    sprintf(tmp, "\tnCPU: %d\n", _config->GetMaxOpenMPThreads());
    s.append(tmp);
    sprintf(tmp, "\tt_max: %f\n", _config->GetTmax());
    s.append(tmp);
    _deltaT = _config->Getdt();
205
    _maxSimTime = _config->GetTmax();
GrgrLmml's avatar
GrgrLmml committed
206 207 208 209 210 211 212 213 214 215 216 217 218
    sprintf(tmp, "\tdt: %f\n", _deltaT);
    _periodic = _config->IsPeriodic();
    sprintf(tmp, "\t periodic: %d\n", _periodic);
    s.append(tmp);

    _fps = _config->GetFps();
    sprintf(tmp, "\tfps: %f\n", _fps);
    s.append(tmp);
    //Log->Write(s.c_str());

    _routingEngine = _config->GetRoutingEngine();
    auto distributor = std::unique_ptr<PedDistributor>(new PedDistributor(_config));
    // IMPORTANT: do not change the order in the following..
219
    _building = std::shared_ptr<Building>(new Building(_config, *distributor));
GrgrLmml's avatar
GrgrLmml committed
220 221 222

    // Initialize the agents sources that have been collected in the pedestrians distributor
    _agentSrcManager.SetBuilding(_building.get());
223
    _agentSrcManager.SetMaxSimTime(GetMaxSimTime());
Mohcine Chraibi's avatar
Mohcine Chraibi committed
224
    _gotSources = (bool) distributor->GetAgentsSources().size(); // did we have any sources? false if no sources
Mohcine Chraibi's avatar
Mohcine Chraibi committed
225 226
    std::cout << " Got sources: " << _gotSources;

GrgrLmml's avatar
GrgrLmml committed
227 228
    for (const auto& src: distributor->GetAgentsSources()) {
        _agentSrcManager.AddSource(src);
Mohcine Chraibi's avatar
Mohcine Chraibi committed
229
        src->Dump();
GrgrLmml's avatar
GrgrLmml committed
230 231 232 233
    }



Mohcine Chraibi's avatar
Mohcine Chraibi committed
234

GrgrLmml's avatar
GrgrLmml committed
235 236 237 238 239 240 241
    //perform customs initialisation, like computing the phi for the gcfm
    //this should be called after the routing engine has been initialised
    // because a direction is needed for this initialisation.
    Log->Write("INFO:\t Init Operational Model starting ...");
    if (!_operationalModel->Init(_building.get()))
        return false;
    Log->Write("INFO:\t Init Operational Model done");
f.mack's avatar
f.mack committed
242 243 244 245 246 247

    // Give the DirectionStrategy the chance to perform some initialization.
    // This should be done after the initialization of the operationalModel
    // because then, invalid pedestrians have been deleted and FindExit()
    // has been called.

GrgrLmml's avatar
GrgrLmml committed
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 274 275 276 277 278 279
    //other initializations
    for (auto&& ped: _building->GetAllPedestrians()) {
        ped->Setdt(_deltaT);
    }
    _nPeds = _building->GetAllPedestrians().size();
    //_building->WriteToErrorLog();
    Log->Write("INFO:\t nPeds %d received", _nPeds);
    //get the seed
    _seed = _config->GetSeed();

    //size of the cells/GCFM/Gompertz
    if (_config->GetDistEffMaxPed()>_config->GetLinkedCellSize()) {
        Log->Write(
                "ERROR: the linked-cell size [%f] should be bigger than the force range [%f]",
                _config->GetLinkedCellSize(), _config->GetDistEffMaxPed());
        return false;
    }

    //read and initialize events
    _em = new EventManager(_building.get(), _config->GetSeed());
    if (!_em->ReadEventsXml()) {
        Log->Write("ERROR: \tCould not initialize events handling");
    }
    _em->ListEvents();

    //_building->SaveGeometry("test.sav.xml");

    //if(_building->SanityCheck()==false)
    //     return false;

    //everything went fine
    return true;
280
}
281

282
double Simulation::RunStandardSimulation(double maxSimTime)
283
{
GrgrLmml's avatar
GrgrLmml committed
284 285 286
    RunHeader(_nPeds+_agentSrcManager.GetMaxAgentNumber());
    double t = RunBody(maxSimTime);
    RunFooter();
287
    return t;
288
}
289

290
void Simulation::UpdateRoutesAndLocations()
291
{
292 293
     //pedestrians to be deleted
     //you should better create this in the constructor and allocate it once.
294 295
     set<Pedestrian*> pedsToRemove;
//     pedsToRemove.reserve(500); //just reserve some space
296 297

     // collect all pedestrians in the simulation.
298 299
     const vector<Pedestrian*>& allPeds = _building->GetAllPedestrians();
     const map<int, Goal*>& goals = _building->GetAllGoals();
Oliver Schmidts's avatar
Oliver Schmidts committed
300
     auto allRooms = _building->GetAllRooms();
301

Oliver Schmidts's avatar
Oliver Schmidts committed
302
#pragma omp parallel for shared(pedsToRemove, allRooms)
Qiancheng Xu's avatar
Qiancheng Xu committed
303
     for (signed int p = 0; p < allPeds.size(); ++p) {
Oliver Schmidts's avatar
Oliver Schmidts committed
304 305 306
          auto ped = allPeds[p];
          Room* room = _building->GetRoom(ped->GetRoomID());
          SubRoom* sub0 = room->GetSubRoom(ped->GetSubRoomID());
307

Oliver Schmidts's avatar
Oliver Schmidts committed
308 309 310
          //set the new room if needed
          if ((ped->GetFinalDestination() == FINAL_DEST_OUT)
                    && (room->GetCaption() == "outside")) {
311

f.mack's avatar
f.mack committed
312
#pragma omp critical(Simulation_Update_pedsToRemove)
313
               pedsToRemove.insert(ped);
Oliver Schmidts's avatar
Oliver Schmidts committed
314
          } else if ((ped->GetFinalDestination() != FINAL_DEST_OUT)
GrgrLmml's avatar
GrgrLmml committed
315
                    && (goals.at(ped->GetFinalDestination())->Contains(
Oliver Schmidts's avatar
Oliver Schmidts committed
316
                              ped->GetPos()))) {
f.mack's avatar
f.mack committed
317
#pragma omp critical(Simulation_Update_pedsToRemove)
318
               pedsToRemove.insert(ped);
Oliver Schmidts's avatar
Oliver Schmidts committed
319
          }
GrgrLmml's avatar
GrgrLmml committed
320

Oliver Schmidts's avatar
Oliver Schmidts committed
321 322 323 324 325
          // reposition in the case the pedestrians "accidently left the room" not via the intended exit.
          // That may happen if the forces are too high for instance
          // the ped is removed from the simulation, if it could not be reassigned
          else if (!sub0->IsInSubRoom(ped))
          {
326

Oliver Schmidts's avatar
Oliver Schmidts committed
327 328 329 330
               bool assigned = false;
               std::function<void(const Pedestrian&)> f = std::bind(&Simulation::UpdateFlowAtDoors, this, std::placeholders::_1);
               assigned = ped->Relocate(f);
               //this will delete agents, that are pushed outside (maybe even if inside obstacles??)
331

Oliver Schmidts's avatar
Oliver Schmidts committed
332
               if (!assigned) {
f.mack's avatar
f.mack committed
333
#pragma omp critical(Simulation_Update_pedsToRemove)
334
                       pedsToRemove.insert(ped); //the agent left the old room
GrgrLmml's avatar
GrgrLmml committed
335
                    //actualize the eggress time for that room
f.mack's avatar
f.mack committed
336
#pragma omp critical(SetEgressTime)
GrgrLmml's avatar
GrgrLmml committed
337 338
                    allRooms.at(ped->GetRoomID())->SetEgressTime(ped->GetGlobalTime());

339 340
               }
          }
Oliver Schmidts's avatar
Oliver Schmidts committed
341 342 343 344
          //finally actualize the route
          if (ped->FindRoute() == -1) {
               //a destination could not be found for that pedestrian
               Log->Write("ERROR: \tCould not find a route for pedestrian %d",ped->GetID());
Mohcine Chraibi's avatar
Mohcine Chraibi committed
345
               //ped->FindRoute(); //debug only, plz remove
Arne Graf's avatar
Arne Graf committed
346 347
               std::function<void(const Pedestrian&)> f = std::bind(&Simulation::UpdateFlowAtDoors, this, std::placeholders::_1);
               ped->Relocate(f);
Oliver Schmidts's avatar
Oliver Schmidts committed
348
               //exit(EXIT_FAILURE);
f.mack's avatar
f.mack committed
349
#pragma omp critical(Simulation_Update_pedsToRemove)
350
               {
Mohcine Chraibi's avatar
Mohcine Chraibi committed
351
                    pedsToRemove.insert(ped);
352 353
                    Log->incrementDeletedAgents();
               }
Oliver Schmidts's avatar
Oliver Schmidts committed
354 355
          }
     }
GrgrLmml's avatar
GrgrLmml committed
356

357

Ulrich Kemloh's avatar
Ulrich Kemloh committed
358
#ifdef _USE_PROTOCOL_BUFFER
359 360
     if (_hybridSimManager)
     {
Arne Graf's avatar
Arne Graf committed
361
          AgentsQueueOut::Add(pedsToRemove);    //this should be critical region (and it is)
362 363
     }
     else
Ulrich Kemloh's avatar
Ulrich Kemloh committed
364
#endif
GrgrLmml's avatar
GrgrLmml committed
365
    {
366

GrgrLmml's avatar
GrgrLmml committed
367
        // remove the pedestrians that have left the building
368 369 370
        for (auto p : pedsToRemove){
            UpdateFlowAtDoors(*p);
            _building->DeletePedestrian(p);
GrgrLmml's avatar
GrgrLmml committed
371
        }
Arne Graf's avatar
Arne Graf committed
372
        pedsToRemove.clear();
GrgrLmml's avatar
GrgrLmml committed
373 374 375 376 377 378 379 380
    }

    //    temporary fix for the safest path router
    //    if (dynamic_cast<SafestPathRouter*>(_routingEngine->GetRouter(1)))
    //    {
    //         SafestPathRouter* spr = dynamic_cast<SafestPathRouter*>(_routingEngine->GetRouter(1));
    //         spr->ComputeAndUpdateDestinations(_allPedestians);
    //    }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
381
}
382 383 384

void Simulation::PrintStatistics()
{
GrgrLmml's avatar
GrgrLmml committed
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 412 413
    Log->Write("\nRooms Egress Time:");
    Log->Write("==================");
    Log->Write("id\tcaption\tegress time (s)");

    for (const auto& it:_building->GetAllRooms()) {
        auto&& room = it.second;
        if (room->GetCaption()!="outside")
            Log->Write("%d\t%s\t%.2f", room->GetID(), room->GetCaption().c_str(), room->GetEgressTime());
    }

    Log->Write("\nUsage of Exits");
    Log->Write("==========");
    for (const auto& itr : _building->GetAllTransitions()) {
        Transition* goal = itr.second;
        if (goal->GetDoorUsage()) {
            Log->Write(
                    "\nExit ID [%d] used by [%d] pedestrians. Last passing time [%0.2f] s",
                    goal->GetID(), goal->GetDoorUsage(),
                    goal->GetLastPassingTime());

            string statsfile = _config->GetTrajectoriesFile()+"_flow_exit_id_"+to_string(goal->GetID())+".dat";
            Log->Write("More Information in the file: %s", statsfile.c_str());
            auto output = new FileHandler(statsfile.c_str());
            output->Write("#Flow at exit "+goal->GetCaption()+"( ID "+to_string(goal->GetID())+" )");
            output->Write("#Time (s)  cummulative number of agents \n");
            output->Write(goal->GetFlowCurve());
        }
    }
    Log->Write("\n");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
414 415
}

416 417
void Simulation::RunHeader(long nPed)
{
GrgrLmml's avatar
GrgrLmml committed
418 419 420 421
    // writing the header
    if (nPed==-1) nPed = _nPeds;
    _iod->WriteHeader(nPed, _fps, _building.get(), _seed);
    _iod->WriteGeometry(_building.get());
422

GrgrLmml's avatar
GrgrLmml committed
423 424 425
    int writeInterval = (int) ((1./_fps)/_deltaT+0.5);
    writeInterval = (writeInterval<=0) ? 1 : writeInterval; // mustn't be <= 0
    int firstframe = (Pedestrian::GetGlobalTime()/_deltaT)/writeInterval;
426

GrgrLmml's avatar
GrgrLmml committed
427
    _iod->WriteFrame(firstframe, _building.get());
428

GrgrLmml's avatar
GrgrLmml committed
429 430 431
    //first initialisation needed by the linked-cells
    UpdateRoutesAndLocations();
    ProcessAgentsQueue();
432
}
Ulrich Kemloh's avatar
Ulrich Kemloh committed
433

434
double Simulation::RunBody(double maxSimTime)
435
{
GrgrLmml's avatar
GrgrLmml committed
436 437 438 439 440 441 442 443 444 445 446
    //needed to control the execution time PART 1
    //in the case you want to run in no faster than realtime
    //time_t starttime, endtime;
    //time(&starttime);

    //take the current time from the pedestrian
    double t = Pedestrian::GetGlobalTime();

    //frame number. This function can be called many times,
    static int frameNr = (int) (1+t/_deltaT); // Frame Number

447 448 449 450
    //##########
    //PROBLEMATIC: time when frame should be printed out
    // possibly skipped when using the following lines
    // NEEDS TO BE FIXED!
GrgrLmml's avatar
GrgrLmml committed
451 452
    int writeInterval = (int) ((1./_fps)/_deltaT+0.5);
    writeInterval = (writeInterval<=0) ? 1 : writeInterval; // mustn't be <= 0
453
    // ##########
GrgrLmml's avatar
GrgrLmml committed
454 455 456 457 458 459

    //process the queue for incoming pedestrians
    //important since the number of peds is used
    //to break the main simulation loop
    ProcessAgentsQueue();
    _nPeds = _building->GetAllPedestrians().size();
Mohcine Chraibi's avatar
Mohcine Chraibi committed
460
    std::cout << "\n";
Mohcine Chraibi's avatar
Mohcine Chraibi committed
461
    std::string description = "Evacutation ";
Mohcine Chraibi's avatar
Mohcine Chraibi committed
462 463 464 465 466 467 468
    ProgressBar *bar = new ProgressBar(_nPeds, description);
    // bar->SetFrequencyUpdate(10);
#ifdef _WINDOWS
    bar->SetStyle("|","-");
#else
    bar->SetStyle("\u2588", "-"); //for linux
#endif
GrgrLmml's avatar
GrgrLmml committed
469 470
    int initialnPeds = _nPeds;
    // main program loop
Mohcine Chraibi's avatar
Mohcine Chraibi committed
471
    while ((_nPeds || (!_agentSrcManager.IsCompleted()&& _gotSources) ) && t<maxSimTime) {
GrgrLmml's avatar
GrgrLmml committed
472
        t = 0+(frameNr-1)*_deltaT;
473
        //process the queue for incoming pedestrians
GrgrLmml's avatar
GrgrLmml committed
474 475 476 477 478 479 480 481 482 483 484 485
        ProcessAgentsQueue();

        if (t>Pedestrian::GetMinPremovementTime()) {
            //update the linked cells
            _building->UpdateGrid();

            // update the positions
            _operationalModel->ComputeNextTimeStep(t, _deltaT, _building.get(), _periodic);

            //update the events
            _em->ProcessEvent();

486 487 488 489 490 491 492 493 494
            //here we could place router-tasks (calc new maps) that can use multiple cores AND we have 't'
            //update quickestRouter
            if (_routingEngine.get()->GetRouter(ROUTING_FF_QUICKEST)) {
                FFRouter* ffrouter = dynamic_cast<FFRouter*>(_routingEngine.get()->GetRouter(ROUTING_FF_QUICKEST));
                if (ffrouter->MustReInit()) {
                    ffrouter->ReInit();
                    ffrouter->SetRecalc(t);
                }
            }
495

GrgrLmml's avatar
GrgrLmml committed
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
            //update the routes and locations
            UpdateRoutesAndLocations();

            //other updates
            //someone might have left the building
            _nPeds = _building->GetAllPedestrians().size();
        }

        // update the global time
        Pedestrian::SetGlobalTime(t);

        // write the trajectories
        if (0==frameNr%writeInterval) {
            _iod->WriteFrame(frameNr/writeInterval, _building.get());
        }
Mohcine Chraibi's avatar
Mohcine Chraibi committed
511 512

        if(!_gotSources && !_periodic && _config->print_prog_bar())
Arne Graf's avatar
Arne Graf committed
513 514 515
              // Log->ProgressBar(initialnPeds, initialnPeds-_nPeds, t);
              bar->Progressed(initialnPeds-_nPeds);
        else
Mohcine Chraibi's avatar
No  
Mohcine Chraibi committed
516 517 518
             if ((!_gotSources) &&
                 ((frameNr < 100 &&  frameNr % 10 == 0) ||
                  (frameNr > 100 &&  frameNr % 100 == 0)))
Mohcine Chraibi's avatar
Mohcine Chraibi committed
519
                  printf("time: %6.2f (%4.0f)  | Agents: %6ld / %d [%4.1f%%]\n",  t , maxSimTime, _nPeds, initialnPeds, (double)(initialnPeds-_nPeds)/initialnPeds*100);
Arne Graf's avatar
Arne Graf committed
520

Mohcine Chraibi's avatar
Mohcine Chraibi committed
521

GrgrLmml's avatar
GrgrLmml committed
522 523 524 525 526 527 528
        // needed to control the execution time PART 2
        // time(&endtime);
        // double timeToWait=t-difftime(endtime, starttime);
        // clock_t goal = timeToWait*1000 + clock();
        // while (goal > clock());
        ++frameNr;
    }
529
    return t;
530 531
}

532 533
void Simulation::RunFooter()
{
GrgrLmml's avatar
GrgrLmml committed
534 535
    // writing the footer
    _iod->WriteFooter();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
536 537
}

538
void Simulation::ProcessAgentsQueue()
539
{
540

541 542 543 544
     /* std::cout << "Call Simulation::ProcessAgentsQueue() at: " << Pedestrian::GetGlobalTime() << std::endl; */
     /* std::cout << KRED << " SIMULATION building " << _building << " size "  << _building->GetAllPedestrians().size() << "\n" << RESET; */
           /* for(auto pp: _building->GetAllPedestrians()) */
     /*           std::cout<< KBLU << "BUL: Simulation: " << pp->GetPos()._x << ", " << pp->GetPos()._y << RESET << std::endl; */
545

GrgrLmml's avatar
GrgrLmml committed
546 547
    //incoming pedestrians
    vector<Pedestrian*> peds;
548 549
    //  std::cout << ">>> peds " << peds.size() << RESET<< std::endl;

GrgrLmml's avatar
GrgrLmml committed
550
    AgentsQueueIn::GetandClear(peds);
551
    //std::cout << "SIMULATION BEFORE BOOL = " <<  _agentSrcManager.IsBuildingUpdated() << " peds size " << peds.size() << "\n" ;
552

553 554
    //_agentSrcManager.SetBuildingUpdated(true);
    /* std::cout << "SIMULATION AFTER BOOL = " <<  _agentSrcManager.IsBuildingUpdated() << "\n" ; */
555

GrgrLmml's avatar
GrgrLmml committed
556
    for (auto&& ped: peds) {
557
            /* std::cout << "Add to building : " << ped->GetPos()._x << ", " << ped->GetPos()._y << " t: "<< Pedestrian::GetGlobalTime() << std::endl; */
GrgrLmml's avatar
GrgrLmml committed
558 559
        _building->AddPedestrian(ped);
    }
560 561 562 563
    //  for(auto pp: _building->GetAllPedestrians())
    //         std::cout<< KBLU << "BUL: Simulation: " << pp->GetPos()._x << ", " << pp->GetPos()._y  << " t: "<< Pedestrian::GetGlobalTime() <<RESET << std::endl;


564
    /* std::cout << "LEAVE Simulation::ProcessAgentsQueue() with " << " size "  << _building->GetAllPedestrians().size() << "\n" << RESET; */
Ulrich Kemloh's avatar
Ulrich Kemloh committed
565
}
Ulrich Kemloh's avatar
Ulrich Kemloh committed
566

567
void Simulation::UpdateDoorticks() const {
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
//    int softstateDecay = 1;
//    //Softstate of _lastTickTime is valid for X seconds as in (X/_deltaT); here it is 2s
//    auto& allCross = _building->GetAllCrossings();
//    for (auto& crossPair : allCross) {
//        crossPair.second->_refresh1 += 1;
//        crossPair.second->_refresh2 += 1;
//        if (crossPair.second->_refresh1 > (softstateDecay/_deltaT)) {
//            crossPair.second->_lastTickTime1 = 0;
//            crossPair.second->_refresh1 = 0;
//        }
//        if (crossPair.second->_refresh2 > (softstateDecay/_deltaT)) {
//            crossPair.second->_lastTickTime2 = 0;
//            crossPair.second->_refresh2 = 0;
//        }
//    }
//
//    auto& allTrans = _building->GetAllTransitions();
//    for (auto& transPair : allTrans) {
//        transPair.second->_refresh1 += 1;
//        transPair.second->_refresh2 += 1;
//        if (transPair.second->_refresh1 > (softstateDecay/_deltaT)) {
//            transPair.second->_lastTickTime1 = 0;
//            transPair.second->_refresh1 = 0;
//        }
//        if (transPair.second->_refresh2 > (softstateDecay/_deltaT)) {
//            transPair.second->_lastTickTime2 = 0;
//            transPair.second->_refresh2 = 0;
//        }
//    }
597 598
};

Ulrich Kemloh's avatar
Ulrich Kemloh committed
599 600
void Simulation::UpdateFlowAtDoors(const Pedestrian& ped) const
{
GrgrLmml's avatar
GrgrLmml committed
601 602 603 604
    if (_config->ShowStatistics()) {
        Transition* trans = _building->GetTransitionByUID(ped.GetExitIndex());
        if (trans) {
            //check if the pedestrian left the door correctly
Arne Graf's avatar
Arne Graf committed
605
            if (trans->DistTo(ped.GetPos())>0.5) {
GrgrLmml's avatar
GrgrLmml committed
606 607 608
                Log->Write("WARNING:\t pedestrian [%d] left room/subroom [%d/%d] in an unusual way. Please check",
                        ped.GetID(), ped.GetRoomID(), ped.GetSubRoomID());
                Log->Write("       :\t distance to last door (%d | %d) is %f. That should be smaller.",
Arne Graf's avatar
fix 233  
Arne Graf committed
609 610
                        trans->GetUniqueID(), ped.GetExitIndex(),
                        trans->DistTo(ped.GetPos()));
GrgrLmml's avatar
GrgrLmml committed
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
                Log->Write("       :\t correcting the door statistics");
                //ped.Dump(ped.GetID());

                //checking the history and picking the nearest previous destination
                double biggest = 0.3;
                bool success = false;
                for (const auto& dest:ped.GetLastDestinations()) {
                    if (dest!=-1) {
                        Transition* trans_tmp = _building->GetTransitionByUID(dest);
                        if (trans_tmp && trans_tmp->DistTo(ped.GetPos())<biggest) {
                            biggest = trans_tmp->DistTo(ped.GetPos());
                            trans = trans_tmp;
                            Log->Write("       :\t Best match found at door %d", dest);
                            success = true;//at least one door was found
                        }
626
                    }
GrgrLmml's avatar
GrgrLmml committed
627 628 629 630 631 632 633
                }

                if (!success) {
                    Log->Write("WARNING       :\t correcting the door statistics");
                    return; //todo we need to check if the ped is in a subroom neighboring the target. If so, no problems!
                }
            }
634
//#pragma omp critical
GrgrLmml's avatar
GrgrLmml committed
635 636 637
            trans->IncreaseDoorUsage(1, ped.GetGlobalTime());
        }
    }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
638 639
}

640
AgentsSourcesManager& Simulation::GetAgentSrcManager()
641
{
GrgrLmml's avatar
GrgrLmml committed
642
    return _agentSrcManager;
643
}
Ulrich Kemloh's avatar
Ulrich Kemloh committed
644 645 646

Building* Simulation::GetBuilding()
{
GrgrLmml's avatar
GrgrLmml committed
647
    return _building.get();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
648
}
649 650 651 652

int Simulation::GetMaxSimTime() const{
      return _maxSimTime;
}