root/applications/doprava/traffic_agent_offset.h @ 1081

Revision 1081, 18.3 kB (checked in by ondrak, 14 years ago)

changing offset only ever n-th cycle and some minor changes

Line 
1#include "traffic_agent.h"
2#include <list>
3#include <fstream>
4
5class GreenWaveTrafficAgent : public BaseTrafficAgent {
6protected:
7        double rating_change;
8        int negot_offset;
9
10        int actual_time;
11
12        RV rv_outputs;
13        vec outputs;
14
15        RV rv_change_request;
16        vec change_request;
17
18        RV rv_recieved_exps;
19        vec recieved_exps;
20
21        RV rv_next_exps;
22        vec next_exps;
23
24        RV rv_recieved_changes;
25        vec recieved_changes;
26
27        //! name of agent, whose change we have accepted
28        string accepted_from;
29
30        //TODO currently useless list of neighbours asking for expectations
31        list<string> seznam;
32       
33        double car_leaving; //s; how long is 1 car leaving queue
34
35        // some state variables
36        bool need_exps;
37        bool new_stable_state;
38        bool send_requests;
39        bool final_state;
40        //bool reset_negot_offset;
41
42        //! sum of final planned_offset values since last reach of cycle_count
43        int total_offset;
44        //! number of finished cycles since last reach of cycle_count
45        int negot_cycle;
46        //! after cycle_count cycles, we count avarege planned_offseta send it to Aimsun
47        int cycle_count;
48
49        //! counts all expected cars going from each lane, saves to outputs and rv_outputs
50        void expected_cars() {
51                double start_time;
52                ivec ind;
53                RV rv_exp;
54                datalink exp2outputs;
55                vec exp;
56
57                for (int i=0;i<lanes.length();i++) {
58                        for (int j=0;j<lanes(i).outputs.length();j++) {
59                                if (lanes(i).outputs(j)!="DUMMY_DET") {
60                                        string group = name+"_"+lanes(i).sg;            //e.g. 495_VA
61                                       
62                                        int index=group_index(group);
63                                       
64                                        double green_time=green_times(index)*cycle_length;
65
66                                        //ivec green_index=rv_inputs.dataind(RV(group,1));
67                                        //vec green_time=inputs(green_index);
68
69                                        //cout << "Green time "<<green_time<<endl;
70
71                                        rv_exp=RV(lanes(i).outputs(j)+"-"+name+"_"+to_string(i),3);
72
73                                        exp.set_size(rv_exp._dsize());
74                                        exp2outputs.set_connection(rv_exp,rv_outputs);
75
76                                        //Number of cars
77                                        exp(0)=lanehs(i)->expected_output(green_time)*lanes(i).alpha(j);       
78
79                                        start_time = green_starts(group_index(name+"_"+lanes(i).sg)) + lanes(i).output_distances(j)/VP + planned_offset;
80                                        //first car arrive time
81                                        exp(1)=start_time;
82                                        //last car arrive time
83                                        exp(2)=start_time + green_time;
84                                        //TODO pushup az na konec
85                                        exp2outputs.pushup(outputs,exp);
86
87                                }                       
88                        }
89                }
90        };
91
92        //! counts planned rating using offset and recieved_exps
93        double count_rating(const int offset) {
94                double virtual_queue;
95                double t_green_begin;
96                double t_green_end;
97                vec cars_count;
98                vec t_cars_begin;
99                vec t_cars_end;
100                bool found;
101
102                double rating=0.0;
103
104                RV rv_vector;
105                vec vector;
106
107                for (int i=0;i<lanes.length();i++) {
108
109                        //Finding, if we have some expectations
110                        found=false;
111                       
112                        for (int k=0;k<lanes(i).inputs.length();k++) { 
113                                int l=0;               
114                                for (int j=0;j<rv_recieved_exps.length();j++) {
115                               
116                                        int result=rv_recieved_exps.name(j).find(lanes(i).inputs(k)+"-");
117                                        if (result>=0) {
118
119                                                t_cars_begin.set_size(l+1,true);
120                                                t_cars_end.set_size(l+1,true);
121                                                cars_count.set_size(l+1,true);
122
123
124                                                rv_vector = RV(rv_recieved_exps.name(j),3);
125                                                ivec ind = rv_vector.dataind(rv_recieved_exps);
126
127                                                cars_count(l)=recieved_exps(ind(0));
128                                                t_cars_begin(l)=recieved_exps(ind(1));
129                                                t_cars_end(l)=recieved_exps(ind(2));
130                                                l++;
131
132                                                found=true;
133                                        }
134                                }
135                                if (found) {                   
136
137                                        //counting rating
138                                        string group = name+"_"+lanes(i).sg;            //e.g. 495_VA
139                                        int index=group_index(group);
140
141                                        t_green_begin=green_starts(index) + offset;
142                                        double green_time=green_times(index)*cycle_length;
143                                        t_green_end=t_green_begin+green_time;
144
145                                        /************** counting with all exps ****************/
146
147                                        int k;
148                                        double t_act=t_green_begin;
149                                        virtual_queue=lanehs(i)->queue;
150
151                                        //cycle goes through all "stopping" points and counts queue lenght at these points
152                                        do {
153                                                k=min_i(t_cars_begin);
154
155                                                if (k!=-1) {                                           
156                                                        double a=cars_count(k);
157                                                        double b=t_cars_begin(k);
158                                                        double c=t_cars_end(k);
159
160                                                        //in case there are cars comming before t_green begin
161                                                        if (t_cars_begin(k)<t_act) {
162                                                                if (t_cars_end(k)<=t_act) {
163                                                                        virtual_queue+=cars_count(k);
164                                                                       
165                                                                        cars_count.del(k);
166                                                                        t_cars_begin.del(k);
167                                                                        t_cars_end.del(k);
168
169                                                                }
170                                                                else {
171                                                                        double pomer=(t_cars_begin(k)-t_act)/(t_cars_end(k)-t_cars_begin(k));
172                                                                        virtual_queue+=cars_count(k)*pomer;
173                                                                        t_cars_begin(k)=t_act;
174                                                                }
175                                                        }
176                                                        else if (t_cars_begin(k)==t_act) {
177                                                                if (t_cars_end(k)<t_green_end) {
178                                                                        virtual_queue+=cars_count(k)-(t_cars_end(k)-t_act)/car_leaving;
179                                                                        t_act=t_cars_end(k);
180
181                                                                        cars_count.del(k);
182                                                                        t_cars_begin.del(k);
183                                                                        t_cars_end.del(k);
184                                                                }
185                                                                //if t_cars_end>=t_green_end
186                                                                else {
187                                                                        virtual_queue+=cars_count(k)-(t_green_end-t_act)/car_leaving;
188                                                                        t_act=t_green_end;
189
190                                                                        cars_count.del(k);
191                                                                        t_cars_begin.del(k);
192                                                                        t_cars_end.del(k);                                                     
193                                                                }
194
195
196                                                        }
197                                                        //if t_cars_begin(k)>=t_act
198                                                        else {
199                                                                if (t_cars_end(k)<t_green_end) {
200                                                                        virtual_queue-=(t_cars_end(k)-t_act)/car_leaving;
201                                                                        t_act=t_cars_end(k);
202                                                                }
203                                                                else {
204                                                                        virtual_queue-=(t_green_end-t_act)/car_leaving;
205                                                                        t_act=t_green_end;
206                                                                }
207                                                        }
208                                                }
209                                                //if no other expectations found
210                                                else {
211                                                        virtual_queue-=(t_green_end-t_act)/car_leaving;
212                                                        t_act=t_green_end;
213                                                }
214                                                if (virtual_queue<0) {
215                                                        rating-=virtual_queue;
216                                                        virtual_queue=0;
217                                                }
218
219                                        } while (t_act<t_green_end);
220                                }
221                        }
222                }
223                return rating;
224        }
225
226        //! finds best offset using recieved_exps. Returns found offset
227        int find_best_offset(const int center, int interval) {
228                //! rating if offset is rised
229                double rating_p;
230                //! rating if offset is unchaged (=center)
231                double rating_c;
232                //! rating if offset is lowered
233                double rating_n;
234
235                int new_center;
236
237                rating_p=count_rating(center+interval);
238                rating_c=count_rating(center);
239                rating_n=count_rating(center-interval);
240
241                new_center=center;
242                int max_index=max_of_three(rating_p,rating_c,rating_n);
243                switch (max_index) {
244                        case 0:
245                                new_center+=interval;
246                                break;
247                        case 1:
248                                break;
249                        case 2:
250                                new_center-=interval;
251                                break;
252                }
253
254                if (interval>2) {
255                        interval/=2;
256                        new_center=find_best_offset(new_center,interval);
257                }
258
259                return new_center;
260        }
261
262        //! finds if changing neighbour's offset could have positive effect, returns found offset change
263        int find_best_exps(const int offset_change, const string neighbour, double &rating_change) {
264                //! expectations recieved from neighbour
265                vec original_exps;
266                //! expactations after positve change of neighbour's offset
267                vec positive_exps;
268                //! expactations after negative change of neighbour's offset
269                vec negative_exps;
270                //! rating if offset is rised
271                double rating_p;
272                //! rating if offset is unchaged
273                double rating_c;
274                //! rating if offset is lowered
275                double rating_n;               
276                original_exps.set_size(recieved_exps.length());
277               
278                original_exps=recieved_exps;
279                positive_exps=recieved_exps;
280                negative_exps=recieved_exps;
281
282                for (int j=0;j<rv_recieved_exps.length();j++) {
283                        int res = rv_recieved_exps.name(j).find("-"+neighbour);
284                        if (res>0) {
285                                ivec ind = RV(rv_recieved_exps.name(j),3).dataind(rv_recieved_exps);
286
287                                rating_n=count_rating(planned_offset);
288
289                                positive_exps(ind(1))+=offset_change;
290                                positive_exps(ind(2))+=offset_change;
291
292                                negative_exps(ind(1))-=offset_change;
293                                negative_exps(ind(2))-=offset_change;
294                        }
295                }
296
297                rating_c=count_rating(planned_offset);
298
299                recieved_exps=positive_exps;
300                rating_p=count_rating(planned_offset);
301
302                recieved_exps=negative_exps;
303                rating_n=count_rating(planned_offset);
304
305                recieved_exps=original_exps;
306
307                int max_index=max_of_three(rating_p,rating_c,rating_n);
308                switch (max_index) {
309                        case 0:
310                                rating_change=rating_p-rating_c;
311                                return offset_change;
312                                break;
313                        case 1:
314                                rating_change=0;
315                                return 0;
316                                break;
317                        case 2:
318                                rating_change=rating_n-rating_c;
319                                return -offset_change;
320                                break;
321                }
322                rating_change=NULL;
323                return NULL;
324        }
325
326        // pravdepodobne s chybou, momentalne se nepouziva
327        void split_exps() {
328                ivec ind;
329                RV rv_exp;
330                datalink recieved2next;
331
332                rv_next_exps=RV();
333                for (int i=0;i<rv_recieved_exps.length();i++) {
334                        if (rv_recieved_exps.size(i)==3) {             
335                                rv_exp=RV(rv_recieved_exps.name(i),3);
336                                ind = rv_exp.dataind(rv_recieved_exps);
337                                //cout << "ind " << ind << endl;
338
339                                int next_cycle_end=2 * cycle_length - (actual_time % cycle_length);
340                                if (recieved_exps(ind(1))>next_cycle_end) {
341                                        rv_next_exps.add(rv_exp);
342                                        next_exps.set_size(rv_next_exps._dsize());
343                                       
344                                        if (actual_time==630) {
345                                                cout << "rv_next_exps " << rv_next_exps.to_string() << endl;
346                                                cout << "rv_recived_exps " << rv_recieved_exps.to_string() << endl;
347                                        }
348
349                                        recieved2next.set_connection(rv_next_exps,rv_recieved_exps);
350                                        recieved2next.filldown(recieved_exps,next_exps);
351                                        rv_recieved_exps=rv_recieved_exps.subt(rv_exp);
352                                }
353                                else if (recieved_exps(ind(2))>next_cycle_end) {
354                                        rv_next_exps.add(rv_exp);
355                                        next_exps.set_size(rv_next_exps._dsize());
356
357                                        ivec ind2=rv_exp.dataind(rv_next_exps);
358                                        next_exps(ind2(0))=recieved_exps(ind(0)); //TODO to neni spravne
359                                        next_exps(ind2(1))=next_cycle_end; 
360                                        next_exps(ind2(2))=recieved_exps(ind(2));
361                                        recieved_exps(ind(2))=next_cycle_end;
362                                }
363                        }
364                }
365        }
366
367        //! returns index of signal group group
368        int group_index(const string group) {
369                for (int i=0;i<green_names.length();i++) {
370                        if (green_names(i)==group) {
371                                return i;
372                        }
373                }
374                return -1;
375        }
376       
377        /*!
378        returns offset value shifted to fit interval <-cycle_length/2;cycle_length/2>
379        or (when second parameter is false)) <0;cycle_length>
380        */
381        int normalize_offset(int offset, bool zero=true) {
382                if (zero) {
383                        while ((offset<(-cycle_length/2)) || (offset>(cycle_length/2))) {
384                                if (offset<0) {
385                                        offset+=cycle_length;
386                                }
387                                else {
388                                        offset-=cycle_length;
389                                }
390                        }
391                        return offset;
392                }
393                else {
394                        while (offset<0 || offset>cycle_length) {
395                                if (offset<0) {
396                                        offset+=cycle_length;
397                                }
398                                else {
399                                        offset-=cycle_length;
400                                }
401                        }
402                        return offset;
403                }
404        }
405
406
407       
408        //! returns value shifted to fit interval <0;cycle_length>
409        //currently not in use
410        template<class T> T normalize(T time) {
411                while (time<0 && time<cycle_length) {
412                        if (time<0) {
413                                time+=cycle_length;
414                        }
415                        else {
416                                time-=cycle_length;
417                        }
418                }
419                return time;
420        }
421
422        //! converts t to string
423        template <class T> inline string to_string (const T& t)
424        {
425                std::stringstream ss;
426                ss << t;
427                return ss.str();
428        }
429
430        //! returns index of maximum of entered values
431        int max_of_three(const double a, const double b, const double c) {
432                int index = a > b ? 0 : 1;
433
434                if (index == 0) {
435                        index = a > c ? 0 : 2;
436                } 
437                else {
438                        index = b > c ? 1 : 2;
439                }
440                return index;
441        }
442
443        //! returns index of smallest element in vector
444        int min_i(vec vector) {
445                if (vector.length()>0) {
446                        double min=vector(0);
447                        int index=0;
448                        for (int i=1;i<vector.length();i++) {
449                                if (vector(i)<min) {
450                                        min=vector(i);
451                                        index=i;
452                                }
453                        }
454                        return index;
455                }
456                return -1;
457        }
458
459public:
460        //! offset set in last simulation step
461        int last_offset;
462        //! actual planned offset to set for next simulation step
463        int planned_offset;
464        //! planned offset for cycle after next cycle
465        int planned_next_offset;
466        //! rating of actual planned offset
467        double planned_rating;
468        //! rating of planned next offset
469        double planned_next_rating;     
470        //! avarage speed of cars
471        int VP;
472
473        void validate() {
474                rv_action = RV(name+"_offset", 1); // <======= example
475
476                for (int i=0; i<green_names.length();i++) {
477                        rv_inputs.add(RV(green_names(i),1));
478                }
479                inputs.set_size(rv_inputs._dsize());
480               
481                BaseTrafficAgent::validate();
482
483                for (int i=0;i<lanehs.length();i++) {
484                        ivec index = RV(lanes(i).queue,1).dataind(rv_queues);
485                        lanehs(i)->queue_index=index(0);
486                }
487        }
488
489        void adapt(const vec &glob_dt) {
490                BaseTrafficAgent::adapt(glob_dt);
491                       
492                for (int i=0;i<lanehs.length();i++) {
493                        lanehs(i)->queue=queues(lanehs(i)->queue_index);               
494                }
495
496                planned_offset=last_offset;
497               
498                //set state variables to default values
499                final_state=false;
500                new_stable_state=false;
501                send_requests=false;
502                need_exps=true;
503                negot_offset=8;
504        }
505
506        void broadcast(Setting& set){
507
508                //ask neighbours for exptected arrive times
509                if (need_exps) {
510                        for (int i=0; i<neighbours.length(); i++){
511                                Setting &msg =set.add(Setting::TypeGroup);
512
513                                UI::save ( neighbours(i), msg, "to");
514                                UI::save (name,msg,"from");
515                                UI::save ( (string)"expected_times_request", msg, "what");
516                        }
517                        need_exps=false;
518                }
519
520                // broadcast expected cars
521                if (!seznam.empty()) {
522                        double a;
523                        expected_cars();
524                        do {
525                                Setting &msg =set.add(Setting::TypeGroup);
526                                UI::save ( seznam.back(), msg, "to");
527                                UI::save ( name, msg, "from");
528                                UI::save ( (string)"new_expected_cars", msg, "what");
529                                UI::save ( &(rv_outputs), msg, "rv");
530                                UI::save ( outputs, msg, "value");
531                                seznam.pop_back();
532                                a=outputs (10);
533                               
534                        } while (!seznam.empty());                     
535                }
536
537                // broadcast new stable state (new stable expectations)
538                if (new_stable_state) {
539                        expected_cars();
540                        for (int i=0;i<neighbours.length();i++) {
541                                Setting &msg = set.add(Setting::TypeGroup);
542                                UI::save ( neighbours(i), msg, "to");
543                                UI::save ( name, msg, "from");
544                                UI::save ( (string)"new_stable_state2", msg, "what");
545                                UI::save ( &(rv_outputs), msg, "rv");
546                                UI::save ( outputs, msg, "value");
547                        }
548                        new_stable_state=false;
549                }
550
551                // broadcast requests to change offset(s)
552                if (send_requests) {
553                        for (int i=0;i<neighbours.length();i++) {
554                                Setting &msg = set.add(Setting::TypeGroup);
555                                UI::save ( neighbours(i), msg, "to");
556                                UI::save ( name, msg, "from");
557                                UI::save ( (string)"offset_change_request", msg, "what");
558                                UI::save ( &(rv_change_request), msg, "rv");
559                                UI::save ( change_request, msg, "value");
560                        }
561                        send_requests=false;
562                }
563
564                /*if (reset_negot_offset) {
565                        for (int i=0;i<neighbours.length();i++) {
566                                Setting &msg = set.add(Setting::TypeGroup);
567                                UI::save ( neighbours(i), msg, "to");
568                                UI::save ( name, msg, "from");
569                                UI::save ( (string)"reset_negot_offset", msg, "what");
570                        }
571                }*/
572
573
574               
575                // reached final offset. Log value?
576                if (final_state) {
577                        cout << "Jmenuji se "<<name<< " a skoncil jsem na offsetu " << planned_offset << " s hodnocenim " << planned_rating <<endl;
578                        final_state=false;
579                }
580        }
581
582        void receive(const Setting &msg){
583                string what;
584                string to;
585
586                string from;
587                vec value;
588                RV *rv;
589               
590                UI::get(what, msg, "what", UI::compulsory);
591                UI::get(to, msg, "to", UI::compulsory);
592                UI::get(from, msg, "from");
593                UI::get(rv, msg, "rv");
594                UI::get(value, msg, "value");
595               
596                if (what=="expected_times_request"){ 
597                        seznam.push_back(from);
598                } 
599                else if (what=="new_expected_cars") {
600                        rv_recieved_exps=*rv;
601                        recieved_exps=value;
602                        //split_exps();
603                       
604                        last_offset=planned_offset;
605
606                        planned_offset=find_best_offset(planned_offset,8);
607                        planned_offset=normalize_offset(planned_offset);
608                       
609
610                        /*if (planned_offset!=last_offset) {
611                                reset_negot_offset=true;
612                        }*/
613
614                        planned_rating=count_rating(planned_offset);
615                        // we have new stable state to broadcast
616                        new_stable_state=true;
617                }
618                else if (what=="new_stable_state2") {
619                        rv_recieved_exps=*rv;
620                        recieved_exps=value;
621                        //split_exps();
622                        planned_rating=count_rating(planned_offset);
623
624                        for (int i=0;i<neighbours.length();i++) {
625                                rv_change_request.add(RV(neighbours(i)+"_change",2));
626                                change_request.set_size(rv_change_request._dsize()); 
627                                ivec ind=RV(neighbours(i)+"_change",2).dataind(rv_change_request);
628                                // offset change
629                                change_request(ind(0))=find_best_exps(negot_offset,neighbours(i),rating_change);
630                                // rating change
631                                change_request(ind(1))=rating_change;
632                        }
633
634                        if (negot_offset>2) { 
635                                negot_offset/=2;
636                                        send_requests=true;
637                        }
638                        else {
639                                final_state=true;
640                        }
641                }
642                else if (what=="offset_change_request") {
643                        double final_rating_diff;
644
645                        rv_recieved_changes=*rv;
646                        recieved_changes=value;
647
648                        for (int i=0;i<rv_recieved_changes.length();i++) {
649
650                                ivec ind=RV(rv_recieved_changes.name(i),2).dataind(rv_recieved_changes);
651
652                                final_rating_diff=-planned_rating+count_rating(planned_offset+(int)recieved_changes(ind(0)))+recieved_changes(ind(1));
653                                if (final_rating_diff>=0) {
654                                        planned_offset+=(int)recieved_changes(ind(0));
655                                        planned_offset=normalize_offset(planned_offset);
656                                        planned_rating+=final_rating_diff;
657                                        accepted_from=from;
658                                }
659                        }
660                        //need_exps=true;s
661                        new_stable_state=true;
662                }
663                /*else if (what=="reset_negot_offset") {
664                        negot_offset=8;
665                }*/
666                else {
667                        BaseTrafficAgent::receive(msg);
668                }
669        }
670       
671        void ds_register(const DS &ds) {
672                BaseTrafficAgent::ds_register(ds);
673                action2ds.set_connection( ds._urv(), rv_action);
674        }
675
676        void from_setting(const Setting &set) {
677                BaseTrafficAgent::from_setting(set);
678
679                RV rv_exp;
680
681                car_leaving=2;
682                VP=45;
683                actual_time=0;
684               
685                negot_cycle=1;
686                cycle_count=5;
687                total_offset=0;
688
689                negot_offset=8;
690               
691                // load from file
692                //UI::get(sgs, set, "sgs", UI::compulsory);     
693
694                //UI::get(green_starts, set, "green_starts", UI::compulsory);
695                UI::get(last_offset, set, "offset", UI::compulsory);
696
697                for (int i=0;i<lanes.length();i++) {
698                        for (int j=0;j<lanes(i).outputs.length();j++) {
699                                if (lanes(i).outputs(j)!="DUMMY_DET") {
700                                        rv_exp=RV(lanes(i).outputs(j)+"-"+name+"_"+to_string(i),3);
701                                        rv_outputs.add(rv_exp);
702                                }
703                        }
704                }
705                outputs.set_size(rv_outputs._dsize()); 
706        }
707
708        void act(vec &glob_ut){
709                if (negot_cycle==cycle_count) {
710               
711                        vec action;
712                        action.set_size(rv_action._dsize());
713               
714                        ivec index = rv_action.dataind(RV(name+"_offset",1));
715
716                        action(index(0))=normalize_offset(total_offset/cycle_count, false);
717                        action2ds.filldown(action,glob_ut);
718
719                        total_offset=0;
720                        negot_cycle=1;
721
722                }
723                else {
724                        total_offset+=planned_offset;
725
726                        negot_cycle++;
727                }
728
729                last_offset=planned_offset;
730                actual_time+=step_length;
731        }
732
733
734};
735UIREGISTER(GreenWaveTrafficAgent);
Note: See TracBrowser for help on using the browser.