async def run(self): if self.fAgent.optimal_result is None: self.fAgent.logger.log_warning( f"Aight, imma head out - disactivating with last cost {min(self.fAgent.allCalculatedCosts.values())}" ) for co in self.fAgent.activeCoworkers: msg = StatesMessage(to=co, body="False") msg.set_metadata("language", "boolean") await self.send(msg) # inform manager that agent went inactive result = { "sequence": self.fAgent.currentSigma, "cost": self.fAgent.getCostAll(str(self.fAgent.currentSigma)) } message = InactiveMessage(to=self.fAgent.manager, body=json.dumps(result)) await self.send(message) end = False while (end == False): resp = await self.receive(timeout=10) if resp is not None: sender = str(resp.sender) if resp.metadata[ "performative"] == "inform" and resp.body == "We have got it!": end = True
async def run(self): msg = await self.receive(timeout=5) if msg is not None: if msg.body is not "": sigma = self.parseMessage(msg.body) cost = self.fAgent.getMyCost(msg.body, sigma) if msg.metadata["save"] == "True": self.fAgent.saveMatesBest(str(msg.sender), sigma) msgResp = StatesMessage(to=msg.sender, body=cost) msgResp.set_metadata("language", "int") await self.send(msgResp)
async def run(self): self.fAgent.logger.log_info("Waiting for coworkers") # in this state we need to check if all coworkers are active and ready to start the next round #right now everyone has computet new sigma so all we have to di is to check what kind of message we got from our active mates #firstly we should inform then that we are ready for co in self.fAgent.activeCoworkers: msg = StatesMessage(to=co, body=True) msg.set_metadata("language", "boolean") await self.send(msg) waitingCoworkers = deepcopy(self.fAgent.activeCoworkers) #firstly we should check saved messages msgToRemove = [] for msg in self.fAgent.mailboxForLater: if msg.metadata["performative"] == "inform" and msg.metadata["language"] == "boolean" and str(msg.sender) in waitingCoworkers: msgToRemove.append(msg) waitingCoworkers.remove(str(msg.sender)) if msg.body == "False": self.fAgent.activeCoworkers.remove(str(msg.sender)) for msg in msgToRemove: self.fAgent.mailboxForLater.remove(msg) count = 0 while len(waitingCoworkers) > 0: resp = await self.receive(timeout=120) if resp is not None: sender = str(resp.sender) if resp.metadata["performative"] == "inform" and resp.metadata["language"] == "boolean" and str(resp.sender) in waitingCoworkers: waitingCoworkers.remove(sender) if resp.body == "False": self.fAgent.activeCoworkers.remove(sender) else: self.fAgent.saveMessage(msg) else: count = count + 1 if count < MAX_TIMES: for cw in waitingCoworkers: msg = StatesMessage(to=cw, body=True) msg.set_metadata("language", "boolean") await self.send(msg) else: for c in waitingCoworkers: self.fAgent.logger.log_error(f"problem with {c}") alarmMsg = WatchdogMessage(to = self.fAgent.manager, body = str(WorkingState.COMPLAINT)+" "+c) await self.send(alarmMsg) break self.clearMailBox() self.set_next_state(STATE_PROPOSE)
async def run(self): waitingActiveCoworkers = deepcopy(self.fAgent.activeCoworkers) self.fAgent.logger.log_info( f"Waiting for proposals from {waitingActiveCoworkers}") toRemove = [] proposals = dict() for msg in self.fAgent.mailboxForLater: if msg.metadata["performative"] == "propose" and msg.metadata[ "language"] == "list" and str( msg.sender) in waitingActiveCoworkers: #print(msg.sender) toRemove.append(msg) sender = str(msg.sender) waitingActiveCoworkers.remove(sender) proposals[sender] = parseMessage(msg.body) for msg in toRemove: self.fAgent.mailboxForLater.remove(msg) counter = 0 while (len(waitingActiveCoworkers) > 0): msg = await self.receive(timeout=10) if msg is not None: if msg.metadata["performative"] == "propose" and msg.metadata[ "language"] == "list" and str( msg.sender) in waitingActiveCoworkers: sender = str(msg.sender) waitingActiveCoworkers.remove(sender) proposals[sender] = parseMessage(msg.body) else: self.fAgent.saveMessage(msg) else: counter = counter + 1 if (counter < MAX_TIME): sigma = self.fAgent.myProposals[ len(self.fAgent.myProposals) - 1] for c in self.fAgent.activeCoworkers: self.fAgent.logger.log_error( f"Retrying sending proposition to {c}") retry = StatesMessage(to=c, body=sigma) retry.set_metadata("performative", "propose") retry.set_metadata("language", "list") await self.send(retry) else: for c in waitingActiveCoworkers: alarmMsg = WatchdogMessage( to=self.fAgent.manager, body=str(WorkingState.COMPLAINT) + " " + c) await self.send(alarmMsg) self.clearMailboxForLater() self.set_next_state(STATE_PROPOSE) return #print("I got all proposals "+self.fAgent.nameMy) for (mate, seq) in proposals.items(): if seq not in self.fAgent.matesProposals[mate]: self.fAgent.matesProposals[mate].append(seq) #print("End "+self.fAgent.nameMy) self.clearMailboxForLater() self.set_next_state(STATE_COMPUTE_PROPOSALS)
async def run(self): #send messages to subordinates and wait to get response from each of them for sub in self.subordinates.keys(): self.manager.logger.log_warning(f"Pinging {sub}") msg = WatchdogMessage(to=sub, body=self.subordinates[sub]) await self.send(msg) currentWorking = [] toRestart = [] timeout = floor(float(PERIOD) / len(self.subordinates)) - 1 if timeout < 1: timeout = timeout + 1 for i in range(len(self.subordinates)): resp = await self.receive(timeout=timeout) if resp is None: self.manager.logger.log_warning("No response!") else: self.manager.logger.log_warning("Ping responded!") if str(WorkingState.COMPLAINT) in resp.body: badAgentJID = resp.body.split(" ") print(badAgentJID) toRestart.append(badAgentJID[1]) else: currentWorking.append(str(resp.sender)) if resp.body == str(WorkingState.RESTARTING): self.subordinates[str(resp.sender)] = self.subordinates[str(resp.sender)] + 1 self.manager.logger.log_warning(f"Restarting {resp.sender}") else: self.subordinates[str(resp.sender)] = 0 self.checkResponses(currentWorking, toRestart) for jid in toRestart: worker, i = self.manager.findWorker(jid) await worker.stopAllBehaviours() p = self.manager.workersParams[i] self.agent.logger.log_info(f"Adding {jid} to the team") notActive = self.manager.getNotActiveDespite(jid) active = self.manager.isAgentActive(jid) created = FactoryAgent.FactoryAgent(p["jid"], p["password"],p["name"],p["priceEle"], p["priceChan"], p["sameIndex"],p["coworkers"], "manager@localhost", active=active, notActiveCovorkers = notActive) self.manager.workers[i] = created await created.start() created.web.start(hostname="localhost", port="10000") self.agent.logger.log_info(f"DeputeBehaviour for {jid} created") msg = StatesMessage(to=jid, body=self.manager.task) msg.set_metadata("performative", "request") # Instantiate the message await self.send(msg) self.agent.logger.log_info(f"Task sent to {jid}")
async def run(self): self.fAgent.logger.log_info(f"Starting negotiation") sigma = self.fAgent.currentSigma myProposition = self.fAgent.myProposals if sigma not in myProposition: myProposition.append(sigma) activeCoworkers = self.fAgent.activeCoworkers for coworker in activeCoworkers: msg = StatesMessage(to=coworker, body=sigma) msg.set_metadata("performative", "propose") msg.set_metadata("language", "list") await self.send(msg) self.set_next_state(STATE_WAIT_FOR_PROPSALS)
async def run(self): msg = await self.receive(timeout=5) if msg is not None: #print("Got a message!") if (msg.body is not ""): #print(msg.body) sigmas = parseMessage( msg.body) #sigmas[0] - other sigmas[1] - my risk = self.computeRisk(sigmas[1], sigmas[0]) msgResp = StatesMessage(to=msg.sender, body=risk) # Instantiate the message msgResp.set_metadata("performative", "inform") msgResp.set_metadata("language", "float") await self.send(msgResp)
async def run(self): msg = await self.receive(timeout=5) if msg is not None: #print("Got a message!") if (msg.body is not ""): sigma = self.parseMessage(msg.body) cost = self.fAgent.getMyCost(msg.body, sigma) response = [] sets = self.createSets(cost) response.append(sets[0]) response.append("break") response.append(sets[1]) howMany, subsets = self.divideString(str(response)) for i in range(howMany): msgResp = StatesMessage(to=msg.sender, body=subsets[i]) msgResp.set_metadata("language", "list") msgResp.set_metadata( "which", str(i + 1)) # bedziemy wysylac pojedynczo msgResp.set_metadata("howMany", str(howMany)) await self.send(msgResp)
async def run(self): self.fAgent.logger.log_info("Starting computing risk") myUtility = 0.0 myUtility = float(self.fAgent.worst - self.fAgent.getMyCost( str(self.fAgent.currentSigma), self.fAgent.currentSigma)) if myUtility == 0.0: myRisk = 1.0 else: myRisk = 0.0 for co in self.fAgent.activeCoworkers: proposition = self.fAgent.matesProposals[co][ len(self.fAgent.matesProposals[co]) - 1] utility = float( self.fAgent.worst - self.fAgent.getMyCost(str(proposition), proposition)) temp = (myUtility - utility) / myUtility if temp > myRisk: myRisk = temp self.fAgent.logger.log_info(f"My risk equals {myRisk}") if myRisk > 1.0005: self.fAgent.logger.log_error(f"My risk equals grater than 1.0") for co in self.fAgent.activeCoworkers: msg = StatesMessage(to=co, body=myRisk) msg.set_metadata("language", "float") await self.send(msg) # waiting for all responses from agents!!! waitingCoworkers = deepcopy(self.fAgent.activeCoworkers) matesRisk = [] counter = 0 while (len(waitingCoworkers) > 0): msg = await self.receive(timeout=5) if msg is not None: sender = str(msg.sender) if msg.metadata["performative"] == "inform" and msg.metadata[ "language"] == "float": waitingCoworkers.remove(sender) matesRisk.append(float(msg.body)) else: self.fAgent.saveMessage(msg) else: counter = counter + 1 if (counter <= MAX_TIMES): for co in self.fAgent.activeCoworkers: msg = StatesMessage(to=co, body=myRisk) msg.set_metadata("language", "float") await self.send(msg) else: self.fAgent.logger.log_error( f"We did not get response from {len(waitingCoworkers)} coworkers" ) for c in waitingCoworkers: alarmMsg = WatchdogMessage( to=self.fAgent.manager, body=str(WorkingState.COMPLAINT) + " " + c) await self.send(alarmMsg) self.set_next_state(STATE_PROPOSE) return # we should tell about it manager # we need to find out who did not responded! #if my risk is the smalles -> I should concede! if myRisk <= min(matesRisk): self.fAgent.logger.log_info("I should concede") self.set_next_state(STATE_COMPUTE_CONCESSION) else: self.fAgent.logger.log_info("I should not concede") self.set_next_state(STATE_WAIT_FOR_NEXT_ROUND)
async def run(self): self.fAgent.logger.log_info("Starting computing proposals") myAgree = dict() myDisagree = dict() sigma = self.fAgent.currentSigma worstProposed = self.fAgent.myWorstProposal limit = self.fAgent.getMyCost( str(worstProposed), worstProposed ) # in the article they used utility but as utility is def as worst - cost, we can use just cost self.fAgent.logger.log_info(f"my limit is {limit}") #compute your decision (if you agree or disagree) self.decide(myAgree, myDisagree, limit) # send it to coworkers for co, sigma in myAgree.items(): msg = StatesMessage(to=co, body="ok") msg.set_metadata("performative", "accept-proposal") await self.send(msg) for co, sigma in myDisagree.items(): msg = StatesMessage(to=co, body="not ok") msg.set_metadata("performative", "reject-proposal") await self.send(msg) #check if others agree with your proposal waitingCoworkers = deepcopy(self.fAgent.activeCoworkers) ok = 0 nok = 0 counter = 0 while (len(waitingCoworkers) > 0): msg = await self.receive(timeout=10) if msg is not None: sender = str(msg.sender) if msg.metadata["performative"] == "accept-proposal": waitingCoworkers.remove(sender) ok = ok + 1 elif msg.metadata["performative"] == "reject-proposal": waitingCoworkers.remove(sender) nok = nok + 1 else: self.fAgent.saveMessage(msg) else: counter = counter + 1 if counter > MAX_TIMES: for co in waitingCoworkers: self.fAgent.logger.log_error( "Error" ) #probably we should raise exception or something !!!!!!!!!!!!! alarmMsg = WatchdogMessage( to=self.fAgent.manager, body=str(WorkingState.COMPLAINT) + " " + co) await self.send(alarmMsg) self.clearFinalResultsInSaved() self.set_next_state(STATE_PROPOSE) return self.fAgent.logger.log_info(f"I've got {ok} oks and {nok} not oks") agreementFound = False if nok == 0: self.fAgent.logger.log_success("Agreement found!!") body = str(sigma) perf = "confirm" agreementFound = True else: perf = "disconfirm" body = "" self.fAgent.logger.log_warning("Need to work more") # notify other if there is or there is not an agreement for co in self.fAgent.activeCoworkers: msg = StatesMessage(to=co, body=body) msg.set_metadata("performative", perf) await self.send(msg) # check if there other agents proposal is correct waitingCoworkers = deepcopy(self.fAgent.activeCoworkers) agreementFound = self.checkFinalResultInSaved(waitingCoworkers, agreementFound) counter = 0 while (len(waitingCoworkers) > 0 and agreementFound == False): msg = await self.receive(timeout=5) if msg is not None: sender = str(msg.sender) if msg.metadata["performative"] == "confirm": waitingCoworkers.remove(sender) agreementFound = True elif msg.metadata["performative"] == "disconfirm": waitingCoworkers.remove(sender) else: self.fAgent.saveMessage(msg) else: counter = counter + 1 if counter > MAX_TIMES: for co in waitingCoworkers: self.fAgent.logger.log_error( "Error" ) #probably we should raise exception or something !!!!!!!!!!!!! alarmMsg = WatchdogMessage( to=self.fAgent.manager, body=str(WorkingState.COMPLAINT) + " " + co) await self.send(alarmMsg) self.clearFinalResultsInSaved() self.set_next_state(STATE_PROPOSE) return self.clearFinalResultsInSaved() if agreementFound == True: self.fAgent.logger.log_success("The end") self.fAgent.logger.log_success( f"The cost {self.fAgent.getCostAll(str(self.fAgent.currentSigma))}" ) self.fAgent.logger.log_success( f"Winning sequence {self.fAgent.currentSigma}") # print(min(self.fAgent.allCalculatedCosts.values())) self.fAgent.optimal_result = self.fAgent.currentSigma for co in self.fAgent.coworkers: msg = StatesMessage(to=co, body="We have got it!") await self.send(msg) result_dict = { "sequence": self.fAgent.currentSigma, "cost": self.fAgent.getCostAll(str(self.fAgent.currentSigma)) } result_message = ResultsMessage(to=self.fAgent.manager, body=json.dumps(result_dict)) await self.send(result_message) self.set_next_state(STATE_NOT_ACTIVE) else: self.set_next_state(STATE_COMPUTE_RISK)