De presentatie wordt gedownload. Even geduld aub

De presentatie wordt gedownload. Even geduld aub

Benodigdheden JADE – environment 3.0 JADE API (jade\doc\api)

Verwante presentaties


Presentatie over: "Benodigdheden JADE – environment 3.0 JADE API (jade\doc\api)"— Transcript van de presentatie:

1

2 Benodigdheden JADE – environment 3.0 JADE API (jade\doc\api)
JADE docs (jade\doc): programming tutorial for beginners (JPT), administrators guide (JAG), … JADE primer: (PRI) Basic aspects: (BAS)

3 Verwijzingen API: jade\doc\api
JPT: JADE Programming Tutorial for Beginners JAG: JADE Administrator’s Guide JPG: JADE Programmer’s Guide CL&O: JADE Application-defined Content Languages and Ontologies Tutorial PRI: JADE primer BAS: Basic aspects (Bath)

4 JADE basisprincipes, graphical tools, Agents en Behaviours
Deel 1 JADE basisprincipes, graphical tools, Agents en Behaviours

5 JADE overview (JPT1) Java Agent DEvelopment framework
JADE is a middleware that facilitates the development of multi-agent systems. It includes A runtime environment where JADE agents can “live” and that must be active on a given host before one or more agents can be executed on that host. A library of classes that programmers have to/can use (directly or by specializing them) to develop their agents. A suite of graphical tools that allows administrating and monitoring the activity of running agents.

6 Containers, platforms, AMS en DF (JPT1)
Remote container Remote platform

7 Running JADE (JAG2.3/JPT3.2)
Classpath set_CLASSPATH=.;c:\jade\lib\jade.jar;c:\jade\lib\jadeTools.jar;c:\jade\lib\Base64.jar;c:\jade\lib\iiop.jar; Agent compileren (PingAgent.java) Bekijk_C:\jade\PingAgent.java en Logger.java javac *.java

8 PingAgent.java /** This agent implements a simple Ping Agent for the AgentCities project. First of all the agent registers itself with the DF of the platform and then waits for ACLMessages. If a QUERY_REF message arrives that contains the string "ping" within the content then it replies with an INFORM message whose content will be the string "alive". If it receives a NOT_UNDERSTOOD message no reply is sent. For any other message received it replies with a NOT_UNDERSTOOD message. The exchanged message are written in a log file whose name is the local name of the agent. @author Tiziana Trucco - CSELT S.p.A. @version $Date: 2002/08/02 08:10:01 $ $Revision: 1.5 $ */

9 Running JADE (JAG2.3/JPT3.2)
Agentenplatform starten met RMA java jade.Boot -gui Agentenplatform + RMA starten met PingAgent (nickname fonske) in main container java jade.Boot –gui fonske:PingAgent Een nieuwe container inpluggen java jade.Boot –container –host dezePC marcel:PingAgent

10 Remote Monitoring Agent (JAG4.1)

11 Dummy Agent (JAG 4.2)

12 DF GUI (JAG4.3)

13 Sniffer Agent (JAG4.4)

14 Agent class (JPT3) We programmeren agents door overerving van klasse jade.core.Agent Override void setup(), void takeDown() Agent methods: AID getAID(), Location here(), Object[] getArguments(), void doDelete(), … Voorbeeld JPT3: BookBuyerAgent (nog geen eigenlijke activiteit)

15

16 Agent life cycle (JPG3.2.1) doActivate() doWait() doSuspend() doWake()
doDelete() doMove(*,*) doStart()

17 Behaviour class (JPT4.1) Eigenlijke activiteit
We programmeren behaviours door overerving van subklasse van klasse jade.core.behaviours.Behaviour Behaviour starten in Agent class m.b.v. addBehaviour() method (vaak in setup()) “Behaviours are scheduled in an execution pool” Override void action() en boolean done()

18 1 THREAD PER AGENT!!!

19 Agent 1 B1.action() B2.action() B1.action() B2.action() B1.action() Agent 2 B8.action() B9.action() B9.action() B9.action() B9.action() Agent 3 B1.action() B6.action() B7.action() B1.action() B6.action() B7.action() tijd

20 Behaviour class Implementeer als inner class van uw agent (soms praktischer) of als aparte klasse (mooier). action() atomische eenheid die steeds wordt uitgevoerd Wanneer done() true wordt, wordt behaviour uit execution pool verwijderd Override eventueel int onEnd() en void onStart() Datamember Agent myAgent

21 Voorbeeld SimpleBehaviour (PRI2)
import jade.core.Agent; import jade.core.behaviours.*; public class myAgent extends Agent { protected void setup() addBehaviour( new myBehaviour( this ) ); } class myBehaviour extends SimpleBehaviour public myBehaviour(Agent a) { super(a); public void action() //...this is where the real programming goes !! private boolean finished = false; public boolean done() { return finished; } // End myBehaviour }//end class myAgent

22 Behaviour class Method block(): roep enkel op op het einde van action()! De behaviour wordt pas gerescheduled als A time of millis milliseconds has passed since the call to block(). An ACL message is received by the agent this behaviour belongs to. Method restart() is called explicitly on this behaviour object. Hou er rekening mee dat hij desondanks eens kan unblocken! “block() blokt niet maar stelt gewoon een delay in die ingaat NA de action() method”

23 Voorbeeld PRI3 class BlockTwice extends SimpleBehaviour {
static long t0 = System.currentTimeMillis(); public void action() System.out.println( "Start: " + (System.currentTimeMillis()-t0) ); block(250); System.out.println( " after block(250): " block(1000); System.out.println( " after block(1000): " System.out.println(); } private int n = 0; public boolean done() { return ++n > 3; } Start: 1 after block(250): 7 after block(1000): 9 Start: 258 after block(250): 261 after block(1000): 263 Start: 512 after block(250): 515 after block(1000): 517 Start: 767 after block(250): 769 after block(1000): 771

24 Voorbeeld Agent3.java (PRI3)
class TwoSteps extends SimpleBehaviour { int state = 1; public void action() switch( state ) { case 1: block( 200 ); break; case 2: System.out.println( "--- Message " ); block( 800 ); case 3: System.out.println( " -- message 2 --" ); finished = true; doDelete(); // applies to the Agent } state++; private boolean finished = false; public boolean done() { return finished; } FSM patroon Er wordt algemeen aangeraden om de CPU tijd tijdens action() kort te houden omwille van de preemptive multitasking; de andere behaviours van dezelfde agent krijgen zo ook een kans!!!! andere SimpleBehaviour Looper unblockt om de 300 ms!!!!!!!! 0: alice --- Message 1 --- 340: alice 640: alice 950: alice -- message 2 --

25 Nog meer behaviours (JPT4.2/4.3)

26 CompositeBehaviour (BAS3)

27 FSMBehaviour (API)

28 Oefening Schrijf een agent met
Een datamember int aantalBranden die het aantal branden in een dorp aangeeft Een behaviour Brandstichter die op random (Math.random()) tijdstippen brand sticht (aantalBranden++). Een SimpleBehaviour Brandweer die zich in verschillende states kan bevinden State 1: om de 500ms wordt er gecheckt of er brand is State 2: de brandweer wordt bij elkaar geroepen (block 1 sec) State 3: er wordt naar de brand gereden (block 1 sec) State 4: de brand wordt geblust (block 1 sec) State 5: er wordt terug naar de kazerne gereden (block 1 sec) - (aantalBranden--).

29 Deel 2 Agent communication, Message Templates, Directory Facilitator, Interaction Protocols en Message Content

30 Agent Communication (JPT5)

31 Agent Communication (Helin)
commun. Act + ontologies syntax (ACLcodec) + semantiek

32 ACLMessage fields (JPT5.1)
The sender of the message The list of receivers The communicative intention (also called “performative”) indicating what the sender intends to achieve by sending the message. REQUEST, INFORM, CFP, … The content i.e. the actual information included in the message (i.e. the action to be performed in a REQUEST message, the fact that the sender wants to disclose in an INFORM message …). The content language i.e. the syntax used to express the content (both the sender and the receiver must be able to encode/parse expressions compliant to this syntax for the communication to be effective). The ontology i.e. the vocabulary of the symbols used in the content and their meaning (both the sender and the receiver must ascribe the same meaning to symbols for the communication to be effective). Some fields used to control several concurrent conversations and to specify timeouts for receiving a reply such as conversation-id, reply-with, in-reply-to, reply-by.

33 Zenden en ontvangen (JPT5)
STERK AANBEVOLEN – PROBEER HET NIET ANDERS!

34 Waarschuwing (JPT5.8) Er bestaat ook zoiets als BlockingReceive()
Gebruik het beter niet: het blokkeert de complete agent-thread tot wanneer er een message arriveert ….

35 Message Templates (PRI4)
Behaviour met “selective reception” Vermijd overlappende actieve templates! MatchPerformative( performative ) MatchSender( AID ) MatchConversationID( String ): this is really useful and( Template1, Template2 ) or ( Template1, Template2 ) not( Template ) and to a lesser extent: MatchOntology( String ) MatchProtocol( String )

36 Message Templates (PRI4)
MessageTemplate mt = MessageTemplate.and( MessageTemplate.MatchPerformative( ACLMessage.INFORM ), MessageTemplate.MatchSender( new AID( "a1", AID.ISLOCALNAME))) ; ACLMessage msg = receive( mt ); if (msg != null) { // handle message } block(); Er zullen meer nutteloze unblocks voorkomen

37 Hoe bekom ik AID’s van collega-agenten? (PRI4)
Nickname opnemen in de code: new AID( "store", AID.ISLOCALNAME) Via gebruikersinterfaces, bijvoorbeeld JADE GUI Via de DF (conventioneel) Via de AMS (inconventioneel)

38 Directory Facilitator (JPT6.1)

39 DFAgentDescription (PRI5)
Name: AID // Required for registration Protocols: set of Strings Ontologies: set of Strings Languages: set of Strings Services: set of { { Name: String // Required for each service specified Type: String // Required ... Owner: String Properties: set of { Name: String Value: String }

40 DF Registratie (PRI5) Registratie doorgaans in setup()
DFAgentDescription dfd = new DFAgentDescription(); dfd.setName( getAID() ); ServiceDescription sd = new ServiceDescription(); sd.setType( "buyer" ); sd.setName( getLocalName() ); dfd.addServices(sd); try { DFService.register(this, dfd ); } catch (FIPAException fe) { fe.printStackTrace(); } Registratie doorgaans in setup() Probeer dit eens te sniffen! Slechts 1 registratie per agent

41 DF Deregistratie (PRI5)
protected void takeDown() { try { DFService.deregister(this); } catch (Exception e) {} } Deregistratie doorgaans in takeDown() Probeer dit eens te sniffen!

42 DF Search (PRI5) Ook vaak in setup()
DFAgentDescription dfd = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType( "buyer" ); dfd.addServices(sd); DFAgentDescription[] result = DFService.search(this, dfd); System.out.println(result.length + " results" ); if (result.length>0) System.out.println(" " + result[0].getName() ); Ook vaak in setup() Met search, deregistratie en registratie is het mogelijk om je eigen description dynamisch bij te werken

43 DF Subscription Service (PRI5)
DFAgentDescription dfd = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType(....); dfd.addServices(sd); SearchConstraints sc = new SearchConstraints(); sc.setMaxResults(new Long(1)); send(DFService.createSubscriptionMessage(this, getDefaultDF(), dfd, sc)); Launch een ontvangende behaviour (template?) met DFAgentDescription dfds =DFService.decodeNotification(msg.getContent());

44 DF Subscription Service (PRI5)
All in one: DFAgentDescription template = // fill the template addBehaviour( new SubscriptionInitiator( this, DFService.createSubscriptionMessage( this, getDefaultDF(), template, null)) { protected void handleInform(ACLMessage inform) { try { DFAgentDescription[] dfds = DFService.decodeNotification(inform.getContent()); // do something with dfds } catch (FIPAException fe) {fe.printStackTrace(); } });

45 Interaction Protocols
Communicative act = performative = “message type” Foundation for Intelligent and Physical Agents (FIPA) definieert bibliotheek van formele modellen: Performatives in JADE: zie API (fields van klasse ACLMessage) FIPA beschrijft protocollen bijv. FIPA Request (/fipa00026/) en FIPA Query (/fipa00027/)

46 SL formalisme i: zender j: ontvanger Φ: proposition FP: feasible precondition RE: rational effect operatoren B: beliefs that … is true U: is uncertain about … but thinks that it is more likely to be true than to be false C: desires that … currently holds BifjΦ = BjΦ v Bj┐Φ UifjΦ = UjΦ v Uj┐Φ

47 SL formalisme operatoren I: intends that … Done(a): a has just taken place Agent (j, a): j is the only agent that (will) perform(s) action a

48

49 Interaction Protocols (BAS5)
Er bestaat een hele reeks gelijkaardige protocols (FIPA-Request, FIPA-query, FIPA-propose, FIPA-Request-When, FIPA-recruiting, FIPA-brokering, FIPA-subscribe, …) “Rational Effect” behaviours in JADE: SimpleAchieveREInitiator en SimpleAchieveREResponder voor 1-to-1 communicatie “Werd het rationeel effect van het verzenden van een eenvoudige communicative act bereikt?” Voorbeeld BAS5: MarriageProposer en MarriageResponder

50 MarriageProposer (BAS5)
class MarriageProposer extends SimpleAchieveREInitiator{ protected MarriageProposer(Agent agent,ACLMessage msg){ super(agent,msg); } protected void handleAgree(ACLMessage msg) { System.out.println(myAgent.getLocalName() + ": OOH! " + msg.getSender().getLocalName() +" Has agreed to marry me, I'm so excited!"); protected void handleRefuse(ACLMessage msg) { // ... ACLMessage msg = new ACLMessage(ACLMessage.REQUEST); AID to = new AID(); to.setLocalName("bob"); msg.setSender(getAID()); msg.addReceiver(to); msg.setContent("Marry Me!"); msg.setProtocol(InteractionProtocol.FIPA_REQUEST); addBehaviour(new MarriageProposer(this,msg));

51 MarriageResponder (BAS5)
class MarriageResponder extends SimpleAchieveREResponder{ public MarriageResponder(Agent agent){ super(agent, createMessageTemplate(InteractionProtocol.FIPA_REQUEST)) ;} protected ACLMessage prepareResponse(ACLMessage msg) { ACLMessage response = msg.createReply(); //afhankelijk van de voorwaarden . . . response.setPerformative(ACLMessage.AGREE); return response; } protected ACLMessage prepareResultNotification(ACLMessage inmsg, ACLMessage outmsg) { ACLMessage msg = inmsg.createReply(); msg.setContent("I Do!"); return msg;

52 Overzicht Interaction Protocols
“Rational Effect” behaviours in JADE: SimpleAchieveREInitiator en SimpleAchieveREResponder voor 1-to-1 conversatie AchieveREInitiator en AchieveREResponder voor 1-to-n conversatie (zie JPG3.5.1) Experimenteel: FIPA-subscribe (/fipa00035/): SubscriptionInitiator en SubscriptionResponder voor 1-to-n conversatie (in JPG beschrijft men iets analoogs voor FIPA-propose) FIPA-contract-net protocol (zie volgende) Zelf IP’s schrijven? JPG3.5.5: “Generic states of interaction protocols” Bijvoorbeeld Dutch Auction (/fipa00032/) of English Auction (/fipa00031/)

53 Contract Net Protocol (/fipa00029/)

54 Contract Net Protocol (/fipa00029/)
Zie JPG3.5.2/API: ContractNetInitiator (handleAllResponses, handleAllResultNotifications) en ContractNetResponder (prepareResonse, prepareResultNotification)

55 ACL Message Content (PRI7)
Content type Getting content Setting content Strings getContent() SetContent() Java Objects getContentObject() SetContentObject() Ontology Objects extractContent() fillContent() Tot nu toe… Handig maar geen FIPA; serialiseer! Content language + ontologie; methods via ContentManager

56 ( ) Oefening Schrijf een agent die
Tijdens setup bij DF op zoek gaat naar geregistreerde PingAgenten () Zich ook subscribet bij de DF om weet te hebben van nieuwe PingAgenten – gebruik hiervoor de SubscriptionInitiator (FIPA-Subscribe) Zelfstandige behaviours bezit die elk op zich één van de aanwezige PingAgenten pingen om de 5 seconden Pas de PingAgent aan zodat pingen gebeurt over het FIPA-Request Interaction Protocol Wat gebeurt er als we een PingAgent verwijderen? Los het probleem op. ( )

57 Content Language en Ontologie, JADE uitbreidingen
Deel 3 Content Language en Ontologie, JADE uitbreidingen

58 ACL Message Content (PRI7)
Content type Getting content Setting content Strings getContent() SetContent() Java Objects getContentObject() SetContentObject() Ontology Objects extractContent() fillContent() Tot nu toe… Handig maar geen FIPA; serialiseer! Content language + ontologie; methods via ContentManager

59 Content Language en ontologie (BAS6)
CL (= codec): hoe wordt de boodschap geëncodeerd? 3 talen worden in JADE ondersteund: FIPA-SL familie (Semantic Language, human-readable, ~ LISP) LEAP encoding: lightweight binary encoding The Java Codec: which is designed for effficient message exchange between agents on the same platform. Talen hebben verschillende semantiek en zijn niet echt compatibel. SL is de rijkste taal. De ontologie beschrijft de structuur en de semantiek van de berichtinhoud, zoals eigenschappen van bepaalde elementen en de relaties ertussen. In JADE dienen ontologieën beschreven te worden in JAVA klassen, manueel of met tools zoals Protégé

60 JADE-tutorial CL&O

61 JADE-tutorial CL&O Predicates (expressie, false of true)
(Works-for (Person :name John) (Company :name TILAB)) Terms (verwijzen naar bestaande entiteiten) Concepts (Person :name John :age 33) Agent actions (verbonden aan performative) (Sell (Book :title “The Lord of the rings”) (Person :name John)) Aggregates (sequence (Person :name John) (Person :name Bill)) Identifying Referential c (all ?x (Works-for ?x (Company :name TILAB)) = alle elementen x waarvoor geldt dat … Variables and primitives

62 JADE-tutorial CL&O Music Shop example
Concepts: Item, CD, Track and Book (and AID) Predicate: Owns Action: Sell

63 JADE-tutorial CL&O public class MusicShopOntology extends Ontology {
public static final String ONTOLOGY_NAME = "Music-shop-ontology"; public static final String ITEM = "Item"; public static final String ITEM_SERIAL = "serial-number"; public static final String CD = "CD"; public static final String CD_NAME = "name"; public static final String CD_TRACKS = "tracks"; public static final String TRACK = "Track"; public static final String TRACK_TITLE = "title"; public static final String TRACK_DURATION = "duration"; public static final String BOOK = "Book"; public static final String BOOK_TITLE = "title"; public static final String OWNS = "Owns"; public static final String OWNS_OWNER = "owner"; public static final String OWNS_ITEM = "item"; public static final String SELL = "Sell"; public static final String SELL_BUYER = "buyer"; public static final String SELL_ITEM = "item";

64 JADE-tutorial CL&O // The singleton instance of this ontology
private static Ontology theInstance = new MusicShopOntology(); public static Ontology getInstance() { return theInstance; } private MusicShopOntology() { super(ONTOLOGY_NAME, BasicOntology.getInstance()) try { add(new ConceptSchema(ITEM), Item.class); add(new ConceptSchema(CD), CD.class); add(new ConceptSchema(TRACK), Track.class); add(new ConceptSchema(BOOK), Book.class); add(new PredicateSchema(OWNS), Owns.class); add(new AgentActionSchema(SELL), Sell.class);

65 JADE-tutorial CL&O ConceptSchema cs = (ConceptSchema) getSchema(ITEM);
cs.add(ITEM_SERIAL, (PrimitiveSchema) getSchema(BasicOntology.INTEGER), ObjectSchema.OPTIONAL); cs = (ConceptSchema) getSchema(CD); cs.addSuperSchema((ConceptSchema) getSchema(ITEM)); cs.add(CD_NAME, (PrimitiveSchema) getSchema(BasicOntology.STRING)); cs.add(CD_TRACKS, (ConceptSchema) getSchema(TRACK), 1, ObjectSchema.UNLIMITED); // . . . PredicateSchema ps = (PredicateSchema) getSchema(OWNS); ps.add(OWNS_OWNER, (ConceptSchema) getSchema(BasicOntology.AID)); ps.add(OWNS_ITEM, (ConceptSchema) getSchema(ITEM)); AgentActionSchema as = (AgentActionSchema) getSchema(SELL); as.add(SELL_ITEM, (ConceptSchema) getSchema(ITEM)); as.add(SELL_BUYER, (ConceptSchema)getSchema(BasicOntology.AID));

66 JADE-tutorial CL&O Bouw Concepts, Predicates en AgentActions volledig analoog op Overerving juiste interface Overerving indien super-schema Juiste datamembers (STRING vertaalt zich in String enzovoort …). Indien cardinaliteit >1 wordt het een List

67 JADE-tutorial CL&O package musicShopOntology;
import jade.util.leap.List; public class CD extends Item { private String name; private List tracks; public String getName() { return name;} public void setName(String n) { name = n;} public List getTracks() { return tracks;} public void setTracks(List l) { tracks = l;}} package musicShopOntology; import jade.content.Predicate; import jade.core.AID; public class Owns implements Predicate{ private AID owner; private Item item; public AID getOwner() { return owner;} public void setOwner(AID id) { owner = id;} public Item getItem() { return item;} public void setItem(Item i) { item = i;}}

68 JADE-tutorial CL&O Content Language Formaat SL (ACTION
(agent-identifier :name John) (Sell (Book :title “The Lord of the rings”) (agent-identifier :name Peter) )

69 JADE-tutorial CL&O Registratie
public class SellerAgent extends Agent { private Codec codec = new SLCodec(); private Ontology ontology = MusicShopOntology.getInstance(); protected void setup() { getContentManager().registerLanguage(codec); getContentManager().registerOntology(ontology) }

70 JADE-tutorial CL&O Gebruik
ACLMessage msg = new ACLMessage(ACLMessage.QUERY_IF); msg.addReceiver(sellerAID); msg.setLanguage(codec.getName()); msg.setOntology(ontology.getName()); // bouw owns object op getContentManager().fillContent(msg, owns); send(msg); MessageTemplate mt = MessageTemplate.and( MessageTemplate.MatchLanguage(codec.getName()), MessageTemplate.MatchOntology(ontology.getName()) ); ce = getContentManager().extractContent(msg); if (ce instanceof Owns) { Owns owns = (Owns) ce; Item it = owns.getItem();}

71 Niet aan bod gekomen GUI programming JADE vanuit externe applicaties
MTP’s (Message Transport Protocols) Mobiliteit en Cloning (+ ontologie voor mobiliteit)

72 JADE uitbreidingen Meer informatie: http://jade.cselt.it/
LEAP: JADE voor mobiele toestellen (J2SE, J2ME en Personal Java) MTP’s: Orbacus, HTTP, JMS Codecs: XML- en RDF-varianten, bit-efficient JADE-S (in ontwikkeling): ondersteuning voor security Ondersteuning voor applets en JSP JADEX: JADE-agents in BDI-formaat -

73 Oefening Bestudeer het PeopleOntology – voorbeeld (zie website). Werk de AgentAction “marry” en eventueel ontbrekende predicaten uit. Pas het voorbeeld uit BAS5 aan: De agenten gebruiken de PeopleOntology Beide agenten bouwen tijdens setup hun stamboom op

74 Agents en het Prisoners’ dilemma
Deel 4 Agents en het Prisoners’ dilemma

75 Prisoners’ dilemma A B Deny Confess 2 3 1
A B Deny Confess 2 3 1

76 Prisoners’ dilemma 1 wedstrijd = 200 iteraties tegen 1 en dezelfde tegenstrever Enkel gedurende cyclus van 200 iteraties (= 1 wedstrijd) geheugenopbouw Tornooi tussen N agenten: elke agent doet (N-1) x 5 wedstrijden

77 Prisoners’ dilemma Ontwikkelen van spelomgeving
Welke agenten? Autoriteit? Gevangenen? Interactie DF? Hoe organiseert de autoriteit? Communicatie tussen autoriteit en gevangenen en tussen gevangenen onderling: interaction protocol, content language en ontologie? Hoe zullen we vermijden dat buiten 1 wedstrijd geheugen wordt opgebouwd? Herstarten agent/behaviour? Registratie van de punten? Ontwerp autoriteit + ev. Ontwerp interface voor gevangene


Download ppt "Benodigdheden JADE – environment 3.0 JADE API (jade\doc\api)"

Verwante presentaties


Ads door Google