CS 561, Lectures 3-5 1 Estrutura de dados para árvore de busca Estrutura do tipo nó (node) { Estado (no espaço de estados ao qual o nó corresponde); Pai.

Slides:



Advertisements
Apresentações semelhantes
Presenter’s Notes Some Background on the Barber Paradox
Advertisements

São Paulo - November 7, 2013 Measuring the Cost of Formalization in Brazil © 2003 The Ronald Coase Institute Adopting RCI methodology to measure start.
Chapter Six Pipelining
INFORMAÇÕES COMPLEMENTARES
Material pedagógico Multiplicar x 5 Clica!
Vamos contar D U De 10 até 69 Professor Vaz Nunes 1999 (Ovar-Portugal). Nenhuns direitos reservados, excepto para fins comerciais. Por favor, não coloque.
1/7/ Introducing the Personal Studies for New Christians curriculum Introduzindo o Currículo dos Estudos Pessoais para Novos Cristãos By Por David.
Exercício do Tangram Tangram é um quebra-cabeças chinês no qual, usando 7 peças deve-se construir formas geométricas.
Nome : Resolve estas operações começando no centro de cada espiral. Nos rectângulos põe o resultado de cada operação. Comprova se no final.
Copyright (c) 2003 by Valery Sklyarov and Iouliia Skliarova: DETUA, IEETA, Aveiro University, Portugal.
ADT – Arvore Binária de Pesquisa
Curso de ADMINISTRAÇÃO
Classificação. 2 Métodos de Classificação Os métodos de classificação podem ser dos tipos: Classificação interna – quando toda a coleção de itens a classificar.
Listas Encadeadas Circulares Listas Duplamente Encadeadas
DIRETORIA ACADÊMICA NÚCLEO DE CIÊNCIAS HUMANAS E ENGENHARIAS DISCIPLINA: INGLÊS FUNDAMENTAL - NOITE PROFESSOR: JOSÉ GERMANO DOS SANTOS PERÍODO LETIVO
Um pouco mais sobre modelos de objetos. Ray Path Categorization Ray Path Categorization. Nehab, D.; Gattass, M. Proceedings of SIBGRAPI 2000, Brazil,
A.4. Trabalhando com elementos de biblioteca STL – Standard Template Libraby Disponibiliza um conjunto de classes templates, provendo algoritmos eficientes.
Fundamentos da teoria dos semicondutores Faixas de energia no cristal semicondutor. Estatística de portadores em equilíbrio. Transporte de portadores.
Aula 02.
Mais sobre classes Baseada no Livro: Deitel&Deitel - C++ How To program Cap. 7 Prentice Hall 1994 SCE 213 Programação Orientada a Objetos, ICMC - USP 2.
CS 561, Session 7 1 Recall: breadth-first search, step by step.
Últimas aulas Definição de IA? Teste de Turing? Agentes Inteligentes:
CS 561, Session 6 1 Last time: Problem-Solving Problem solving: Goal formulation Problem formulation (states, operators) Search for solution Problem formulation:
Aula 4 Nomes, Vinculações, Tipos e Escopos
EXEMPLOS DE ESTRUTURAS PROTENDIDAS
Uniform Resource Identifier (URI). Uniform Resource Identifiers Uniform Resource Identifiers (URI) ou Identificador de Recursos Uniforme provê um meio.
Because we were commissioned toGo…make disciples World Evangelism Fund Offering(date)
FLUP - Elena Zagar Galvão Faculdade de Letras da Universidade do Porto INFORMÁTICA DE TRADUÇÃO FALL SEMESTER 2010 Lesson 9 26 October 2010 Teacher: Elena.
SECEX SECRETARIA DE COMÉRCIO EXTERIOR MINISTÉRIO DO DESENVOLVIMENTO, INDUSTRIA E COMÉRCIO EXTERIOR BRAZILIAN EXPORTS STATISTICAL DEPURATION SYSTEM Presentation.
Provas de Concursos Anteriores
Renda até 2 SM.
Diagnósticos Educativos = Diagnósticos Preenchidos 100% = 1.539
Criação de objetos da AD 1Luis Rodrigues e Claudia Luz.
OER LIFE CYCLE Andrew Moore and Tessa Welch.
(CESPE/ Técnico Judiciário do TRT 17ª Região/ES) O Superior Tribunal de Justiça entende que o candidato aprovado em concurso público dentro do limite.
MECÂNICA - DINÂMICA Exercícios Cap. 13, 14 e 17. TC027 - Mecânica Geral III - Dinâmica © 2013 Curotto, C.L. - UFPR 2 Problema
Tópicos Especiais em Aprendizagem Reinaldo Bianchi Centro Universitário da FEI 2012.
Part 5: Regression Algebra and Fit 5-1/34 Econometrics I Professor William Greene Stern School of Business Department of Economics.
INPE / CAP-315 Airam J. Preto, Celso L. Mendes Aula 30 (1) Empacotamento de Dados em MPI Tópicos: Buffer de Mensagem Empacotamento/Desempacotamento.
CATÁLOGO GÉIA PÁG. 1 GÉIA PÁG. 2 HESTIA PÁG. 3.
Resolução de problemas por meio de busca
Lemas (Sudkamp)  .
Universidade de Brasília Laboratório de Processamento de Sinais em Arranjos 1 Adaptive & Array Signal Processing AASP Prof. Dr.-Ing. João Paulo C. Lustosa.
Coordenação Geral de Ensino da Faculdade
Avaliação Constituição dos grupos de trabalho:
Lecture 4 Pressure distribution in fluids. Pressure and pressure gradient. Hydrostatic pressure 1.
Lecture 2 Properties of Fluids Units and Dimensions 1.
Projeto Marcas que Eu Gosto 1 PROJETO MARCAS QUE EU GOSTO Estudos Quantitativo de Consumidores Janeiro / 2005.
C ORROPIOS, C ARDINCHAS E C ÃES G RANDES O LIVRO de José Paixão em imagens – com pistas de leitura propostas por por www.joraga.net.
Introdução à Criptografia Moderna – 2ª Lista de Exercícios
A KobrA and OCL model for backward state-space search planning and partial order-planning with STRIPS Ana Emília Jairson Vitorino
Hoje é domingo, 14 de setembro de 2014 Agora mesmo são 22:54 h. Relaxe por uns momentos e aprecie … Com som Today is Monday, 1 st December Relax.
Instituto de Engenharia de Sistemas e Computadores Investigação e Desenvolvimento em Lisboa Understanding Epidemic Quorum Systems INESC-ID Lisbon/Technical.
IEEE PES General Meeting, Tampa FL June 24-28, 2007 Conferência Brasileira de Qualidade de Energia Santos, São Paulo, Agosto 5-8, Chapter 5: Harmonic.
1 Aplicações do Fecho Regular. 2 A interseção de uma linguagem livre de contexto e uma linguagem regular é uma linguagem livre de contexto livre de contexto.
RELATÓRIO CEMEC 06 COMPARAÇÕES INTERNACIONAIS Novembro 2013.
Microprocessadores 8051 – Aula 3 Interrupção
Aula Teórica 18 & 19 Adimensionalização. Nº de Reynolds e Nº de Froude. Teorema dos PI’s , Diagrama de Moody, Equação de Bernoulli Generalizada e Coeficientes.
Unit 22 Relative Clauses and Pronouns.
VOCÊ JÁ FALA INGLÊS FLUENTEMENTE?
Olhe fixamente para a Bruxa Nariguda
Equação de Bernoulli e Equação de Conservação da Energia
Clicar para rolar Click to run Caminha de 10 a 30 minutos todos os dias.... Sorri enquanto caminhas. Walk 10 to 30 minutes every day… Smile while you’re.
Faculdade de Ciências Económicas e Empresariais Universidade Católica Portuguesa 17/12/2014Ricardo F Reis 2 nd session: Principal –
IEEE PES General Meeting, Tampa FL June 24-28, 2007 Conferência Brasileira de Qualidade de Energia Santos, São Paulo, Agosto 5-8, Chapter 8: Procedure.
Máquina de Turing Universal
AM020C A interface entre Meio Ambiente, Sociedade e Economia Indicadores de produtividade e empregabilidade da agricultura do Brasil. Aluna Andressa Santos.
Inteligência Artificial
Teste e Qualidade de Software
Tópicos Avançados em Engenharia de Software
Transcrição da apresentação:

CS 561, Lectures Estrutura de dados para árvore de busca Estrutura do tipo nó (node) { Estado (no espaço de estados ao qual o nó corresponde); Pai (nó que gerou o nó corrente); Operador (ação realizada para gerar o nó corrente); Profundidade (número de nós desde a raiz); Custo (do caminho desde a raiz); } Nó = (State, Parent-node, Operator, Depth, Path-cost)

CS 561, Lectures Encapsulando informação sobre estado em nós

CS 561, Lectures Relembrando: algoritmo de busca geral Function General-Search(problem, Queuing-Fn) returns a solution, or failure nodes make-queue(make-node(initial-state[problem])) loop do if nodes is empty then return failure node Remove-Front(nodes) if Goal-Test[problem] applied to State(node) succeeds then return node nodes Queuing-Fn(nodes, Expand(node, Operators[problem])) end Queuing-Fn(queue, elements) é uma função que insere um conjunto de elementos numa fila e determina a ordem de expansão dos nós. Variando esta função produz diferentes algoritmos de busca.

CS 561, Lectures Avaliação de estratégias de busca Uma estratégia é definida pela sequência de expansão dos nós. São geralmente avaliados segundo 4 critérios: Completude: encontra sempre uma solução (se existir uma)? Complexidade de tempo: quanto demora (função do número de nós)? Complexidade em memória: quanta memória requer? Optimalidade: garante solução de custo mínimo? Tempo e complexidade são medidos em termos de: b – número máximo de galhos da árvore de busca d – profundidade da solução de custo mínimo m – profundidade máxima da árvore de busca (pode ser infinito)

CS 561, Lectures Estratégias de busca Uninformed Usa apenas informação disponível na formulação do problema, sem número de passos, custo de caminhos Apenas distingue estado objetivo de estado não-objetivo (blind search) Breadth-first (primeiro em largura) Uniform-cost (custo uniforme) Depth-first (primeiro em profundidade) Depth-limited (limitado em profundidade) Iterative deepening (aprofundando iterativamente)

CS 561, Lectures Breadth-first search (primeiro em largura) Expande nó mais raso ainda não expandido Implementação: Function Breadth-first-search (problem) returns a solution or failure return General-search(problem, Enqueue-at-end). Enqueue-at-end = coloca sucessores no final da fila

CS 561, Lectures Exemplo: viajando de Arad para Bucharest

CS 561, Lectures Breadth-first search

CS 561, Lectures Breadth-first search

CS 561, Lectures Breadth-first search

CS 561, Lectures Propiedades do algoritmo breadth-first Complettude: Tempo: Memória: Otimalidade: Search algorithms are commonly evaluated according to the following four criteria: Completeness: does it always find a solution if one exists? Time complexity: how long does it take as function of num. of nodes? Space complexity: how much memory does it require? Optimality: does it guarantee the least-cost solution? Time and space complexity are measured in terms of: b – max branching factor of the search tree d – depth of the least-cost solution m – max depth of the search tree (may be infinity)

CS 561, Lectures Propriedades do algoritmo breadth-first Completude: Sim, se b for finito Tempo:1+b+b 2 +…+b d = O(b d ), exponencial em d Memória:O(b d ), keeps every node in memory Otimalidade:Sim (assumindo custo = 1 por passo) Por que manter todos os nós em memória? Para evitar ter que revisitar nós já visitados, os quais podem levar a loops infinitos.

CS 561, Lectures Complexidade de tempo para o breadth-first search Se um nó objetivo for encontrado em profundidade d da árvore, todos os nós até esta profundidade são criados. m G b d Então: O(b d )

CS 561, Lectures FILA contém todos os nós e. (Então: 4). Em geral: b d Complexidade de memória do breadth-first search Maior número de nós na FILA são atingidos no nível d do nó objetivo. G m b d G

CS 561, Lectures Uniform-cost search (custo uniforme) Então, a função que coloca na fila mantém uma lista de nós ordenada por custo de caminho crescente, e expandimos o primeiro nó não expandido (com menor custo) Custo uniforme é refinamento de breadth-first: Breadth-first = uniform-cost, basta fazer custo = profundidade do nó Expandir nó não expandido de custo mínimo. Implementação: QueuingFN = inserir em ordem de custo de caminho crescente.

CS 561, Lectures Romania com custo de cada passo em KM

CS 561, Lectures Uniform-cost search

CS 561, Lectures Uniform-cost search

CS 561, Lectures Uniform-cost search

CS 561, Lectures Propriedades do algoritmo uniform-cost Completude:Sim, se custo de cada passo >0 Tempo:# nós com g custo da solução ótima, O(b d ) Espaço:# nodes with g cost of optimal solution, O(b d ) Otimalidade:Sim, se custo dos caminhos nunca diminuirem g(n) é o custo do caminho para o nó n Lembre-se: b = número de galhos (branching factor) d = profundidade da solução de custo mínimo

CS 561, Lectures Implementação da busca uniform-cost Initialize Queue with root node (built from start state) Repeat until (Queue is empty) or (first node has Goal state): Remove first node from front of Queue Expand node (find its children) Reject those children that have already been considered, to avoid loops Add remaining children to Queue, in a way that keeps entire queue sorted by increasing path cost If Goal was reached, return success, otherwise failure

CS 561, Lectures Precaução! Uniform-cost search não é ótimo se for terminado quando qualquer nó na fila te o estado objetivo. G D 5 10 E 5 15 F 5 20 S A C B 1 2 Uniform cost retorna o caminho com custo 102 (se qq nó contendo objetivo for considerado solução), enquanto há um caminho com custo 25.

CS 561, Lectures Nota: detecção de Loop Vimos que a busca pode falhar ou ser sub-ótima se : - não detectar loop: então o algoritmo roda infinitos ciclos (A -> B -> A -> B -> …) - não tirar da fila um nó contendo um estado já visitado: pode levar a uma solução sub-ótima - simplesmente evitando voltar aos nosso pai: parece promissor, mas não provamos que isso funciona Solução? Não colocar na fila um nó se seu estado casa com o estado de algum de seus pais (assumindo custo de caminho > 0). Assim, se custo de caminho > 0,sempre custará mais considerar um nó com aquele estado novamente do que ele já custou na primeira vez. Isto é suficiente??

CS 561, Lectures Exemplo G

CS 561, Lectures Solução pelo Breadth-First Search

CS 561, Lectures Solução pelo Uniform-Cost Search

CS 561, Lectures Note: Queueing in Uniform-Cost Search In the previous example, it is wasteful (but not incorrect) to queue-up three nodes with G state, if our goal if to find the least-cost solution: Although they represent different paths, we know for sure that the one with smallest path cost (9 in the example) will yield a solution with smaller total path cost than the others. So we can refine the queueing function by: - queue-up node if 1) its state does not match the state of any parent and2) path cost smaller than path cost of any unexpanded node with same state in the queue (and in this case, replace old node with same state by our new node) Is that it??

CS 561, Lectures A Clean Robust Algorithm Function UniformCost-Search(problem, Queuing-Fn) returns a solution, or failure open make-queue(make-node(initial-state[problem])) closed [empty] loop do if open is empty then return failure currnode Remove-Front(open) if Goal-Test[problem] applied to State(currnode) then return currnode children Expand(currnode, Operators[problem]) while children not empty [… see next slide …] end closed Insert(closed, currnode) open Sort-By-PathCost(open) end

CS 561, Lectures A Clean Robust Algorithm [… see previous slide …] children Expand(currnode, Operators[problem]) while children not empty child Remove-Front(children) if no node in open or closed has childs state open Queuing-Fn(open, child) else if there exists node in open that has childs state if PathCost(child) < PathCost(node) open Delete-Node(open, node) open Queuing-Fn(open, child) else if there exists node in closed that has childs state if PathCost(child) < PathCost(node) closed Delete-Node(closed, node) open Queuing-Fn(open, child) end [… see previous slide …]

CS 561, Lectures Example G D 5 E 5 F 5 S A C 1 5 B 1 1 # State Depth Cost Parent 1S00-

CS 561, Lectures Example G D 5 E 5 F 5 S A C 1 5 B 1 1 # State Depth Cost Parent 1S00- 2A111 3C151 Insert expanded nodes Such as to keep open queue sorted Black = open queue Grey = closed queue

CS 561, Lectures Example G D 5 E 5 F 5 S A C 1 5 B 1 1 # State Depth Cost Parent 1S00- 2A111 4B222 3C151 Node 2 has 2 successors: one with state B and one with state S. We have node #1 in closed with state S; but its path cost 0 is smaller than the path cost obtained by expanding from A to S. So we do not queue-up the successor of node 2 that has state S.

CS 561, Lectures Example G D 5 E 5 F 5 S A C 1 5 B 1 1 # State Depth Cost Parent 1S00- 2A111 4B222 5C334 6G31024 Node 4 has a successor with state C and Cost smaller than node #3 in open that Also had state C; so we update open To reflect the shortest path.

CS 561, Lectures Example G D 5 E 5 F 5 S A C 1 5 B 1 1 # State Depth Cost Parent 1S00- 2A111 4B222 5C334 7D485 6G31024

CS 561, Lectures Example G D 5 E 5 F 5 S A C 1 5 B 1 1 # State Depth Cost Parent 1S00- 2A111 4B222 5C334 7D485 8E5137 6G31024

CS 561, Lectures Example G D 5 E 5 F 5 S A C 1 5 B 1 1 # State Depth Cost Parent 1S00- 2A111 4B222 5C334 7D485 8E5137 9F6188 6G31024

CS 561, Lectures Example G D 5 E 5 F 5 S A C 1 5 B 1 1 # State Depth Cost Parent 1S00- 2A111 4B222 5C334 7D485 8E5137 9F G7239 6G31024

CS 561, Lectures Example G D 5 E 5 F 5 S A C 1 5 B 1 1 # State Depth Cost Parent 1S00- 2A111 4B222 5C334 7D485 8E5137 9F G7239 6G31024 Goal reached

CS 561, Lectures Depth-first search Expande o nó não expandido de maior profundidade Implementação: QueuingFN = insere sucessores na frente da fila

CS 561, Lectures Romania with step costs in km

CS 561, Lectures Depth-first search

CS 561, Lectures Depth-first search

CS 561, Lectures Depth-first search

CS 561, Lectures Properties of depth-first search Completeness: No, fails in infinite state-space (yes if finite state space) Time complexity:O(b m ) Space complexity:O(bm) Optimality:No Remember: b = branching factor m = max depth of search tree

CS 561, Lectures Time complexity of depth-first: details In the worst case: the (only) goal node may be on the right-most branch, G m b Time complexity == b m + b m-1 + … + 1 = b m+1 -1 Thus: O(b m ) b - 1

CS 561, Lectures Space complexity of depth-first Largest number of nodes in QUEUE is reached in bottom left- most node. Example: m = 3, b = 3 :... QUEUE contains all nodes. Thus: 7. In General: ((b-1) * m) + 1 Order: O(m*b)

CS 561, Lectures Avoiding repeated states In increasing order of effectiveness and computational overhead: do not return to state we come from, i.e., expand function will skip possible successors that are in same state as nodes parent. do not create paths with cycles, i.e., expand function will skip possible successors that are in same state as any of nodes ancestors. do not generate any state that was ever generated before, by keeping track (in memory) of every state generated, unless the cost of reaching that state is lower than last time we reached it.

CS 561, Lectures Depth-limited search Is a depth-first search with depth limit l Implementation: Nodes at depth l have no successors. Complete: if cutoff chosen appropriately then it is guaranteed to find a solution. Optimal: it does not guarantee to find the least-cost solution

CS 561, Lectures Iterative deepening search Function Iterative-deepening-Search(problem) returns a solution, or failure for depth = 0 to do result Depth-Limited-Search(problem, depth) if result succeeds then return result end return failure Combines the best of breadth-first and depth-first search strategies. Completeness: Yes, Time complexity:O(b d ) Space complexity:O(bd) Optimality:Yes, if step cost = 1

CS 561, Lectures Romania with step costs in km

CS 561, Lectures

CS 561, Lectures

CS 561, Lectures

CS 561, Lectures

CS 561, Lectures

CS 561, Lectures

CS 561, Lectures

CS 561, Lectures

CS 561, Lectures Iterative deepening complexity Iterative deepening search may seem wasteful because so many states are expanded multiple times. In practice, however, the overhead of these multiple expansions is small, because most of the nodes are towards leaves (bottom) of the search tree: thus, the nodes that are evaluated several times (towards top of tree) are in relatively small number. In iterative deepening, nodes at bottom level are expanded once, level above twice, etc. up to root (expanded d+1 times) so total number of expansions is: (d+1)1 + (d)b + (d-1)b^2 + … + 3b^(d-2) + 2b^(d-1) + 1b^d = O(b^d) In general, iterative deepening is preferred to depth-first or breadth-first when search space large and depth of solution not known.

CS 561, Lectures Bidirectional search Both search forward from initial state, and backwards from goal. Stop when the two searches meet in the middle. Problem: how do we search backwards from goal?? predecessor of node n = all nodes that have n as successor this may not always be easy to compute! if several goal states, apply predecessor function to them just as we applied successor (only works well if goals are explicitly known; may be difficult if goals only characterized implicitly). for bidirectional search to work well, there must be an efficient way to check whether a given node belongs to the other search tree. select a given search algorithm for each half.

CS 561, Lectures Comparing uninformed search strategies CriterionBreadth-UniformDepth-Depth-Iterative Bidirectional firstcostfirstlimiteddeepening (if applicable) Timeb^db^db^mb^lb^d b^(d/2) Spaceb^db^dbmblbd b^(d/2) Optimal?YesYesNoNoYes Yes Complete? YesYesNoYes if l dYes Yes b – max branching factor of the search tree d – depth of the least-cost solution m – max depth of the state-space (may be infinity) l – depth cutoff

CS 561, Lectures Summary Problem formulation usually requires abstracting away real-world details to define a state space that can be explored using computer algorithms. Once problem is formulated in abstract form, complexity analysis helps us picking out best algorithm to solve problem. Variety of uninformed search strategies; difference lies in method used to pick node that will be further expanded. Iterative deepening search only uses linear space and not much more time than other uniformed search strategies.