From the Specification to the Implementation of Norms:

Post on 05-Jan-2016

19 views 0 download

Tags:

description

From the Specification to the Implementation of Norms:. An Automatic Approach to Generate Rules from Norms to Govern the Behavior of Agents. Autor: Viviane Torres Silva Departamento de Sistemas Informáticos y Comptuación – UCM, Spain, Madrid viviane@fdi.ucm.es. Normas. Normas Permissões - PowerPoint PPT Presentation

Transcript of From the Specification to the Implementation of Norms:

An Automatic Approach to Generate Rules from Norms to Govern the Behavior of

Agents

Autor: Viviane Torres SilvaDepartamento de Sistemas Informáticos y Comptuación – UCM, Spain, Madrid

viviane@fdi.ucm.es

Normas• Permissões• Proibições• Obrigações

Proposta• Uma linguagem de especificação de normas

(estendida)• Usar regras de produção para implementar as

normas (JESS)• Usar uma aplicação de tradução automática de

linguagens (TXL)

[GARCIA-CAMINO] Propõe uma linguagem de especificação de normas• Suporta ações de diálogo (dialogical

actions)• Conjunto de punições e recompensas

limitado• Não há dependência entre normas• Não definiu um método de tradução da

especificação para regras de produção

Proposta• Estender a linguagem BNF de [GARCIA-

CAMINO]• Permitir normas para ações não dialogais

(non-dialogical actions)• Permitir dependência entre normas• Permitir normas com condições e situações

temporais• Definir quem faz as punições e as

recompensas

Jogo de futebol• O jogo em si é uma

organização• Papéis:

Árbitro (inicia, termina, checa

equipamento, puni) Treinador

(substituir os jogadores) Jogador Normal (kicker)

(kick the ball, handle the ball)

Goleiro (kick the ball, handle the

ball)

Norm 1: The referee must check the players’ equipment before starting the game.• Punishment: The referee is fired and substituted by the second

referee by the referees’ syndicate.• Reward: The referee’s reputation is increased.

Norm 2: A coach cannot substitute more than three players in the same game.• Punishment: The referee sends off the coach.

Norm 3: The referee must send off a coach if (s)he has substituted more than three players in the same game.• Norm 3 is activated when norm 2 is violated.• Punishment: The referee’s reputation is decreased.

Norm 4: Players cannot leave the playing field during the game.• Punishments: The first time, the player receives a yellow card from

the referee. The second time, the player is sent off the game by the referee.

Norm 5: The referee must show a yellow card to a player after (s)he has left the field for the first time.• Norm 5 is activated when norm 4 is violated for the first time.• Punishment: The referee’s reputation is decreased.

Norm 6: The referee must send off a player after (s)he has left the field for the second time.• Norm 6 is activated when norm 4 is violated for the second time.• Punishment: The referee is fired and substituted by the second

referee by the referees’ syndicate.• Punishment: The referee’s reputation is decreased.

Norm 7: Kickers cannot handle the ball.• Punishment: The referee declares a penalty.

Norm 8: The referee must declare a penalty if a kicker handles the ball.• Norm 8 is activated when norm 7 is violated.• Punishment: The referee is fired and substituted by the second

referee by the referees’ syndicate.

Norm 9: The goalkeeper is allowed to handle the ball.

Norm 10: The referee is only allowed to stop the game 1h and 30 min after the game has started.• Punishment: The referee’ reputation is decreased.

Ações• Dialogais: ocorre quando um agente

se comunica com outro através de uma mensagem explícita Ex. Iniciar / Parar a partida

• Não Dialogais: Ocorre quando um agente executa não relacionada a interação via mensagens. Modificar ambiente Ex. Chutar ou pegar a bola

A linguagem de Garcia-Camino não suporta ações não-dialogais• É preciso especificar uma nova regra da

linguagem: <action> ::= <non_dialogical_action> |

<dialogical_action>

<non_dialogical_action> ::=|<entity> ‘EXECUTE’ <exec>|<agent>’:’<role> ‘EXECUTE’ <exec>|<role> ‘EXECUTE’ <exec>|’ALL EXECUTE’ <exec>

<exec>::=• |

<objectORclass>’.’<method>’(‘<parameters>’)’ ’(‘<contract>’)’

• |<plan>:<action>‘(’<parameters>’)’’(‘<contract’)’

Exemplo• goalKeeperHandBall PERMISSION {(goalKeeper

EXECUTE play:handleBall () (;;) ) }

Para permitir abstrair comportamento de métodos/planos durante a verificação de uma norma, assim como inferir sobre o comportamento dos agentes para gerir as normas, sugere-se o uso de contratos (contracts) e a linguagem OCL (Object Constraint Language)

Specifying Norm 2:substitutePlyer FORBIDDEN {( coach EXECUTE

managingTeam:SubstitutePlayer (outPlayer,inPlayer,team)( ::team.coach = coach;

::team.substitutions = ::team.substitutions@PRE+1 AND

::team.playersInField->excludes(outPlayer) AND::team.playersInField->includes(inPlayer);

)IF ::team.substitutions >= 3 )(PUNISHMENT: referee PUNISHES UTTER(game;si;CAUTION(S:;SR:referee;R:_;RR:coach [RT:_;CO: sendOff ;LA:_;EN:_;ON: soccerGame ;PR:_;ID:_;RW:_;IR:_;RB:_]))

) }

<temporal_situation> ::= BEFORE <situation>| AFTER <situation>| BETWEEN '(' <situation> ',' <situation> ')‘

Specifying Norm 5:yellowCard OBLIGED {(

UTTER(game;si; CAUTION(S:;SR:referee;R:_;RR:kicker [RT:_;CO:yellowCard;LA:_;EN:_;ON:soccerGame;P

R:_;ID:_;RW:_;IR:_;RB:_])) AFTER ( kicker EXECUTE moving:LeaveField()

(::agent.position@PRE=inField;;::agent.position<>inField) ) IF ::kicker.yellowCard = false )

(PUNISHMENT: refereeSyndicate PUNISHES ::referee.reputation = ::referee.reputation@PRE-1) }

<if_condition> ::= <situation>| 'NOT' <situation>

Specifying Norm 8:penalty OBLIGED {(UTTER(game; si;

PENALTY(S:z;SR:referee;R:kickerTeam;RR:_ [RT:_;CO:penalty;LA:_;EN:_;ON:soccerGame;PR:_;ID:_;RW:_;IR:_;RB:_]))

IF kicker EXECUTE play:handleBall ()(;;))(PUNISHMENT: refereeSyndicate PUNISHES

refereeSyndicate EXECUTE managingReferees:FireReferee(game,referee)(;;) )

(PUNISHMENT: refereeSyndicate PUNISHES refereeSyndicate EXECUTE managingReferees:ContractReferee(game)(;;)) }

A violação, contemplação, ativação ou desativação de uma norma pode ativar outra norma• Proibir atividades para sanar uma norma

violada ou punir o infrator• Permitir atividades para premiar o agente

que cumpriu com uma norma

Relação de punição/recomensa:

Specifying Norm 2:substitutePlyer FORBIDDEN {( coach EXECUTE

managingTeam:SubstitutePlayer (outPlayer,inPlayer,team)( ::team.coach = coach;

::team.substitutions = ::team.substitutions@PRE+1 AND

::team.playersInField->excludes(outPlayer) AND::team.playersInField->includes(inPlayer);

)IF ::team.substitutions >= 3 )(PUNISHMENT: referee PUNISHES UTTER(game;si;CAUTION(S:;SR:referee;R:_;RR:coach [RT:_;CO: sendOff ;LA:_;EN:_;ON: soccerGame ;PR:_;ID:_;RW:_;IR:_;RB:_]))

) }

Relação de ativação, desativação, violação ou contemplação

Specifying Norm 6:

norm6 OBLIGED {( UTTER(game;si;CAUTION(S:;SR:referee;R:_;RR:kicker [RT:_;CO:sendOff;LA:_;EN:_;ON:soccerGame;PR:_;ID:_;RW:_;IR:_;RB:_]))BETWEEN ( ::kicker.yellowCard = true , 2 MINUTES OF kicker EXECUTE play:handleBall ()(;;) )

IF VIOLATEDnorm4 FORBIDDEN {( kicker EXECUTE moving:LeaveField ()

( ::agent.position@PRE=inField; ::agent.position<>inField; )BETWEEN ( UTTER(game; si; INFORM(S:;SR:referee;R:_;RR:_

[RT:_;CO:gameStart;LA:_;EN:_;ON:_;PR:_;ID:_;RW:_;IR:_;RB:_])),UTTER(game; si; INFORM(S:;SR:referee;R:_;RR:_

[RT:_;CO:gameStop;LA:_;EN:_;ON:_;PR:_;ID:_;RW:_;IR:_;RB:_])) ))(PUNISHMENT: IF ::kicker.yellowCard = false referee PUNISHESUTTER(game;si;CAUTION(S:;SR:referee;R:_;RR:kicker

[RT:_;CO:yellowCard;LA:_;EN:_;ON:soccerGame;PR:_;ID:_;RW:_;IR:_;RB:_])) )(PUNISHMENT: IF ::kicker.yellowCard = true referee PUNISHESUTTER(game;si;CAUTION(S:;SR:referee;R:_;RR:kicker

[RT:_;CO:sendOff;LA:_;EN:_;ON:soccerGame;PR:_;ID:_;RW:_;IR:_;RB:_])) ) }

AND ::kicker.yellowCard = true )(PUNISHMENT: refereeSyndicate PUNISHES refereeSyndicate EXECUTE

managingReferees:FireReferee(game,referee)(;;) ) (PUNISHMENT: refereeSyndicate PUNISHES refereeSyndicate EXECUTE

managingReferees:ContractReferee(game)(;;) ) }

Adições:• Omissão do agente ou papel que

envia/recebe a mensagem• Uso da linguagem ACL para especificar as

mensagens

Como?• Transformar as normas especificadas na

linguagem proposta em regras de produção legíveis por um motor de inferência JESS: www.jessrules.com

Fatos são atributos observáveis e ações executadas pelos agentes,além da informação das normas ativadas, desativadas, violadas ou contempladas

É possível especificar uma norma com 4 regras• Rule i: Ativa uma norma• Rule ii: Desativa uma norma• Rule iii: recompensa um agente que tenha

contemplado uma norma Obrigações -> quando executa a ação Proibições -> quando não executa a ação até a

desativação da norma Permissões -> não é usualmente recompensado

• Rule iv: Puni um agente que tenha violado a norma

Propõe o uso de TXL (http://www.txl.ca) para a tradução das regras da linguagem normativa para regras do JESS• Norm-independent rules• Norm-dependent rules

Simples obrigação, proibição ou permissão (sem condição ou condição temporal)• Nunca são desativadas (- rule(ii) )

Obrigação e permissão• Somente rule(i) e rule(iii) são necessárias• Não é possível puní-las (pois não há um deadline)

Proibição• Somente rule(i) e rule(iv) são necessárias• Não é possível recomensá-las (pois não há um

deadline)

Implementing Norm 7:;(rule i)

(defrule handleBall_rule_i?agents <- (agentsPlayingRole (role kicker))=>(foreach ?agent (list ?agents)

(assert (FORBIDDEN-non-dialogical-action-plan(entity (fact-slot-value ?agent agents)) (role kicker)(plan play) (action handleBall)(attribs "_ ")(contract-pre "_ ") (contract-post "_ ") (contract-inv "_ ")(punishment "string de punição")(condition "_ ") (status ACTIVATED)))

) )

;(rule iv)(defrule handleBall_rule_iv

?currentTime <- (currentTime)?forbidden <- (FORBIDDEN-non-dialogical-action-plan(plan play) (action handleBall)(attribs "_ ")(contract-pre "_ ") (contract-post "_ ") (contract-inv "_ ")(punishment "string de punição")(condition "_ ") (status ACTIVATED))?factViolatingNorm <- (non-dialogical-action-plan(plan play) (action handleBall)(attribs "_ ")(contract-pre "_ ") (contract-post "_ ") (contract-inv "_ "))

=>(if (= (fact-slot-value ?factViolatingNorm role)(fact-slot-value ?forbidden role)) then(assert (NormStatus_per_Agent(agent (fact-slot-value ?factViolatingNorm entity))(norm (fact-id ?forbidden))(status VIOLATED)(reason (fact-id ?factViolatingNorm))))(assert (PUNISHMENT (norm (fact-id ?forbidden)) (authority

referee)(punishedAgent (fact-slot-value ?factViolatingNorm entity))(punishment "string de punição"))) )

)

Obrigações onde X deve executar antes de W ocorrer

Deve-se definir as 4 rules• Rule(i): Ativa a obrigação de executar X• Rule(ii): Desativa a obligação de executar X

quando W ocorrer• Rule(iii): Detecta o cumprimento da

obrigação e gera a recompensa• Rule(iv): Detecta a violação e gera a

violação caso X não seja executada até W ocorrer

Norm 1;(rule i)(defrule checkEquipment_rule_i=>(assert (OBLIGED-non-dialogical-action-plan(entity referee) (plan managingGame) (action checkEquipment)(attribs "_ players ")(contract-pre "_ ") (contract-post "_ ") (contract-inv "_ ")(punishment "_ refereeSyndicate PUNISHES refereeSyndicate EXECUTE managingReferees : FireReferee (game, referee) (;;) ")(punishment "_ refereeSyndicate PUNISHES refereeSyndicate EXECUTE managingReferees : ContractReferee (game) (;;) ")(reward "_ refereeSyndicate REWARDS : referee.reputation = : referee.reputation @ PRE + 1 “) (condition "_ BEFORE (UTTER (game; si; INFORM (S :; SR : referee; R : _; RR : _ [RT : _; CO : gameStart; LA : _; EN: _; ON : _; PR : _; ID : _; RW : _; IR: _; RB : _]))) ")(status ACTIVATED))))

;(rule ii)(defrule checkEquipment_rule_ii?currentTime <- (currentTime)?obliged <- (OBLIGED-non-dialogical-action-plan (plan managingGame) (action checkEquipment)(attribs "_ players ") (contract-pre "_ ") (contract-post "_ ") (contract-inv "_ ")(punishment "_ refereeSyndicate PUNISHES refereeSyndicate EXECUTE managingReferees : FireReferee (game, referee) (;;) ")(punishment "_ refereeSyndicate PUNISHES refereeSyndicate EXECUTE managingReferees : ContractReferee (game) (;;) ")(reward "_ refereeSyndicate REWARDS : referee.reputation = : referee.reputation @ PRE + 1 ") (condition "_ BEFORE (UTTER (game; si; INFORM (S :; SR : referee; R : _; RR: _ [RT : _; CO : gameStart; LA : _; EN: _; ON : _; PR : _; ID : _; RW : _; IR :_; RB : _]))) ")(status ACTIVATED))?factDeactivatingNorm <- (dialogical-action (scene game) (state si) (performative INFORM)(sRole referee) (receiver _) (rRole _)(reply-to _) (content gameStart) (language _) (encode _) (ontology _) (protocol _)(conversation-id _) (reply-with _)(in-reply-to _) (reply-by _))=>(modify ?obliged (status DEACTIVATED)))

;(rule iii)(defrule checkEquipment_rule_iii?currentTime <- (currentTime)?obliged <- (OBLIGED-non-dialogical-action-plan (plan managingGame) (action checkEquipment)(attribs "_ players ")(contract-pre "_ ") (contract-post "_ ") (contract-inv "_ ")(punishment "_ refereeSyndicate PUNISHES ...")(punishment "_ refereeSyndicate PUNISHES ... ")(reward "_ refereeSyndicate REWARDS ...)(status ACTIVATED))?factFulfillingNorm <- (non-dialogical-action-plan (plan managingGame) (action checkEquipment) (attribs "_ players ") (contract-pre "_ ") (contract-post "_ ") (contract-inv "_ "))=>(if (= (fact-slot-value ?factFulfillingNorm entity)(fact-slot-value ?obliged entity)) then(assert (NormStatus_per_Agent (norm (fact-id ?obliged))(agent (fact-slot-value ?factFulfillingNorm entity))(status FULFILLED) (reason (fact-id ?factFulfillingNorm))))(assert (REWARD (norm (fact-id ?forbidden)) (promoter refereeSyndicate)(rewardedAgent (fact-slot-value ?factFulfillingNorm entity))(reward "_ : referee.reputation = : referee.reputation @ PRE + 1 "))) ))

;(rule iv)(defrule checkEquipment_rule_iv?currentTime <- (currentTime)?obliged <- (OBLIGED-non-dialogical-action-plan (plan managingGame) (action checkEquipment)(attribs "_ players ...(status DEACTIVATED))=>(foreach ?agent (list ?agents)(bind ?result (assert (NormStatus_per_Agent(agent (fact-slot-value ?agent agents)) (norm ?obliged)(status FULFILLMENT))))(try (= false ?result) ; the agent has fulfilled the normcatch(modify ?result (status VIOLATED))(assert (PUNISHMENT (norm (fact-id ?forbidden)) (authority refereeSyndicate) (punishedAgent (fact-slot-value ?factViolatingNorm entity))(punishment "_ refereeSyndicate EXECUTE managingReferees : FireReferee (game, referee) (;;) ")))(assert (PUNISHMENT (norm (fact-id ?forbidden)) (authority refereeSyndicate) (punishedAgent (fact-slot-value ?factViolatingNorm entity))(punishment "_ refereeSyndicate EXECUTE managingReferees : ContractReferee (game) (;;) "))) )) )

Normas regulando ações que ocorrem depois de um fato (permissão)• Rule(i) Ativa X (permissão) quando Y ocorrer• Rule(ii) Inicia como inativa• Rule(iii) Não definida• Rule(iv) Detecta quando a ação foi

executada enquanto X estava inativa• Exemplo Norma 10

Rule(i)• Se ?agente é o juiz e ?tempo é o tempo

atual• Então

Se agora = ?tempo então ative a Norma 10 Rule(ii)

• Se ?agente é o juiz e ?tempo é o tempo inicial de jogo

• Então desative a norma

Rule (iv)• Se

?tempo é o tempo atual ?proibição é a permissão de finalizar a partida

desativada ?fatoViolador = mensagem de parar o jogo

Então• Se ?fatoViolador.papel == ?probição então

Agente que mandou parar o jogo violou a norma Punição: Sindicato dos juízes deve punir o ?

fatorViolador.entidade

Normas que regulam ações entre ocorrência de dois fatos

Obrigação• Rule(i) ativa a obrigação X quando Y ocorrer• Rule(ii) desativa a obligação X quando

estiver ativada e W ocorrer• Rule(iii) verifica o cumprimento de X e gera

a recompensa quando X estiver ativada• Rule(iv) verifica a violação e gera a punição

quando Y e W ocorrerem e X não foi efetuada

Permissão• Rule(i) Ativa X quando Y ocorrer• Rule(ii) Desativa X quando X estiver ativa e

W ocorrer• Rule(iii) Gera a recompensa quando W

ocorrer• Rule(iv) Verifica a execução de X e W já

ocorreu• Rule(v) Verifica a execução de X e Y não

ocorreu

Proibição• Rule(i) Ativa X quando Y ocorrer• Rule(ii) Desativa X quando X estiver ativa e

W ocorrer• Rule(iii) Verifica se X não ocorreu e gera a

recompensa quando W ocorrer• Rule(iv) Verifica a execução de X e W

ocorreu• Rule(v) Verifica a execução de X e Y não

ocorreu

Norma 4 (proibição) Rule (i)

• Se ?fatoAtivandoNorma é juiz manda mensagem de

iniciar a partida• Então

Ative norma 4

Rule(ii)• Se

?tempoAtual é o tempoAtual ?proibição é a norma 4 ativada ?fatoDesativador é juiz enviar uma mensagem

de parar a partida• Então

Desativar Norma 4

Rule(iii)• Se

?tempoAtual é o tempo atual ?proibição é norma 4 desativada

• Então Para todos os agentes ‘a’, ‘a’ contemplou a norma 4

(foreach ?agent (list ?agents)(bind ?result (assert (NormStatus_per_Agent(agent (fact-slot-value ?agent agents)) (norm ?forbidden)

(status FULFILLED))))(try(= false ?result)catch )))

Rule(iv)• Se

?tempoAtual é o tempo atual ?proibição é a norma 4 ativada ?fatoViolador é o plano de deixar o campo

• Então Se ?fatoViolador.entidade é igual a ?

proibição.entidade ?fatoViolador.entidade violou a ?proibição (norma 4) O juiz deve punir o violador enviando para ele a

mensagem de cartão amarelo O juiz deve punir o violador enviando uma mensagem

de expulsão (???)

Bloqueio entre duas normas (uma norma se ativa devido a ativação / desativação / cumprimento / violação de outra norma)

Abordagens:• Incluir a ativação da norma B nos eventos

da norma A• Criar regras separadas para a Norma A que

é ativada por eventos da norma B

Norma 2• Rule(iv)

Se ?tempoAtual é o tempo atual ?fato são as substituições ?ação é a ação de substituir um jogador do treinador ?proibição é a norma 2

Então Se o time proibido for o time que realizou ?ação

Quem realizou ?ação violou ?proibição (norma 2) Juiz deve enviar para fora quem violou ?proibição Ativa a norma 4 (obriga ao juiz a expulsar o treinador

que infligiu a norma 2)

Pode-se usar Jess como um sistema de governança numa perspectiva de sistema

Agentes devem conhecer as regras das normas assim como o estado de violação delas para poder inferir suas ações• Dada a centralização desta informação na

base de dados do Jess, como determinar a privacidade desta informação?

Jess foi escolhido devido a facilidades na perspectiva de Eng. de Software• Facilmente integrável a implementações de

SMA. A maioria delas é feita em JAVA• JESS é parte do FIPA-OS (uma

implementação Open Source do FIPA standards

• JESS é integrável com JADE

Não é possível definir algumas rules para algumas normas

Algumas normas não podem ser definidas (suas rules)• Uma obrigação sem condições não permite

checagem de sua violação• Uma obrigação condicionada por um

“depois” (after)

Dificuldade de representar situações não realizadas• Norma: Execute A se B não foi executado

Como saber se B foi executado se não há informação nenhuma na base de dados sobre eventos não ocorridos?

Atribuir uma norma a grupo de agentes Relacionar uma situação normalizada

com momentos de execução de uma ação• O agente envia ao Jess o momento da execução

da ação

O nome de uma regra é único• Cada norma possui ~4 regras• O sistema de tradução não garante esta

característica Muitos não-terminais podem estar

vazios, exigindo a definição de duas regras• Uso de um valor default para não terminais

nulos (‘_’) Regras geradas automaticamente são

maiores que as geradas manualmente

Violações consecutivas de uma norma poderiam permitir punições diferentes• Não é tratado pelo tradutor automático

Não é possível criar normas ativadas antes/depois da realização de mais de uma ação (Ex. Norma X é ativada depois de A e B ocorrerem)