root/applications/doprava/traffic_agent_offset.h @ 1126

Revision 1120, 19.0 kB (checked in by ondrak, 14 years ago)

bugfix in count_rating

v textech rozpracován popis výpočtu hodnocení

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                                        if (k!=-1) {                                           
161                                                //in case there are cars comming before t_green begin
162                                                if (t_cars_begin(k)<t_act) {
163                                                        if (t_cars_end(k)<=t_act) {
164                                                                virtual_queue+=cars_count(k);
165
166                                                                cars_count.del(k);
167                                                                t_cars_begin.del(k);
168                                                                t_cars_end.del(k);
169
170                                                        }
171                                                        else {
172                                                                double frac=(t_cars_begin(k)-t_act)/(t_cars_end(k)-t_cars_begin(k));
173                                                                virtual_queue+=cars_count(k)*frac;
174                                                                t_cars_begin(k)=t_act;
175                                                        }
176                                                }
177                                                else if (t_cars_begin(k)==t_act) {
178                                                        if (t_cars_end(k)<t_green_end) {
179                                                                virtual_queue+=cars_count(k)-(t_cars_end(k)-t_act)/car_leaving;
180                                                                t_act=t_cars_end(k);
181                                                        }
182                                                        //if t_cars_end>=t_green_end
183                                                        else {
184                                                                virtual_queue+=cars_count(k)-(t_green_end-t_act)/car_leaving;
185                                                                t_act=t_green_end;
186                                                        }
187                                                        //more cars than cars_count(k) couldn't pass without stopping
188                                                        if (virtual_queue < -cars_count(k)) {
189                                                                virtual_queue = -cars_count(k);
190                                                        }
191                                                        cars_count.del(k);
192                                                        t_cars_begin.del(k);
193                                                        t_cars_end.del(k);
194                                                }
195                                                //if t_cars_begin(k)>=t_act
196                                                else {
197                                                        if (t_cars_begin(k)<t_green_end) {
198                                                                virtual_queue-=(t_cars_begin(k)-t_act)/car_leaving;
199                                                                t_act=t_cars_begin(k);
200                                                        }
201                                                        else {
202                                                                virtual_queue-=(t_green_end-t_act)/car_leaving;
203                                                                t_act=t_green_end;
204                                                        }
205                                                        // in case we managed to empty whole queue
206                                                        if (virtual_queue<0) {
207                                                                virtual_queue=0;
208                                                        }
209                                                }
210                                        }
211                                        //if no other expectations found
212                                        else {
213                                                virtual_queue-=(t_green_end-t_act)/car_leaving;
214                                                t_act=t_green_end;
215                                        }
216                                        if (virtual_queue<0) {
217                                                rating-=virtual_queue;
218                                                virtual_queue=0;
219                                        }
220                                } while (t_act<t_green_end);
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_i_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_i_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_i_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=4;
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                       
605                        if (!passive) {
606                                last_offset=planned_offset;
607                                planned_offset=find_best_offset(planned_offset,8);
608                                planned_offset=normalize_offset(planned_offset);
609                        }
610                       
611
612                        /*if (planned_offset!=last_offset) {
613                                reset_negot_offset=true;
614                        }*/
615
616                        planned_rating=count_rating(planned_offset);
617                        // we have new stable state to broadcast
618                        new_stable_state=true;
619                }
620                else if (what=="new_stable_state2") {
621                        rv_recieved_exps=*rv;
622                        recieved_exps=value;
623                        //split_exps();
624                        planned_rating=count_rating(planned_offset);
625
626                        if (!passive) {
627
628                                for (int i=0;i<neighbours.length();i++) {
629                                        rv_change_request.add(RV(neighbours(i)+"_change",2));
630                                        change_request.set_size(rv_change_request._dsize()); 
631                                        ivec ind=RV(neighbours(i)+"_change",2).dataind(rv_change_request);
632                                        // offset change
633                                        change_request(ind(0))=find_best_exps(negot_offset,neighbours(i),rating_change);
634                                        // rating change
635                                        change_request(ind(1))=rating_change;
636                                }
637
638                                if (negot_offset>negot_limit) { 
639                                        negot_offset/=2;
640                                        send_requests=true;
641                                }
642                                else {
643                                        final_state=true;
644
645                                }
646                        }
647                        else {
648                                final_state=true;
649                        }
650                }
651                else if (what=="offset_change_request") {
652                        double final_rating_diff;
653
654                        rv_recieved_changes=*rv;
655                        recieved_changes=value;
656
657                        for (int i=0;i<rv_recieved_changes.length();i++) {
658
659                                ivec ind=RV(rv_recieved_changes.name(i),2).dataind(rv_recieved_changes);
660
661                                final_rating_diff=-planned_rating+count_rating(planned_offset+(int)recieved_changes(ind(0)))+recieved_changes(ind(1));
662                                if (final_rating_diff>=0) {
663                                        planned_offset+=(int)recieved_changes(ind(0));
664                                        planned_offset=normalize_offset(planned_offset);
665                                        planned_rating+=final_rating_diff;
666                                        accepted_from=from;
667                                }
668                        }
669                        //need_exps=true;s
670                        new_stable_state=true;
671                }
672                /*else if (what=="reset_negot_offset") {
673                        negot_offset=8;
674                }*/
675                else {
676                        BaseTrafficAgent::receive(msg);
677                }
678        }
679       
680        void ds_register(const DS &ds) {
681                BaseTrafficAgent::ds_register(ds);
682                action2ds.set_connection( ds._urv(), rv_action);
683        }
684
685        void from_setting(const Setting &set) {
686                BaseTrafficAgent::from_setting(set);
687
688                RV rv_exp;
689
690                car_leaving=2;
691                VP=45;
692                actual_time=0;
693               
694                negot_cycle=1;
695                cycle_count=5;
696                total_offset=0;
697
698                negot_offset=4;
699                negot_limit=1;
700
701                passive=0;
702               
703                // load from file
704                //UI::get(sgs, set, "sgs", UI::compulsory);     
705
706                //UI::get(green_starts, set, "green_starts", UI::compulsory);
707                UI::get(last_offset, set, "offset", UI::compulsory);
708                UI::get(passive, set, "passive", UI::optional);
709
710                for (int i=0;i<lanes.length();i++) {
711                        for (int j=0;j<lanes(i).outputs.length();j++) {
712                                if (lanes(i).outputs(j)!="DUMMY_DET") {
713                                        rv_exp=RV(lanes(i).outputs(j)+"-"+name+"_"+to_string(i),3);
714                                        rv_outputs.add(rv_exp);
715                                }
716                        }
717                }
718                outputs.set_size(rv_outputs._dsize()); 
719
720                log_level[logoffset]=true;
721        }
722
723        void act(vec &glob_ut){
724                if (negot_cycle==cycle_count) {
725               
726                        vec action;
727                        action.set_size(rv_action._dsize());
728               
729                        ivec index = rv_action.dataind(RV(name+"_offset",1));
730
731                        action(index(0))=normalize_offset(total_offset/cycle_count, false);
732                        action2ds.filldown(action,glob_ut);
733
734                        total_offset=0;
735                        negot_cycle=1;
736
737                }
738                else {
739                        total_offset+=planned_offset;
740
741                        negot_cycle++;
742                }
743
744                last_offset=planned_offset;
745                actual_time+=step_length;
746        }
747
748        void log_register(logger &l, const string &prefix){
749                if ( log_level[logoffset]){
750                        l.add_vector ( log_level, logoffset, RV("mujoffset",1), prefix );       //TODO
751                }
752        }
753        void log_write() const {
754                if (log_level[logoffset]){
755                        vec offset_vec(1);
756                        offset_vec(0)=(double)planned_offset;
757                        log_level.store(logoffset, offset_vec);
758                        //log_level.store(logoffset, planned_rating);
759                }
760        }
761};
762UIREGISTER(GreenWaveTrafficAgent);
Note: See TracBrowser for help on using the browser.