EventManager.cpp 24.7 KB
Newer Older
Ulrich Kemloh's avatar
Ulrich Kemloh committed
1 2 3
/**
 * \file        EventManager.cpp
 * \date        Jul 4, 2014
4 5
 * \version     v0.7
 * \copyright   <2009-2015> Forschungszentrum Jülich GmbH. All rights reserved.
Ulrich Kemloh's avatar
Ulrich Kemloh committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 *
 * \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
 *
 *
 **/

#include <string>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <math.h>
34
#include "../pedestrian/Pedestrian.h"
Ulrich Kemloh's avatar
Ulrich Kemloh committed
35
#include "../pedestrian/Knowledge.h"
36
#include "../mpi/LCGrid.h"
Ulrich Kemloh's avatar
Ulrich Kemloh committed
37 38
#include "../geometry/SubRoom.h"
#include "../tinyxml/tinyxml.h"
39 40
#include "../routing/global_shortest/GlobalRouter.h"
#include "../routing/quickest/QuickestPathRouter.h"
41
#include "../routing/smoke_router/SmokeRouter.h"
Arne Graf's avatar
Arne Graf committed
42
#include "../routing/ff_router/ffRouter.h"
43
#include "EventManager.h"
Ulrich Kemloh's avatar
Ulrich Kemloh committed
44
#include "Event.h"
45

Ulrich Kemloh's avatar
Ulrich Kemloh committed
46 47 48
using std::map;
using std::cout;
using std::endl;
49

50

51
EventManager::EventManager(Building *_b, unsigned int seed)
Ulrich Kemloh's avatar
Ulrich Kemloh committed
52 53 54 55 56
{
     _building = _b;
     _eventCounter = 0;
     _dynamic = false;
     _lastUpdateTime = 0;
57 58
     _projectFilename=_building->GetProjectFilename();
     _projectRootDir=_building->GetProjectRootDir();
59 60
     _updateFrequency =1 ;//seconds
     _updateRadius =2;//meters
Ulrich Kemloh's avatar
Ulrich Kemloh committed
61 62 63

     //generate random number between 0 and 1 uniformly distributed
     _rdDistribution = std::uniform_real_distribution<double> (0,1);
64 65
     //std::random_device rd;
     //_rdGenerator=std::mt19937(rd());
66
     _rdGenerator=std::mt19937(seed);
tobias schroedter's avatar
tobias schroedter committed
67
     _file = nullptr;
68 69
     //save the first graph
     CreateRoutingEngine(_b, true);
70

71 72
     //create some events
     //CreateSomeEngine();
73 74
}

75 76 77 78
EventManager::~EventManager()
{
     if(_file)
          fclose(_file);
79 80

     _eventEngineStorage.clear();
81 82
}

Ulrich Kemloh's avatar
Ulrich Kemloh committed
83
bool EventManager::ReadEventsXml()
Ulrich Kemloh's avatar
Ulrich Kemloh committed
84
{
85
     Log->Write("INFO: \tLooking for pre-defined events in other files");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
86 87
     //get the geometry filename from the project file
     TiXmlDocument doc(_projectFilename);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
88
     if (!doc.LoadFile()) {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
89 90
          Log->Write("ERROR: \t%s", doc.ErrorDesc());
          Log->Write("ERROR: \t could not parse the project file.");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
91
          return false;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
92 93 94
     }

     TiXmlElement* xMainNode = doc.RootElement();
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111

     string realtimefile;
     if (xMainNode->FirstChild("event_realtime")) {
          realtimefile = _projectRootDir
                    + xMainNode->FirstChild("event_realtime")->FirstChild()->Value();
          _file = fopen(realtimefile.c_str(), "r");
          if (!_file) {
               Log->Write("INFO:\tFiles '"+ realtimefile+ "' missing. "
                          "Realtime interaction with the simulation not possible.");
          } else {
               Log->Write("INFO:\tFile '"+ realtimefile+ "' will be monitored for new events.");
               _dynamic = true;
          }
     } else {
          Log->Write("INFO: \tNo realtime events found");
     }

Ulrich Kemloh's avatar
Ulrich Kemloh committed
112
     string eventfile = "";
Ulrich Kemloh's avatar
Ulrich Kemloh committed
113
     if (xMainNode->FirstChild("events_file")) {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
114
          eventfile = _projectRootDir
115
                    + xMainNode->FirstChild("events_file")->FirstChild()->Value();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
116 117
          Log->Write("INFO: \tevents <" + eventfile + ">");
     } else {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
118
          Log->Write("INFO: \tNo events found");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
119
          return true;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
120 121
     }

122

Ulrich Kemloh's avatar
Ulrich Kemloh committed
123 124
     Log->Write("INFO: \tParsing the event file");
     TiXmlDocument docEvent(eventfile);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
125 126
     if (!docEvent.LoadFile()) {
          Log->Write("ERROR: \t%s", docEvent.ErrorDesc());
Ulrich Kemloh's avatar
Ulrich Kemloh committed
127
          Log->Write("ERROR: \t could not parse the event file.");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
128
          return false;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
129 130 131
     }

     TiXmlElement* xRootNode = docEvent.RootElement();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
132
     if (!xRootNode) {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
133
          Log->Write("ERROR:\tRoot element does not exist.");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
134
          return false;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
135 136
     }

Ulrich Kemloh's avatar
Ulrich Kemloh committed
137
     if (xRootNode->ValueStr() != "JPScore") {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
138
          Log->Write("ERROR:\tRoot element value is not 'JPScore'.");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
139
          return false;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
140 141 142
     }

     TiXmlNode* xEvents = xRootNode->FirstChild("events");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
143
     if (!xEvents) {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
144
          Log->Write("ERROR:\tNo events found.");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
145
          return false;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
146
     }
147
     _updateFrequency = xmltoi(xEvents->ToElement()->Attribute("update_frequency"), 1);
148 149 150
     _updateRadius = xmltoi(xEvents->ToElement()->Attribute("update_radius"), 2);

     //Pedestrian::SetColorMode(BY_SPOTLIGHT);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
151

Ulrich Kemloh's avatar
Ulrich Kemloh committed
152 153
     for (TiXmlElement* e = xEvents->FirstChildElement("event"); e;
               e = e->NextSiblingElement("event")) {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
154 155 156 157 158 159

          int id = atoi(e->Attribute("id"));
          double zeit = atoi(e->Attribute("time"));
          string state (e->Attribute("state"));
          string type (e->Attribute("type"));
          _events.push_back(Event(id,zeit,type,state));
Ulrich Kemloh's avatar
Ulrich Kemloh committed
160
     }
161
     Log->Write("INFO: \tEvents were initialized");
162 163

     //create some events
164 165 166
     //FIXME: creating some engine before starting is not working.
     // seom doors are still perceived as beeing closed.
     //CreateSomeEngines();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
167
     return true;
168 169
}

Ulrich Kemloh's avatar
Ulrich Kemloh committed
170
void EventManager::ListEvents()
171
{
Ulrich Kemloh's avatar
Ulrich Kemloh committed
172
     for(const auto& event: _events)
173
     {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
174
          Log->Write("INFO:\t " + event.GetDescription());
Ulrich Kemloh's avatar
Ulrich Kemloh committed
175
     }
176 177
}

Ulrich Kemloh's avatar
Ulrich Kemloh committed
178 179 180 181 182 183
void EventManager::ReadEventsTxt(double time)
{
     rewind(_file);
     char cstring[256];
     int lines = 0;
     do {
184 185
          if (fgets(cstring, 30, _file) == nullptr) {
//               Log->Write("WARNING: \tCould not read the event file");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
186 187
               return;
          }
188
          if (cstring[0] != '#') {// skip comments
Ulrich Kemloh's avatar
Ulrich Kemloh committed
189 190
               lines++;
               if (lines > _eventCounter) {
191
                    Log->Write("INFO:\tEvent: after %.2f sec: ", time);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
192 193 194 195 196
                    GetEvent(cstring);
                    _eventCounter++;
               }
          }
     } while (feof(_file) == 0);
197 198
}

199
bool EventManager::CollectNewKnowledge(Building* _b)
200
{
201
     //#pragma omp parallel for
202 203 204 205
     for(auto&& ped:_b->GetAllPedestrians())
     {
          for (auto&& door: _b->GetAllTransitions())
          {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
206
               if(door.second->DistTo(ped->GetPos())<0.5)//distance to door to register its state
207 208 209
               {
                    //actualize the information about the newly closed door
                    if(door.second->IsOpen()==false)
210
                    {
211 212
                         //1.0 because the information is sure
                         ped->AddKnownClosedDoor(door.first, Pedestrian::GetGlobalTime(), !door.second->IsOpen(),_updateFrequency,1.0);
213
                         UpdateRoute(ped);
214
                    }
215 216
               }
          }
217 218 219 220 221 222 223 224 225

     }
     return true;
}

bool EventManager::DisseminateKnowledge(Building* _b)
{
     for(auto&& ped:_b->GetAllPedestrians())
     {
226
          //update the latency for new and old information
227 228 229 230
          for(auto&& info: ped->GetKnownledge())
          {
               info.second.DecreaseLatency(_updateFrequency);
          }
231
     }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
232

233
     for(auto&& ped1:_b->GetAllPedestrians())
234 235 236 237 238
     {
          vector<Pedestrian*> neighbourhood;
          _b->GetGrid()->GetNeighbourhood(ped1,neighbourhood);
          for(auto&& ped2:neighbourhood)
          {
239
               if( (ped1->GetPos()-ped2->GetPos()).Norm()<_updateRadius)
240 241
               {
                    //maybe same room and subroom ?
242 243
                    vector<SubRoom*> empty;
                    if(_b->IsVisible(ped1->GetPos(),ped2->GetPos(),empty))
Ulrich Kemloh's avatar
Ulrich Kemloh committed
244
                    {
245 246 247
                         //if(!SynchronizeKnowledge(ped1, ped2))  //ped1->SetSpotlight(true);
                         //if(!MergeKnowledgeUsingProbability(ped1, ped2))
                         if(!MergeKnowledge(ped1, ped2))
Ulrich Kemloh's avatar
Ulrich Kemloh committed
248 249
                         {
                              //p2 is now an informant
250 251 252
                              //Log->Write("INFO:\tthe information was refused by ped %d",ped2->GetID());
                              //ped2->SetSpotlight(true);
                              //Pedestrian::SetColorMode(AgentColorMode::BY_SPOTLIGHT);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
253
                         }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
254
                    }
255 256 257 258
               }
          }
     }

259

260
     //TODO Was passiert hier?
261 262
     //update the routers based on the configurations
     //#pragma omp parallel
263 264
//     for(auto&& ped:_b->GetAllPedestrians())
//     {
265 266 267 268 269 270 271 272 273 274 275 276 277 278
//          if(UpdateRoute(ped)==false)
//          {
//               //Clear the memory and attempt to reroute
//               //this can happen if all doors are known to be closed
//               ped->ClearKnowledge();
//               Log->Write("ERROR: \t clearing ped knowledge");
//               //ped->Dump(ped->GetID());
//               if(UpdateRoute(ped)==false)
//               {
//                    Log->Write("ERROR: \t cannot reroute the pedestrian. unknown problem");
//                    //return false;
//                    exit(EXIT_FAILURE);
//               }
//          }
279
//     }
280 281 282 283 284 285 286
     return true;
}

bool EventManager::UpdateRoute(Pedestrian* ped)
{
     //create the key as string.
     //map are sorted by default
287
     string key= ped->GetKnowledgeAsString();
288
//     std::cout << "key: <" << key << ">" << std::endl;
289 290
     //get the router engine corresponding to the actual configuration
     bool status=true;
291 292 293 294 295 296 297 298

//     for (auto event : _eventEngineStorage){
//          std::cout << "_eventEngineStorage " << event.first << ": " << std::endl;
//          for (auto router : event.second->GetAvailableRouters()){
//               std::cout << router->GetStrategy() << std::endl;
//          }
//     }

299 300 301 302 303 304 305
     if (_eventEngineStorage.count(key)>0)
     {
          RoutingEngine* engine=_eventEngineStorage[key];
          //retrieve the old strategy
          RoutingStrategy strategy=ped->GetRouter()->GetStrategy();
          //retrieve the new router
          Router*rout =engine->GetRouter(strategy);
306 307 308 309 310 311 312 313
          //only update if it is a new router
          if(ped->GetRouter()!=rout)
          {
               //check for validity
               ped->SetRouter(rout);
               //clear all previous routes
               ped->ClearMentalMap();
          }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
314
          //ped->ClearKnowledge();
315 316 317 318 319
          //overwrite/update the pedestrian router
          if(!rout) status= false;
     }
     else
     {
320 321 322
//          Log->Write("WARNING: \t unknown configuration <%s>", key.c_str());
//          Log->Write("WARNING: \t  [%d] router available", _eventEngineStorage.size());
//          Log->Write("       : \t trying to create");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
323
          //CreateRoutingEngine(_building);
324 325 326 327 328
          status= false;
     }
     return status;
}

Ulrich Kemloh's avatar
Ulrich Kemloh committed
329
bool EventManager::SynchronizeKnowledge(Pedestrian* p1, Pedestrian* p2)
330
{
331 332
     auto const & old_info1 = p1->GetKnownledge();
     auto const & old_info2 = p2->GetKnownledge();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
333
     map<int, Knowledge> merge_info;
334 335 336 337 338 339 340

     //collect the most recent knowledge
     for (auto&& info1 : old_info1)
     {
          merge_info[info1.first] = info1.second;
     }

341
     for (auto&& info2 : old_info2)
342 343
     {
          //update infos according to a newest time
344
          if (merge_info.count(info2.first) > 0)
345
          {
346
               if (info2.second.GetTime() > merge_info[info2.first].GetTime())
347
               {
348
                    merge_info[info2.first] = info2.second;
349 350
               }
          }
351
          else //the info was not present, just add
352
          {
353
               merge_info[info2.first] = info2.second;
354 355 356 357 358 359 360 361
          }
     }

     //synchronize the knowledge
     p1->ClearKnowledge();
     p2->ClearKnowledge();
     for (auto&& info : merge_info)
     {
362 363 364 365
          p1->AddKnownClosedDoor(info.first, info.second.GetTime(),
                    info.second.GetState(), info.second.GetQuality(),_updateFrequency);
          p2->AddKnownClosedDoor(info.first, info.second.GetTime(),
                    info.second.GetState(), info.second.GetQuality(),_updateFrequency);
366
     }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
367 368 369
     return true;
}

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 412 413 414 415 416 417 418 419 420 421 422 423 424 425
bool EventManager::MergeKnowledgeUsingProbability(Pedestrian* p1, Pedestrian* p2)
{
     auto const & old_info1 = p1->GetKnownledge();
     auto const & old_info2 = p2->GetKnownledge();

     map<int, Knowledge> merge_info;
     //collect the most recent knowledge
     //only the knowledge that has been accepted
     for (auto&& info1 : old_info1)
     {
          merge_info[info1.first] = info1.second;
     }

     for (auto&& info2 : old_info2)
     {
          //update infos according to a newest time
          if (merge_info.count(info2.first) > 0)
          {
               if (info2.second.GetTime() > merge_info[info2.first].GetTime())
                    // and the quality
                    // only if I never refused that information
               {
                    merge_info[info2.first] = info2.second;
               }
          }
          else //the info was not present, just add
          {
               merge_info[info2.first] = info2.second;
          }
     }

     //synchronize the knowledge
     //accept the information with a certain probability
     if(_rdDistribution(_rdGenerator)< (1-p1->GetRiskTolerance()))
     {
          //p1->ClearKnowledge();
          p2->ClearKnowledge();
          for (auto&& info : merge_info)
          {
               p2->AddKnownClosedDoor(info.first, info.second.GetTime(),info.second.GetState(),_updateFrequency,1.0);
          }
          //p2->SetSpotlight(false);
          return true;
     }
     else
     {
          cout<<"refusing the information:"<<p2->GetID()<<endl;
          //Pedestrian::SetColorMode(BY_SPOTLIGHT);
          //p2->SetSpotlight(true);
          //exit(0);
          return false;
     }


}

Ulrich Kemloh's avatar
Ulrich Kemloh committed
426 427 428
bool EventManager::MergeKnowledge(Pedestrian* p1, Pedestrian* p2)
{
     auto const & old_info1 = p1->GetKnownledge();
429
     auto & old_info2 = p2->GetKnownledge();
430
     bool status=true;
431 432 433 434 435 436
     //accept the new information
     if(_rdDistribution(_rdGenerator)< (1-p1->GetRiskTolerance()))
     {
          for (const auto& info1 : old_info1)
          {
               //I dont forward information that I refused already
437
               //if(info1.second.HasBeenRefused()) continue;
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466

               // Is the latency ok ?
               if(!info1.second.CanBeForwarded()) continue;

               //do I already have that information ?
               if (old_info2.count(info1.first) > 0)
               {
                    //only accept if it is newer
                    if (info1.second.GetTime() > old_info2[info1.first].GetTime())
                    {
                         //maybe I already refused that information earlier. Keep refusing
                         if(old_info2[info1.first].HasBeenRefused()==false)
                         {
                              old_info2[info1.first]=info1.second;
                              //alter the quality of the info
                              old_info2[info1.first].SetQuality(0.5);
                              old_info2[info1.first].SetLatency(_updateFrequency);
                         }
                    }
               }
               else
               {
                    //new piece of information
                    old_info2[info1.first]=info1.second;
                    //alter the quality of the info
                    old_info2[info1.first].SetQuality(0.5);
                    old_info2[info1.first].SetLatency(_updateFrequency);
               }
          }
467
          status= true;
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
     }
     //refuse the new information
     else
     {
          for (const auto& info1 : old_info1)
          {
               if (old_info2.count(info1.first) > 0)
               {
                    old_info2[info1.first].Refuse(true);
                    old_info2[info1.first].SetLatency(_updateFrequency);
                    //cout<<"refusing present: "<<p2->GetID()<<endl;
               }
               else
               {//refuse the information and set a bad quality
                    old_info2[info1.first]=info1.second;
                    //alter the quality of the info
                    old_info2[info1.first].SetQuality(0.0);
                    old_info2[info1.first].Refuse(true);
                    old_info2[info1.first].SetLatency(_updateFrequency);
                    //cout<<"refusing: "<<p2->GetID()<<endl;
               }
489 490
               //es gibt mindestens eine info zum ablehnen
               status=false;
491 492 493
          }
          //p2->SetSpotlight(true);
          //Pedestrian::SetColorMode(BY_SPOTLIGHT);
494
          //cout<<"refusing..."<<p2->GetID()<<endl;
495
     }
496
     return status;
497 498 499 500
}

void EventManager::ProcessEvent()
{
Ulrich Kemloh's avatar
Ulrich Kemloh committed
501
     if (_events.size() == 0) return;
502 503 504

     int current_time = Pedestrian::GetGlobalTime();

505 506 507
     //update knowledge about closed doors
     CollectNewKnowledge(_building);

508
     if ( (current_time != _lastUpdateTime) &&
509
               ((current_time % _updateFrequency) == 0))
510
     {
511

512
          //share the information between the pedestrians
513
          DisseminateKnowledge(_building);
514 515
          //actualize based on the new knowledge
          _lastUpdateTime = current_time;
516
          //cout<<"update: "<<current_time<<endl;
517 518 519 520 521
     }

     //update the building state
     // the time is needed as double
     double current_time_d = Pedestrian::GetGlobalTime();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
522 523

     for(const auto& event: _events)
524
     {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
525
          if (fabs(event.GetTime() - current_time_d) < J_EPS_EVENT) {
526
               //Event with current time stamp detected
527
               Log->Write("INFO:\tEvent: after %.2f sec: ", current_time_d);
528 529
               switch (event.GetState()){
               case DoorState::OPEN:
Ulrich Kemloh's avatar
Ulrich Kemloh committed
530
                    OpenDoor(event.GetId());
531 532 533 534 535 536 537
                    break;
               case DoorState::CLOSE:
                    CloseDoor(event.GetId());
                    break;
               case DoorState::TEMP_CLOSE:
                    TempCloseDoor(event.GetId());
                    break;
538
               }
539
               _building->GetRoutingEngine()->setNeedUpdate(true);
540
          }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
541

542 543 544 545 546 547
     }

     if (_dynamic)
          ReadEventsTxt(current_time);
}

Ulrich Kemloh's avatar
Ulrich Kemloh committed
548
//close the door if it was open and relaunch the routing procedure
Ulrich Kemloh's avatar
Ulrich Kemloh committed
549 550 551
void EventManager::CloseDoor(int id)
{
     Transition *t = _building->GetTransition(id);
552

553
     if (!t->IsClose())
Ulrich Kemloh's avatar
Ulrich Kemloh committed
554
     {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
555
          t->Close();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
556
          Log->Write("INFO:\tClosing door %d ", id);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
557 558 559 560 561
          //Create and save a graph corresponding to the actual state of the building.
          if(CreateRoutingEngine(_building)==false)
          {
               Log->Write("ERROR: \tcannot create a routing engine with the new event");
          }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
562
     } else {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
563
          Log->Write("WARNING: \tdoor %d is already close", id);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
564
     }
565 566 567

}

568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
void EventManager::TempCloseDoor(int id)
{
     Transition *t = _building->GetTransition(id);

     if (!t->IsTempClose())
     {
          t->TempClose();
          Log->Write("INFO:\tClosing door %d ", id);
          //Create and save a graph corresponding to the actual state of the building.
          if(CreateRoutingEngine(_building)==false)
          {
               Log->Write("ERROR: \tcannot create a routing engine with the new event");
          }
     } else {
          Log->Write("WARNING: \tdoor %d is already close", id);
     }

}


Ulrich Kemloh's avatar
Ulrich Kemloh committed
588
//open the door if it was open and relaunch the routing procedure
Ulrich Kemloh's avatar
Ulrich Kemloh committed
589 590 591
void EventManager::OpenDoor(int id)
{
     Transition *t = _building->GetTransition(id);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
592 593
     if (!t->IsOpen())
     {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
594
          t->Open();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
595
          Log->Write("INFO:\tOpening door %d ", id);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
596 597 598 599 600
          //Create and save a graph corresponding to the actual state of the building.
          if(CreateRoutingEngine(_building)==false)
          {
               Log->Write("ERROR: \tcannot create a routing engine with the new event");
          }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
601
     } else {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
602
          Log->Write("WARNING: \tdoor %d is already open", id);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
603
     }
604 605
}

Ulrich Kemloh's avatar
Ulrich Kemloh committed
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
void EventManager::GetEvent(char* c)
{
     int split = 0;
     string type = "";
     string id = "";
     string state = "";
     for (int i = 0; i < 20; i++) {
          if (!c[i]) {
               break;
          } else if (c[i] == ' ') {
               split++;
          } else if (c[i] == '\n') {

          } else {
               if (split == 0) {
                    type += c[i];
               } else if (split == 1) {
                    id += c[i];
               } else if (split == 2) {
                    state += c[i];
               }
          }
     }
     if (state.compare("close") == 0) {
          CloseDoor(atoi(id.c_str()));
     } else {
          OpenDoor(atoi(id.c_str()));
     }
634
}
635 636 637 638

bool EventManager::CreateRoutingEngine(Building* _b, int first_engine)
{
     std::vector<int> closed_doors;
639
     closed_doors.clear();
640 641 642

     for(auto&& t:_b->GetAllTransitions())
     {
643
          if(!t.second->IsClose())
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
               closed_doors.push_back(t.second->GetID());
     }
     std::sort(closed_doors.begin(), closed_doors.end());

     //create the key as string.
     string key="";
     for(int door:closed_doors)
     {
          if(key.empty())
               key.append(std::to_string(door));
          else
               key.append(":"+std::to_string(door));
     }

     //the first (default) engine was created in the simulation
     // collect the defined routers
     if(first_engine)
     {
          RoutingEngine* engine=_b->GetRoutingEngine();
          _eventEngineStorage[key]=engine;

          for(auto&& rout: engine->GetAvailableRouters())
          {
               _availableRouters.push_back(rout->GetStrategy());
          }
          Log->Write("INFO: \tAdding a new routing Engine with the key: "+key+"\n");
          return true;
     }

     // the engine was not created
     // create a new one with the actual configuration
     if (_eventEngineStorage.count(key)==0)
     {

          //populate the engine with the routers defined in the ini file
          //and initialize
          RoutingEngine* engine= new RoutingEngine();
          for(auto&& rout:_availableRouters)
          {
               engine->AddRouter(CreateRouter(rout));
          }

          if(engine->Init(_b)==false)
               return false;

          //save the configuration
          _eventEngineStorage[key]=engine;
          Log->Write("INFO: \tAdding a new routing Engine with the key: "+key+"\n");
     }
     else
     {
          Log->Write("INFO: \tA routing already exits with the key: "+key+"\n");
     }

     return true;
}

Router * EventManager::CreateRouter(const RoutingStrategy& strategy)
{
Ulrich Kemloh's avatar
Ulrich Kemloh committed
703
     Router * rout=nullptr;
704 705 706

     switch(strategy)
     {
Arne Graf's avatar
Arne Graf committed
707
          case ROUTING_LOCAL_SHORTEST:
708
               rout = new GlobalRouter(ROUTING_LOCAL_SHORTEST, ROUTING_LOCAL_SHORTEST);
Arne Graf's avatar
Arne Graf committed
709 710 711
               break;

          case ROUTING_GLOBAL_SHORTEST:
712
               rout = new GlobalRouter(ROUTING_GLOBAL_SHORTEST, ROUTING_GLOBAL_SHORTEST);
Arne Graf's avatar
Arne Graf committed
713 714 715 716 717 718
               break;

          case ROUTING_QUICKEST:
               rout = new QuickestPathRouter(ROUTING_QUICKEST, ROUTING_QUICKEST);
               break;

719 720
          case ROUTING_SMOKE:
               rout = new SmokeRouter(ROUTING_SMOKE, ROUTING_SMOKE);
Arne Graf's avatar
Arne Graf committed
721 722 723 724 725 726 727 728 729 730 731 732 733
               break;

          case ROUTING_FF_GLOBAL_SHORTEST:
               rout = new FFRouter(ROUTING_FF_GLOBAL_SHORTEST, ROUTING_FF_GLOBAL_SHORTEST, _building->GetConfig()->get_has_specific_goals(), _building->GetConfig());
               break;

          case ROUTING_FF_QUICKEST:
               rout = new FFRouter(ROUTING_FF_QUICKEST, ROUTING_FF_QUICKEST, _building->GetConfig()->get_has_specific_goals(), _building->GetConfig());

          default:
               Log->Write("ERROR: \twrong value for routing strategy [%d]!!!\n", strategy );
               exit(EXIT_FAILURE);
               break;
734 735 736 737

     }
     return rout;
}
738

739
void EventManager::CreateSomeEngines()
740 741 742 743
{
     Log->Write("INFO: \tpopulating routers");
     std::map<int, bool> doors_states;

744 745 746 747 748
     for(auto&& t:_building->GetAllTransitions())
     {
          printf("ID: %d  IsOpen: %d\n",t.second->GetID(),t.second->IsOpen());
     }

749 750 751
     //save the doors states
     for(auto&& t:_building->GetAllTransitions())
     {
752
          doors_states[t.second->GetID()]=t.second->IsOpen();
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
     }

     //open all doors
     for(auto&& t:_building->GetAllTransitions())
     {
          t.second->Open();
     }

     //close the doors one by one and create engines
     for(auto&& t1:_building->GetAllTransitions())
     {
          for(auto&& t2:_building->GetAllTransitions())
          {
               t2.second->Open();
          }
          t1.second->Close();

          //create the engine;
          CreateRoutingEngine(_building, false);
     }


     //restore the door states
     for(auto&& t:_building->GetAllTransitions())
     {
          if (doors_states[t.second->GetID()])
          {
               t.second->Open();
          }
          else
          {
               t.second->Close();
          }
     }
     Log->Write("INFO: \tdone");
788 789 790 791 792 793 794

     cout<<endl<<endl;
     for(auto&& t:_building->GetAllTransitions())
     {
          printf("ID: %d  IsOpen: %d\n",t.second->GetID(),t.second->IsOpen());
     }
     exit(0);
795
}
796