1   package examples.bookTrading;
2   
3   
4   
5   import jade.core.AID;
6   import jade.core.Agent;
7   import jade.core.behaviours.Behaviour;
8   import jade.domain.DFService;
9   import jade.domain.FIPAException;
10  import jade.domain.FIPAAgentManagement.DFAgentDescription;
11  import jade.domain.FIPAAgentManagement.ServiceDescription;
12  import jade.lang.acl.ACLMessage;
13  import jade.lang.acl.MessageTemplate;
14  import jade.lang.acl.UnreadableException;
15  
16  import java.io.IOException;
17  import java.util.ArrayList;
18  import java.util.Collections;
19  import java.util.Comparator;
20  import java.util.Enumeration;
21  import java.util.HashMap;
22  import java.util.HashSet;
23  import java.util.Iterator;
24  import java.util.LinkedHashMap;
25  import java.util.LinkedList;
26  import java.util.List;
27  import java.util.Map;
28  import java.util.Map.Entry;
29  import java.util.Random;
30  import java.util.Set;
31  import java.util.StringTokenizer;
32  import java.util.TreeMap;
33  import java.util.concurrent.ConcurrentHashMap;
34  
35  //import UOMM.de.uni_stuttgart.informatik.canu.uomm.CommunicatingVehicles;
36  
37  
38  /**
39   * This user-defined Java class represents a vehicle (agent). It consists of the core functionality of an agent
40   * such as autonomous evaluation of the agent preferences, inter-agent cooperation based on sending and 
41   * receiving messages and inter-agent negotiation.
42   * @author prajakta
43   *
44   */
45  
46  public class NegotiatingVehicleAgent extends Agent {
47          private static final long serialVersionUID = 1L;
48          // The list of known seller agents
49          private AID[] otherAgents;
50          private AID secondAgent;
51          private int intCnt;
52          private String pref;
53          private String flag;
54          private boolean flagIt = false;
55          private boolean destReachedFlag = false;
56          private String communicID;
57          private String agentsInVicinity = null;
58          private boolean vehOnRIQNotif = false;
59          private NotificationPattern onCongRoute = null;
60          private HashMap requestAlloc = new HashMap();
61          private boolean allocFlag = false;
62          private boolean req_resp = false;
63          private boolean init_proposal = false;
64          private int invoke_cnt = 0;
65          private int mapCnt = 0;
66          ConcurrentHashMap routeChoice = null;
67          private double systemOptimalCost=0.0;
68  
69          private double degreeOfUserSatisfaction=0.0;
70          private double systemOptimalIndCost=0.0;
71          private double degreeOfUserIndSatisfaction=0.0;
72          private double totalIndCost=0.0;
73          private int typeOfWelfare = Constants.SOCIAL_WELFARE;
74          private double totalNormalisedCost=0.0;
75          private double lowestUtility=0.0;
76          private String myPoorestAgent=null;
77          private boolean replaced = false;
78          private int preRandomInteger = Constants.ADD;
79          PreferenceUtilityIndex prefIndex = null;
80          public CommunicatingVehicles vehMaps = null;
81          private boolean sentPref = false;
82          private boolean sentRoutes = false;
83          private double preferenceMultiplier = 0;
84          private double costMultiplier = 1;
85  
86          private double maxCost=0.0,minCost=0.0;
87          private double maxPref=0.0,minPref=0.0;
88  
89          private double normalisedSystemOptimalCost=0.0;
90          private double normalisedSystemOptimalPreference=0.0;
91          private double normalisedCostAfterNeg = 0.0;
92          private double normalisedPrefAfterNeg=0.0;
93  
94          private double numCost;
95          private double denoCost;
96          private double numPref;
97          private double denoPref;
98  
99  
100         private int rd=0;
101 
102         private boolean pathallocated =false;
103 
104         EvaluateRouteInfo evalInfo = null;
105         public boolean getVehOnRIQNotif() {
106                 return vehOnRIQNotif;
107         }
108 
109         public void setVehOnRIQNotif(boolean vehOnRIQNotif) {
110             this.vehOnRIQNotif = vehOnRIQNotif;
111         }
112 
113         boolean readyToEval = false;
114         public String getAgentsInVicinity() {
115             return agentsInVicinity;
116         }
117 
118         public void setAgentsInVicinity(String agentsInVicinity) {
119             this.agentsInVicinity = agentsInVicinity;
120         }
121 
122         private String path = null;
123         private boolean junctionReached = true;
124         public boolean isJunctionReached() {
125             return junctionReached;
126         }
127 
128         public void setJunctionReached(boolean junctionReached) {
129             this.junctionReached = junctionReached;
130         }
131 
132         private static ConcurrentHashMap regVInfo = new ConcurrentHashMap();
133         private static ConcurrentHashMap<String, PreferenceUtilityIndex> regVInfoCpy = new ConcurrentHashMap();
134         private ConcurrentHashMap retSegMap = new ConcurrentHashMap();
135         HashMap<String,Double> weightMap = new HashMap<String,Double>();
136         ValueComparator bvc =  new ValueComparator(weightMap);
137         TreeMap<String,Double> sortedWeightMap = new TreeMap(bvc);
138         //TreeMap shortestRIQTTMap = new TreeMap();
139         ConcurrentHashMap routeMap = new ConcurrentHashMap();
140         ConcurrentHashMap myMegaMap = new ConcurrentHashMap();
141 
142         //map which contains the number of agents found on each route segment, this value is set by the simulator
143         ConcurrentHashMap mapOfNumberOfNodes = new ConcurrentHashMap();
144         public ConcurrentHashMap getMapOfNumberOfNodes() {
145             return mapOfNumberOfNodes;
146         }
147 
148         public void setMapOfNumberOfNodes(ConcurrentHashMap mapOfNumberOfNodes) {
149             this.mapOfNumberOfNodes = mapOfNumberOfNodes;
150         }
151 
152         //this map maintains a map of allocations fo  agent corresponginf to each congested route
153         ConcurrentHashMap agentMapOfAlloc = new ConcurrentHashMap();
154 
155         //this map maointina a map of number of agents found for a corresponding congested road
156         ConcurrentHashMap agentMapOfCount = new ConcurrentHashMap();
157 
158 
159 
160 
161 
162         ArrayList savedList = new ArrayList();
163         boolean queueMap = true;
164 
165         private static ConcurrentHashMap finalAllocation = new ConcurrentHashMap();
166 
167         String yCoordinatesOfEdge = null;
168 
169         public String getyCoordinatesOfEdge() {
170 
171             return yCoordinatesOfEdge;
172         }
173 
174         public void setyCoordinatesOfEdge(String yCoordinatesOfEdge) {
175 
176             this.yCoordinatesOfEdge = yCoordinatesOfEdge;
177         }
178 
179 
180         String xCoordinatesOfEdge = null;
181 
182         public String getxCoordinatesOfEdge() {
183 
184             return xCoordinatesOfEdge;
185         }
186 
187         public void setxCoordinatesOfEdge(String xCoordinatesOfEdge) {
188             this.xCoordinatesOfEdge = xCoordinatesOfEdge;
189         }
190 
191 
192         private String onCongestedRoute;
193         ArrayList myMegaList = new ArrayList();
194 
195         int maxAgents = 0;
196 
197         public ConcurrentHashMap getRouteMap() {
198             return routeMap;
199         }
200 
201         public void setRouteMap(ConcurrentHashMap routeMap) {
202 
203             this.routeMap = routeMap;
204         }
205 
206         HashMap genralRouteMap = new HashMap();
207 
208         public boolean isDestReachedFlag() {
209             return destReachedFlag;
210         }
211 
212         public void setDestReachedFlag(boolean destReachedFlag) {
213             this.destReachedFlag = destReachedFlag;
214         }
215 
216         private boolean rngChk = false;
217 
218         public boolean isRngChk() {
219             return rngChk;
220         }
221 
222         public void setRngChk(boolean rngChk) {
223             this.rngChk = rngChk;
224         }
225 
226         CondVariable  latch1 = QueueManager.getMssgQueue();
227         public boolean isFlagIt() {
228             return this.flagIt;
229         }
230 
231         public void setFlagIt(boolean flagIt) {
232             //System.out.println("SETting FLAG "+flagIt );
233             this.flagIt = flagIt;
234         }
235 
236         private HashMap mssgContent = new HashMap();
237 
238         public String getFlag() {
239             return this.flag;
240         }
241 
242         public void setFlag(String flag) {
243             this.flag = flag;
244         }
245 
246         public int getIntCnt() {
247             return intCnt;
248         }
249 
250         public void setIntCnt(int intCnt) {
251             this.intCnt = intCnt;
252         }
253 
254         private Object road = new Object();
255         private boolean isCommonSegment;
256 
257         public boolean isCommonSegment() {
258             return isCommonSegment;
259         }
260 
261         public void setCommonSegment(boolean isCommonSegment) {
262             this.isCommonSegment = isCommonSegment;
263         }
264         public String getCommunicID() {
265             return communicID;
266         }
267 
268         public void setCommunicID(String communicID) {
269             this.communicID = communicID;
270 
271         }
272 
273         //variables for VehicleCountReachedNotification
274         private String owner;
275         private String commID;
276         private String congSegID;
277         private int agentCnt;
278         private int invoke_cnt_interval=20;
279         public String getOwner() {
280             return owner;
281         }
282         public void setOwner(String owner) {
283             this.owner = owner;
284         }
285     
286         public String getCongSegIDToCompare() {
287             return congSegID;
288         }
289         public void setCongSegID(String congSegID) {
290     //      System.out.println("if cong:"+congSegID);
291             this.congSegID = congSegID;
292         }
293         public int getAgentCnt() {
294             return agentCnt;
295         }
296         public void setAgentCnt(int agentCnt) {
297             if(xCoordinatesOfEdge.equals("0.0") && yCoordinatesOfEdge.equals("120.0")){
298             //  System.out.println("agent count..."+agentCnt);
299             }
300             this.agentCnt = agentCnt;
301         }
302 
303         //variables for VehicleCountReachedNotification
304 
305 
306         /**
307          * This method is used for agent parameter initialisation
308          */
309          protected void setup() {
310 
311             // Register the vehicle agent service in the yellow pages
312             DFAgentDescription dfd = new DFAgentDescription();
313             dfd.setName(getAID());
314             ServiceDescription sd = new ServiceDescription();
315             sd.setType("traffic");
316             sd.setName("JADE-traffic-mngt");
317             dfd.addServices(sd);
318             try {
319                 DFService.register(this, dfd);
320             } catch (FIPAException fe) {
321                 fe.printStackTrace();
322             }
323             Object[] args = getArguments();
324             if (args != null && args.length > 0) {
325                 /*counter = (String) args[0];*/
326                 intCnt = 2000;/*Integer.parseInt(counter);*/
327                 pref = new String("SD");/*(String) args[1];*/
328                 communicID = (String)args[3];
329                 agentsInVicinity = (String)args[4];
330                 junctionReached = ((Boolean) args[6]).booleanValue();
331                 isCommonSegment = ((Boolean) args[7]).booleanValue();
332                 yCoordinatesOfEdge = (String)args[8];
333                 xCoordinatesOfEdge = (String)args[9];
334             }
335 
336             QueueManager.addUpdateAgentDetails(this.getLocalName(), intCnt);
337             QueueManager.addUpdateAgentPreferences(this.getLocalName(), pref);
338             QueueManager.addAgentToMap(this);
339             final DFAgentDescription recAgents = new DFAgentDescription();
340             sd = new ServiceDescription();
341             sd.setType("traffic");
342             sd.setName("JADE-traffic-mngt");
343 
344 
345 
346             //new code
347             if(xCoordinatesOfEdge.equals("0.0") && yCoordinatesOfEdge.equals("120.0")){
348             //  System.out.println("debug path");
349             }
350             onCongestedRoute = DataAccess.getTheCongSeg(xCoordinatesOfEdge,yCoordinatesOfEdge);//DataAccess.getRIQPath(this.getLocalName(),xCoordinatesOfEdge,yCoordinatesOfEdge);
351 
352             if(congSegID!=null && congSegID.equals("s2")){
353                 onCongestedRoute=congSegID;
354             }
355 
356 
357 
358             if(onCongestedRoute!=null && onCongestedRoute.equals("s43")){
359 
360                 onCongestedRoute = DataAccess.getTheCongSeg(xCoordinatesOfEdge,yCoordinatesOfEdge);//DataAccess.getRIQPath(this.getLocalName(),xCoordinatesOfEdge,yCoordinatesOfEdge);
361             }
362             
363             //new code
364 
365             intCnt = 20000;
366             
367             if(!isDestReachedFlag()){
368                         //new code
369                         try {
370                             DFAgentDescription[] result = DFService.search(this,
371                                     recAgents);
372                         //  //System.out.println("Found the following agents:");
373                             otherAgents = new AID[result.length];
374                             maxAgents = otherAgents.length;
375                             if(QueueManager.getMaxAgentCntRecorded(communicID)< maxAgents){
376                                 QueueManager.setMaxAgentCntRecorded(maxAgents,communicID);
377                             }
378                             this.addBehaviour(new ExchangeMessageBehaviour());
379                         } catch (FIPAException fe) {
380                             fe.printStackTrace();
381                         }
382                         if(otherAgents.length==0){
383 
384                                   CondVariable  latch = QueueManager.getStartUpLatch();
385                                   latch.signal();
386                         }
387 
388             }
389             else {
390 
391                 // Make the agent terminate
392                 //System.out.println("Agent travel time not specified");
393                 doDelete();
394             }
395             //new code}
396         }
397 
398         /**
399          * This method returns the execution step number
400          * @param secondAgent agentID of the agent
401          * @return
402          */
403          private int getStepToExec(AID secondAgent) {
404            AgentInteractionModel theModel  = QueueManager.getAgentInteractionModel(this.getAID(), secondAgent);
405             String status = null;
406             if(theModel==null){
407                 status = "INIT";
408                 theModel = new AgentInteractionModel();
409                 theModel.setSenderAgent(this.getAID());
410                 theModel.setRecAgent(secondAgent);
411                 theModel.setStatus("INIT");
412                 QueueManager.addToAgentInteractionList(theModel);
413                 return 0;
414             }else{
415             status = theModel.getStatus();
416             }
417             if(status.equals("EXCG_DEST")){
418                 return 1;
419             }else if(status.equals("REC_DEST")){
420                 return 2;
421             }else if(status.equals("EXCH_PREVSEG")){
422                 return 3;
423             }if(status.equals("RECD_PREVSEG")){
424                 return 4;
425             }else if(status.equals("REC_ALLOC")){
426                 return 5;
427             }else
428                 return 0;
429         }
430         // Put agent clean-up operations here
431         protected void takeDown() {
432         }
433 
434         private class ExchangeMessageBehaviour extends Behaviour {
435 
436                 private int step = 0;
437                 private AID bestSeller; // The agent who provides the best offer
438                 ArrayList AID = new ArrayList();
439                 AID[] sellerAgents = null;
440                 private int repliesCnt = 0;
441                 int len = 0;
442                 String agentName;
443                 String value, rcdAgentKey;
444                 String agentVal;
445                 PreferenceUtilityIndex rcdAgentValOne;
446                 HashMap pathCntMap = new HashMap();
447                 HashMap pathCntMapCpy = new HashMap();
448 
449                 private HashMap rcdHash = new HashMap();
450                 private ConcurrentHashMap rcdReqHash = new ConcurrentHashMap();
451                 private ConcurrentHashMap sendRouteHash = new ConcurrentHashMap();
452                 private HashMap rcdRespHash = new HashMap();
453                 private boolean swapFlag = false;
454 
455 
456 
457 
458                 public ExchangeMessageBehaviour() {
459 
460             //      secondAgent = myAgent.getAID();
461                 }
462 
463 
464                 /**
465                  * This method retrieves the agent in vicinity.
466                  */
467                 private void retrieveAgentsInVicinity()
468                 {
469 
470                     Agent agt = null;
471                     //new code
472                     if(isRngChk())
473                     {
474                         agentsInVicinity = getAgentsInVicinity();
475                     }
476                     //new code
477                     StringTokenizer st = new StringTokenizer(agentsInVicinity, ",");
478             //      //System.out.println("SellerAgent Adding AIDx  : "+agentsInVicinity+" by "+myAgent.getLocalName());
479                     AID = new ArrayList();
480                     if(st!=null){
481                     while (st.hasMoreElements()) {
482                         String agentName = (String) st.nextElement();
483                         if (agentName != null) {
484                             agt = QueueManager.getAgent(agentName);
485 
486                                 if(agt!=null ){//new code&& DataAccess.checkPathForRIQ(agentName)!=null){
487                                     if(agt.getLocalName()!=null && !agt.getLocalName().equals(myAgent.getLocalName()))
488 
489                                         AID.add(agt.getAID());
490 
491                                 }
492 
493                         }
494                     }
495                     sellerAgents = (AID[]) AID.toArray(new AID[0]);
496 
497                     maxAgents = sellerAgents.length+1;
498                     if(QueueManager.getMaxAgentCntRecorded(communicID)< maxAgents){
499                         QueueManager.setMaxAgentCntRecorded(maxAgents,communicID);
500                     }
501 
502                     }
503 
504                 }
505 
506                 @Override
507                 /**
508                  * Runs the agent behaviour implementation
509                  */
510                 public void action() {
511 
512                      int S11=0;
513                      int S17=0;
514                     String retSeg = null;
515                     boolean mssgSent = false;
516                     boolean mssgSentCFP = false;
517 
518 
519                     retrieveAgentsInVicinity();
520                     if(evalInfo==null){
521                     EvaluateRouteInfo evalInfo = new EvaluateRouteInfo(myAgent.getLocalName());
522                     }
523 
524                     onCongestedRoute = DataAccess.getTheCongSeg(xCoordinatesOfEdge,yCoordinatesOfEdge);//DataAccess.getRIQPath(myAgent.getLocalName(),xCoordinatesOfEdge,yCoordinatesOfEdge);
525                     CommunicatingVehicles vehMaps = (CommunicatingVehicles) QueueManager.getCVMaps(communicID);
526                     step = getStepToExec(myAgent.getAID());
527                     /*
528                      * new code
529                      */
530 
531 
532                     if(onCongestedRoute==null){
533                     step = 1;
534 
535                     QueueManager.addToRouteChoiceForOutOfPathAgents(myAgent.getLocalName());
536 
537                     }
538                     //new code ends
539 
540                     CondVariable  latch = QueueManager.getStartUpLatch();
541                     boolean toProcess = false;
542                     //comment
543 
544                     /*if(!toProcess){
545                         QueueManager.setRouteChoice(rcdReqHash, communicID,null);
546                     }*/
547                     if(communicID!=null && communicID.equals(myAgent.getLocalName())){
548                         QueueManager.setRouteChoice(rcdReqHash, communicID,null);
549                     }
550                     else if(communicID!=null){
551                         toProcess = QueueManager.continueProcessing(sellerAgents,communicID);
552                     }else{
553                         prefIndex = DataAccess.getPreferenceUtilityIndex(myAgent.getLocalName(), communicID,preferenceMultiplier,costMultiplier,onCongestedRoute,yCoordinatesOfEdge,vehMaps);
554                         registerVehicleRouteInfo(myAgent.getLocalName(),prefIndex,vehMaps,evalInfo);
555 
556                         evaluateRoutes(vehMaps);
557                     }
558                     boolean agentFlag = QueueManager.compareAgents(sellerAgents,routeMap);
559 
560 
561                     if(!allocFlag && intCnt<0 || !toProcess){
562 
563                         latch.signal();
564                          try {
565                             latch.waitOn();
566                         } catch (InterruptedException e) {
567                             // TODO Auto-generated catch block
568                             e.printStackTrace();
569                         }
570 
571                     }else if(!allocFlag && !agentFlag){
572 
573                         if(myAgent.getLocalName()!=null && sellerAgents.length == QueueManager.getMaxAgentCntRecorded(communicID)){
574                             //System.out.println("Stopped Exchanging");
575 
576                         }
577                         latch.signal();
578                          try {
579                             latch.waitOn();
580                         } catch (InterruptedException e) {
581                             // TODO Auto-generated catch block
582                             e.printStackTrace();
583                         }
584                     }
585                     else if(invoke_cnt%getInterval()==0 && congSegID!=null){
586 
587                     boolean checkProcess =  QueueManager.checkIfRoutesRecorded(myAgent.getLocalName(),vehMaps);
588                     if(congSegID!=null && !QueueManager.doneFinalCommAlloc(communicID, congSegID)){
589 
590                         switch(step){
591 
592                     case 0:
593 
594                         // sending mssg
595                         ACLMessage cfp = new ACLMessage(ACLMessage.CFP);
596                         ACLMessage reqMessage = new ACLMessage(ACLMessage.PROPOSE);
597                 //      ACLMessage reqInformMessage = new ACLMessage(ACLMessage.INFORM);
598 
599                         mssgContent = new HashMap();
600 
601                         if(xCoordinatesOfEdge.equals("0.0") && yCoordinatesOfEdge.equals("120.0") && myAgent.getLocalName().equals("#5")){
602                     //      System.out.println("For communicID:"+communicID+ " xCoordinatesOfEdge:"+xCoordinatesOfEdge+" yCoordinatesOfEdge:"+yCoordinatesOfEdge+" agent: "+myAgent.getLocalName());
603                             }
604                         if(onCongestedRoute!=null && onCongestedRoute.equals("s43")){
605                     //  System.out.println("case 0 : check the route choice map");
606                         }
607 
608                         vehMaps = (CommunicatingVehicles) QueueManager.getCVMaps(communicID);
609                         if(vehMaps!=null && onCongestedRoute!=null){
610 
611                             if(vehMaps.getPathID()!=null && !vehMaps.getPathID().equals(onCongestedRoute)){
612                                 savedList = new ArrayList();
613                                 vehMaps=null;
614                             }
615                         }
616                         if(vehMaps!=null && !isValidMasterMap(vehMaps,onCongestedRoute)){
617                             savedList = new ArrayList();
618                             vehMaps=null;
619                         }
620                         if(vehMaps==null){
621                             System.out.println("For vehMaps:"+communicID+ " xCoordinatesOfEdge:"+xCoordinatesOfEdge+" yCoordinatesOfEdge:"+yCoordinatesOfEdge+" agent: "+myAgent.getLocalName());
622                         }
623 
624                         if(vehMaps==null){
625                             vehMaps = new CommunicatingVehicles(communicID);
626                             sendRouteHash = new ConcurrentHashMap();
627                         }
628 
629 
630                         savedList = formValidSavedList(savedList, onCongestedRoute);
631                         QueueManager.setCVMaps(communicID, vehMaps);
632                         prefIndex = DataAccess.getPreferenceUtilityIndex(myAgent.getLocalName(), communicID,preferenceMultiplier,costMultiplier,onCongestedRoute,yCoordinatesOfEdge,vehMaps);
633 
634 
635                         registerVehicleRouteInfo(myAgent.getLocalName(), prefIndex,vehMaps,evalInfo);
636 
637 
638 
639                         mssgContent.put(myAgent.getLocalName(),prefIndex);
640 
641                         if(finalAllocation!=null /*&& isCommonSegment()*/){
642                             mssgContent.put(myAgent.getLocalName()+"PREVRT", finalAllocation.get(myAgent.getLocalName()));
643                             setCommonSegment(false);
644                             }
645 
646                         try {
647 
648                             cfp.setContentObject(mssgContent);
649                         } catch (IOException e) {
650 
651                             e.printStackTrace();
652                         }
653 
654 
655                             for (int k = 0; k < sellerAgents.length; ++k) {
656                             if(finalAllocation!=null){
657 
658                                 //commented on 14/03/2013
659                             }
660 
661                                 if(allocFlag /*&& routeChoice.size()==Constants.VEHICLESEED*/){
662                                 //  if(!sentRoutes){
663                                     reqMessage.addReceiver(sellerAgents[k]);
664                                     if(typeOfWelfare==Constants.RATIONAL_WELFARE){
665                                         sendRouteHash.put(routeChoice, lowestUtility);
666                                         myMegaMap.put(routeChoice, lowestUtility);
667 
668                                     }else if(routeChoice!=null){
669                                         if(onCongestedRoute!=null && onCongestedRoute.equals(congSegID)){
670 
671                                             if(routeChoice!=null && routeChoice.size()==getAgentCnt()){
672                                                 if(preferenceMultiplier==1 && costMultiplier==1){
673                                                     if(!swapFlag ){
674                                                     sendRouteHash.put(routeChoice, totalNormalisedCost);
675                                                     myMegaMap.put(routeChoice, totalNormalisedCost);
676                                                     }else{
677                                                         sendRouteHash.put(routeChoice, degreeOfUserSatisfaction);
678                                                         myMegaMap.put(routeChoice, degreeOfUserSatisfaction);
679                                                     }
680                                                 }else if(preferenceMultiplier==0 && costMultiplier==1){
681                                                     sendRouteHash.put(routeChoice, -systemOptimalCost);
682                                                     myMegaMap.put(routeChoice, -systemOptimalCost);
683                                                 }else if(preferenceMultiplier==1 && costMultiplier==0){
684                                                     sendRouteHash.put(routeChoice, degreeOfUserSatisfaction);
685                                                     myMegaMap.put(routeChoice, degreeOfUserSatisfaction);
686                                                 }
687                                             }else{
688                                                 break;
689                                             }
690                                         }else{
691                                     //      System.out.println(myAgent.getLocalName()+" onCongestedRoute"+onCongestedRoute+ " congSegID"+congSegID);
692                                             break;
693                                         }
694                                     }
695 
696 
697                                     int expListLength=0;
698                                     if(onCongestedRoute!=null && savedList!=null){
699                                     if(onCongestedRoute.equals(congSegID)){
700                                         expListLength=getAgentCnt();
701                                     //  System.out.println("agent cnt for "+congSegID+" is "+getAgentCnt());
702                                         //expListLength=Constants.VEHICLESEED;
703                                     }
704                                     }
705 
706 
707 
708 
709 
710 
711                                     if(routeChoice!=null && routeChoice.size() >= expListLength){
712                                         
713                                     myMegaList.add(sendRouteHash);
714                                     queueMap = QueueManager.updateAndGetAssignedRouteChoice(myAgent.getLocalName(),  sendRouteHash, vehMaps,onCongestedRoute);
715                                     if(queueMap){
716                                         myMegaList.add(sendRouteHash);
717                                     }
718                                     }
719                                     if(sendRouteHash!=null && routeChoice!=null){
720                                         if(!QueueManager.allAgentsRcd(communicID,agentCnt)){
721                                         QueueManager.addToMyCheckList(myAgent.getLocalName(), routeChoice.size(),communicID,lowestUtility,agentCnt);
722 
723                                         }
724                                     }
725                                     try {
726                                         if(sendRouteHash!=null){
727                                         reqMessage.setContentObject(sendRouteHash);
728                                         reqMessage.setConversationId("vehicleRouteChoice");
729 
730                                         mssgSent = QueueManager.checkIfMessageAlreadySent(sendRouteHash, myAgent.getLocalName(), sellerAgents[k].getLocalName(), onCongestedRoute,agentCnt,sellerAgents);
731                                         reqMessage.setReplyWith("vrc" + System.currentTimeMillis());
732                                         myAgent.setQueueSize(0);
733                                         if(!mssgSent){
734                                     //      System.out.println("Checking message sent by : "+myAgent.getLocalName()+ "to :  "+sellerAgents[k].getLocalName()+" for congested segment : "+onCongestedRoute);
735                                         myAgent.send(reqMessage);
736                                         }
737 
738                                         //sentRoutes = true;
739                                         }
740 
741                                     } catch (IOException e) {
742                                         // TODO Auto-generated catch block
743                                         e.printStackTrace();
744                                     }
745                                 //}
746                                 }
747                                 
748                             }
749 
750                         AID[] newRecipients =   QueueManager.sentInitPrefTo(myAgent.getLocalName(), sellerAgents);
751                     //  System.out.println(myAgent.getLocalName()+" original number : "+sellerAgents.length+" and new number : "+newRecipients.length);
752                         if(newRecipients!=null){
753 
754                         for (int k = 0; k < newRecipients.length; ++k) {
755                         cfp.addReceiver(newRecipients[k]);
756                         cfp.setConversationId("vehiclePosition");
757                         cfp.setReplyWith("cfp" + System.currentTimeMillis());
758                         myAgent.setQueueSize(0);
759                         mssgSentCFP = QueueManager.checkIfCFPAlreadySent(prefIndex,myAgent.getLocalName(), newRecipients[k].getLocalName(), onCongestedRoute,newRecipients);
760                         if(!mssgSentCFP){
761                             myAgent.send(cfp);
762                         }
763                         }
764                         }
765                        AgentInteractionModel theModel = new AgentInteractionModel();
766                         theModel.setSenderAgent(myAgent.getAID());
767                         theModel.setRecAgent(myAgent.getAID());
768                         theModel.setStatus("EXCG_DEST");
769                         QueueManager.addToAgentInteractionList(theModel);
770 
771 
772 
773                         intCnt--;
774                         QueueManager.addUpdateAgentDetails(myAgent.getLocalName(),
775                                 intCnt);
776                         //break;
777                     case 1:
778                         MessageTemplate mtReq = MessageTemplate.MatchPerformative(ACLMessage.PROPOSE);
779                         ACLMessage msgReq = myAgent.receive(mtReq);
780 
781                         if(msgReq!=null && allocFlag){
782                             // CFP Message received. Process it
783                             try {
784                         //      //System.out.println("Request rcd.....processing resp");
785                                 rcdReqHash = (ConcurrentHashMap) msgReq.getContentObject();
786 
787                                 Set rcdSet = rcdReqHash.entrySet();
788                                 if(rcdSet!=null){
789                                     Iterator subIter = rcdSet.iterator();
790                                     if(subIter!=null && subIter.hasNext()){
791                                         Map.Entry map = (Entry) subIter.next();
792                                         ConcurrentHashMap rcdRouteMap = (ConcurrentHashMap) map.getKey();
793 
794                                         if(rcdRouteMap!=null){
795                                         //  System.out.println(myAgent.getLocalName()+ " Checking "+msgReq.getSender().getLocalName()+" " +rcdRouteMap.size()+" QM:"+QueueManager.getMaxAgentCntRecorded(communicID)+" cong "+congSegID);
796                                         }
797                                         if(rcdRouteMap!=null && rcdRouteMap.size()==QueueManager.getMaxAgentCntRecorded(communicID)){
798 
799                                             boolean check = QueueManager.checkRcdResponse(msgReq.getSender().getLocalName(),rcdRouteMap.size());
800 
801                                             if(!check){
802 
803                                                 if(rcdRouteMap!=null){
804                                                     if(!QueueManager.allAgentsRcd(communicID,agentCnt)){
805                                                     QueueManager.addToMyCheckList(msgReq.getSender().getLocalName(), rcdRouteMap.size(),communicID,Double.parseDouble(map.getValue().toString()),agentCnt);
806                                                 //  //System.out.println(msgReq.getSender().getLocalName() + " and "+ myAgent.getLocalName() + " Entering " + map.getValue());
807                                                     int expListLength=0;
808                                                     if(onCongestedRoute!=null && onCongestedRoute.equals(congSegID)){
809                                                         expListLength=getAgentCnt();//Constants.VEHICLESEED;
810                                                     }
811 
812                                                     if(rcdRouteMap.size() >= expListLength){
813                                                         if(onCongestedRoute!=null && onCongestedRoute.equals("s47")){
814                                                 //          System.out.println("Adding to the savedList RECEIVE : "+routeChoice.size()+" for agt: "+myAgent.getLocalName()+"  onCongestedRoute:-"+onCongestedRoute);
815                                                             }
816 
817                                                         queueMap = QueueManager.updateAndGetAssignedRouteChoice(msgReq.getSender().getLocalName(),  rcdReqHash,vehMaps,onCongestedRoute);
818                                                         if(queueMap){
819                                                             myMegaList.add(rcdReqHash);
820                                                         }
821                                                     }
822                                                     }
823                                                 }
824 
825                                                 myMegaMap.put(rcdRouteMap,map.getValue());
826 
827                                                 if(myMegaList!=null && myMegaList.size()>=QueueManager.getMaxAgentCntRecorded(communicID)){
828                                                     theModel = new AgentInteractionModel();
829                                                     theModel.setSenderAgent(msgReq.getSender());
830                                                     theModel.setRecAgent(myAgent.getAID());
831                                                     theModel.setStatus("REC_ALLOC");
832                                                     QueueManager.addToAgentInteractionList(theModel);
833 
834                                                         //step = 5;
835                                                     break;
836                                                 }
837                                             }
838                                         }
839                                         /*if(rcdRouteMap.size()==Constants.VEHICLESEED){
840                                         //System.out.println("++//++//Routes rcd by "+myAgent.getLocalName()+"from "+msgReq.getSender().getLocalName()+" map of size "+rcdRouteMap.size());
841                                         }*/
842                                         mapCnt++;
843                                     //  //System.out.println("Mega map size:"+mapCnt);
844                                     }
845                                 }
846                                 
847                                 savedList = QueueManager.returnQueueList(vehMaps);
848                                 if(myMegaList!=null && savedList!=null /*&& savedList.size()==Constants.VEHICLESEED */){
849                                 if(typeOfWelfare==Constants.RATIONAL_WELFARE){
850                                     selectListEgalitarianRouteAllocation(savedList);
851                                 }
852                                 else if(myMegaList!=null){
853                                     if(onCongestedRoute!=null && savedList!=null){
854                                         savedList = formValidSavedList(savedList,onCongestedRoute);
855                                         if(onCongestedRoute!=null && onCongestedRoute.equals("s47")){
856                                         /*if(getAgentCnt()==10 && savedList.size()==9){
857                                             if(vehMaps.getSavedPathMap().get("#0")==null){*/
858                                                 System.out.println("congested segment Id : "+congSegID+ "and vehicleCount "+getAgentCnt()+" and savedList size : "+savedList.size()+" vehicle ID"+myAgent.getLocalName());
859 
860                                         /*  }
861                                         }*/
862                                         }
863                                     //  if(onCongestedRoute!=null && onCongestedRoute.equals("s4")&& savedList.size()==getAgentCnt()){
864                                             System.out.println("onCongestedRoute..select: "+onCongestedRoute+ " "+savedList.size()+" AND agentCnt "+getAgentCnt()+" by agent : "+myAgent.getLocalName());
865                                     //  }
866                                         if(onCongestedRoute.equals(congSegID) && savedList.size()==getAgentCnt()){
867 
868                                             if(congSegID!=null && congSegID.equals("s60")){
869                                                 System.out.println("check the flow");
870                                             }
871                                             QueueManager.doFinalAllocationfForCommunicationID(communicID, onCongestedRoute);
872                                             QueueManager.doFinalAlloc(myAgent.getLocalName(), onCongestedRoute);
873                                             System.out.println("doing the final route allocation:"+congSegID+ "count "+getAgentCnt()+" agentID: "+myAgent.getLocalName());
874                                             selectListRouteAllocation(savedList, vehMaps);
875 
876 
877                                         }
878                                 }//null check
879                                     }
880                                 }
881 
882                                 req_resp = true;
883                                 allocFlag = false;
884                             } catch (UnreadableException e) {
885                                 // TODO Auto-generated catch block
886                                 e.printStackTrace();
887                             }
888                         }
889 
890 
891                         MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.CFP);
892                         mt = MessageTemplate.MatchConversationId("vehiclePosition");
893                         ACLMessage msg = myAgent.receive(mt);
894                         if (msg != null) {
895                             // CFP Message received. Process it
896                             try {
897                                 rcdHash = (HashMap) msg.getContentObject();
898 
899                             } catch (UnreadableException e) {
900                                 // TODO Auto-generated catch block
901                                 e.printStackTrace();
902                             }
903                         if(rcdHash!=null){
904                             Set entries = rcdHash.entrySet();
905                             if (entries != null && !entries.isEmpty()) {
906                                 for (Iterator it = entries.iterator(); it.hasNext();) {
907                                     Map.Entry entry = (Entry) it.next();
908                                     rcdAgentKey = (String) entry.getKey();
909 
910                                     if (rcdAgentKey!=null && !rcdAgentKey.equals(myAgent.getLocalName())) {
911 
912                                         rcdAgentValOne = (PreferenceUtilityIndex) entry.getValue();
913                                         System.out.println(myAgent.getLocalName()+" Received following message......"+rcdAgentValOne.getVehicleID());
914 
915                                     //  //System.out.println(rcdAgentValOne.getDest());
916                                         //new code
917 
918                                         retSeg = rcdAgentValOne.getSegmentID();
919                                         int reason = rcdAgentValOne.getReasonForCongestion();
920                                         if(onCongestedRoute==null){
921                                             path = retSeg;
922                                             ////System.out.println("Got path .."+path);
923                                             addToSegMap(msg.getSender().getLocalName(),retSeg,reason);
924                                         }else if(onCongestedRoute!=null){
925                                             path = onCongestedRoute;
926                                         }
927 
928                                         //new code
929                                         //if(onCongRoute!=null)
930                                         registerVehicleRouteInfo(rcdAgentKey, rcdAgentValOne,vehMaps,evalInfo);
931 
932                                     }
933                                 }
934                             }
935                         }
936                         }
937 
938                         theModel = new AgentInteractionModel();
939                         theModel.setSenderAgent(myAgent.getAID());
940                         theModel.setRecAgent(secondAgent);
941                         theModel.setStatus("REC_DEST");
942                         QueueManager.addToAgentInteractionList(theModel);
943 
944                         intCnt--;
945 
946                     }
947                     }//if !doneFinalAlloc
948                     }
949                     invoke_cnt++;
950                 }
951 
952 
953 
954             private int getInterval() {
955                 if(congSegID==null){
956                     return 50;
957                 }else{
958                     return 10;
959                 }
960                 }
961 
962 
963             /**
964              * Returns the valid list of routes for the given congested segment 
965              * @param vehMaps map of communicating vehicles
966              * @param congRt congested segment
967              * @return boolean true if matching valid routes exist else false
968              */
969             private boolean isValidMasterMap(CommunicatingVehicles vehMaps,String congRt) {
970                     String allowedRoutes = null;
971                     if(congRt.equals("s1")){
972                         allowedRoutes = "1,2";
973                     }if(congRt.equals("s2")){
974                         allowedRoutes = "3,4";
975                     }if(congRt.equals("s24")){
976                         allowedRoutes = "5,6";
977                     }if(congRt.equals("s37")){
978                         allowedRoutes = "7,8";
979                     }if(congRt.equals("s39")){
980                         allowedRoutes = "9,10";
981                     }if(congRt.equals("s43")){
982                         allowedRoutes = "11,12";
983                     }if(congRt.equals("s27")){
984                         allowedRoutes = "13,14";
985                     }if(congRt.equals("s10")){
986                         allowedRoutes = "15,16";
987                     }if(congRt.equals("s17")){
988                         allowedRoutes = "17,18";
989                     }if(congRt.equals("s31")){
990                         allowedRoutes = "24,25";
991                     }if(congRt.equals("s11")){
992                         allowedRoutes = "26,27";
993                     }
994 
995                     ConcurrentHashMap mapToCheck = vehMaps.getMasterMapForCommID();
996                     if(mapToCheck!=null){
997                         Set mapSet = mapToCheck.entrySet();
998                         if(mapSet!=null){
999                             Iterator iter = mapSet.iterator();{
1000                                while(iter!=null && iter.hasNext()){
1001                                    Map.Entry entry = (Entry) iter.next();
1002                                    if(entry!=null){
1003                                        if(entry.getKey()!=null && allowedRoutes.indexOf(entry.getKey().toString())<=-1){
1004                                            System.out.println("returninf false. "+onCongestedRoute+" ID: "+myAgent.getLocalName()+" for invalid key "+entry.getKey());
1005                                            return false;
1006                                        }
1007                                    }
1008                                }
1009                            }
1010                        }
1011                    }
1012                    return true;
1013                }
1014
1015
1016                /**
1017                 * This method returns a list of valid routes based on the congested segment ID
1018                 * @param savedList list of saved routes
1019                 * @param congRt congested segment ID
1020                 * @return list of valid routes
1021                 */
1022                private ArrayList formValidSavedList(ArrayList savedList, String congRt) {
1023                    if(savedList!=null && congRt!=null){
1024                    boolean entryRemoved = false;
1025                    ArrayList newSavedList = new ArrayList();
1026                    Object temp = null;
1027                    String allowedRoutes = null;
1028                    if(congRt!=null){
1029                        if(congRt.equals("s1")){
1030                            allowedRoutes = "1,2";
1031                        }if(congRt.equals("s2")){
1032                            allowedRoutes = "3,4";
1033                        }if(congRt.equals("s24")){
1034                            allowedRoutes = "5,6";
1035                        }if(congRt.equals("s37")){
1036                            allowedRoutes = "7,8";
1037                        }if(congRt.equals("s39")){
1038                            allowedRoutes = "9,10";
1039                        }if(congRt.equals("s43")){
1040                            allowedRoutes = "11,12";
1041                        }if(congRt.equals("s27")){
1042                            allowedRoutes = "13,14";
1043                        }if(congRt.equals("s10")){
1044                            allowedRoutes = "15,16";
1045                        }if(congRt.equals("s17")){
1046                            allowedRoutes = "17,18";
1047                        }if(congRt.equals("s31")){
1048                            allowedRoutes = "24,25";
1049                        }if(congRt.equals("s11")){
1050                            allowedRoutes = "26,27";
1051                        }
1052                        }
1053
1054                    Iterator routeIter = savedList.iterator();
1055                    while(routeIter!=null && routeIter.hasNext()){
1056                        ConcurrentHashMap innerHashMap = (ConcurrentHashMap) routeIter.next();
1057                        temp = innerHashMap;
1058                        Set tempSet = innerHashMap.entrySet();
1059                        if(tempSet!=null){
1060                            Iterator tempIter = tempSet.iterator();
1061                            if(tempIter!=null){
1062                                while(tempIter.hasNext()){
1063                                    Map.Entry routeEntry = (Entry) tempIter.next();
1064                                    ConcurrentHashMap tempHashMap = (ConcurrentHashMap) routeEntry.getKey();
1065                                    temp = tempHashMap;
1066                                        if(tempHashMap!=null){
1067                                            Set innerMostSet = tempHashMap.entrySet();
1068                                                if(innerMostSet!=null){
1069                                                    Iterator innerMostIterator = innerMostSet.iterator();
1070                                                    if(innerMostIterator!=null){
1071                                                        while(allowedRoutes!=null && innerMostIterator.hasNext()){
1072                                                            Map.Entry routeEntryInnermost = (Entry) innerMostIterator.next();
1073                                                                if(allowedRoutes.indexOf(routeEntryInnermost.getValue().toString())<=-1)
1074                                                                {
1075                                                                    
1076                                                                    tempHashMap.remove(routeEntryInnermost);
1077                                                                    entryRemoved = true;
1078                                                                    break;
1079                                                                }
1080                                                        }
1081
1082                                                    }
1083                                                }
1084                                        }
1085                                        if(entryRemoved){
1086                                            innerHashMap.remove(temp);
1087
1088                                            entryRemoved = false;
1089                                            savedList = new ArrayList();
1090                                        }
1091                                }
1092
1093                            }
1094                        }
1095                    }
1096                    }
1097                    return savedList;
1098                }
1099
1100
1101                private void selectRouteAllocation(ConcurrentHashMap rcdReqRouteHash, CommunicatingVehicles vehMaps) {
1102
1103                    ConcurrentHashMap finalAlloc = new ConcurrentHashMap();
1104                    double finalCost =0.0;
1105                    int cnt=0;
1106                    boolean routeEvaluationFlag = true;
1107                    if(rcdReqRouteHash!=null){
1108                    Set rcdRouteAllocHash = rcdReqRouteHash.entrySet();
1109                    if(rcdRouteAllocHash!=null){
1110                        Iterator routeIter = rcdRouteAllocHash.iterator();
1111                        while(routeIter!=null && routeIter.hasNext()){
1112                            Map.Entry routeEntry = (Entry) routeIter.next();
1113                            ConcurrentHashMap tempHashMap = (ConcurrentHashMap) routeEntry.getKey();
1114
1115                            if(routeChoice!=null && tempHashMap!=null){
1116                                if(routeChoice.size()!=tempHashMap.size()){
1117                                    finalAlloc = routeChoice;
1118                                    continue;
1119                                }
1120                            }
1121
1122                            double val = (Double) routeEntry.getValue();
1123                            if(cnt==0){
1124                                finalAlloc = tempHashMap;
1125                                finalCost = val;
1126                            }else{
1127                                if(val>finalCost){
1128                                    finalAlloc = tempHashMap;
1129                                    finalCost = val;
1130                                    routeEvaluationFlag = true;
1131                                }
1132                            }
1133
1134                            cnt++;
1135                            if(tempHashMap!=null && tempHashMap.size()==QueueManager.getMaxAgentCntRecorded(communicID)){
1136                                if(routeEvaluationFlag){
1137                                Set tempSet = finalAlloc.entrySet();
1138                                if(tempSet!=null){
1139                                    Iterator tempIter = tempSet.iterator();
1140                                    while(tempIter.hasNext()){
1141                                        Map.Entry tempEntry = (Entry) tempIter.next();
1142                                        if(tempEntry!=null){
1143                                            String tempKey = (String) tempEntry.getKey();
1144                                            String tempVal = (String) tempEntry.getValue();
1145
1146                                        }
1147                                    }
1148                                }
1149
1150                                }
1151                            }
1152                        }
1153                    }
1154                    }
1155
1156                    if(routeEvaluationFlag){
1157                        System.out.println(myAgent.getLocalName()+ " now invoking QM");
1158                        QueueManager.setRouteChoice(finalAlloc,communicID,vehMaps);
1159                    }else{
1160                        System.out.println(myAgent.getLocalName()+ " now invoking QM");
1161                        QueueManager.setRouteChoice(routeChoice,communicID,vehMaps);
1162                    }
1163                }
1164
1165                /**
1166                 * This method selects the best allocation for egalitarian welfare
1167                 * @param rcdReqRouteList list of all final allocaations
1168                 */
1169                private void selectListEgalitarianRouteAllocation(ArrayList rcdReqRouteList){
1170                    ConcurrentHashMap finalAlloc = new ConcurrentHashMap();
1171                    double finalCost =0.0;
1172                    int zeroCnt = 0;
1173                    int cnt=0;
1174                    double lowestUtility = 0.0;
1175                    boolean routeEvaluationFlag = true;
1176                    if(rcdReqRouteList!=null){
1177                        finalCost = DataAccess.getLowestUtility(routeChoice);
1178
1179                        Iterator routeIter = rcdReqRouteList.iterator();
1180                        while(routeIter!=null && routeIter.hasNext()){
1181                            ConcurrentHashMap innerHashMap = (ConcurrentHashMap) routeIter.next();
1182                            Set tempSet = innerHashMap.entrySet();
1183                            if(tempSet!=null){
1184                                Iterator tempIter = tempSet.iterator();
1185                                if(tempIter!=null){
1186                                    while(tempIter.hasNext()){
1187                                        Map.Entry routeEntry = (Entry) tempIter.next();
1188                                        ConcurrentHashMap tempHashMap = (ConcurrentHashMap) routeEntry.getKey();
1189                            if(routeChoice!=null && tempHashMap!=null){
1190                                if(tempHashMap.size()!=QueueManager.getMaxAgentCntRecorded(communicID)){
1191                                    finalAlloc = routeChoice;
1192                                    continue;
1193                                }
1194                            }
1195
1196                            double val = (Double) routeEntry.getValue();
1197
1198                            if(cnt==0){
1199                                finalAlloc = routeChoice;
1200                                finalCost = val;
1201                            }else{
1202                                if(val>finalCost){
1203                                    finalAlloc = tempHashMap;
1204                                    finalCost = val;
1205                                    routeEvaluationFlag = true;
1206                                }
1207                            }
1208
1209                            cnt++;
1210                            if(tempHashMap!=null && tempHashMap.size()==QueueManager.getMaxAgentCntRecorded(communicID)){
1211                                if(routeEvaluationFlag){
1212                
1213
1214                                }
1215                            }
1216
1217                        }
1218
1219                    }
1220                    }//temSet
1221                        }//if tempIter
1222                    }//tempIter has next
1223
1224                    QueueManager.setList(rcdReqRouteList);
1225                    if(!QueueManager.isSimNoticeFlag(vehMaps)){
1226                        if(rcdReqRouteList!=null){
1227                            if(onCongestedRoute!=null&& onCongestedRoute.equals(onCongRoute) && rcdReqRouteList.size()==getAgentCnt())
1228                        
1229                            {
1230                            if(routeEvaluationFlag){
1231                            QueueManager.setRouteChoice(finalAlloc,communicID,vehMaps);
1232                        }else{
1233                            QueueManager.setRouteChoice(routeChoice,communicID,vehMaps);
1234                        }
1235                        }
1236                    }
1237                    }
1238                }
1239
1240                /**
1241                 * This method selects the best route allocation for social welfare
1242                 * @param rcdReqRouteList list of final allocations
1243                 * @param vehMaps map of stored parameters
1244                 */
1245                private void selectListRouteAllocation(ArrayList rcdReqRouteList, CommunicatingVehicles vehMaps) {
1246                    ConcurrentHashMap finalAlloc = new ConcurrentHashMap();
1247                    double finalCost =0.0;
1248                    int cnt=0;
1249                    boolean routeEvaluationFlag = true;
1250                    if(rcdReqRouteList!=null){
1251                        Iterator routeIter = rcdReqRouteList.iterator();
1252                        while(routeIter!=null && routeIter.hasNext()){
1253                            ConcurrentHashMap innerHashMap = (ConcurrentHashMap) routeIter.next();
1254                            Set tempSet = innerHashMap.entrySet();
1255                            if(tempSet!=null){
1256                                Iterator tempIter = tempSet.iterator();
1257                                if(tempIter!=null){
1258                                    while(tempIter.hasNext()){
1259                                        Map.Entry routeEntry = (Entry) tempIter.next();
1260                                        ConcurrentHashMap tempHashMap = (ConcurrentHashMap) routeEntry.getKey();
1261                            if(routeChoice!=null && tempHashMap!=null){
1262                                if(routeChoice.size()!=tempHashMap.size()){
1263                                    finalAlloc = routeChoice;
1264                                    continue;
1265                                }
1266                            }
1267
1268                            double val = (Double) routeEntry.getValue();
1269                            if(cnt==0){
1270                                finalAlloc = tempHashMap;
1271                                finalCost = val;
1272                            }else{
1273                                if(val>finalCost){
1274                                    finalAlloc = tempHashMap;
1275                                    finalCost = val;
1276                                    routeEvaluationFlag = true;
1277                                }
1278                            }
1279
1280                            cnt++;
1281                            if(tempHashMap!=null && tempHashMap.size()==QueueManager.getMaxAgentCntRecorded(communicID)){
1282                                if(routeEvaluationFlag){
1283            
1284
1285                                }
1286                            }
1287                        }
1288
1289                    }
1290
1291
1292                    }//temSet
1293}//if tempIter
1294                    }//tempIter has next
1295                    QueueManager.setList(rcdReqRouteList);
1296                    if(!QueueManager.isSimNoticeFlag(vehMaps)){
1297
1298                        if(routeEvaluationFlag){
1299                            Set tempSet = finalAlloc.entrySet();
1300                            if(tempSet!=null){
1301                                Iterator tempIter = tempSet.iterator();
1302                                while(tempIter.hasNext()){
1303                                    Map.Entry tempEntry = (Entry) tempIter.next();
1304                                    if(tempEntry!=null){
1305                                        String tempKey = (String) tempEntry.getKey();
1306                                        String tempVal = (String) tempEntry.getValue();
1307                                        //System.out.println("Setting final choice.."+tempKey+" and val "+tempVal);
1308                                    }
1309                                }
1310                            }
1311                            finalAllocation = finalAlloc;
1312                            QueueManager.setRouteChoice(finalAlloc,communicID,vehMaps);
1313                        }else{
1314                            Set tempSet = routeChoice.entrySet();
1315                            if(tempSet!=null){
1316                                Iterator tempIter = tempSet.iterator();
1317                                while(tempIter.hasNext()){
1318                                    Map.Entry tempEntry = (Entry) tempIter.next();
1319                                    if(tempEntry!=null){
1320                                        String tempKey = (String) tempEntry.getKey();
1321                                        String tempVal = (String) tempEntry.getValue();
1322                                        //System.out.println("Setting route choice.."+tempKey+" and val "+tempVal);
1323                                    }
1324                                }
1325                            }
1326                            System.out.println(myAgent.getLocalName()+ " setting route");
1327                            QueueManager.setRouteChoice(routeChoice,communicID,vehMaps);
1328                        }
1329                    }
1330                }
1331
1332                private void addToSegMap(String srcVeh,String retSeg, int res) {
1333
1334                         DataAccess.addNotifPattern(myAgent.getLocalName(),retSeg,res);
1335                    //}
1336                }
1337
1338
1339
1340
1341                @Override
1342                public boolean done() {
1343                    // TODO Auto-generated method stub
1344                    return false;
1345                }
1346
1347
1348                /**
1349                 * This method registers the vehicle route information
1350                 * @param agentName Id of agent
1351                 * @param prefIndx map of preferences
1352                 * @param vehMaps map of vehicle parameters
1353                 * @param evalInfo route information map
1354                 */
1355                public synchronized void registerVehicleRouteInfo(String agentName, PreferenceUtilityIndex prefIndx,CommunicatingVehicles vehMaps,EvaluateRouteInfo evalInfo) {
1356                    String agentPrefKey;
1357                   PreferenceUtilityIndex preferenceIndxVal = null;
1358
1359                    if(regVInfo!=null){
1360                    regVInfoCpy = new ConcurrentHashMap(regVInfo);
1361                    Set entries = regVInfo.entrySet();
1362                    boolean entryFound = true;
1363            //      synchronized(entries){
1364                        if(entries!=null && !entries.isEmpty()){
1365                            for(Iterator it = entries.iterator(); it.hasNext();) {
1366                                Map.Entry entry = (Entry) it.next();
1367                                agentPrefKey =  (String) entry.getKey();
1368
1369                                 if(agentPrefKey.equals(agentName)){
1370                                     regVInfoCpy.remove(agentName);
1371                                 }
1372                            }
1373
1374                                 regVInfoCpy.put(agentName, prefIndx);
1375
1376                        }else{
1377
1378                        regVInfoCpy.put(agentName, prefIndx);
1379                        }
1380                        regVInfo = new ConcurrentHashMap(regVInfoCpy);
1381                        readyToEval = QueueManager.getRouteChoiceNegAgent(myAgent.getLocalName(),regVInfoCpy,communicID,sellerAgents.length);
1382                        DataAccess.setRegisteredVehicleInfo(regVInfo);
1383                        if(onCongestedRoute!=null && (onCongestedRoute.equals("s1") || onCongestedRoute.equals("s2") || onCongestedRoute.equals("s24") || onCongestedRoute.equals("s37") || onCongestedRoute.equals("s39") || onCongestedRoute.equals("s43") || onCongestedRoute.equals("s27") || onCongestedRoute.equals("s10") || onCongestedRoute.equals("s17") || onCongestedRoute.equals("s31")|| onCongestedRoute.equals("s11"))){
1384                            readyToEval = true;
1385                        }
1386
1387                        if(readyToEval && !junctionReached){
1388
1389
1390                                evaluateRoutes(vehMaps);
1391                        //  }
1392                        //assignRandomRoutes();
1393                        }
1394
1395                //  }
1396                    }
1397                }
1398
1399
1400                /**
1401                 * This method is used for route evaluation
1402                 * @param vehMaps map of vehicle parameters
1403                 */
1404
1405                public synchronized void evaluateRoutes(CommunicatingVehicles vehMaps)
1406                {
1407                    Object assgnRt = null;
1408                    String rc=null;
1409                    if(xCoordinatesOfEdge.equals("0.0") && yCoordinatesOfEdge.equals("120.0")){
1410                        if(myAgent.getLocalName().equals("#5")){
1411                        //System.out.println("Str:"+communicID+ " xCoordinatesOfEdge:"+xCoordinatesOfEdge+" yCoordinatesOfEdge:"+yCoordinatesOfEdge+" agent: "+myAgent.getLocalName());
1412                        }
1413                    }
1414
1415
1416                    if(congSegID!=null && congSegID.equals("s2")){
1417//                      System.out.println("compeare");
1418                    }
1419
1420                    vehMaps = (CommunicatingVehicles) QueueManager.getCVMaps(communicID);
1421                    if(vehMaps==null){
1422                        vehMaps = new CommunicatingVehicles(communicID);
1423                        sendRouteHash = new ConcurrentHashMap();
1424                    }
1425
1426
1427                    QueueManager.setCVMaps(communicID, vehMaps);
1428                    prefIndex = DataAccess.getPreferenceUtilityIndex(myAgent.getLocalName(), communicID,preferenceMultiplier,costMultiplier,onCongestedRoute,yCoordinatesOfEdge,vehMaps);
1429
1430                    int lenSellerAgents=0;
1431                    if(onCongestedRoute!=null && onCongestedRoute.equals(congSegID)){
1432                        lenSellerAgents=getAgentCnt();//Constants.VEHICLESEED;
1433                    }/*else if(onCongestedRoute!=null && onCongestedRoute.equals("s11")){
1434                        lenSellerAgents=7;
1435                    }else if(onCongestedRoute!=null && onCongestedRoute.equals("s34")){
1436                        lenSellerAgents=2;
1437                    }else if(onCongestedRoute!=null && onCongestedRoute.equals("s10")){
1438                        lenSellerAgents=3;
1439                    }
1440                    */
1441
1442            //      System.out.println("in evaluateRoutes: "+onCongestedRoute+" my name is: "+myAgent.getLocalName());
1443                    
1444
1445                    if(sellerAgents.length+1 >= lenSellerAgents){
1446            //      if(onCongestedRoute!=null && onCongestedRoute.equals("s27")){
1447                //      if(routeChoice!=null && routeChoice.size()==27){
1448//                          System.out.println("rank routes: "+myAgent.getLocalName());
1449                //      }
1450            //      }
1451
1452                    routeChoice = DataAccess.rankTheRoutesAndAssignAgents(prefIndex,communicID);
1453
1454                    //routeChoice
1455                    if(routeChoice!=null && routeChoice.size()==26 && myAgent.getLocalName().equals("#38")){
1456                        Set routeRankSetOther = routeChoice.entrySet();
1457                        Iterator secIterOther = routeRankSetOther.iterator();
1458                        while(secIterOther!=null && secIterOther.hasNext()){
1459                            Map.Entry subEntry = (Entry)secIterOther.next();
1460                            String key = (String) subEntry.getKey();
1461                            String val = (String) subEntry.getValue();
1462                            System.out.println("Initially : "+key + " and val: "+val);
1463                        }
1464                    }
1465                    //routeChoice
1466
1467
1468                    if(routeChoice!=null){
1469                        if(QueueManager.checkIfEvalRouteInfoIsValid(myAgent.getLocalName(), onCongestedRoute, routeChoice, vehMaps )){
1470                        //  System.out.println("evaluated and returned for : "+myAgent.getLocalName());
1471                        //commented on 14/3/2013    if(/*QueueManager.recordSize()*/savedList!=null && savedList.size()==getAgentCnt()){
1472                                allocFlag=true;
1473                            //commented on 14/3/2013}
1474                                //commented on 14/3/2013    return;
1475                        }
1476                    }
1477                    if(routeChoice!=null){
1478
1479                    systemOptimalCost = QueueManager.evaluateCost(routeChoice,null);
1480                    maxCost = systemOptimalCost;
1481                    minCost = systemOptimalCost;
1482                    normalisedSystemOptimalCost=0.0;
1483
1484                    degreeOfUserSatisfaction  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoice,null);
1485                    maxPref=degreeOfUserSatisfaction;
1486                    minPref=degreeOfUserSatisfaction;
1487                    normalisedSystemOptimalPreference=0.0;
1488
1489                    totalNormalisedCost = preferenceMultiplier*normalisedSystemOptimalPreference-costMultiplier*normalisedSystemOptimalCost;
1490                    if(preferenceMultiplier==0){
1491                        totalNormalisedCost = -normalisedSystemOptimalCost;
1492                    }else if(costMultiplier==0){
1493                        totalNormalisedCost = normalisedSystemOptimalPreference;
1494                    }
1495                    /*if(preferenceMultiplier==0 && totalCost==0.0){
1496                        totalNormalisedCost=Double.NEGATIVE_INFINITY;
1497                    }*/
1498                //  System.out.println("TOTAL COST OF INITIAL SOLUTION (social/mixed): "+totalNormalisedCost+" for route size : "+routeChoice.size());
1499
1500
1501                    assgnRt = routeChoice.get(myAgent.getLocalName());
1502                    if(myAgent.getLocalName().equals("#1") && assgnRt==null){
1503
1504
1505                        rc="18";
1506                    }else{
1507                        try{
1508
1509                        if(routeChoice.get(myAgent.getLocalName())==null){
1510                            //System.out.println("null");
1511                            routeChoice = DataAccess.rankTheRoutesAndAssignAgents(prefIndex,communicID);
1512                        }
1513                        rc = routeChoice.get(myAgent.getLocalName()).toString();
1514                        }catch(NullPointerException e){
1515                            //System.out.println("NPE "+myAgent.getLocalName());
1516                        }
1517                    }
1518
1519                    Random rand = new Random();
1520                    int randInt = 0;
1521                    int randomAgent = 0;
1522                    Set randomSet = new HashSet();
1523                    Set randomSetAgents = new HashSet();
1524                    /*if(preferenceMultiplier==0){
1525
1526                        randomSet.add(Constants.ADD);
1527                        randomSet.add(Constants.DROP);
1528                    }else{*/
1529                        randomSet.add(Constants.ADD);
1530                        randomSet.add(Constants.DROP);
1531                        randomSet.add(Constants.SWAP);
1532                    //  randomSet.add(Constants.MULTIAGENTDEAL);
1533                    //}
1534
1535                        if(routeChoice!=null && routeChoice.size()==20){
1536
1537//                          System.out.println("checking deals");
1538
1539                        }
1540                        
1541                    //  if(routeChoice!=null&& routeChoice.size())
1542
1543                    for(rd=0;rd<20;rd++){
1544
1545
1546                    randomAgent =rand.nextInt(20-0)+0;
1547
1548                    randInt = rand.nextInt(4-0)+0;
1549
1550                        Object obj = randomSet.toArray()[rand.nextInt(randomSet.size())];
1551                        if(obj!=null){
1552                        randInt = Integer.parseInt(obj.toString());
1553                        }
1554
1555                        if(routeChoice!=null && routeChoice.size()==20){
1556            //              System.out.println("randInt: "+randInt+" by: "+myAgent.getLocalName());
1557                        }
1558                        if(congSegID!=null /*&& !(congSegID.equals("s2") ||congSegID.equals("s24")*/ /*|| congSegID.equals("s37") || congSegID.equals("s43") *//*|| congSegID.equals("s27")|| congSegID.equals("s17")|| congSegID.equals("s31")*//*|| congSegID.equals("s39"))*/){
1559                    routeChoice = negotiateRoutesForSocialWelfare(routeChoice, 0, myAgent.getLocalName(),vehMaps);/*negotiateRoutes(routeChoice,randInt,typeOfWelfare);*/
1560                        }
1561                        
1562                        QueueManager.setMaxAgentCntRecorded(sellerAgents.length+1,communicID);
1563                        allocFlag = true;
1564
1565                        if(routeChoice!=null && routeChoice.size()==30){
1566                            if(rd==9 && myAgent.getLocalName().equals("#5")){
1567        //                      System.out.println("end of it..."+myAgent.getLocalName());
1568                            }
1569                        }
1570                        preRandomInteger = randInt;
1571
1572                    }
1573
1574
1575
1576
1577                        }//rtChoice is not null
1578                    }
1579                /*  if(myAgent.getLocalName().equals("#3") && routeChoice!=null){
1580                        System.out.println("Rt chc size .. evaluateRoutes"+routeChoice.size()+ " onCongested- "+onCongestedRoute);
1581                    }*/
1582                if(vehMaps!=null && routeChoice!=null && routeChoice.size()==getAgentCnt()){
1583                    QueueManager.checkIfEvalRouteInfoIsValid(myAgent.getLocalName(), onCongestedRoute, routeChoice, vehMaps);
1584                }
1585
1586                }
1587
1588
1589                /**
1590                 * This method executes virtual deal negotiation for social welfare 
1591                 * @param routeChoice map of route choice
1592                 * @param dealType type of deal
1593                 * @param agentID agent ID
1594                 * @param vehMaps map of vehicle parameters
1595                 * @return final allocation map
1596                 */
1597                private ConcurrentHashMap negotiateRoutesForSocialWelfare(ConcurrentHashMap routeChoice,int dealType, String agentID, CommunicatingVehicles vehMaps){
1598
1599                    //System.out.println("Comparing social welfare b4....for "+myAgent.getLocalName()+"......"+totalCost);
1600                    if(routeChoice!=null && routeChoice.size()==40){
1601                        System.out.println("compeare");
1602                    }
1603
1604
1605                    double cost = 0.0,degree=0.7,tCostAfterNeg=0.0;
1606                    boolean searchBetterDeals = true;
1607                    ConcurrentHashMap routeChoiceCopy=null;
1608                    String assignedRoute="";
1609                    if(routeChoice!=null){
1610                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
1611                    ConcurrentHashMap finalRouteChoiceCopy = null;//new ConcurrentHashMap(routeChoice);
1612                    assignedRoute = (String) routeChoiceCopy.get(myAgent.getLocalName());
1613
1614
1615                    if(routeChoice==null)
1616                    {
1617                        //System.out.println("k cost");
1618                    }else{
1619                        if(routeChoice!=null && routeChoice.size()==30){
1620                    //      System.out.println("rt choice");
1621                        }
1622                    Map rankedRouteMap = DataAccess.getRoutesInOrderForDROP(vehMaps);
1623
1624                    if(onCongestedRoute!=null && onCongestedRoute.equals("s11")){
1625                        if(rankedRouteMap!=null && rankedRouteMap.get("8")!=null){
1626                        System.out.println("routes for drop");
1627                        }
1628                    }
1629                    if(dealType==Constants.SWAP && assignedRoute!=null){
1630                        int equalVal=0;
1631                    if(routeChoice!=null){
1632                        if(routeChoice.size()!=Constants.VEHICLESEED)
1633                        {
1634                            agentID= myAgent.getLocalName();
1635                        }
1636                        Set allRoutes = routeChoice.entrySet();
1637                        if(allRoutes!=null){
1638                            Iterator iter = allRoutes.iterator();
1639                            if(iter!=null){
1640                                while(iter.hasNext()){
1641                                    assignedRoute = (String) routeChoiceCopy.get(myAgent.getLocalName());
1642                                    Map.Entry entry = (Entry) iter.next();
1643                                    String vehicle =  (String) entry.getKey();
1644                                    String route =  (String) entry.getValue();
1645                                    if(route!=null && route.indexOf(assignedRoute)<=-1){
1646                                    degree=0.7;
1647                                    replaced=false;
1648
1649                                    routeChoiceCopy.put(vehicle, assignedRoute);
1650                                    routeChoiceCopy.put(myAgent.getLocalName(), route);
1651                                    cost = QueueManager.evaluateCost(routeChoiceCopy,null);
1652                                    if(cost==0.0){
1653                                        routeChoiceCopy = new ConcurrentHashMap(routeChoice);
1654                                        continue;
1655                                    }else{
1656                                        degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,null);
1657                                    }
1658
1659                                    if(routeChoice!=null && routeChoice.size()>=20){
1660                                        if((myAgent.getLocalName().equals("#15")||myAgent.getLocalName().equals("#10")||myAgent.getLocalName().equals("#11")||myAgent.getLocalName().equals("#12")||myAgent.getLocalName().equals("#13")||myAgent.getLocalName().equals("#14"))){
1661                                            if(vehicle.equalsIgnoreCase("#0")){
1662                                            if(degree>maxPref){
1663                                                System.out.println("degree : "+degree+ " and degreeOfUserSatisfaction : "+degreeOfUserSatisfaction+ " by : "+ myAgent.getLocalName());
1664                                            }
1665                                            }
1666                                        }
1667                                    }
1668
1669                                    if(rd==0){
1670                                        rd++;
1671
1672                                        if(preferenceMultiplier==1 &&costMultiplier==0){
1673                                            tCostAfterNeg = degree;
1674                                            if(degree>degreeOfUserSatisfaction && equalVal==0){
1675                                                equalVal++;
1676                                                degreeOfUserSatisfaction = degree;
1677                                                replaced=true;
1678                                            }
1679                                        }else if(preferenceMultiplier==0 &&costMultiplier==1){
1680
1681                                            tCostAfterNeg=-cost;
1682                                            if(cost>=systemOptimalCost && equalVal==0){
1683                                                equalVal++;
1684                                                systemOptimalCost = cost;
1685                                                replaced=true;
1686
1687                                            }
1688                                        }
1689                                        if(cost>=maxCost){
1690                                            maxCost = cost;
1691                                            
1692                                        }
1693                                        if(cost<=minCost){
1694                                            minCost = cost;
1695                                        }
1696                                        if(degree>maxPref){
1697                                            maxPref = degree;
1698                                            replaced=true;
1699                                        }
1700                                        if(degree<minPref){
1701                                            minPref = degree;
1702                                        }
1703                                        if(preferenceMultiplier==1 && costMultiplier==1){
1704                                            numCost = (cost-minCost);
1705                                            denoCost = (maxCost-minCost);
1706
1707                                            numPref=degree-minPref;
1708                                            denoPref=(maxPref-minPref);
1709
1710                                            tCostAfterNeg = preferenceMultiplier*normalisedPrefAfterNeg-costMultiplier*normalisedCostAfterNeg;
1711
1712                                            if(tCostAfterNeg>0){
1713                                                systemOptimalCost = cost;
1714                                                degreeOfUserSatisfaction = degree;
1715                                                replaced=true;
1716                                                equalVal++;
1717                                            }
1718                                        }// p and c are 1
1719                                    }
1720                                    else{
1721                                        rd++;
1722                                        if(cost>maxCost && equalVal==0){
1723                                            equalVal++;
1724                                            maxCost = cost;
1725                                            replaced=true;
1726                                        }
1727                                        if(cost<=minCost && equalVal==0){
1728                                            equalVal++;
1729                                            minCost = cost;
1730                                            //replaced=true;
1731                                        }
1732                                        if(degree>maxPref){
1733                                            maxPref = degree;
1734                                            replaced=true;
1735                                        }
1736                                        if(degree<minPref){
1737                                            minPref = degree;
1738                                        }
1739                                        numCost = (cost-minCost);
1740                                        denoCost = (maxCost-minCost);
1741
1742                                        numPref=degree-minPref;
1743                                        denoPref=(maxPref-minPref);
1744
1745                                        if(costMultiplier==1 && preferenceMultiplier==1){
1746                                            normalisedCostAfterNeg = numCost/denoCost;
1747                                            normalisedPrefAfterNeg = numPref/denoPref;
1748                                            tCostAfterNeg = preferenceMultiplier*normalisedPrefAfterNeg-costMultiplier*normalisedCostAfterNeg;
1749                                        }else if(costMultiplier==0 && preferenceMultiplier==1){
1750                                                normalisedPrefAfterNeg = numPref/denoPref;
1751                                                tCostAfterNeg = preferenceMultiplier*normalisedPrefAfterNeg;
1752                                        }else{
1753                                                normalisedCostAfterNeg = numCost/denoCost;
1754                                                normalisedPrefAfterNeg = numPref/denoPref;
1755                                                tCostAfterNeg = -costMultiplier*normalisedCostAfterNeg;
1756                                        }
1757
1758                                        
1759                                        if(tCostAfterNeg==0.0){
1760                                            if(preferenceMultiplier==1 && costMultiplier==1){
1761                                                //If the normalised utility of second iteration is also zero, compare the actual value of preference utility index and cost
1762                                                if(cost<systemOptimalCost && degree>degreeOfUserSatisfaction){
1763                                                    totalNormalisedCost=tCostAfterNeg;
1764                                                    systemOptimalCost = cost;
1765                                                    degreeOfUserSatisfaction = degree;
1766                                                    replaced=true;
1767                                                }
1768                                            }// p and c are 1
1769                                            else if(preferenceMultiplier==1 &&costMultiplier==0){
1770                                                /*If the normalised preference utility index of second iteration is also zero, compare the actual value of preference utility index*/
1771                                                if(degree>degreeOfUserSatisfaction){
1772                                                    if(equalVal==0 || replaced){
1773                                                        equalVal++;
1774                                                    totalNormalisedCost=tCostAfterNeg;
1775                                                    degreeOfUserSatisfaction = degree;
1776                                                    replaced=true;
1777                                                    }else
1778                                                    {
1779                                                        replaced=false;
1780                                                    }
1781                                                }
1782                                        }else if(preferenceMultiplier==0 &&costMultiplier==1){
1783
1784                                            /*If the normalised cost of second iteration is also zero, compare the actual value of cost*/
1785                                            if(cost<=systemOptimalCost){
1786                                                    if(equalVal==0 || replaced){
1787                                                    equalVal++;
1788                                                    totalNormalisedCost=tCostAfterNeg;
1789                                                    systemOptimalCost = cost;
1790                                                    replaced=true;
1791                                                    }else
1792                                                    {
1793                                                        replaced=false;
1794                                                    }
1795                                                }
1796                                            }
1797                                        }else{
1798                                                if(tCostAfterNeg>=totalNormalisedCost && equalVal==0){
1799                                                    equalVal++;
1800                                                    if(routeChoice!=null && routeChoice.size()==40 && myAgent.getLocalName().equals("#38")){
1801                                                
1802                                                    }
1803                                                    totalNormalisedCost=tCostAfterNeg;
1804                                                    systemOptimalCost = cost;
1805                                                    degreeOfUserSatisfaction = degree;
1806                                                    replaced=true;
1807
1808                                                    normalisedSystemOptimalCost = normalisedCostAfterNeg;
1809                                                    normalisedSystemOptimalPreference = normalisedPrefAfterNeg;
1810                                                }else{
1811                                                    
1812                                                    
1813                                                    if(costMultiplier!=0 && preferenceMultiplier!=0){
1814                                                        if(!replaced){
1815                                                            if(routeChoice!=null && routeChoice.size()>=20){
1816                                                                if((myAgent.getLocalName().equals("#15")||myAgent.getLocalName().equals("#10")||myAgent.getLocalName().equals("#11")||myAgent.getLocalName().equals("#12")||myAgent.getLocalName().equals("#13")||myAgent.getLocalName().equals("#14"))){
1817                                                                    if(vehicle.equalsIgnoreCase("#0")){
1818                                                                    if(degree>maxPref){
1819                                                                        System.out.println("! replaced degree : "+degree+ " and degreeOfUserSatisfaction : "+degreeOfUserSatisfaction+ " by : "+ myAgent.getLocalName());
1820                                                                    }
1821                                                                    }
1822                                                                }
1823                                                            }
1824                                                            replaced=false;/// = null;
1825                                                            routeChoiceCopy = null;
1826                                                            routeChoiceCopy = new ConcurrentHashMap(routeChoice);   
1827                                                        }
1828                                                        else{
1829                                                    
1830                                                        }
1831                                                    }
1832                                                }
1833
1834                                        }//tCostAfterNeg!=0
1835
1836                                        }
1837
1838                                    }//if-else loop
1839                                    if(!replaced){/// = null;
1840                                        routeChoiceCopy = null;
1841                                        routeChoiceCopy = new ConcurrentHashMap(routeChoice);
1842                                    }else{
1843                                        if(routeChoice!=null && routeChoice.size()==40){
1844//                                          System.out.println("route choice for myAgent : "+ myAgent.getLocalName()+ " is: "+routeChoice.get(myAgent.getLocalName()));
1845    //                                      System.out.println("route choice for myAgent : "+ myAgent.getLocalName()+ " is: "+routeChoiceCopy.get(myAgent.getLocalName()));
1846                                            double tempDegree = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoice, null);
1847                                            double tempDegree1 = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy, null);
1848                                        }
1849                                        routeChoice=null;
1850                                        routeChoice = new ConcurrentHashMap(routeChoiceCopy);
1851                                    }
1852                                }
1853                                 }//else loop rd>0
1854                                }
1855
1856                            } //routeChoice!=null
1857                        } //if SWAP deal
1858
1859                    else if(dealType == Constants.ADD){
1860
1861                        if(routeChoice!=null && routeChoice.size()==20){
1862                    //      if(assignedRoute!=null && assignedRoute.equals("4")){
1863//                          System.out.println("checking deals");
1864                    //      }
1865                        }
1866
1867
1868
1869
1870                        if(rankedRouteMap!=null){
1871                            Set rankSet = rankedRouteMap.entrySet();
1872                            Iterator rankIter = rankSet.iterator();
1873                            if(rankIter!=null){
1874                                while(rankIter.hasNext()){
1875                                    Map.Entry subEntry =(Entry) rankIter.next();
1876                                    if(subEntry!=null){
1877                                        degree=0.0;
1878                                        replaced=false;
1879                                        double normalisedCostCost = 0.0;
1880                                        String routeInOrder = (String) subEntry.getKey();
1881
1882                                        if(assignedRoute!=null && assignedRoute.equals("8"))
1883                                        {
1884                                            if(routeInOrder!=null && routeInOrder.equals("7")){
1885                                                agentID= myAgent.getLocalName();
1886                                            }
1887                                        }
1888
1889
1890                                        routeChoiceCopy.put(agentID, routeInOrder);
1891                                        cost = QueueManager.evaluateCost(routeChoiceCopy,null);
1892
1893
1894                                        if(cost==0.0){
1895                                            routeChoiceCopy = new ConcurrentHashMap(routeChoice);
1896                                            continue;
1897                                        }else{
1898                                            degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,null);
1899                                        //  System.out.println("Degree for : "+routeInOrder+ " for agent : "+myAgent.getLocalName()+ " is ="+degree);
1900                                        }
1901
1902                                        if(agentID.equals("#1") && assignedRoute!=null && routeInOrder!=null){
1903                                            if(assignedRoute.equals("1") && routeInOrder.equals("2")){
1904                                                if(routeChoice.size()==40){
1905                                                    System.out.println("new route");
1906                                                }
1907                                            }
1908                                        }
1909
1910                                        if(rd==0){
1911                                            rd++;
1912
1913                                            if(preferenceMultiplier==1 &&costMultiplier==0){
1914                                                tCostAfterNeg = degree;
1915                                                if(degree>degreeOfUserSatisfaction){
1916                                                    degreeOfUserSatisfaction = degree;
1917                                                    replaced=true;
1918                                                }
1919                                            }else if(preferenceMultiplier==0 &&costMultiplier==1){
1920
1921                                                tCostAfterNeg=-cost;
1922                                                if(cost<systemOptimalCost){
1923                                                    systemOptimalCost = cost;
1924                                                    replaced=true;
1925                                            //      System.out.println("DEAL!!");
1926                                                }
1927                                            }
1928                                            if(cost>=maxCost){
1929                                                maxCost = cost;
1930                                                replaced=true;
1931                                            }
1932                                            if(cost<=minCost){
1933                                                minCost = cost;
1934                                            }
1935                                            if(degree>maxPref){
1936                                                maxPref = degree;
1937                                                replaced=true;
1938                                            }
1939                                            if(degree<minPref){
1940                                                minPref = degree;
1941                                            }
1942                                            if(preferenceMultiplier==1 && costMultiplier==1){
1943                                                numCost = (cost-minCost);
1944                                                denoCost = (maxCost-minCost);
1945
1946                                                numPref=degree-minPref;
1947                                                denoPref=(maxPref-minPref);
1948
1949                                                normalisedCostAfterNeg = numCost/denoCost;
1950                                                normalisedPrefAfterNeg = numPref/denoPref;
1951
1952
1953                                                tCostAfterNeg = preferenceMultiplier*normalisedPrefAfterNeg-costMultiplier*normalisedCostAfterNeg;
1954
1955                                                if(tCostAfterNeg>0){
1956                                                    systemOptimalCost = normalisedCostAfterNeg;
1957                                                    degreeOfUserSatisfaction = normalisedPrefAfterNeg;
1958                                                    replaced=true;
1959                                                }
1960                                            }// p and c are 1
1961                                        }
1962                                        else{
1963                                            rd++;
1964                                            if(cost>maxCost){
1965                                                maxCost = cost;
1966                                                replaced=true;
1967                                            }
1968                                            if(cost<minCost){
1969                                                minCost = cost;
1970                                            //  replaced=true;
1971                                            }
1972                                            if(degree>maxPref){
1973                                                maxPref = degree;
1974                                                replaced=true;
1975                                            }
1976                                            if(degree<minPref){
1977                                                minPref = degree;
1978                                            }
1979                                            numCost = (cost-minCost);
1980                                            denoCost = (maxCost-minCost);
1981
1982                                            numPref=degree-minPref;
1983                                            denoPref=(maxPref-minPref);
1984
1985                                            if(costMultiplier==1 && preferenceMultiplier==1){
1986                                                normalisedCostAfterNeg = numCost/denoCost;
1987                                                normalisedPrefAfterNeg = numPref/denoPref;
1988                                                tCostAfterNeg = preferenceMultiplier*normalisedPrefAfterNeg-costMultiplier*normalisedCostAfterNeg;
1989                                            }else if(costMultiplier==0 && preferenceMultiplier==1){
1990                                                    normalisedPrefAfterNeg = numPref/denoPref;
1991                                                    tCostAfterNeg = preferenceMultiplier*normalisedPrefAfterNeg;
1992                                            }else{
1993                                                    normalisedCostAfterNeg = numCost/denoCost;
1994                                                    normalisedPrefAfterNeg = numPref/denoPref;
1995                                                    tCostAfterNeg = -costMultiplier*normalisedCostAfterNeg;
1996                                            }
1997
1998                                            if(tCostAfterNeg>1){
1999//                                              System.out.println("how is it possible?");
2000                                            }
2001
2002                                            if(tCostAfterNeg==0.0){
2003                                                if(preferenceMultiplier==1 && costMultiplier==1){
2004                                                    /*If the normalised utility of second iteration is also zero, compare the actual value of preference utility index and cost*/
2005                                                    if(cost<systemOptimalCost && degree>degreeOfUserSatisfaction){
2006                                                        totalNormalisedCost=tCostAfterNeg;
2007                                                        systemOptimalCost = cost;
2008                                                        degreeOfUserSatisfaction = degree;
2009                                                        replaced=true;
2010                                                    }
2011                                                }// p and c are 1
2012                                                else if(preferenceMultiplier==1 &&costMultiplier==0){
2013                                                    /*If the normalised preference utility index of second iteration is also zero, compare the actual value of preference utility index*/
2014                                                    if(degree>degreeOfUserSatisfaction){
2015                                                        totalNormalisedCost=tCostAfterNeg;
2016                                                        degreeOfUserSatisfaction = degree;
2017                                                        replaced=true;
2018                                                    }
2019                                                }else if(preferenceMultiplier==0 &&costMultiplier==1){
2020
2021                                                /*If the normalised cost of second iteration is also zero, compare the actual value of cost*/
2022                                                    if(cost<=systemOptimalCost){
2023                                                        totalNormalisedCost=tCostAfterNeg;
2024                                                        systemOptimalCost = cost;
2025                                                        replaced=true;
2026                                                    }
2027                                                }
2028                                            }else{
2029                                                    if(tCostAfterNeg>=totalNormalisedCost){
2030                                                
2031                                                        totalNormalisedCost=tCostAfterNeg;
2032                                                        systemOptimalCost = cost;
2033                                                        degreeOfUserSatisfaction = degree;
2034                                                        replaced=true;
2035
2036                                                        normalisedSystemOptimalCost = normalisedCostAfterNeg;
2037                                                        normalisedSystemOptimalPreference = normalisedPrefAfterNeg;
2038                                                    }else{
2039                                                        replaced=false;/// = null;
2040                                                        routeChoiceCopy = null;
2041                                                        routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2042                                                    }
2043
2044                                            }//tCostAfterNeg!=0
2045
2046                                            }
2047                                    }// not null subEntry
2048                                    if(!replaced){/// = null;
2049                                        routeChoiceCopy = null;
2050                                        routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2051                                    }else{
2052                                        if(routeChoice!=null && routeChoice.size()==40){
2053//                                          System.out.println("route choice for myAgent : "+ myAgent.getLocalName()+ " is: "+routeChoice.get(myAgent.getLocalName()));
2054    //                                      System.out.println("route choice for myAgent : "+ myAgent.getLocalName()+ " is: "+routeChoiceCopy.get(myAgent.getLocalName()));
2055                                        }
2056                                        double tempDegree = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoice, null);
2057                                        double tempDegree1 = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy, null);
2058                                        routeChoice=null;
2059                                        routeChoice = new ConcurrentHashMap(routeChoiceCopy);
2060                                    }
2061                                } //while iter hasNext
2062
2063                            } //rankIter!=null
2064                        } //if rankedRouteMap is not null
2065                    }//else ipe == ADD
2066                    else if(dealType == Constants.DROP){
2067                        if(routeChoice.size()!=Constants.VEHICLESEED)
2068                        {
2069                            agentID= myAgent.getLocalName();
2070                        }
2071
2072                        if(routeChoice!=null){
2073                            Set allRoutes = routeChoice.entrySet();
2074                            if(allRoutes!=null){
2075                                Iterator iter = allRoutes.iterator();
2076                                if(iter!=null){
2077                                    while(iter.hasNext()){
2078                                        degree=0.0;
2079
2080                                        replaced=false;
2081                                        double normalisedCostCost = 0.0;
2082                                        Map.Entry entry = (Entry) iter.next();
2083                                        String vehicle =  (String) entry.getKey();
2084                                        String route =  (String) entry.getValue();
2085
2086
2087                                        if(route!=null){
2088                                        if(rankedRouteMap!=null){
2089                                            Set rankSet = rankedRouteMap.entrySet();
2090                                            Iterator rankIter = rankSet.iterator();
2091                                            if(rankIter!=null){
2092                                                while(rankIter.hasNext()){
2093                                                    Map.Entry subEntry =(Entry) rankIter.next();
2094                                                    if(subEntry!=null){
2095                                                        String routeInOrder = (String) subEntry.getKey();
2096                                                        if(routeInOrder!=null /*&& !routeInOrder.equals(route)*/){
2097                                                            routeChoiceCopy.put(vehicle, routeInOrder);
2098                                                            routeChoiceCopy.put(agentID, route);
2099                                                            cost = QueueManager.evaluateCost(routeChoiceCopy,null);
2100                                                            if(cost==0.0){
2101                                                                routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2102                                                                continue;
2103                                                            }else{
2104                                                                degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,null);
2105                                                            }
2106
2107
2108                                                            if(rd==0){
2109                                                                rd++;
2110
2111                                                                if(preferenceMultiplier==1 &&costMultiplier==0){
2112                                                                    tCostAfterNeg = degree;
2113                                                                    if(degree>degreeOfUserSatisfaction){
2114                                                                        degreeOfUserSatisfaction = degree;
2115                                                                        replaced=true;
2116                                                                    }
2117                                                                }else if(preferenceMultiplier==0 &&costMultiplier==1){
2118
2119                                                                    tCostAfterNeg=-cost;
2120                                                                    if(cost>systemOptimalCost){
2121                                                                        systemOptimalCost = cost;
2122                                                                        replaced=true;
2123
2124                                                                    }
2125                                                                }
2126                                                                if(cost>=maxCost){
2127                                                                    maxCost = cost;
2128                                                                    replaced=true;
2129                                                                }
2130                                                                if(cost<minCost){
2131                                                                    minCost = cost;
2132                                                                }
2133                                                                if(degree>maxPref){
2134                                                                    maxPref = degree;
2135                                                                    replaced=true;
2136                                                                }
2137                                                                if(degree<minPref){
2138                                                                    minPref = degree;
2139                                                                }
2140                                                                if(preferenceMultiplier==1 && costMultiplier==1){
2141                                                                    numCost = (cost-minCost);
2142                                                                    denoCost = (maxCost-minCost);
2143
2144                                                                    numPref=degree-minPref;
2145                                                                    denoPref=(maxPref-minPref);
2146
2147                                                                    tCostAfterNeg = preferenceMultiplier*normalisedPrefAfterNeg-costMultiplier*normalisedCostAfterNeg;
2148
2149                                                                    if(tCostAfterNeg>0){
2150                                                                        systemOptimalCost = cost;
2151                                                                        degreeOfUserSatisfaction = degree;
2152                                                                        replaced=true;
2153                                                                    }
2154                                                                }// p and c are 1
2155                                                            }
2156                                                            else{
2157                                                                rd++;
2158                                                                if(cost>maxCost){
2159                                                                    maxCost = cost;
2160                                                                }
2161                                                                if(cost<minCost){
2162                                                                    minCost = cost;
2163                                                                    replaced=true;
2164                                                                }
2165                                                                if(degree>maxPref){
2166                                                                    maxPref = degree;
2167                                                                }
2168                                                                if(degree<minPref){
2169                                                                    minPref = degree;
2170                                                                }
2171                                                                numCost = (cost-minCost);
2172                                                                denoCost = (maxCost-minCost);
2173
2174                                                                numPref=degree-minPref;
2175                                                                denoPref=(maxPref-minPref);
2176
2177                                                                if(costMultiplier==1 && preferenceMultiplier==1){
2178                                                                    normalisedCostAfterNeg = numCost/denoCost;
2179                                                                    normalisedPrefAfterNeg = numPref/denoPref;
2180                                                                    tCostAfterNeg = preferenceMultiplier*normalisedPrefAfterNeg-costMultiplier*normalisedCostAfterNeg;
2181                                                                }else if(costMultiplier==0 && preferenceMultiplier==1){
2182                                                                        normalisedPrefAfterNeg = numPref/denoPref;
2183                                                                        tCostAfterNeg = preferenceMultiplier*normalisedPrefAfterNeg;
2184                                                                }else{
2185                                                                        normalisedCostAfterNeg = numCost/denoCost;
2186                                                                        normalisedPrefAfterNeg = numPref/denoPref;
2187                                                                        tCostAfterNeg = -costMultiplier*normalisedCostAfterNeg;
2188                                                                }
2189
2190                                                                if(tCostAfterNeg>1){
2191//                                                                  System.out.println("how is it possible?");
2192                                                                }
2193
2194                                                                if(tCostAfterNeg==0.0){
2195                                                                    if(preferenceMultiplier==1 && costMultiplier==1){
2196                                                                        /*If the normalised utility of second iteration is also zero, compare the actual value of preference utility index and cost*/
2197                                                                        if(cost<systemOptimalCost && degree>degreeOfUserSatisfaction){
2198                                                                            totalNormalisedCost=tCostAfterNeg;
2199                                                                            systemOptimalCost = cost;
2200                                                                            degreeOfUserSatisfaction = degree;
2201                                                                            replaced=true;
2202                                                                        }
2203                                                                    }// p and c are 1
2204                                                                    else if(preferenceMultiplier==1 &&costMultiplier==0){
2205                                                                        /*If the normalised preference utility index of second iteration is also zero, compare the actual value of preference utility index*/
2206                                                                        if(degree>degreeOfUserSatisfaction){
2207                                                                            totalNormalisedCost=tCostAfterNeg;
2208                                                                            degreeOfUserSatisfaction = degree;
2209                                                                            replaced=true;
2210                                                                        }
2211                                                                    }else if(preferenceMultiplier==0 &&costMultiplier==1){
2212
2213                                                                    /*If the normalised cost of second iteration is also zero, compare the actual value of cost*/
2214                                                                        if(cost<systemOptimalCost){
2215                                                                            totalNormalisedCost=tCostAfterNeg;
2216                                                                            systemOptimalCost = cost;
2217                                                                            replaced=true;
2218                                                                        }
2219                                                                    }
2220                                                                }else{
2221                                                                        if(tCostAfterNeg>=totalNormalisedCost){
2222                                                            
2223                                                                            totalNormalisedCost=tCostAfterNeg;
2224                                                                            systemOptimalCost = cost;
2225                                                                            degreeOfUserSatisfaction = degree;
2226                                                                            replaced=true;
2227
2228                                                                            normalisedSystemOptimalCost = normalisedCostAfterNeg;
2229                                                                            normalisedSystemOptimalPreference = normalisedPrefAfterNeg;
2230                                                                        }else{
2231                                                                            replaced=false;/// = null;
2232                                                                            routeChoiceCopy = null;
2233                                                                            routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2234                                                                        }
2235
2236                                                                }//tCostAfterNeg!=0
2237
2238                                                                }
2239                                                        }//routeInOrder!=null
2240                                                    }//subEntry!=null
2241                                                    if(!replaced){/// = null;
2242                                                    routeChoiceCopy = null;
2243                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2244                                                    }else{
2245                                                        routeChoice=null;
2246                                                        routeChoice = new ConcurrentHashMap(routeChoiceCopy);
2247                                                    }
2248                                                }//while rankIter hasNext
2249
2250
2251                                    }//rankIter!=null
2252
2253                                }//rankedRouteMap!=null
2254                                    }//route!=null
2255
2256                            }//while iter!=null
2257
2258                        }//iter!=null
2259                    }//allRoutes!=null
2260                }//routeChoice!=null
2261                    }if(dealType==Constants.MULTIAGENTDEAL)
2262                    {
2263                        Enumeration<String> vIDSet = routeChoice.keys();
2264                        if(vIDSet!=null){
2265                            while(vIDSet.hasMoreElements()){
2266                                String key = vIDSet.nextElement();
2267
2268                                if(key!=null && !key.equals(myAgent.getAID())){
2269                                    String secondAgentRt = (String) routeChoice.get(key);
2270
2271                                    Enumeration<String> vIDSetInner = routeChoice.keys();
2272                                    if(vIDSetInner!=null){
2273                                        while(vIDSetInner.hasMoreElements()){
2274                                            double normalisedCostCost =0.0;
2275                                            String keyInner = vIDSetInner.nextElement();
2276                                            if(keyInner!=null && !keyInner.equals(myAgent.getAID())){
2277                                                String thirdAgentRt = null;
2278                                                if(!keyInner.equals(key)){
2279                                                  thirdAgentRt = (String) routeChoice.get(keyInner);
2280                                                routeChoiceCopy.put(myAgent.getLocalName(), secondAgentRt);
2281                                                routeChoiceCopy.put(key, thirdAgentRt);
2282                                                routeChoiceCopy.put(keyInner, assignedRoute);
2283                                                cost = QueueManager.evaluateCost(routeChoiceCopy,null);
2284
2285                                                if(cost==0.0){
2286                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2287                                                    continue;
2288                                                }else{
2289                                                    degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,null);
2290                                                }
2291
2292                                                if(rd==0){
2293                                                    rd++;
2294
2295                                                    if(preferenceMultiplier==1 &&costMultiplier==0){
2296                                                        if(degree>degreeOfUserSatisfaction){
2297                                                            degreeOfUserSatisfaction = degree;
2298                                                            replaced=true;
2299                                                        }
2300                                                    }else if(preferenceMultiplier==0 &&costMultiplier==1){
2301
2302                                                        tCostAfterNeg=-cost;
2303                                                        if(cost>systemOptimalCost){
2304                                                            systemOptimalCost = cost;
2305                                                            replaced=true;
2306
2307                                                        }
2308                                                    }
2309                                                    if(cost>maxCost){
2310                                                        maxCost = cost;
2311                                                    }
2312                                                    if(cost<minCost){
2313                                                        minCost = cost;
2314                                                    }
2315                                                    if(degree>maxPref){
2316                                                        maxPref = degree;
2317                                                    }
2318                                                    if(degree<minPref){
2319                                                        minPref = degree;
2320                                                    }
2321                                                    if(preferenceMultiplier==1 && costMultiplier==1){
2322                                                        numCost = (cost-minCost);
2323                                                        denoCost = (maxCost-minCost);
2324
2325                                                        numPref=degree-minPref;
2326                                                        denoPref=(maxPref-minPref);
2327
2328                                                        tCostAfterNeg = preferenceMultiplier*normalisedPrefAfterNeg-costMultiplier*normalisedCostAfterNeg;
2329
2330                                                        if(tCostAfterNeg>0){
2331                                                            systemOptimalCost = cost;
2332                                                            degreeOfUserSatisfaction = degree;
2333                                                            replaced=true;
2334                                                        }
2335                                                    }// p and c are 1
2336                                                }
2337                                                else{
2338                                                    rd++;
2339                                                    if(cost>maxCost){
2340                                                        maxCost = cost;
2341                                                    }
2342                                                    if(cost<minCost){
2343                                                        minCost = cost;
2344                                                        replaced=true;
2345                                                    }
2346                                                    if(degree>maxPref){
2347                                                        maxPref = degree;
2348                                                    }
2349                                                    if(degree<minPref){
2350                                                        minPref = degree;
2351                                                    }
2352                                                    numCost = (cost-minCost);
2353                                                    denoCost = (maxCost-minCost);
2354
2355                                                    numPref=degree-minPref;
2356                                                    denoPref=(maxPref-minPref);
2357
2358                                                    if(costMultiplier==1 && preferenceMultiplier==1){
2359                                                        normalisedCostAfterNeg = numCost/denoCost;
2360                                                        normalisedPrefAfterNeg = numPref/denoPref;
2361                                                        tCostAfterNeg = preferenceMultiplier*normalisedPrefAfterNeg-costMultiplier*normalisedCostAfterNeg;
2362                                                    }else if(costMultiplier==0 && preferenceMultiplier==1){
2363                                                            normalisedPrefAfterNeg = numPref/denoPref;
2364                                                            tCostAfterNeg = preferenceMultiplier*normalisedPrefAfterNeg;
2365                                                    }else{
2366                                                            normalisedCostAfterNeg = numCost/denoCost;
2367                                                            normalisedPrefAfterNeg = numPref/denoPref;
2368                                                            tCostAfterNeg = -costMultiplier*normalisedCostAfterNeg;
2369                                                    }
2370
2371                                                    if(tCostAfterNeg>1){
2372//                                                      System.out.println("how is it possible?");
2373                                                    }
2374
2375                                                    if(tCostAfterNeg==0.0){
2376                                                        if(preferenceMultiplier==1 && costMultiplier==1){
2377                                                            /*If the normalised utility of second iteration is also zero, compare the actual value of preference utility index and cost*/
2378                                                            if(cost<systemOptimalCost && degree>degreeOfUserSatisfaction){
2379                                                                totalNormalisedCost=tCostAfterNeg;
2380                                                                systemOptimalCost = cost;
2381                                                                degreeOfUserSatisfaction = degree;
2382                                                                replaced=true;
2383                                                            }
2384                                                        }// p and c are 1
2385                                                        else if(preferenceMultiplier==1 &&costMultiplier==0){
2386                                                            /*If the normalised preference utility index of second iteration is also zero, compare the actual value of preference utility index*/
2387                                                            if(degree>degreeOfUserSatisfaction){
2388                                                                totalNormalisedCost=tCostAfterNeg;
2389                                                                degreeOfUserSatisfaction = degree;
2390                                                                replaced=true;
2391                                                            }
2392                                                        }else if(preferenceMultiplier==0 &&costMultiplier==1){
2393
2394                                                        /*If the normalised cost of second iteration is also zero, compare the actual value of cost*/
2395                                                            if(cost<systemOptimalCost){
2396                                                                totalNormalisedCost=tCostAfterNeg;
2397                                                                systemOptimalCost = cost;
2398                                                                replaced=true;
2399                                                            }
2400                                                        }
2401                                                    }else{
2402                                                            if(tCostAfterNeg>totalNormalisedCost){
2403                                                        
2404                                                                totalNormalisedCost=tCostAfterNeg;
2405                                                                systemOptimalCost = cost;
2406                                                                degreeOfUserSatisfaction = degree;
2407                                                                replaced=true;
2408
2409                                                                normalisedSystemOptimalCost = normalisedCostAfterNeg;
2410                                                                normalisedSystemOptimalPreference = normalisedPrefAfterNeg;
2411                                                            }else{
2412                                                                replaced=false;/// = null;
2413                                                                routeChoiceCopy = null;
2414                                                                routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2415                                                            }
2416
2417                                                    }//tCostAfterNeg!=0
2418
2419                                                    }
2420
2421                                                }//keyInner != key
2422                                            }//if keyInner!=null
2423
2424                                        }//while vIDSetInner has more elements
2425                                    }//vIDSetInner!=null
2426
2427                                }//key!=null
2428                            }//while hasMoreElements
2429                        }//vIDSet!=null
2430
2431                } //MULTIAGENT deal
2432                    }
2433                    }
2434                return routeChoice;
2435
2436                }
2437
2438                private String getSpeedLimitDifference(String assignedRoute,String route,ConcurrentHashMap routeChoice) {
2439                    double spd1 = 0,spd = 0,deltaSpd;
2440                    int assgnRt = 0, rt=0;
2441                    if(routeChoice!=null){
2442                        Set mapSet = routeChoice.entrySet();
2443                        if(mapSet!=null){
2444                            Iterator iter = mapSet.iterator();
2445                            while(iter!=null && iter.hasNext()){
2446                                Map.Entry entry = (Entry) iter.next();
2447                                String vehicle =  (String) entry.getKey();
2448                                String value =  (String) entry.getValue();
2449
2450                                if(value!=null && value.equals(assignedRoute)){
2451                                    assgnRt++;
2452                                }else if (value!=null && value.equals(route)){
2453                                    rt++;
2454                                }
2455                            }
2456                        }
2457                    }
2458                    return String.valueOf(assgnRt+","+rt);
2459                }
2460
2461
2462                private String getLengthDifference(String assignedRoute,String route) {
2463                    int len1 = 0,len2 = 0,deltaLen;
2464
2465                    if(assignedRoute!=null){
2466                        if(assignedRoute.equals("1")){
2467                        len1 = 3690;
2468                        }else if(assignedRoute.equals("2")){
2469                            len1 = 4680;
2470                        }else if(assignedRoute.equals("3")){
2471                            len1=5050;
2472                        }
2473                    }
2474
2475
2476
2477                    if(route!=null){
2478                        if(route.equals("1")){
2479                        len2 = 3690;
2480                        }else if(route.equals("2")){
2481                            len2 = 4680;
2482                        }else if(route.equals("3")){
2483                            len2=5050;
2484                        }
2485                    }
2486
2487                    deltaLen = len1-len2;
2488
2489                    return String.valueOf(deltaLen);
2490
2491                }
2492
2493
2494                private void updatDB(String localName, String route,String vehicle, String routeInOrder, ConcurrentHashMap rtChoiceCopy, int dType,String status, ConcurrentHashMap prevRt) {
2495                    int firstVehCnt=0,secVehCnt=0;
2496                    double firstPerOcc=0.0,secPercOcc=0.0;
2497                    if(rtChoiceCopy!=null){
2498                        Set routeSet = rtChoiceCopy.entrySet();
2499                        if(routeSet!=null){
2500                            if(routeSet!=null && !routeSet.isEmpty()){
2501                                for(Iterator it = routeSet.iterator(); it.hasNext();) {
2502                                    Map.Entry entry = (Entry) it.next();
2503                                    String veh =  (String) entry.getKey();
2504                                    String rt =  (String) entry.getValue();
2505                                    if(rt!=null && rt.equals(route)){
2506                                        if(veh!=null && !veh.equals(localName)){
2507                                            firstVehCnt++;
2508                                        }
2509                                    }
2510                                if(dType!=Constants.ADD){
2511                                    if(rt!=null && rt.equals(routeInOrder)){
2512                                        if(veh!=null && !veh.equals(vehicle)){
2513                                            secVehCnt++;
2514                                        }
2515                                    }
2516                                }else{
2517                                    if(rt!=null && rt.equals(routeInOrder)){
2518
2519                                            secVehCnt++;
2520
2521                                    }
2522                                }
2523                                }
2524
2525                                firstPerOcc = (firstVehCnt*100)/ DataAccess.selectRoadCapacity(route);
2526                                secPercOcc = (secVehCnt*100) / DataAccess.selectRoadCapacity(routeInOrder);
2527
2528                            //9 System.out.println("firstPerOcc  "+firstPerOcc+ "for route "+ route+" AND "+"secPercOcc "+secPercOcc+ " dealType "+dType+ " status "+status+ " for route "+routeInOrder);
2529                            }
2530                        }
2531                    }
2532
2533                }
2534
2535
2536                private ConcurrentHashMap negotiateRoutes(ConcurrentHashMap routeChoice,int dealType,int typeOfWelfare) {
2537                    // TODO Auto-generated method stub
2538                    String myPref = "";
2539                    String assignedRoute = "";
2540                    String tokenStr="";
2541                    int remainingCap=0;
2542                    double cost = 0.0,degree=0.0,tCost=0.0;
2543                    boolean searchBetterDeals = true;
2544                    boolean foundBetterDeal = false;
2545                    int cnt=1;
2546                    ConcurrentHashMap routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2547                    ConcurrentHashMap finalRouteChoiceCopy = new ConcurrentHashMap(routeChoice);
2548                    double totalCost=0.0;
2549
2550                    assignedRoute = (String) routeChoiceCopy.get(myAgent.getLocalName());
2551                    systemOptimalCost = QueueManager.evaluateCost(routeChoice,null);
2552                    degreeOfUserSatisfaction  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoice,null);
2553                    while(searchBetterDeals)
2554                    {
2555                    if(prefIndex!=null){
2556                        switch(cnt){
2557                        case 1:
2558                            myPref = prefIndex.getB1();
2559                            if(myPref!=null && !myPref.equals(""))
2560                                break;
2561                            else
2562                                cnt=2;
2563                        case 2:
2564                            myPref = prefIndex.getB2();
2565                            if(myPref!=null && !myPref.equals(""))
2566                                break;
2567                            else
2568                                cnt=3;
2569                        case 3:
2570                            myPref = prefIndex.getB3();
2571                            if(myPref!=null && !myPref.equals(""))
2572                                break;
2573                            else
2574                                cnt=4;
2575                        case 4:
2576                            myPref = prefIndex.getB4();
2577                            if(myPref!=null && !myPref.equals(""))
2578                                break;
2579                            else
2580                                cnt=5;
2581                        case 5:
2582                            myPref = prefIndex.getB5();
2583                            if(myPref!=null && !myPref.equals(""))
2584                                break;
2585                            else{
2586                                myPref = null;
2587                                searchBetterDeals = true;
2588                            }
2589                        }
2590                    }
2591                    if(myPref!=null && assignedRoute!=null){
2592
2593                        if(myPref.indexOf(",")>-1 || myPref.indexOf(assignedRoute)<=-1){
2594
2595                            Set routeSet = routeChoiceCopy.entrySet();
2596                            if(routeSet!=null && !routeSet.isEmpty()){
2597                                for(Iterator it = routeSet.iterator(); it.hasNext();) {
2598                                    Map.Entry entry = (Entry) it.next();
2599                                    String vehicle =  (String) entry.getKey();
2600                                    String route =  (String) entry.getValue();
2601                                    if(vehicle!=null && vehicle.equals(myAgent.getLocalName())){
2602                                        //searchBetterDeals = false;
2603                                        continue;
2604                                    }
2605                                    if(route!=null && myPref.indexOf(route)>-1){
2606                                    if(typeOfWelfare==Constants.MIXED_WELFARE){
2607                                        if(myAgent.getLocalName().equals("#5") && routeChoice.size()==13)
2608                                        {
2609                                            //System.out.println("how does the cost incresa");
2610                                        }
2611
2612                                        degree=0.0;
2613                                        tCost=0.0;
2614                                        replaced=false;
2615                                        if(dealType==Constants.ADD){
2616
2617                                            if(routeChoice.size()==QueueManager.getMaxAgentCntRecorded(communicID)){
2618                                                //System.out.println(myAgent.getLocalName()+ " ADDING .. MIXED WELFARE");
2619                                            }
2620                                             //ADD deal
2621                                            if(myPref!=null && myPref.indexOf(",")>-1){
2622                                                StringTokenizer st = new StringTokenizer(myPref,",");
2623                                                if(st!=null){
2624                                                    while(st.hasMoreTokens()){
2625
2626                                                        replaced=false;
2627                                                        tokenStr = st.nextToken();
2628                                                        if(tokenStr!=null && tokenStr.indexOf(assignedRoute)<=-1){
2629                                                        routeChoiceCopy.put(myAgent.getLocalName(), tokenStr);
2630                                                        cost = QueueManager.evaluateCost(routeChoiceCopy,null);
2631                                                        if(cost==0.0){
2632                                                            tCost = Double.NEGATIVE_INFINITY;
2633                                                            routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2634                                                        }else{
2635                                                            degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,null);
2636                                                            tCost = preferenceMultiplier*degree-costMultiplier*cost;
2637                                                        }
2638                                                        if(tCost>totalCost){
2639                                                            replaced=true;
2640                                                            totalCost=tCost;
2641                                                            finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2642                                                            routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2643                                                        //  searchBetterDeals = false;
2644                                                        
2645                                                        }else if(costMultiplier==0 && tCost==totalCost){
2646                                                            if(cost>systemOptimalCost){
2647                                                                replaced=true;
2648                                                                totalCost=tCost;
2649                                                                finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2650                                                                routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2651                                                            }
2652
2653                                                        }else if(preferenceMultiplier==0 && tCost==totalCost){
2654                                                            if(degree>degreeOfUserSatisfaction){
2655                                                                replaced=true;
2656                                                                totalCost=tCost;
2657                                                                finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2658                                                                routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2659                                                            }
2660
2661                                                        }
2662                                                        }
2663                                                    }
2664                                                }
2665                                            }else  if(myPref!=null && myPref.indexOf(assignedRoute)<=-1) {
2666                                                routeChoiceCopy.put(myAgent.getLocalName(), myPref);
2667                                                cost = QueueManager.evaluateCost(routeChoiceCopy,null);
2668                                                if(cost==0.0){
2669                                                    tCost = Double.NEGATIVE_INFINITY;
2670                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2671                                                }else{
2672                                                    degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,null);
2673                                                    tCost = preferenceMultiplier*degree-costMultiplier*cost;
2674                                                }
2675                                                if(tCost>totalCost){
2676                                                    totalCost=tCost;
2677                                                    finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2678                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2679                                                    //searchBetterDeals = false;
2680                                                
2681                                                }else if(costMultiplier==0 && tCost==totalCost){
2682                                                    if(cost>systemOptimalCost){
2683                                                        replaced=true;
2684                                                        totalCost=tCost;
2685                                                        finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2686                                                        routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2687                                                    }
2688
2689                                                }else if(preferenceMultiplier==0 && tCost==totalCost){
2690                                                    if(degree>degreeOfUserSatisfaction){
2691                                                        replaced=true;
2692                                                        totalCost=tCost;
2693                                                        finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2694                                                        routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2695                                                    }
2696
2697                                                }
2698                                            }
2699                                        }
2700                                        if(dealType==Constants.SWAP)
2701                                        {
2702                                            if(routeChoice.size()==QueueManager.getMaxAgentCntRecorded(communicID)){
2703                                                //System.out.println(myAgent.getLocalName()+ " SWAPPING .. MIXED WELFARE");
2704                                            }
2705                                        if(myPref!=null && myPref.indexOf(",")>-1){
2706                                            StringTokenizer st = new StringTokenizer(myPref,",");
2707                                            if(st!=null){
2708                                                while(st.hasMoreTokens()){
2709
2710                                                    replaced=false;
2711                                                    tokenStr = st.nextToken();
2712                                                    if(tokenStr!=null && tokenStr.indexOf(assignedRoute)<=-1){
2713                                                    routeChoiceCopy.put(vehicle, assignedRoute);
2714                                                    routeChoiceCopy.put(myAgent.getLocalName(), tokenStr);
2715                                                    cost = QueueManager.evaluateCost(routeChoiceCopy,null);
2716                                                    if(cost==0.0){
2717                                                        tCost = Double.NEGATIVE_INFINITY;
2718                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2719                                                    }else{
2720                                                    degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,null);
2721                                                    tCost = preferenceMultiplier*degree-costMultiplier*cost;
2722                                                    }
2723                                                    if(tCost>totalCost){
2724                                                        replaced=true;
2725                                                        if(routeChoiceCopy.size()==QueueManager.getMaxAgentCntRecorded(communicID) && myAgent.getLocalName().equals("#5")){
2726                                                        
2727                                                        }
2728                                                        totalCost=tCost;
2729                                                        searchBetterDeals = false;
2730
2731                                                        foundBetterDeal = true;
2732                                                        finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2733                                                        routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2734                                                        /*Set tempSet = finalRouteChoiceCopy.entrySet();
2735                                                        if(tempSet!=null){
2736                                                            Iterator tempIter = tempSet.iterator();
2737                                                            while(tempIter.hasNext()){
2738                                                                Map.Entry tempEntry = (Entry) tempIter.next();
2739                                                                if(tempEntry!=null){
2740                                                                    String tempKey = (String) tempEntry.getKey();
2741                                                                    String tempVal = (String) tempEntry.getValue();
2742                                                                    //System.out.println("post deal..by "+myAgent.getLocalName()+tempKey+" and val "+tempVal);
2743                                                                }
2744                                                            }
2745                                                        }*/
2746                                                    }else if(costMultiplier==0 && tCost==totalCost){
2747                                                        if(cost>systemOptimalCost){
2748                                                            replaced=true;
2749                                                            totalCost=tCost;
2750                                                            finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2751                                                            routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2752                                                        }
2753
2754                                                    }else if(preferenceMultiplier==0 && tCost==totalCost){
2755                                                        if(degree>degreeOfUserSatisfaction){
2756                                                            replaced=true;
2757                                                            totalCost=tCost;
2758                                                            finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2759                                                            routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2760                                                        }
2761
2762                                                    }
2763                                                }
2764                                                }
2765                                            }
2766                                        }else if(myPref!=null && myPref.indexOf(assignedRoute)<=-1){
2767                                            routeChoiceCopy.put(vehicle, assignedRoute);
2768                                            routeChoiceCopy.put(myAgent.getLocalName(), myPref);
2769                                            cost = QueueManager.evaluateCost(routeChoiceCopy,null);
2770                                            if(cost==0.0){
2771                                                tCost = Double.NEGATIVE_INFINITY;
2772                                                routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2773                                            }else{
2774                                                degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,null);
2775                                                tCost = preferenceMultiplier*degree-costMultiplier*cost;
2776                                            }
2777                                            if(tCost>totalCost){
2778                                                if(routeChoiceCopy.size()==QueueManager.getMaxAgentCntRecorded(communicID) && myAgent.getLocalName().equals("#5")){
2779                                                
2780                                                    }
2781                                                totalCost=tCost;
2782                                                searchBetterDeals = false;
2783                                                finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2784                                                routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2785
2786                                                foundBetterDeal = true;
2787                                            }else if(costMultiplier==0 && tCost==totalCost){
2788                                                if(cost>systemOptimalCost){
2789                                                    replaced=true;
2790                                                    totalCost=tCost;
2791                                                    finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2792                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2793                                                }
2794
2795                                            }else if(preferenceMultiplier==0 && tCost==totalCost){
2796                                                if(degree>degreeOfUserSatisfaction){
2797                                                    replaced=true;
2798                                                    totalCost=tCost;
2799                                                    finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2800                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2801                                                }
2802
2803                                            }
2804                                        }
2805                                    } //SWAP deal
2806                                    else if(dealType == Constants.DROP){
2807                                        if(routeChoice.size()==QueueManager.getMaxAgentCntRecorded(communicID)){
2808                                            //System.out.println(myAgent.getLocalName()+ " DROPPING .. MIXED WELFARE");
2809                                        }
2810                                        Map rankedRouteMap = DataAccess.getRoutesInOrderForDROP(vehMaps);
2811                                        if(rankedRouteMap!=null){
2812                                            Set rankSet = rankedRouteMap.entrySet();
2813                                            Iterator rankIter = rankSet.iterator();
2814                                            if(rankIter!=null){
2815                                                while(rankIter.hasNext()){
2816                                                    Map.Entry subEntry =(Entry) rankIter.next();
2817                                                    if(subEntry!=null){
2818                                                    String routeInOrder = (String) subEntry.getKey();
2819                                        if(myPref!=null && myPref.indexOf(",")>-1){
2820                                            StringTokenizer st = new StringTokenizer(myPref,",");
2821                                            if(st!=null){
2822                                                while(st.hasMoreTokens()){
2823                                                    replaced=false;
2824                                                    tokenStr = st.nextToken();
2825                                                    if(tokenStr!=null && tokenStr.indexOf(assignedRoute)<=-1){
2826                                                    routeChoiceCopy.put(vehicle, routeInOrder);
2827                                                    routeChoiceCopy.put(myAgent.getLocalName(), tokenStr);
2828                                                    cost = QueueManager.evaluateCost(routeChoiceCopy,null);
2829                                                    if(cost==0.0){
2830                                                        tCost = Double.NEGATIVE_INFINITY;
2831                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2832                                                    }else{
2833                                                    degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,null);
2834                                                    tCost = preferenceMultiplier*degree-costMultiplier*cost;
2835                                                    }
2836                                                    if(tCost>totalCost){
2837                                                        replaced=true;
2838                                                        totalCost=tCost;
2839                                                        searchBetterDeals = false;
2840                                                        finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2841                                                        routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2842                                                        if(myAgent.getLocalName().equals("#2") && routeChoiceCopy.size()==QueueManager.getMaxAgentCntRecorded(communicID)){
2843                                                        
2844                                                        }
2845                                                        foundBetterDeal = true;
2846                                                
2847                                                    }else if(costMultiplier==0 && tCost==totalCost){
2848                                                        if(cost>systemOptimalCost){
2849                                                            replaced=true;
2850                                                            totalCost=tCost;
2851                                                            finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2852                                                            routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2853                                                        }
2854
2855                                                    }else if(preferenceMultiplier==0 && tCost==totalCost){
2856                                                        if(degree>degreeOfUserSatisfaction){
2857                                                            replaced=true;
2858                                                            totalCost=tCost;
2859                                                            finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2860                                                            routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2861                                                        }
2862
2863                                                    }
2864                                                }
2865                                                }
2866                                            }
2867                                        }else if(myPref!=null && myPref.indexOf(assignedRoute)<=-1){
2868                                            routeChoiceCopy.put(vehicle, routeInOrder);
2869                                            routeChoiceCopy.put(myAgent.getLocalName(), myPref);
2870                                            cost = QueueManager.evaluateCost(routeChoiceCopy,null);
2871                                            if(cost==0.0){
2872                                                tCost = Double.NEGATIVE_INFINITY;
2873                                                routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2874                                            }else{
2875                                                degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,null);
2876                                                tCost = preferenceMultiplier*degree-costMultiplier*cost;
2877                                            }
2878                                            if(tCost>totalCost){
2879                                                totalCost=tCost;
2880                                                searchBetterDeals = false;
2881                                                finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2882                                                routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2883                                                
2884                                                foundBetterDeal = true;
2885                                            }else if(costMultiplier==0 && tCost==totalCost){
2886                                                if(cost>systemOptimalCost){
2887                                                    replaced=true;
2888                                                    totalCost=tCost;
2889                                                    finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2890                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2891                                                }
2892
2893                                            }else if(preferenceMultiplier==0 && tCost==totalCost){
2894                                                if(degree>degreeOfUserSatisfaction){
2895                                                    replaced=true;
2896                                                    totalCost=tCost;
2897                                                    finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2898                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2899                                                }
2900
2901                                            }
2902                                        }
2903                                                }//while rankIter hasNext
2904                                                }//if subEntry not null
2905                                            }//if rank Iter not null
2906                                    }
2907                                    }//if not null
2908                                    }
2909                                    else if (typeOfWelfare == Constants.RATIONAL_WELFARE){
2910                                        degree=0.0;
2911                                        tCost=0.0;
2912                                        if(dealType==Constants.ADD){
2913                                            if(routeChoice.size()==QueueManager.getMaxAgentCntRecorded(communicID)){
2914                                                //System.out.println(myAgent.getLocalName()+ " ADDING .. RATIONAL WELFARE");
2915                                            }
2916                                            //ADD deal
2917                                            if(myPref!=null && myPref.indexOf(",")>-1){
2918                                                StringTokenizer st = new StringTokenizer(myPref,",");
2919                                                if(st!=null){
2920                                                    while(st.hasMoreTokens()){
2921                                                        replaced=false;
2922                                                        tokenStr = st.nextToken();
2923                                                        if(tokenStr!=null && tokenStr.indexOf(assignedRoute)<=-1){
2924                                                        routeChoiceCopy.put(myAgent.getLocalName(), tokenStr);
2925                                                        cost = QueueManager.evaluateCost(routeChoiceCopy,tokenStr);
2926                                                        if(cost==0.0){
2927                                                            tCost = Double.NEGATIVE_INFINITY;
2928                                                            routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2929                                                        }else{
2930                                                            degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,myAgent.getLocalName());
2931                                                            tCost = preferenceMultiplier*degree-costMultiplier*cost;
2932                                                        }
2933                                                        if(tCost>totalIndCost){
2934                                                            replaced=true;
2935                                                            totalIndCost=tCost;
2936                                                            searchBetterDeals = false;
2937                                                            finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2938                                                            routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2939                                                        }else if(tCost==totalIndCost){
2940                                                            double initTempSystemCost = QueueManager.evaluateCost(routeChoiceCopy, null);
2941                                                            double initTempUserSatisfaction = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy, null);
2942                                                            double initTempCost = initTempSystemCost-initTempUserSatisfaction;
2943
2944                                                            double finalTempSystemCost = QueueManager.evaluateCost(finalRouteChoiceCopy, null);
2945                                                            double finalTempUserSatisfaction = DataAccess.evaluateDegreeOfUserSatisfaction(finalRouteChoiceCopy, null);
2946                                                            double finalTempCost = finalTempSystemCost-finalTempUserSatisfaction;
2947
2948                                                            if(finalTempCost>initTempCost){
2949                                                                replaced=true;
2950                                                                totalIndCost=tCost;
2951                                                                searchBetterDeals = false;
2952                                                                finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2953                                                                routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2954                                                                //System.out.println("DEAL-atleast inc overall utility!!!!! by "+myAgent.getLocalName()+"with "+vehicle+" gave up "+assignedRoute+" added to "+tokenStr+" and solution cost "+tCost);
2955                                                            }
2956                                                        }
2957                                                    }//if
2958                                                    }
2959                                                }
2960                                            }else  if(myPref!=null && myPref.indexOf(assignedRoute)<=-1){
2961                                                routeChoiceCopy.put(myAgent.getLocalName(), myPref);
2962                                                cost = QueueManager.evaluateCost(routeChoiceCopy,myPref);
2963                                                if(cost==0.0){
2964                                                    tCost = Double.NEGATIVE_INFINITY;
2965                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2966                                                }else{
2967                                                    degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,myAgent.getLocalName());
2968                                                    tCost = preferenceMultiplier*degree-costMultiplier*cost;
2969                                                }
2970                                                if(tCost>totalIndCost){
2971                                                    replaced=true;
2972                                                    totalIndCost=tCost;
2973                                                    searchBetterDeals = false;
2974                                                    finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2975                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2976                                                
2977                                                }else if(tCost==totalIndCost){
2978                                                    double initTempSystemCost = QueueManager.evaluateCost(routeChoiceCopy, null);
2979                                                    double initTempUserSatisfaction = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy, null);
2980                                                    double initTempCost = initTempSystemCost-initTempUserSatisfaction;
2981
2982                                                    double finalTempSystemCost = QueueManager.evaluateCost(finalRouteChoiceCopy, null);
2983                                                    double finalTempUserSatisfaction = DataAccess.evaluateDegreeOfUserSatisfaction(finalRouteChoiceCopy, null);
2984                                                    double finalTempCost = finalTempSystemCost-finalTempUserSatisfaction;
2985
2986                                                    if(finalTempCost>initTempCost){
2987                                                        replaced=true;
2988                                                        totalIndCost=tCost;
2989                                                        searchBetterDeals = false;
2990                                                        finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
2991                                                        routeChoiceCopy = new ConcurrentHashMap(routeChoice);
2992                                                        //System.out.println("DEAL-atleast inc overall utility!!!!! by "+myAgent.getLocalName()+"with "+vehicle+" gave up "+assignedRoute+" added to "+tokenStr+" and solution cost "+tCost);
2993                                                    }
2994                                                }
2995                                            }
2996                                        }
2997                                        if(dealType==Constants.SWAP)
2998                                        {
2999                                            if(routeChoice.size()==QueueManager.getMaxAgentCntRecorded(communicID)){
3000                                                //System.out.println(myAgent.getLocalName()+ " SWAPPING .. RATIONAL WELFARE");
3001                                            }
3002                                        if(myPref!=null && myPref.indexOf(",")>-1){
3003                                            StringTokenizer st = new StringTokenizer(myPref,",");
3004                                            if(st!=null){
3005                                                while(st.hasMoreTokens()){
3006                                                    replaced=false;
3007                                                    tokenStr = st.nextToken();
3008                                                    if(tokenStr!=null && tokenStr.indexOf(assignedRoute)<=-1){
3009                                                    routeChoiceCopy.put(vehicle, assignedRoute);
3010                                                    routeChoiceCopy.put(myAgent.getLocalName(), tokenStr);
3011                                                    cost = QueueManager.evaluateCost(routeChoiceCopy, tokenStr);
3012                                                    if(cost==0.0){
3013                                                        tCost = Double.NEGATIVE_INFINITY;
3014                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3015                                                    }else{
3016                                                    degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,myAgent.getLocalName());
3017                                                    tCost = preferenceMultiplier*degree-costMultiplier*cost;
3018                                                    }
3019                                                    if(tCost>totalIndCost){
3020                                                        replaced=true;
3021                                                        totalIndCost=tCost;
3022                                                        searchBetterDeals = false;
3023                                                        finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
3024                                                        routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3025                                                
3026                                                        foundBetterDeal = true;
3027                                                        Set tempSet = routeChoiceCopy.entrySet();
3028                                                        if(tempSet!=null){
3029                                                            Iterator tempIter = tempSet.iterator();
3030                                                            while(tempIter.hasNext()){
3031                                                                Map.Entry tempEntry = (Entry) tempIter.next();
3032                                                                if(tempEntry!=null){
3033                                                                    String tempKey = (String) tempEntry.getKey();
3034                                                                    String tempVal = (String) tempEntry.getValue();
3035                                                                
3036                                                                }
3037                                                            }
3038                                                        }
3039                                                    }else if(tCost==totalIndCost){
3040                                                            double initTempSystemCost = QueueManager.evaluateCost(routeChoiceCopy, null);
3041                                                            double initTempUserSatisfaction = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy, null);
3042                                                            double initTempCost = initTempSystemCost-initTempUserSatisfaction;
3043
3044                                                            double finalTempSystemCost = QueueManager.evaluateCost(finalRouteChoiceCopy, null);
3045                                                            double finalTempUserSatisfaction = DataAccess.evaluateDegreeOfUserSatisfaction(finalRouteChoiceCopy, null);
3046                                                            double finalTempCost = finalTempSystemCost-finalTempUserSatisfaction;
3047
3048                                                            if(finalTempCost>initTempCost){
3049                                                                replaced=true;
3050                                                                totalIndCost=tCost;
3051                                                                searchBetterDeals = false;
3052                                                                finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
3053                                                                routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3054                                                                //System.out.println("DEAL-atleast inc overall utility!!!!! by "+myAgent.getLocalName()+"with "+vehicle+" gave up "+assignedRoute+" added to "+tokenStr+" and solution cost "+tCost);
3055                                                            }
3056                                                        }
3057                                                }
3058                                                }
3059                                            }
3060                                        }else if(myPref!=null && myPref.indexOf(assignedRoute)<=-1){
3061                                            routeChoiceCopy.put(vehicle, assignedRoute);
3062                                            routeChoiceCopy.put(myAgent.getLocalName(), myPref);
3063                                            cost = QueueManager.evaluateCost(routeChoiceCopy, myPref);
3064                                            if(cost==0.0){
3065                                                tCost = Double.NEGATIVE_INFINITY;
3066                                                routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3067                                            }else{
3068                                                degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,myAgent.getLocalName());
3069                                                tCost = preferenceMultiplier*degree-costMultiplier*cost;
3070                                            }
3071                                            if(tCost>totalIndCost){
3072                                                replaced=true;
3073                                                totalIndCost=tCost;
3074                                                searchBetterDeals = false;
3075                                                finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
3076                                                routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3077                                            
3078                                                foundBetterDeal = true;
3079                                            }else if(tCost==totalIndCost){
3080                                                double initTempSystemCost = QueueManager.evaluateCost(routeChoiceCopy, null);
3081                                                double initTempUserSatisfaction = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy, null);
3082                                                double initTempCost = initTempSystemCost-initTempUserSatisfaction;
3083
3084                                                double finalTempSystemCost = QueueManager.evaluateCost(finalRouteChoiceCopy, null);
3085                                                double finalTempUserSatisfaction = DataAccess.evaluateDegreeOfUserSatisfaction(finalRouteChoiceCopy, null);
3086                                                double finalTempCost = finalTempSystemCost-finalTempUserSatisfaction;
3087
3088                                                if(finalTempCost>initTempCost){
3089                                                    replaced=true;
3090                                                    totalIndCost=tCost;
3091                                                    searchBetterDeals = false;
3092                                                    finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
3093                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3094                                                    
3095                                                }
3096                                            }
3097                                        }
3098                                    } //SWAP deal
3099                                    else if(dealType == Constants.DROP){
3100
3101                                        Map rankedRouteMap = DataAccess.getRoutesInOrderForDROP(vehMaps);
3102                                        if(rankedRouteMap!=null){
3103                                            Set rankSet = rankedRouteMap.entrySet();
3104                                            Iterator rankIter = rankSet.iterator();
3105                                            if(rankIter!=null){
3106                                                while(rankIter.hasNext()){
3107                                                    replaced=false;
3108                                                    Map.Entry subEntry =(Entry) rankIter.next();
3109                                                    if(subEntry!=null){
3110                                                    String routeInOrder = (String) subEntry.getKey();
3111                                        if(myPref!=null && myPref.indexOf(",")>-1){
3112                                            StringTokenizer st = new StringTokenizer(myPref,",");
3113                                            if(st!=null){
3114                                                while(st.hasMoreTokens()){
3115
3116                                                    replaced=false;
3117                                                    tokenStr = st.nextToken();
3118                                                    if(tokenStr!=null && tokenStr.indexOf(assignedRoute)<=-1){
3119                                                    routeChoiceCopy.put(vehicle, routeInOrder);
3120                                                    routeChoiceCopy.put(myAgent.getLocalName(), tokenStr);
3121                                                    cost = QueueManager.evaluateCost(routeChoiceCopy, tokenStr);
3122                                                    if(cost==0.0){
3123                                                        tCost = Double.NEGATIVE_INFINITY;
3124                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3125                                                    }else{
3126                                                    degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,myAgent.getLocalName());
3127                                                    tCost = preferenceMultiplier*degree-costMultiplier*cost;
3128                                                    }
3129                                                    if(tCost>totalIndCost){
3130                                                        replaced=true;
3131                                                        totalIndCost=tCost;
3132                                                        searchBetterDeals = false;
3133                                                        finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
3134                                                        routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3135                                                    
3136                                                        foundBetterDeal = true;
3137                                                        Set tempSet = routeChoiceCopy.entrySet();
3138                                                        if(tempSet!=null){
3139                                                            Iterator tempIter = tempSet.iterator();
3140                                                            while(tempIter.hasNext()){
3141                                                                Map.Entry tempEntry = (Entry) tempIter.next();
3142                                                                if(tempEntry!=null){
3143                                                                    String tempKey = (String) tempEntry.getKey();
3144                                                                    String tempVal = (String) tempEntry.getValue();
3145                                                                    
3146                                                                }
3147                                                            }
3148                                                        }
3149                                                    }else if(tCost==totalIndCost){
3150                                                        double initTempSystemCost = QueueManager.evaluateCost(routeChoiceCopy, null);
3151                                                        double initTempUserSatisfaction = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy, null);
3152                                                        double initTempCost = initTempSystemCost-initTempUserSatisfaction;
3153
3154                                                        double finalTempSystemCost = QueueManager.evaluateCost(finalRouteChoiceCopy, null);
3155                                                        double finalTempUserSatisfaction = DataAccess.evaluateDegreeOfUserSatisfaction(finalRouteChoiceCopy, null);
3156                                                        double finalTempCost = finalTempSystemCost-finalTempUserSatisfaction;
3157
3158                                                        if(finalTempCost>initTempCost){
3159                                                            replaced=true;
3160                                                            totalIndCost=tCost;
3161                                                            searchBetterDeals = false;
3162                                                            finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
3163                                                            routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3164                                                            //System.out.println("DEAL-atleast inc overall utility!!!!! by "+myAgent.getLocalName()+"with "+vehicle+" gave up "+assignedRoute+" added to "+tokenStr+" and solution cost "+tCost);
3165                                                        }
3166                                                    }
3167                                                }
3168                                                }
3169                                            }
3170                                        }else if(myPref!=null && myPref.indexOf(assignedRoute)<=-1){
3171                                            routeChoiceCopy.put(vehicle, routeInOrder);
3172                                            routeChoiceCopy.put(myAgent.getLocalName(), myPref);
3173                                            cost = QueueManager.evaluateCost(routeChoiceCopy, myPref);
3174                                            if(cost==0.0){
3175                                                tCost = Double.NEGATIVE_INFINITY;
3176                                                routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3177                                            }else{
3178                                                degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,myAgent.getLocalName());
3179                                                tCost = preferenceMultiplier*degree-costMultiplier*cost;
3180                                            }
3181                                            if(tCost>totalIndCost){
3182                                                replaced=true;
3183                                                totalIndCost=tCost;
3184                                                searchBetterDeals = false;
3185                                                finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
3186                                                routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3187                                            
3188                                                foundBetterDeal = true;
3189                                            }else if(tCost==totalIndCost){
3190                                                double initTempSystemCost = QueueManager.evaluateCost(routeChoiceCopy, null);
3191                                                double initTempUserSatisfaction = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy, null);
3192                                                double initTempCost = initTempSystemCost-initTempUserSatisfaction;
3193
3194                                                double finalTempSystemCost = QueueManager.evaluateCost(finalRouteChoiceCopy, null);
3195                                                double finalTempUserSatisfaction = DataAccess.evaluateDegreeOfUserSatisfaction(finalRouteChoiceCopy, null);
3196                                                double finalTempCost = finalTempSystemCost-finalTempUserSatisfaction;
3197
3198                                                if(finalTempCost>initTempCost){
3199                                                    replaced=true;
3200                                                    totalIndCost=tCost;
3201                                                    searchBetterDeals = false;
3202                                                    finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
3203                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3204                                            
3205                                                }
3206                                            }
3207                                        }
3208                                                }//while rankIter hasNext
3209                                                }//if subEntry not null
3210                                            }//if rank Iter not null
3211                                    }
3212                                    }//if not null
3213                                    }
3214                                }//end of case 2 - the most wanted preferences do not match that of other agents use DROP operation
3215                                    else{
3216                                        if(typeOfWelfare==Constants.MIXED_WELFARE){
3217                                            if(routeChoice.size()==QueueManager.getMaxAgentCntRecorded(communicID)){
3218                                                //System.out.println(myAgent.getLocalName()+ " DROPPING .. MIXED WELFARE");
3219                                            }
3220                                            Map rankedRouteMap = DataAccess.getRoutesInOrderForDROP(vehMaps);
3221                                            if(rankedRouteMap!=null){
3222                                                Set rankSet = rankedRouteMap.entrySet();
3223                                                Iterator rankIter = rankSet.iterator();
3224                                                if(rankIter!=null){
3225                                                    while(rankIter.hasNext()){
3226                                                        Map.Entry subEntry =(Entry) rankIter.next();
3227                                                        if(subEntry!=null){
3228                                                        String routeInOrder = (String) subEntry.getKey();
3229                                            if(myPref!=null && myPref.indexOf(",")>-1){
3230                                                StringTokenizer st = new StringTokenizer(myPref,",");
3231                                                if(st!=null){
3232                                                    while(st.hasMoreTokens()){
3233                                                        replaced=false;
3234                                                        tokenStr = st.nextToken();
3235                                                        if(tokenStr!=null && tokenStr.indexOf(assignedRoute)<=-1){
3236                                                        routeChoiceCopy.put(vehicle, routeInOrder);
3237                                                        routeChoiceCopy.put(myAgent.getLocalName(), tokenStr);
3238                                                        cost = QueueManager.evaluateCost(routeChoiceCopy,null);
3239                                                        if(cost==0.0){
3240                                                            tCost = Double.NEGATIVE_INFINITY;
3241                                                        routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3242                                                        }else{
3243                                                        degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,null);
3244                                                        tCost = preferenceMultiplier*degree-costMultiplier*cost;
3245                                                        }
3246                                                        if(tCost>totalCost){
3247                                                            replaced=true;
3248                                                            totalCost=tCost;
3249                                                            searchBetterDeals = false;
3250                                                            finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
3251                                                            routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3252                                                        
3253                                                            foundBetterDeal = true;
3254                                                            /*Set tempSet = routeChoiceCopy.entrySet();
3255                                                            if(tempSet!=null){
3256                                                                Iterator tempIter = tempSet.iterator();
3257                                                                while(tempIter.hasNext()){
3258                                                                    Map.Entry tempEntry = (Entry) tempIter.next();
3259                                                                    if(tempEntry!=null){
3260                                                                        String tempKey = (String) tempEntry.getKey();
3261                                                                        String tempVal = (String) tempEntry.getValue();
3262                                                                        //System.out.println("post deal..by "+myAgent.getLocalName()+tempKey+" and val "+tempVal);
3263                                                                    }
3264                                                                }
3265                                                            }*/
3266                                                        }else if(costMultiplier==0 && tCost==totalCost){
3267                                                            if(cost>systemOptimalCost){
3268                                                                replaced=true;
3269                                                                totalCost=tCost;
3270                                                                finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
3271                                                                routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3272                                                            }
3273
3274                                                        }else if(preferenceMultiplier==0 && tCost==totalCost){
3275                                                            if(degree>degreeOfUserSatisfaction){
3276                                                                replaced=true;
3277                                                                totalCost=tCost;
3278                                                                finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
3279                                                                routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3280                                                            }
3281
3282                                                        }
3283                                                    }
3284                                                    }
3285                                                }
3286                                            }else if(myPref!=null && myPref.indexOf(assignedRoute)<=-1){
3287                                                routeChoiceCopy.put(vehicle, routeInOrder);
3288                                                routeChoiceCopy.put(myAgent.getLocalName(), myPref);
3289                                                cost = QueueManager.evaluateCost(routeChoiceCopy,null);
3290                                                if(cost==0.0){
3291                                                    tCost = Double.NEGATIVE_INFINITY;
3292                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3293                                                }else{
3294                                                    degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,null);
3295                                                    tCost = preferenceMultiplier*degree-costMultiplier*cost;
3296                                                }
3297                                                if(tCost>totalCost){
3298                                                    totalCost=tCost;
3299                                                    searchBetterDeals = false;
3300                                                    finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
3301                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3302                                                    
3303                                                    foundBetterDeal = true;
3304                                                }else if(costMultiplier==0 && tCost==totalCost){
3305                                                    if(cost>systemOptimalCost){
3306                                                        replaced=true;
3307                                                        totalCost=tCost;
3308                                                        finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
3309                                                        routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3310                                                    }
3311
3312                                                }else if(preferenceMultiplier==0 && tCost==totalCost){
3313                                                    if(degree>degreeOfUserSatisfaction){
3314                                                        replaced=true;
3315                                                        totalCost=tCost;
3316                                                        finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
3317                                                        routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3318                                                    }
3319
3320                                                }
3321                                            }
3322                                                    }//while rankIter hasNext
3323                                                    }//if subEntry not null
3324                                                }//if rank Iter not null
3325                                        }
3326
3327                                    }//end of else - the most wanted preferences do not match that of other agents use DROP operation
3328
3329                                    }//If Mixed welfare END
3330                                    if(typeOfWelfare == Constants.RATIONAL_WELFARE){
3331                                        if(routeChoice.size()==QueueManager.getMaxAgentCntRecorded(communicID)){
3332                                    //      //System.out.println(myAgent.getLocalName()+ " DROPPING .. RATIONAL WELFARE");
3333                                        }
3334                                        Map rankedRouteMap = DataAccess.getRoutesInOrderForDROP(vehMaps);
3335                                        if(rankedRouteMap!=null){
3336                                            Set rankSet = rankedRouteMap.entrySet();
3337                                            Iterator rankIter = rankSet.iterator();
3338                                            if(rankIter!=null){
3339                                                while(rankIter.hasNext()){
3340                                                    replaced=false;
3341                                                    Map.Entry subEntry =(Entry) rankIter.next();
3342                                                    if(subEntry!=null){
3343                                                    String routeInOrder = (String) subEntry.getKey();
3344                                        if(myPref!=null && myPref.indexOf(",")>-1){
3345                                            StringTokenizer st = new StringTokenizer(myPref,",");
3346                                            if(st!=null){
3347                                                while(st.hasMoreTokens()){
3348                                                    replaced=false;
3349                                                    tokenStr = st.nextToken();
3350                                                    if(tokenStr!=null && tokenStr.indexOf(assignedRoute)<=-1){
3351                                                    routeChoiceCopy.put(vehicle, routeInOrder);
3352                                                    routeChoiceCopy.put(myAgent.getLocalName(), tokenStr);
3353                                                    cost = QueueManager.evaluateCost(routeChoiceCopy, tokenStr);
3354                                                    if(cost==0.0){
3355                                                        tCost = Double.NEGATIVE_INFINITY;
3356                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3357                                                    }else{
3358                                                    degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,myAgent.getLocalName());
3359                                                    tCost = preferenceMultiplier*degree-costMultiplier*cost;
3360                                                    }
3361                                                    if(tCost>totalIndCost){
3362                                                        replaced=true;
3363                                                        totalIndCost=tCost;
3364                                                        searchBetterDeals = false;
3365                                                        finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
3366                                                        routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3367                                                    
3368                                                        foundBetterDeal = true;
3369                                                        Set tempSet = routeChoiceCopy.entrySet();
3370                                                        if(tempSet!=null){
3371                                                            Iterator tempIter = tempSet.iterator();
3372                                                            while(tempIter.hasNext()){
3373                                                                Map.Entry tempEntry = (Entry) tempIter.next();
3374                                                                if(tempEntry!=null){
3375                                                                    String tempKey = (String) tempEntry.getKey();
3376                                                                    String tempVal = (String) tempEntry.getValue();
3377                                                                    //System.out.println("post deal..by "+myAgent.getLocalName()+tempKey+" and val "+tempVal);
3378                                                                }
3379                                                            }
3380                                                        }
3381                                                    }else if(tCost==totalIndCost){
3382                                                        double initTempSystemCost = QueueManager.evaluateCost(routeChoiceCopy, null);
3383                                                        double initTempUserSatisfaction = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy, null);
3384                                                        double initTempCost = initTempSystemCost-initTempUserSatisfaction;
3385
3386                                                        double finalTempSystemCost = QueueManager.evaluateCost(finalRouteChoiceCopy, null);
3387                                                        double finalTempUserSatisfaction = DataAccess.evaluateDegreeOfUserSatisfaction(finalRouteChoiceCopy, null);
3388                                                        double finalTempCost = finalTempSystemCost-finalTempUserSatisfaction;
3389
3390                                                        if(finalTempCost>initTempCost){
3391                                                            replaced=true;
3392                                                            totalIndCost=tCost;
3393                                                            searchBetterDeals = false;
3394                                                            finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
3395                                                            routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3396                                                            //System.out.println("DEAL-atleast inc overall utility!!!!! by "+myAgent.getLocalName()+"with "+vehicle+" gave up "+assignedRoute+" added to "+tokenStr+" and solution cost "+tCost);
3397                                                        }
3398                                                    }
3399                                                }
3400                                                }
3401                                            }
3402                                        }else if(myPref!=null && myPref.indexOf(assignedRoute)<=-1){
3403                                            routeChoiceCopy.put(vehicle, routeInOrder);
3404                                            routeChoiceCopy.put(myAgent.getLocalName(), myPref);
3405                                            cost = QueueManager.evaluateCost(routeChoiceCopy, myPref);
3406                                            if(cost==0.0){
3407                                                tCost = Double.NEGATIVE_INFINITY;
3408                                                routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3409                                            }else{
3410                                                degree  = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy,myAgent.getLocalName());
3411                                                tCost = preferenceMultiplier*degree-costMultiplier*cost;
3412                                            }
3413                                            if(tCost>totalIndCost){
3414                                                replaced=true;
3415                                                totalIndCost=tCost;
3416                                                searchBetterDeals = false;
3417                                                finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
3418                                                routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3419                                            
3420                                                foundBetterDeal = true;
3421                                            }else if(tCost==totalIndCost){
3422                                                double initTempSystemCost = QueueManager.evaluateCost(routeChoiceCopy, null);
3423                                                double initTempUserSatisfaction = DataAccess.evaluateDegreeOfUserSatisfaction(routeChoiceCopy, null);
3424                                                double initTempCost = initTempSystemCost-initTempUserSatisfaction;
3425
3426                                                double finalTempSystemCost = QueueManager.evaluateCost(finalRouteChoiceCopy, null);
3427                                                double finalTempUserSatisfaction = DataAccess.evaluateDegreeOfUserSatisfaction(finalRouteChoiceCopy, null);
3428                                                double finalTempCost = finalTempSystemCost-finalTempUserSatisfaction;
3429
3430                                                if(finalTempCost>initTempCost){
3431                                                    replaced=true;
3432                                                    totalIndCost=tCost;
3433                                                    searchBetterDeals = false;
3434                                                    finalRouteChoiceCopy = new ConcurrentHashMap(routeChoiceCopy);
3435                                                    routeChoiceCopy = new ConcurrentHashMap(routeChoice);
3436                                                    
3437                                                }
3438                                            }
3439                                        }
3440                                                }//while rankIter hasNext
3441                                                }//if subEntry not null
3442                                            }//if rank Iter not null
3443                                    }
3444                                    }//if RATIONAL WELFARE ENd DROP
3445                                }
3446
3447
3448                            }
3449
3450                        }else if(myPref.equals("") && myPref.indexOf(assignedRoute)>=-1){
3451                            searchBetterDeals=false;
3452                        }else if(myPref.indexOf(assignedRoute)>-1){
3453                            searchBetterDeals=false;
3454                        }
3455                    }
3456
3457
3458                    if(searchBetterDeals){
3459                        cnt++;
3460                        if(cnt==Constants.VEHICLESEED){
3461                            searchBetterDeals = false;
3462                        }
3463                    }
3464                }//end of while
3465
3466                    double tLowestUtiltiy=0.0;
3467                    if (typeOfWelfare == Constants.RATIONAL_WELFARE){
3468                        tLowestUtiltiy = DataAccess.getLowestUtility(routeChoice);
3469                        if(tLowestUtiltiy!=0 && tLowestUtiltiy>lowestUtility){
3470                            lowestUtility = tLowestUtiltiy;
3471                            if(finalRouteChoiceCopy!=null){
3472                                routeChoice = finalRouteChoiceCopy;
3473                            }else{
3474                            routeChoice = routeChoiceCopy;
3475                            }
3476                        }
3477                        if(routeChoice.size()==Constants.VEHICLESEED){
3478
3479                    //  System.out.println("cc");
3480
3481                        }
3482
3483                    }else if(typeOfWelfare == Constants.MIXED_WELFARE){
3484                        if(finalRouteChoiceCopy!=null){
3485                            routeChoice = finalRouteChoiceCopy;
3486                        }else{
3487                        routeChoice = routeChoiceCopy;
3488                        }
3489
3490                    }
3491
3492                        if(routeChoice.size()==Constants.VEHICLESEED){
3493
3494                    //  System.out.println("cc");
3495
3496                        }
3497                        return routeChoice;
3498
3499                }
3500
3501
3502
3503
3504        }
3505
3506
3507
3508
3509
3510        private static synchronized Map sortAscByComparator(Map unsortMap) {
3511
3512            List list = new LinkedList(unsortMap.entrySet());
3513
3514            //sort list based on comparator
3515            Collections.sort(list, new Comparator() {
3516                 public int compare(Object o1, Object o2) {
3517                   return ((Comparable) ((Map.Entry) (o1)).getValue())
3518                   .compareTo(((Map.Entry) (o2)).getValue());
3519                 }
3520            });
3521
3522            //put sorted list into map again
3523            Map sortedMap = new LinkedHashMap();
3524            for (Iterator it = list.iterator(); it.hasNext();) {
3525             Map.Entry entry = (Map.Entry)it.next();
3526             sortedMap.put(entry.getKey(), entry.getValue());
3527            }
3528            return sortedMap;
3529        }
3530
3531
3532
3533    }// main class ends
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545