Shannon's Theseus

Shannon's Theseus preview image

1 collaborator

Tags

machine learning, claude shannon, theseus, maze 

"The first machine learning app (1952)"

Tagged by Diego Díaz Córdova 9 days ago

Visible to everyone | Changeable by everyone
Model was written in NetLogo 7.0.0 • Viewed 88 times • Downloaded 0 times • Run 0 times
Download the 'Shannon's Theseus' modelDownload this modelEmbed this model

Do you have questions or comments about this model? Ask them here! (You'll first need to log in.)


WHAT IS THIS?

This model emulates Shannon's Theseus from the 1950s. It is probably one of the first AI applications and surely the first learning machine application. Theseus is a maze-solving mouse who wanders around until it finds the goal. The mouse marks its path and can also remember the winning path. The world in this case is a 5x5 square maze and can be rearranged in any form. In Shannon's original model, the engine was beneath the floor: a set of electromagnets mounted on a motorized platform that could move in a von Neumann neighborhood (north, east, west, and south). When Theseus finds a wall, the relay under the ground switches from on to off and records that square. Then the mouse rotates 90 degrees and keeps moving forward until it finds the goal. Once the mouse has learned the path, it can go directly to the cheese. In this version, we use a slightly different approach, seizing the power of the NetLogo turtle (recording the path and the success as global variables).

HOW IT WORKS

Theseus follows a very simple rule: at each step, it marks the patch as visited, then it tries the 4 directions. If there is no wall and there is available room, it decides the next move. If the mouse arrives at the goal, it learns the path and can repeat that trajectory in the minimum number of steps. The user can rearrange the maze and choose another path for Theseus to learn again.

HOW TO USE IT

Pressing the "Setup" button initializes the model. The goal and the start are marked at their locations in the corners, with yellow and green colors respectively. Theseus is placed at the start patch. The user can build the maze at their pleasure by pressing the "Draw Wall" button to draw the maze walls and the "Erase" button to eliminate the walls. The entire design is built patch by patch. The "Go" button starts the model, with Theseus moving and exploring the maze step by step (it is not a continuous button) until it finds the goal. Pressing the "Mouse House" button resets the model and puts the mouse at the start location.

THINGS TO TRY

You can try with differents types of maze, more complex or more simple and evaluate how many steps take the mouse to find the cheese.

EXTENDING THE MODEL

The model can be extended applying new algorithms to solve the different mazes.

CREDITS AND REFERENCES

Claude Shannon Theseus, 1952, Bell Laboratories Diego Díaz Córdova Cátedra de Informática Escuela de Nutrición Facultad de Medicina Universidad de Buenos Aires ddiazcordova@fmed.uba.ar

Comments and Questions

Please start the discussion about this model! (You'll first need to log in.)

Click to Run Model

patches-own [
  es-pared?      ;; ¿Es una pared? (true/false)
  direccion-optima ;; Dirección guardada (0=N,1=E,2=S,3=O, -1=sin memoria)
  visitado?      ;; ¿El ratón pasó por aquí?
  en-camino?     ;; ¿Está en el camino exitoso?  
]

globals [
  inicio         ;; Patch donde empieza el ratón
  meta           ;; Patch del queso
  intento        ;; Número de intento
  modo-aprendizaje ;; ¿Está en modo exploración? (true=aprendiendo, false=usando memoria)
  maximo-pasos-esperados  ;; Total de casillas del laberinto
  flagmanysteps? ;;flag que se prende si el raton dio más de 25 pasos
]

turtles-own [
  paso-actual    ;; Contador de pasos en el intento actual
  exito?         ;; ¿Encontró el queso en este intento?
  camino-temporal ;; Lista de patches visitados en este intento
  direccion-actual
]

to setup
clear-all
;; crea la base del laberinto
ask patches 
  [ 
    set es-pared? false 
    set pcolor black
    set direccion-optima -1
    set visitado? false
    set en-camino? false
    ;; comienzo
    if pxcor = min-pxcor and pycor = min-pycor
      [
        set es-pared? false 
        set pcolor green 
      ]
    ;; queso como recompensa
    if pxcor = max-pxcor and pycor = max-pycor
      [
        set es-pared? false 
        set pcolor yellow
      ]
  ]
;;guardo la meta
set meta patch max-pxcor max-pycor  
;; Marcar inicio (esquina inferior izquierda)
 
;; Crear el ratón (tortuga)
create-turtles 1 
  [
    set shape "mouseside"
    set color brown
    setxy min-pxcor min-pycor
    set paso-actual 0
    set exito? false
    set camino-temporal []
    set inicio patch-here
    set direccion-actual 1
  ]
set intento 1
set modo-aprendizaje true
set maximo-pasos-esperados 100  ;; Para un laberinto 5x5  
set flagmanysteps? false  
reset-ticks
end 

to drawwall
   if mouse-down? [
    ; Find the patch corresponding to the mouse's X and Y coordinates
    let target-patch patch mouse-xcor mouse-ycor
    
    ; Ensure the mouse is actually inside the view limits
    if target-patch != nobody [
      ask target-patch [
        set pcolor white  ; Change this to any color you want to draw with
        set es-pared? true
      ]
    ]
  ]
end 

to erasewall
   if mouse-down? [
    ; Find the patch corresponding to the mouse's X and Y coordinates
    let target-patch patch mouse-xcor mouse-ycor
    
    ; Ensure the mouse is actually inside the view limits
    if target-patch != nobody [
      ask target-patch [
        set pcolor black  ; Change this to any color you want to draw with
        set es-pared? false
      ]
    ]
  ]
end   

to go
  if any? turtles [
    ask turtles [ explorar-y-aprender ]
  ]
  if flagmanysteps? = true
      [
        set flagmanysteps? false
        mousehouse
      ]
  tick
end 

to explorar-y-aprender
  ;; Si ya encontró el queso en este intento, no seguir
  
  if exito? [ stop ]
 
  if paso-actual > maximo-pasos-esperados [
    user-message "Demasiados pasos! Posible loop detectado. Reiniciando intento..."
    set flagmanysteps? true  ;; prende flag para Reiniciar sin grabar el camino
    stop
  ]
  
  ;; Verificar si llegó a la meta
  if patch-here = meta [
    set exito? true
    user-message (word "¡Encontré el queso en el intento " intento "! en " paso-actual " pasos")
    aprender-camino      ;; Grabar el camino exitoso en los relés
    reiniciar-para-nuevo-intento
    stop
  ]
   ;; Marcar patch como visitado
  ask patch-here [
    set visitado? true
    ;set pcolor pcolor + 0.5  ;; Aclarar ligeramente para indicar visita
  ]
   ;; Registrar este patch en el camino temporal
  set camino-temporal lput patch-here camino-temporal
   
  ;; Decidir hacia dónde moverse
  let siguiente-direccion decidir-movimiento
  
  ;; Ejecutar el movimiento
  if siguiente-direccion != -1 [
    mover-en-direccion siguiente-direccion
    set paso-actual paso-actual + 1
  ]
end 

to-report decidir-movimiento
  ;; PRIMERO: ¿Hay memoria de relé en este patch?
  let memoria [direccion-optima] of patch-here
  
  if (memoria != -1) and (not modo-aprendizaje) [
    ;; Usar el camino aprendido (explotación)
    report memoria
  ]
  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  let direcciones-a-probar []
  
  if direccion-actual = 0 [ set direcciones-a-probar [1 0 3 2] ]  ;; N: derecha(E), adelante(N), izquierda(O), atrás(S)
  if direccion-actual = 1 [ set direcciones-a-probar [2 1 0 3] ]  ;; E: derecha(S), adelante(E), izquierda(N), atrás(O)
  if direccion-actual = 2 [ set direcciones-a-probar [3 2 1 0] ]  ;; S: derecha(O), adelante(S), izquierda(E), atrás(N)
  if direccion-actual = 3 [ set direcciones-a-probar [0 3 2 1] ]  ;; O: derecha(N), adelante(O), izquierda(S), atrás(E)
  
  foreach direcciones-a-probar [ d ->
    let dxL 0
    let dyL 0
    if d = 0 [ set dyL 1 ]  ;; Norte
    if d = 1 [ set dxL 1 ]  ;; Este
    if d = 2 [ set dyL -1 ] ;; Sur
    if d = 3 [ set dxL -1 ] ;; Oeste
    
    let destino patch-at dxL dyL
    
    if destino != nobody and not [es-pared?] of destino [
      ;; ¡Movimiento posible!
      set direccion-actual d  ;; Actualizar dirección del ratón
      report d
    ]
  ]
  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  ;; Obtener direcciones disponibles (sin paredes)
  ;let disponibles []
  ;let direcciones [0 1 2 3]  ;; N, E, S, O
  ;foreach direcciones 
  ;[ d ->
  ;  let dxL 0
  ;  let dyL 0
  ;  if d = 0 [ set dyL 1 ]  ;; Norte
  ;  if d = 1 [ set dxL 1 ]  ;; Este
  ;  if d = 2 [ set dyL -1 ] ;; Sur
  ;  if d = 3 [ set dxL -1 ] ;; Oeste
    
  ;  let destino patch-at dxL dyL
    
  ;  if destino != nobody and not [es-pared?] of destino [
  ;    set disponibles lput d disponibles
  ;  ]
  ;]
  
  ;; Priorizar caminos NO visitados (exploración inteligente)
  ;let no-visitados []
  ;foreach disponibles [ d ->
  ;  let dxL 0
  ;  let dyL 0
  ;  if d = 0 [ set dyL 1 ]
  ;  if d = 1 [ set dxL 1 ]
  ;  if d = 2 [ set dyL -1 ]
  ;  if d = 3 [ set dxL -1 ]
  ;  let destino patch-at dxL dyL
  ;  if not [visitado?] of destino [
  ;    set no-visitados lput d no-visitados
  ;  ]
  ;]
  
  ;; Si hay no-visitados, elegir uno aleatoriamente
  ;if length no-visitados > 0 [
  ;  report one-of no-visitados
  ;]
  
  ;; Si todos están visitados, elegir cualquier disponible
  ;if length disponibles > 0 [
  ;  report one-of disponibles
  ;]
  
  ;; Si no hay disponibles, estoy atrapado
  report -1
end 

to mover-en-direccion [dir]
  let dxL 0
  let dyL 0
  if dir = 0 [ set dyL 1 ]  ;; Norte
  if dir = 1 [ set dxL 1 ]  ;; Este
  if dir = 2 [ set dyL -1 ] ;; Sur
  if dir = 3 [ set dxL -1 ] ;; Oeste
  
  let destino patch-at dxL dyL
  
  if destino != nobody and not [es-pared?] of destino [
    
    move-to destino
  ]
end 

to aprender-camino
   ;; Esto es el corazón del modelo de Shannon
  ;; Cada patch en el camino exitoso guarda hacia dónde ir
  
  if length camino-temporal < 2 [ stop ]
  
  ;; Recorrer el camino desde el inicio hasta la meta
  ;; (excluyendo el último paso porque ya estamos en la meta)
  let i 0
  while [i < (length camino-temporal) - 1] [
    let patch-actual item i camino-temporal
    let patch-siguiente item (i + 1) camino-temporal
    
    ;; Calcular dirección del movimiento
    let dxL [pxcor] of patch-siguiente - [pxcor] of patch-actual
    let dyL [pycor] of patch-siguiente - [pycor] of patch-actual
    
    let direccion -1
    if dyL = 1 [ set direccion 0 ]  ;; Norte
    if dxL = 1 [ set direccion 1 ]  ;; Este
    if dyL = -1 [ set direccion 2 ] ;; Sur
    if dxL = -1 [ set direccion 3 ] ;; Oeste
    
    ;; Guardar en el "relé" del patch actual (¡como Shannon!)
    ask patch-actual [
      set direccion-optima direccion
      set en-camino? true
      ;set pcolor color-para-direccion direccion
    ]
    
    set i i + 1
  ]
  
  ;; Marcar la meta también
  ask meta [ 
             set en-camino? true 
             ;set pcolor [pcolor] of meta + 2 
            ]
end 

to-report color-para-direccion [dir]
  if dir = 0 [ report 105 ]  ;; Azul claro (Norte)
  if dir = 1 [ report 55 ]   ;; Verde claro (Este)
  if dir = 2 [ report 25 ]   ;; Naranja (Sur)
  if dir = 3 [ report 15 ]   ;; Rojo (Oeste)
  report white
end 

to reiniciar-para-nuevo-intento
  ;; El ratón vuelve al inicio, pero mantiene la memoria (relés)
  setxy [pxcor] of inicio [pycor] of inicio
  set paso-actual 0
  set exito? false
  set camino-temporal []
  set intento intento + 1
  
  ;; Cambiar a modo explotación después del primer éxito estaba en 2 lo puse en 1 como en el original de shannon
  if intento > 1 [
    set modo-aprendizaje false
    user-message "¡Ya aprendí el camino! Ahora voy directo al queso."

  ]
end 

to mousehouse
  ask turtles[
  setxy min-pxcor min-pycor
    set paso-actual 0
    set exito? false

    set camino-temporal []
    set inicio patch-here
  ]
  ask patches [
    set direccion-optima -1
    set visitado? false
  ]
  reset-ticks
end 

There is only one version of this model, created 10 days ago by Diego Díaz Córdova.

Attached files

File Type Description Last updated
Shannon's Theseus.png preview Preview for 'Shannon's Theseus' 10 days ago, by Diego Díaz Córdova Download

This model does not have any ancestors.

This model does not have any descendants.