Sunteți pe pagina 1din 14

Modelarea i analiza sistemelor multiagent

Laboratorul 4

Mobilitatea agenilor
1. Considerente generale................................................................................................................... 1
1.1 Mobilitatea ntre diferite containere ...................................................................................... 1
1.2 Mobilitatea indirect.............................................................................................................. 3
2. Exemplificare printr-o aplicaie .................................................................................................... 6
3. Aplicaii ...................................................................................................................................... 14

1. Considerente generale
Mobilitatea unui agent se refer la mutarea sau duplicarea (clonarea) acestuia din containerul n
care rezid n alt container de pe aceeai platform. Deplasarea agentului ntre containere se
realizeaz prin apelul metodei doMove(), care primete ca parametru o instan a clasei
ContainerID, care conine datele referitoare la containerul destinaie.

1.1 Mobilitatea ntre diferite containere


Procesul de mutare al unui agent din containerul curent ntr-un container din aceeai platform
se realizeaz printr-un simplu apel al funciei doMove(), ce aparine clasei Agent.
[C#]
public class MobileAgent : Agent
{
public override void setup()
{
Console.WriteLine("Agent {0} started...", getAID().getName());
doMove(new ContainerID("Container1", null));
}
public override void beforeMove()
{
Console.WriteLine("Agent {0} began moving...", getAID().getName());
}
public override void afterMove()
{
Console.WriteLine("Agent {0} finished moving...", getAID().getName());
}
}

[JAVA]
public class MobileAgent extends Agent
{
@Override
public void setup()
{
1

Modelarea si analiza sistemelor multi-agent - Laborator


http://florinleon.byethost24.com/lab_masma.htm

System.out.println("Agent " + getAID().getName() + " started...");


doMove(new ContainerID("container1", null));
}
@Override
public void beforeMove()
{
System.out.println("Agent " + getAID().getName() + " began moving...");
}
@Override
public void afterMove()
{
System.out.println("Agent " + getAID().getName() + " finished moving...");
}
}

n exemplul de mai sus, agentul se va muta automat n containerul Container1 dup ce va fi


pornit. Dup cum se poate observa, JADE pune la dispoziie dou metode ce pot fi suprascrise
pentru a realiza o serie de funcii necesare operaiilor pe care agentul le are de fcut nainte de a
prsi containerul curent, prin metoda beforeMove(), i a operaiilor imediat urmtoare mutrii,
cnd agentul se afl deja n noul container, prin metoda afterMove(). Aceste dou metode sunt
apelate automat de ctre JADE, nainte, respectiv dup ce agentul a trecut din starea ACTIVE n
starea TRANSIT, specific ciclului de via al agentului mobil.
Pe lng mutarea unui agent, JADE pune la dispoziie i funcia doClone() pentru clonarea unui
agent pe un container (poate fi i acelai container). Se vor obine astfel dou instane ale agentului.
De asemenea, ca i la mutarea unui agent, avem la dispoziie funciile beforeClone() i afterClone()
pentru a interpune diferite secvene de cod n procesul de clonare al agentului.
[C#]
public class CloningAgent : Agent
{
public override void setup()
{
Console.WriteLine("Agent {0} started...", getAID().getName());
Thread.Sleep(1000);
doClone(new ContainerID("Container1", null), "MobileAgent_Clone");
}
public override void beforeClone()
{
Console.WriteLine("Cloning agent {0}...", getAID().getName());
}
public override void afterClone()
{
Console.WriteLine("Clone {0} ready...", getAID().getName());
}
}

[JAVA]
public class CloningAgent extends Agent
{
@Override
public void setup()
{
System.out.println("Agent " + getAID().getName() + "started...");
try
2

Modelarea si analiza sistemelor multi-agent - Laborator


http://florinleon.byethost24.com/lab_masma.htm

{
Thread.sleep(1000);
}catch(InterruptedException e){}
doClone(new ContainerID("container1", null), "Agent_Clone");
}
@Override
public void beforeClone()
{
System.out.println("Cloning agent " + getAID().getName() + " ...");
}
@Override
public void afterClone()
{
System.out.println("Clone " + getAID().getName() + " ready...");
}
}

1.2. Mobilitatea indirect


Mutarea unui agent poate fi fcut i din exteriorul agentului ce urmeaz a fi mutat, folosind
serviciul AMS (Agent Management Service) din containerul n care se afla agentul (prin
intermediul clasei AMSService). Acestuia i se pot trimite mesaje cu un limbaj standardizat (FIPASL) prin care s se ceara mutarea unui agent n alt container. Aceast procedur este simplificat
prin aciunea move-agent (clasa MoveAction), pentru care se vor specifica numele agentului ce
trebuie mutat i destinaia (ContainerID sau PlatformID). n JADE exist mai multe clase de tip
Action ce comunic n diverse scopuri cu serviciul AMS, astfel c se recomand folosirea metodei
urmtoare pentru a stabili ontologia i tipul comunicaiei cu acesta, indiferent de aciunea pe care
dorim s o executm:
[C#]
public class Common
{
// sends a request to the AMS (Agent Management Service)
public static void sendRequest(Agent caller, Action action)
{
// registers the ontology and the standard language for communicating with
the AMS
caller.getContentManager().registerLanguage(new SLCodec());
caller.getContentManager().registerOntology(MobilityOntology.getInstance());
// Send the request to the AMS
ACLMessage request = new ACLMessage(ACLMessage.REQUEST);
request.setLanguage(new SLCodec().getName());
request.setOntology(MobilityOntology.getInstance().getName());
try
{
caller.getContentManager().fillContent(request, action);
request.addReceiver(action.getActor());
caller.send(request);
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
}
3

Modelarea si analiza sistemelor multi-agent - Laborator


http://florinleon.byethost24.com/lab_masma.htm

[JAVA]
public class Common
{
// sends a request to the AMS (Agent Management Service)
public static void sendRequest(Agent caller, Action action)
{
// registers the ontology and the standard language for communicating with
the AMS
caller.getContentManager().registerLanguage(new SLCodec());
caller.getContentManager().registerOntology(MobilityOntology.getInstance());
// Send the request to the AMS
ACLMessage request = new ACLMessage(ACLMessage.REQUEST);
request.setLanguage(new SLCodec().getName());
request.setOntology(MobilityOntology.getInstance().getName());
try
{
caller.getContentManager().fillContent(request, action);
request.addReceiver(action.getActor());
caller.send(request);
}
catch (Exception ex)
{
System.out.println(ex.StackTrace);
}
}
}

n continuare, ne vom folosi de metoda sendRequest() pentru a trimite cererea de mutare a unui
agent. Pentru uurin, s-a folosit un agent custom MobilityServiceAgent ce va avea ca unic scop
mutarea unui agent:
[C#]
public class MobilityServiceAgent : Agent
{
private AID agentToMove;
private ContainerID newContainer;
public MobilityServiceAgent(AID AgentToMove, ContainerID NewContainer)
{
agentToMove = AgentToMove;
newContainer = NewContainer;
}
public override void setup()
{
base.setup();
addBehaviour(new RequestToMoveAgentBehaviour(agentToMove, newContainer));
takeDown();
}
}

Modelarea si analiza sistemelor multi-agent - Laborator


http://florinleon.byethost24.com/lab_masma.htm

public class RequestToMoveAgentBehaviour : OneShotBehaviour


{
private AID agentToMove;
private ContainerID newContainer;
public RequestToMoveAgentBehaviour(AID AgentToMove, ContainerID NewContainer)
{
agentToMove = AgentToMove;
newContainer = NewContainer;
}
public override void action()
{
MoveAction moveAction = new MoveAction();
MobileAgentDescription describeMovement = new MobileAgentDescription();
describeMovement.setName(agentToMove);
describeMovement.setDestination(newContainer);
moveAction.setMobileAgentDescription(describeMovement);
Common.sendRequest(myAgent, new Action(myAgent.getAMS(), moveAction));
}
}

[JAVA]
public class MobilityServiceAgent extends Agent
{
private AID agentToMove;
private ContainerID newContainer;
public MobilityServiceAgent(AID AgentToMove, ContainerID NewContainer)
{
agentToMove = AgentToMove;
newContainer = NewContainer;
}
@Override
public void setup()
{
super();
addBehaviour(new RequestToMoveAgentBehaviour(agentToMove, newContainer));
takeDown();
}
}
public class RequestToMoveAgentBehaviour extends OneShotBehaviour
{
private AID agentToMove;
private ContainerID newContainer;
public RequestToMoveAgentBehaviour(AID AgentToMove, ContainerID NewContainer)
{
agentToMove = AgentToMove;
5

Modelarea si analiza sistemelor multi-agent - Laborator


http://florinleon.byethost24.com/lab_masma.htm

newContainer = NewContainer;
}
@Override
public void action()
{
MoveAction moveAction = new MoveAction();
MobileAgentDescription describeMovement = new MobileAgentDescription();
describeMovement.setName(agentToMove);
describeMovement.setDestination(newContainer);
moveAction.setMobileAgentDescription(describeMovement);
Common.sendRequest(myAgent, new Action(myAgent.getAMS(), moveAction));
}
}

2. Exemplificare printr-o aplicaie


Dorim s dezvoltm o aplicaie cu dou containere care s conin dou tipuri de ageni:
- MonitorAgent, care va conine cte o fereastr (Form, Frame etc.) pentru fiecare container din
sistem
- MyAgent, ageni ce se vor putea muta ntre containere i care vor trimite MonitorAgent-ului
mesaje de informare legate de starea lor curent
Vor exista 4 ageni de tip MyAgent: Agent0 i Agent1 n primul container, Agent2 i Agent3 n
cel de-al doilea. Agent0 i Agent2 se vor putea muta de la un container la altul i vor informa
MonitorAgent-ul n acest sens. MonitorAgent-ul va afia n ferestre lista agenilor din fiecare
container, precum i diverse mesaje legate de starea i aciunile ntreprinse de ceilali ageni din
sistem.
Agentul MonitorAgent va implementa urmtoarele comportamente:

Refresh periodic la cele dou ferestre ce monitorizeaz containerele din aplicaie


Ateapt mesaje de la ceilali ageni: unde se afl acetia n mod curent, unde doresc s
se mute, etc.

Agentul MyAgent va implementa urmtoarele comportamente:

Agent0 i Agent2 se vor muta periodic de la un container la altul i, de fiecare dat, vor
trimite agentului monitor mesaje informative nainte i dup mutare
Agent1 i Agent3 vor rmne n containerele n care au fost ceai i vor trimite agentului
monitor cate un mesaj de salut.

Modelarea si analiza sistemelor multi-agent - Laborator


http://florinleon.byethost24.com/lab_masma.htm

Construim clasa care implementeaz MonitorAgent-ul. In metoda setup() se iniializeaz dou


ferestre, care corespund celor dou containere ntre care se vor muta ceilali ageni.
[C#]
public class MonitorAgent : Agent
{
public static FormContainer fc1, fc2;
public override void setup()
{
fc1 = new FormContainer();
fc1.Text = "Container1M";
fc1.Location = new System.Drawing.Point(100, 100);
fc2 = new FormContainer();
fc2.Text = "Container2";
fc2.Location = new System.Drawing.Point(120 + fc1.Width, 100);
fc1.Show();
fc2.Show();
fc1.Write(this.getLocalName() + " started");
this.addBehaviour(new MonitorRefreshBehaviour(this, 100));
this.addBehaviour(new MonitorReceiveBehaviour(this));
}
public override void takeDown()
{
MonitorAgent.fc1.Write("Bye from " + this.getLocalName());
}
}

[JAVA]
public class MonitorAgent extends Agent {
public static FormContainer fc1, fc2;
@Override
public void setup()
{
fc1 = new FormContainer();
fc1.setName("Container1M");
fc1.setTitle("Container1M");
7

Modelarea si analiza sistemelor multi-agent - Laborator


http://florinleon.byethost24.com/lab_masma.htm

fc1.setLocation(100, 100);
fc2 = new FormContainer();
fc2.setName("Container2");
fc2.setTitle("Container2");
fc2.setLocation(120 + fc1.getSize().width, 100);
fc1.setVisible(true);
fc2.setVisible(true);
fc1.Write(this.getLocalName() + " started");
this.addBehaviour(new MonitorRefreshBehaviour(this, 250));
this.addBehaviour(new MonitorReceiveBehaviour(this));
}
@Override
public void takeDown()
{
MonitorAgent.fc1.Write("Bye from " + this.getLocalName());
}
}

MonitorAgent are dou comportamente. Primul realizeaz refresh-ul ferestrelor de afiare. Al


doilea, de tip CyclicBehavior, asteapt mesaje de la ceilalti ageni, care i vor semnala schimbarea
strii sau mutarea de la un container la altul. MonitorAgentul va actualiza corespunztor ferestrele
containerelor, adaugnd/tergnd din liste agenii care sosesc/pleac.
[C#]
public class MonitorReceiveBehaviour : CyclicBehaviour
{
public MonitorReceiveBehaviour(Agent a) : base(a) { }
public override void action()
{
ACLMessage message = myAgent.receive();
if (message != null)
{
string[] msg = message.getContent().Split('|');
switch (msg[0])
{
case "Created":
if (msg[2] == "Container1M")
{
MonitorAgent.fc1.AddToList(msg[1]);
MonitorAgent.fc1.Write(msg[1] + " was created");
}
else if (msg[2] == "Container2")
{
MonitorAgent.fc2.AddToList(msg[1]);
MonitorAgent.fc2.Write(msg[1] + " was created");
}
break;
case "Died":
if (msg[2] == "Container1M")
{
MonitorAgent.fc1.RemoveFromList(msg[1]);
8

Modelarea si analiza sistemelor multi-agent - Laborator


http://florinleon.byethost24.com/lab_masma.htm

MonitorAgent.fc1.Write(msg[1] + " died");


}
else if (msg[2] == "Container2")
{
MonitorAgent.fc2.AddToList(msg[1]);
MonitorAgent.fc2.Write(msg[1] + " died");
}
break;
case "Moving":
if (msg[2] == "Container1M")
{
MonitorAgent.fc1.Write(msg[1] + " is about to move
from " + msg[2]);
}
else if (msg[2] == "Container2")
{
MonitorAgent.fc2.Write(msg[1] + " is about to move
from " + msg[2]);
}
break;
case "Moved":
if (msg[2] == "Container1M")
{
MonitorAgent.fc1.Write(msg[1] + " has moved to " +
msg[2]);
MonitorAgent.fc2.RemoveFromList(msg[1]);
MonitorAgent.fc1.AddToList(msg[1]);
}
else if (msg[2] == "Container2")
{
MonitorAgent.fc2.Write(msg[1] + " has moved to " +
msg[2]);
MonitorAgent.fc1.RemoveFromList(msg[1]);
MonitorAgent.fc2.AddToList(msg[1]);
}
break;
case "Hello":
if (msg[2] == "Container1M")
{
MonitorAgent.fc1.Write(msg[1] + " says hello from "
+ msg[2]);
}
else if (msg[2] == "Container2")
{
MonitorAgent.fc2.Write(msg[1] + " says hello from "
+ msg[2]);
}
break;
}
}
this.block();
}
}

Modelarea si analiza sistemelor multi-agent - Laborator


http://florinleon.byethost24.com/lab_masma.htm

[JAVA]
public class MonitorReceiveBehaviour extends CyclicBehaviour {
public MonitorReceiveBehaviour(Agent a) {
super(a);
}
@Override
public void action() {
ACLMessage message = myAgent.receive();
if (message != null) {
String[] msg = message.getContent().split("\\|");
switch (msg[0]) {
case "Created":
if (msg[2].equals("Container1M")) {
MonitorAgent.fc1.AddToList(msg[1]);
MonitorAgent.fc1.Write(msg[1] + " was created");
} else if (msg[2].equals("Container2")) {
MonitorAgent.fc2.AddToList(msg[1]);
MonitorAgent.fc2.Write(msg[1] + " was created");
}
break;
case "Died":
if (msg[2].equals("Container1M")) {
MonitorAgent.fc1.RemoveFromList(msg[1]);
MonitorAgent.fc1.Write(msg[1] + " died");
} else if (msg[2].equals("Container2")) {
MonitorAgent.fc2.AddToList(msg[1]);
MonitorAgent.fc2.Write(msg[1] + " died");
}
break;
case "Moving":
if (msg[2].equals("Container1M")) {
MonitorAgent.fc1.Write(msg[1] + " is about to move from
" + msg[2]);
} else if (msg[2].equals("Container2")) {
MonitorAgent.fc2.Write(msg[1] + " is about to move from
" + msg[2]);
}
break;
case "Moved":
if (msg[2].equals("Container1M")) {
MonitorAgent.fc1.Write(msg[1] + " has moved to " +
msg[2]);
MonitorAgent.fc2.RemoveFromList(msg[1]);
MonitorAgent.fc1.AddToList(msg[1]);
} else if (msg[2].equals("Container2")) {
MonitorAgent.fc2.Write(msg[1] + " has moved to " +
msg[2]);
MonitorAgent.fc1.RemoveFromList(msg[1]);
MonitorAgent.fc2.AddToList(msg[1]);
}
break;
case "Hello":
if (msg[2].equals("Container1M")) {
MonitorAgent.fc1.Write(msg[1] + " says hello from " +
10

Modelarea si analiza sistemelor multi-agent - Laborator


http://florinleon.byethost24.com/lab_masma.htm

msg[2]);
} else if (msg[2].equals("Container2")) {
MonitorAgent.fc2.Write(msg[1] + " says hello from " +
msg[2]);
}
break;
}
} else {
this.block();
}
}
}

Construim clasa care va implementa agentul MyAgent. Agenii de acest tip vor comunica
MonitorAgentului locaia i starea lor. Unii dintre aceti ageni (Agent0 i Agent2) se vor putea
muta ntre cele dou containere:
[C#]
public class MyAgent : Agent
{
public string localhost;
public void sendToMonitorAgent(string messageContents)
{
ACLMessage m = new ACLMessage();
m.addReceiver(new AID("MonAgent@" + localhost + ":1090/JADE",
AID.ISGUID));
m.setContent(messageContents);
send(m);
}
public override void setup()
{
string strHostName = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
IPAddress[] addr = ipEntry.AddressList;
localhost = addr[0].ToString();
sendToMonitorAgent("Created|" + getLocalName() + "|" +
here().getName());
addBehaviour(new MySendBehaviour(this));
if (this.getLocalName() == "Agent0")
{
this.addBehaviour(new MyMoveBehaviour(this, 3000));
}
if (this.getLocalName() == "Agent2")
{
this.addBehaviour(new MyMoveBehaviour(this, 5000));
}
}
public override void takeDown()
{
sendToMonitorAgent("Died|" + getLocalName() + "|" +
here().getName());
}
public override void beforeMove()
11

Modelarea si analiza sistemelor multi-agent - Laborator


http://florinleon.byethost24.com/lab_masma.htm

{
sendToMonitorAgent("Moving|" + getLocalName() + "|" +
here().getName());
}
public override void afterMove()
{
sendToMonitorAgent("Moved|" + getLocalName() + "|" +
here().getName());
}
}

[JAVA]
public class MyAgent extends Agent {
public String localhost;
public void sendToMonitorAgent(String messageContents) {
ACLMessage m = new ACLMessage();
m.addReceiver(new AID("MonAgent@" + localhost + ":1090/JADE",
AID.ISGUID));
m.setContent(messageContents);
send(m);
}
@Override
public void setup() {
InetAddress[] addr = null;
try {
addr =
InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException ex) {
Logger.getLogger(MyAgent.class.getName()).log(Level.SEVERE, null,
ex);
}
String[] add = addr[0].toString().split("/");
localhost = add[1];
sendToMonitorAgent("Created|" + getLocalName() + "|" +
here().getName());
addBehaviour(new MySendBehaviour(this));
if (this.getLocalName().equals("Agent0")) {
this.addBehaviour(new MyMoveBehaviour(this, 3000));
}
if (this.getLocalName().equals("Agent2")) {
this.addBehaviour(new MyMoveBehaviour(this, 5000));
}
}
@Override
public void takeDown() {
sendToMonitorAgent("Died|" + getLocalName() + "|" + here().getName());
}
@Override
public void beforeMove() {
sendToMonitorAgent("Moving|" + getLocalName() + "|" + here().getName());
12

Modelarea si analiza sistemelor multi-agent - Laborator


http://florinleon.byethost24.com/lab_masma.htm

}
@Override
public void afterMove() {
sendToMonitorAgent("Moved|" + getLocalName() + "|" + here().getName());
}
}

Unii ageni se vor putea muta de la un container la altul la anumite intervale, fapt definit prin
intermediul urmtorului comportament:
[C#]
public class MyMoveBehaviour : TickerBehaviour
{
private int _iter = 8;
public MyMoveBehaviour(Agent a, long period) : base(a, period) { }
public override void onTick()
{
if (--_iter > 0)
{
if (myAgent.here().getName() == "Container1M")
myAgent.doMove(new ContainerID("Container2", null));
else
myAgent.doMove(new ContainerID("Container1M", null));
}
else
block();
}
}

[JAVA]
public class MyMoveBehaviour extends TickerBehaviour {
private int _iter = 8;
public MyMoveBehaviour(Agent a, long period)
{
super(a, period);
}
@Override
public void onTick()
{
if (--_iter > 0)
{
if (myAgent.here().getName().equals("Container1M")) {
myAgent.doMove(new ContainerID("Container2", null));
}
else {
myAgent.doMove(new ContainerID("Container1M", null));
}
}
else {
block();
}
}
}
13

Modelarea si analiza sistemelor multi-agent - Laborator


http://florinleon.byethost24.com/lab_masma.htm

3. Aplicaii
3.1. S se creeze dou containere, primul container s conin doi ageni:

un agent (DisplayAgent) n containerul principal care afiseaz informaiile primite de la


ali ageni ntr-o fereastr windows
un agent mobil ReadFileMobileAgent n containerul principal care citete o list de
preuri de produse dintr-un fiier i le transmite apoi la agentul DisplayAgent.

Containerul secundar s conin un agent FilePathInfoAgent care tie din ce fiier trebuie
citite informaiile cu lista de produse.
Implementai urmtorul comportament: agentul ReadFileMobileAgent se va muta n
cointainerul secundar i va cere agentului FilePathInfoAgent (prin intermediul mesajelor) locaia
n care se afl fiierul cu lista de produse i va trimite aceast list la agentul DisplayAgent.
3.2 S se creeze o aplicaie cu mai multe containere, n care iniial s existe un numr inegal de
ageni. Creai un alt tip de agent (DistributorAgent) care s redistribuie agenii astfel nct ei s fie
uniform repartizai n fiecare container.
Pe msur ce agenii obinuii intr n sistem, ei vor trimite mesaje ctre DistributorAgent n
care se vor identifica. DistributorAgent va ine evidena pe containere a agenilor i le va trimite
mesaje n care le va solicita s se mute, astfel nct containerele s fie echilibrate.

14

Modelarea si analiza sistemelor multi-agent - Laborator


http://florinleon.byethost24.com/lab_masma.htm

S-ar putea să vă placă și