root/applications/doprava/traffic_agent_offset.h @ 1118

Revision 1118, 18.9 kB (checked in by ondrak, 14 years ago)

fixed passive behavior
attempt to log offset

directory texty added

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