Advertisement
Guest User

Untitled

a guest
Jan 16th, 2017
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.47 KB | None | 0 0
  1. package mas.agent.student;
  2.  
  3. import java.util.*;
  4.  
  5. import cz.agents.alite.communication.content.Content;
  6. import mas.agent.MASQueenAgent;
  7. import cz.agents.alite.communication.Message;
  8.  
  9. public class MyQueenAgent extends MASQueenAgent {
  10.  
  11.     private int currentAssignment;
  12.     private Map<Integer, Integer> agentView = new HashMap<>();
  13.     private Set<Map<Integer, Integer>> noGoodStore = new HashSet<>();;
  14.  
  15.     public MyQueenAgent(int agentId, int nAgents) {
  16.         super(agentId, nAgents);
  17.     }
  18.    
  19.     @Override
  20.     protected void start(int agentId, int nAgents) {
  21.         // this method is called when the agent is initialized.
  22.         currentAssignment = new Random().nextInt(nAgents);
  23.         messageLowerAgents();
  24.     }
  25.  
  26.     @Override
  27.     protected void processMessages(List<Message> newMessages) {
  28.         for (Message message : newMessages) {
  29.             Content content = message.getContent();
  30.  
  31.             if(content instanceof HandleOk) {
  32.                 processOkMessage(message);
  33.             }
  34.             if(content instanceof HandleNoGood) {
  35.                 processNoGoodMessage(message);
  36.             }
  37.             if(content instanceof HandlePossibleSolution) {
  38.                 processPossibleSolutionMessage(message);
  39.             }
  40.             if(content instanceof HandleSolutionDoesNotExist) {
  41.                 processSolutionDoesNotExist();
  42.             }
  43.             if(content instanceof HandleSolutionFound) {
  44.                 processSolutionFound();
  45.             }
  46.         }
  47.     }
  48.  
  49.     private ArrayList<Integer> getNewAssignments() {
  50.         ArrayList<Integer> list = new ArrayList<>();
  51.         // iterate through all columns
  52.         for (int i = 0; i < nAgents(); i++) {
  53.             // process every column except current column
  54.             if (i != currentAssignment) {
  55.                 //first check my agent view
  56.                 boolean add = checkAgentView(i);
  57.                 //if agent view is ok check my noGoodStore
  58.                 if (add) {
  59.                     add = checkNoGoodStore(i);
  60.                 }
  61.                 // if everything ok I can add this assignment to result list
  62.                 if(add) {
  63.                     list.add(i);
  64.                 }
  65.             }
  66.         }
  67.         return list;
  68.     }
  69.  
  70.     private boolean checkAgentView(int i) {
  71.         // iterate through every entry in agent view
  72.         for (Map.Entry<Integer, Integer> mapEntry : agentView.entrySet()) {
  73.             int agentName = mapEntry.getKey();
  74.             int agentAssignment = mapEntry.getValue();
  75.             // check if any constraint is violated
  76.             if(constraintsViolated(getAgentId(), i, agentName, agentAssignment)) {
  77.                 return false;
  78.             }
  79.         }
  80.         return true;
  81.     }
  82.  
  83.     private boolean checkNoGoodStore(int i) {
  84.         boolean add = true;
  85.         // list for storing noGoods which will be removed
  86.         ArrayList<Map<Integer, Integer>> toRemove = new ArrayList<>();
  87.         for (Map<Integer, Integer> noGood : noGoodStore) {
  88.             boolean removeNoGood = false;
  89.             for (Map.Entry<Integer, Integer> mapEntry : noGood.entrySet()) {
  90.                 int key = mapEntry.getKey();
  91.                 int value = mapEntry.getValue();
  92.                 if (key != getAgentId()) {
  93.                     if (agentView.containsKey(key)) {
  94.                         if (agentView.get(key) != value){
  95.                             removeNoGood = true;
  96.                         }
  97.                     } else {
  98.                         removeNoGood = true;
  99.                     }
  100.                 } else {
  101.                     if (value == i) {
  102.                         add = false;
  103.                         break;
  104.                     }
  105.                 }
  106.             }
  107.             if (removeNoGood) {
  108.                 // we cannot remove element directly from set we are iterating
  109.                 toRemove.add(noGood);
  110.             }
  111.         }
  112.         for (Map<Integer, Integer> noGood : toRemove) {
  113.             noGoodStore.remove(noGood);
  114.         }
  115.         return add;
  116.     }
  117.  
  118.     private int sendNoGood() {
  119.         if (!agentView.isEmpty()) {
  120.             int targetAgent = Integer.MIN_VALUE;
  121.             // get agent from my agent view with lowest priority
  122.             for (Integer integer : agentView.keySet()) {
  123.                 if (integer > targetAgent)  targetAgent = integer;
  124.             }
  125.             // send him noGood
  126.             sendMessage(String.valueOf(targetAgent), new HandleNoGood(agentView));
  127.             return targetAgent;
  128.         } else {
  129.             // if agent view is empty I can broadcast that no solution exists
  130.             broadcast(new HandleSolutionDoesNotExist());
  131.             notifySolutionDoesNotExist();
  132.             terminated = true;
  133.             return Integer.MIN_VALUE;
  134.         }
  135.     }
  136.  
  137.     private boolean lowestAgent() {
  138.         return ( nAgents() == agentView.size() + 1 ) && ( nAgents() == getAgentId() + 1 );
  139.     }
  140.  
  141.     private boolean constraintsViolated(int agent1Name, int agent1Assignment, int agent2Name, int agent2Assignment) {
  142.         // check if agent1 isn't in the same column as agent2 or that agent1 isn't in same diagonal as agent2
  143.         return (agent1Assignment == agent2Assignment) || (Math.abs(agent1Assignment - agent2Assignment) == Math.abs(agent1Name - agent2Name));
  144.     }
  145.  
  146.     private boolean solutionOkForMe(Map<Integer, Integer> finalAssignments) {
  147.         // iterate through all assignments
  148.         for (Map.Entry<Integer, Integer> mapEntry : finalAssignments.entrySet()) {
  149.             // check if my assignment matches with solution assignment
  150.             if ( (getAgentId() == mapEntry.getKey()) && (currentAssignment != mapEntry.getValue()) ) {
  151.                 return false;
  152.             }
  153.         }
  154.         return true;
  155.     }
  156.  
  157.     private boolean noGoodOkForMe(Map<Integer, Integer> map) {
  158.         // iterate through all assignment pairs
  159.         for (Map.Entry<Integer, Integer> mapEntry : map.entrySet()) {
  160.             int key = mapEntry.getKey();
  161.             int value = mapEntry.getValue();
  162.             // if I encounter key same as my id
  163.             if ( key == getAgentId() ) {
  164.                 // check if my current assignment is different from its value
  165.                 if ( currentAssignment != value ) {
  166.                     return false;
  167.                 }
  168.             }
  169.             // also check if current key is contained in my agent view
  170.             else if ( agentView.containsKey(key) ) {
  171.                 // check if this key has different value from key in my agent view
  172.                 if ( agentView.get(key) != value ){
  173.                     return false;
  174.                 }
  175.             } else {
  176.                 return false;
  177.             }
  178.         }
  179.         return true;
  180.     }
  181.  
  182.     private void backtrack() {
  183.         // get all new available assignments
  184.         ArrayList<Integer> list = getNewAssignments();
  185.         // if there is none, send NoGood
  186.         if (list.isEmpty()) {
  187.             int targetAgent = sendNoGood();
  188.             // if I got some agent
  189.             if (targetAgent != Integer.MIN_VALUE) {
  190.                 // I can remove it from my agent view (cause he will change)
  191.                 agentView.remove(targetAgent);
  192.                 backtrack();
  193.             }
  194.         } else {
  195.             // else choose randomly on of the assignment
  196.             currentAssignment = list.get(new Random().nextInt(list.size()));
  197.             // and send it to lower priority agents
  198.             messageLowerAgents();
  199.             // check if current agent is agent with lowest priority
  200.             if ( lowestAgent() ) {
  201.                 sendSolutionAssignments();
  202.             }
  203.         }
  204.     }
  205.  
  206.     private void messageLowerAgents() {
  207.         // send message to agents with lower priority than me
  208.         Content content = new HandleOk(getAgentId(), currentAssignment);
  209.         for (int i = getAgentId() + 1; i < nAgents(); i++) {
  210.             sendMessage(String.valueOf(i), content);
  211.         }
  212.     }
  213.  
  214.     private void sendSolutionAssignments() {
  215.         Map<Integer, Integer> finalAssignments = new HashMap<>(agentView);
  216.         // lowest priority agent puts his assignment into assignment map
  217.         finalAssignments.put(getAgentId(), currentAssignment);
  218.         // and send this map to the agent with higher priority
  219.         sendMessage(String.valueOf(getAgentId() - 1), new HandlePossibleSolution(finalAssignments));
  220.     }
  221.  
  222.     private void processOkMessage(Message message) {
  223.         HandleOk content = (HandleOk) message.getContent();
  224.         int senderName = content.getSenderName();
  225.         int senderAssignment = content.getSenderAssignment();
  226.         agentView.put(senderName, senderAssignment);
  227.         // check if current agent doesn't violate constraints in agent view
  228.         if ( constraintsViolated(senderName, senderAssignment, getAgentId(), currentAssignment) ) {
  229.             backtrack();
  230.         }
  231.         // check if current agent is agent with lowest priority
  232.         if ( lowestAgent() ) {
  233.             sendSolutionAssignments();
  234.         }
  235.     }
  236.  
  237.     private void processNoGoodMessage(Message message) {
  238.         HandleNoGood handleNoGood = (HandleNoGood) message.getContent();
  239.         // check if sent noGood doesn't violate any constrains
  240.         if( noGoodOkForMe(handleNoGood.getAssignments()) ){
  241.             // if it's ok I can add it to my noGoodStore
  242.             noGoodStore.add(handleNoGood.getAssignments());
  243.             backtrack();
  244.         } else {
  245.             messageLowerAgents();
  246.         }
  247.     }
  248.  
  249.     private void processPossibleSolutionMessage(Message message) {
  250.         HandlePossibleSolution handlePossibleSolution = (HandlePossibleSolution) message.getContent();
  251.         // check if given solution assignment is ok for me
  252.         if (solutionOkForMe(handlePossibleSolution.getAssignments())) {
  253.             // if I am agent with the highest priority (0)
  254.             if (getAgentId() == 0) {
  255.                 // I can broadcast that we found a solution
  256.                 broadcast(new HandleSolutionFound());
  257.                 // I notify that we found solution and my assignment
  258.                 notifySolutionFound(currentAssignment);
  259.             }
  260.             // else I just send the solution to agent with higher priority than me
  261.             else {
  262.                 sendMessage(String.valueOf(getAgentId() - 1), handlePossibleSolution);
  263.             }
  264.         } else {
  265.             // if the solution is not ok I send my assignment to agent with lower priority
  266.             messageLowerAgents();
  267.         }
  268.     }
  269.  
  270.     private void processSolutionDoesNotExist() {
  271.         // notify that no solution exists and terminate
  272.         notifySolutionDoesNotExist();
  273.         terminated = true;
  274.     }
  275.  
  276.     private void processSolutionFound() {
  277.         // I notify that we found solution and my assignment
  278.         notifySolutionFound(currentAssignment);
  279.     }
  280.  
  281. }
  282.  
  283. class HandleNoGood extends Content {
  284.  
  285.     private Map<Integer, Integer> assignments;
  286.  
  287.     HandleNoGood(Map<Integer, Integer> assignments) {
  288.         super(assignments);
  289.         this.assignments = new HashMap<>(assignments);
  290.     }
  291.  
  292.     Map<Integer, Integer> getAssignments() {
  293.         return assignments;
  294.     }
  295.  
  296.     @Override
  297.     public String toString() {
  298.         return "HandleNoGood [" +
  299.                 "assignments=" + assignments +
  300.                 ']';
  301.     }
  302. }
  303.  
  304. class HandleOk  extends Content {
  305.  
  306.     private int senderName, senderAssignment;
  307.  
  308.     HandleOk(int senderName, int senderAssignment) {
  309.         super(senderAssignment);
  310.         this.senderName = senderName;
  311.         this.senderAssignment = senderAssignment;
  312.     }
  313.  
  314.     int getSenderName() {
  315.         return senderName;
  316.     }
  317.  
  318.     int getSenderAssignment() {
  319.         return senderAssignment;
  320.     }
  321.  
  322.     @Override
  323.     public String toString() {
  324.         return "HandleOk [" +
  325.                 "senderAssignment=" + senderAssignment +
  326.                 ']';
  327.     }
  328. }
  329.  
  330. class HandleSolutionDoesNotExist extends Content {
  331.  
  332.     HandleSolutionDoesNotExist() {
  333.         super("HandleSolutionDoesNotExist");
  334.     }
  335.  
  336. }
  337.  
  338. class HandleSolutionFound extends Content {
  339.  
  340.      HandleSolutionFound() {
  341.         super("HandleSolutionFound");
  342.     }
  343.  
  344. }
  345.  
  346. class HandlePossibleSolution extends Content {
  347.  
  348.     private final Map<Integer, Integer> assignments;
  349.  
  350.     HandlePossibleSolution(Map<Integer, Integer> assignments) {
  351.         super(assignments);
  352.         this.assignments = new HashMap<>(assignments);
  353.     }
  354.  
  355.     Map<Integer, Integer> getAssignments() {
  356.         return assignments;
  357.     }
  358.  
  359.     @Override
  360.     public String toString() {
  361.         return "HandlePossibleSolution [" +
  362.                 "assignments=" + assignments +
  363.                 ']';
  364.     }
  365.  
  366. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement