Skip to content
Snippets Groups Projects
Commit 4e9a18df authored by hagrid67's avatar hagrid67
Browse files

update notebook. The last commit comment should have been:

Apply a valid direction in add_agent
parent d53639ea
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Jupyter Canvas Widget - Rail Editor # Jupyter Canvas Widget - Rail Editor
From - https://github.com/Who8MyLunch/Jupyter_Canvas_Widget/blob/master/notebooks/example%20mouse%20events.ipynb From - https://github.com/Who8MyLunch/Jupyter_Canvas_Widget/blob/master/notebooks/example%20mouse%20events.ipynb
Follow his instructions to do a local dev install and enable the widget. Follow his instructions to do a local dev install and enable the widget.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## You need to run all cells before trying to edit the rails! ## You need to run all cells before trying to edit the rails!
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
%load_ext autoreload %load_ext autoreload
%autoreload 2 %autoreload 2
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import image_attendant as imat import image_attendant as imat
import ipywidgets import ipywidgets
import IPython import IPython
import jpy_canvas import jpy_canvas
import numpy as np import numpy as np
from numpy import array from numpy import array
import time import time
from collections import deque from collections import deque
from matplotlib import pyplot as plt from matplotlib import pyplot as plt
import io import io
from PIL import Image from PIL import Image
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from ipywidgets import IntSlider, link, VBox, RadioButtons, HBox, interact from ipywidgets import IntSlider, link, VBox, RadioButtons, HBox, interact
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import flatland.core.env import flatland.core.env
from flatland.envs.rail_env import RailEnv, random_rail_generator from flatland.envs.rail_env import RailEnv, random_rail_generator
from flatland.core.transitions import RailEnvTransitions from flatland.core.transitions import RailEnvTransitions
from flatland.core.env_observation_builder import TreeObsForRailEnv from flatland.core.env_observation_builder import TreeObsForRailEnv
import flatland.utils.rendertools as rt import flatland.utils.rendertools as rt
from flatland.utils.editor import JupEditor from flatland.utils.editor import JupEditor
``` ```
%% Output %% Output
cpu cpu
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from IPython.core.display import display, HTML from IPython.core.display import display, HTML
display(HTML("<style>.container { width:90% !important; }</style>")) display(HTML("<style>.container { width:90% !important; }</style>"))
``` ```
%% Output %% Output
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
oEnv = RailEnv(width=20, oEnv = RailEnv(width=20,
height=20, height=20,
rail_generator=random_rail_generator(cell_type_relative_proportion=[1,1] + [0.5] * 6), rail_generator=random_rail_generator(cell_type_relative_proportion=[1,1] + [0.5] * 6),
number_of_agents=0, number_of_agents=0,
obs_builder_object=TreeObsForRailEnv(max_depth=2)) obs_builder_object=TreeObsForRailEnv(max_depth=2))
obs = oEnv.reset() obs = oEnv.reset()
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
sfEnv = "../flatland/env-data/tests/test1.npy" sfEnv = "../flatland/env-data/tests/test1.npy"
if True: if True:
oEnv.rail.load_transition_map(sfEnv) oEnv.rail.load_transition_map(sfEnv)
oEnv.width = oEnv.rail.width oEnv.width = oEnv.rail.width
oEnv.height = oEnv.rail.height oEnv.height = oEnv.rail.height
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
oRT = rt.RenderTool(oEnv) oRT = rt.RenderTool(oEnv)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
oEnv.width oEnv.width
``` ```
%% Output %% Output
10 10
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Clear the rails ### Clear the rails
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
oEnv.rail.grid[:,:] = 0 oEnv.rail.grid[:,:] = 0
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Render the env in the usual way, and take an image snapshot as numpy array ### Render the env in the usual way, and take an image snapshot as numpy array
If you have already edited the env in the cell below, these changes should be reflected here. If you have already edited the env in the cell below, these changes should be reflected here.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
oFig = plt.figure(figsize=(10,10)) oFig = plt.figure(figsize=(10,10))
oRT.renderEnv(spacing=False, arrows=False, sRailColor="gray", show=False) oRT.renderEnv(spacing=False, arrows=False, sRailColor="gray", show=False)
img = oRT.getImage() img = oRT.getImage()
print(type(img)) print(type(img))
plt.clf() # if you don't want the image to appear here plt.clf() # if you don't want the image to appear here
pass pass
wid_img = jpy_canvas.Canvas(img) wid_img = jpy_canvas.Canvas(img)
``` ```
%% Output %% Output
<class 'numpy.ndarray'> <class 'numpy.ndarray'>
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Update the function - in case external code updated ### Update the function - in case external code updated
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
wid_img.unregister_all() wid_img.unregister_all()
oEditor = JupEditor(oEnv, wid_img) oEditor = JupEditor(oEnv, wid_img)
wid_img.register_move(oEditor.event_handler) wid_img.register_move(oEditor.event_handler)
wid_img.register_click(oEditor.on_click) wid_img.register_click(oEditor.on_click)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Some more widgets ### Some more widgets
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
wid_drawMode = ipywidgets.RadioButtons(options=["Draw", "Erase", "Origin", "Destination"]) wid_drawMode = ipywidgets.RadioButtons(options=["Draw", "Erase", "Origin", "Destination"])
wid_drawMode.observe(oEditor.setDrawMode, names="value") wid_drawMode.observe(oEditor.setDrawMode, names="value")
wid_debug = ipywidgets.Checkbox(description = "Debug") wid_debug = ipywidgets.Checkbox(description = "Debug")
wid_debug.observe(oEditor.setDebug, names="value") wid_debug.observe(oEditor.setDebug, names="value")
wid_output = ipywidgets.Output() wid_output = ipywidgets.Output()
oEditor.setOutput(wid_output) oEditor.setOutput(wid_output)
wid_filename = ipywidgets.Text(description = "Filename") wid_filename = ipywidgets.Text(description = "Filename")
wid_filename.value = sfEnv wid_filename.value = sfEnv
oEditor.setFilename(sfEnv) oEditor.setFilename(sfEnv)
wid_filename.observe(oEditor.setFilename_event, names="value") wid_filename.observe(oEditor.setFilename_event, names="value")
wid_size = ipywidgets.IntSlider(min=5, max=30, step=5, description="Regen Size") wid_size = ipywidgets.IntSlider(min=5, max=30, step=5, description="Regen Size")
wid_size.observe(oEditor.setRegenSize_event, names="value") wid_size.observe(oEditor.setRegenSize_event, names="value")
prog_steps = ipywidgets.IntProgress(value=0, min=0, max=20, step=1, description="Step") prog_steps = ipywidgets.IntProgress(value=0, min=0, max=20, step=1, description="Step")
#prog_steps.observe(oEditor.) #prog_steps.observe(oEditor.)
ldButtons = [ ldButtons = [
dict(name = "Refresh", method = oEditor.redraw_event), dict(name = "Refresh", method = oEditor.redraw_event),
dict(name = "Clear", method = oEditor.clear), dict(name = "Clear", method = oEditor.clear),
dict(name = "Regenerate", method = oEditor.regenerate_event), dict(name = "Regenerate", method = oEditor.regenerate_event),
dict(name = "Load", method = oEditor.load), dict(name = "Load", method = oEditor.load),
dict(name = "Save", method = oEditor.save), dict(name = "Save", method = oEditor.save),
dict(name = "Step", method = oEditor.step_event), dict(name = "Step", method = oEditor.step_event),
dict(name = "Run Steps", method = oEditor.start_run_event), dict(name = "Run Steps", method = oEditor.start_run_event),
] ]
lwid_buttons = [] lwid_buttons = []
for dButton in ldButtons: for dButton in ldButtons:
wid_button = ipywidgets.Button(description = dButton["name"]) wid_button = ipywidgets.Button(description = dButton["name"])
wid_button.on_click(dButton["method"]) wid_button.on_click(dButton["method"])
lwid_buttons.append(wid_button) lwid_buttons.append(wid_button)
#wid_debug = interact(oEditor.setDebug, debug=False) #wid_debug = interact(oEditor.setDebug, debug=False)
vbox_controls = VBox([wid_filename, wid_drawMode, *lwid_buttons, wid_size, wid_debug]) vbox_controls = VBox([wid_filename, wid_drawMode, *lwid_buttons, wid_size, wid_debug])
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Edit the map below here by dragging the mouse to create transitions ### Edit the map below here by dragging the mouse to create transitions
You can create a dead-end by dragging foward and backward, ie Cell A -> Adjacent Cell B -> back to Cell A You can create a dead-end by dragging foward and backward, ie Cell A -> Adjacent Cell B -> back to Cell A
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# wid_box # wid_box
wid_main = HBox([wid_img, vbox_controls]) wid_main = HBox([wid_img, vbox_controls])
wid_output.clear_output() wid_output.clear_output()
wid_main wid_main
``` ```
%% Output %% Output
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
~/projects/aicrowd/rl-trains/flatland/flatland/utils/editor.py in on_click(self, wid, event)
80
81 if self.drawMode == "Origin":
---> 82 self.iAgent = self.env.add_agent(rcCell, rcCell, None)
83 self.drawMode = "Destination"
84 self.player = None # will need to start a new player
~/projects/aicrowd/rl-trains/flatland/flatland/envs/rail_env.py in add_agent(self, rcPos, rcTarget, iDir)
536 if iDir is None:
537 iDir = self.pick_agent_direction(rcPos, rcTarget)
--> 538 self.agents_direction[iAgent] = iDir
539
540 self.agents_direction.append(0)
IndexError: list assignment index out of range
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
oEditor.env.number_of_agents oEditor.env.number_of_agents
``` ```
%% Output %% Output
0 0
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
wid_output wid_output
``` ```
%% Output %% Output
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import threading import threading
def bgUpdate(editor): def bgUpdate(editor):
for i in range(100): for i in range(100):
editor.step_event() editor.step_event()
time.sleep(0.2) time.sleep(0.2)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
thread = threading.Thread(target=bgUpdate, args = (oEditor,)) thread = threading.Thread(target=bgUpdate, args = (oEditor,))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
#thread.start() #thread.start()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Save the image (change the filename...) ### Save the image (change the filename...)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
oEnv.rail.save_transition_map("../flatland/env-data/tests/test-editor.npy") oEnv.rail.save_transition_map("../flatland/env-data/tests/test-editor.npy")
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Junk below here ## Junk below here
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def evListen(wid, ev): def evListen(wid, ev):
x = ev["canvasX"] x = ev["canvasX"]
y=ev["canvasY"] y=ev["canvasY"]
yxBase = array([6, 21]) yxBase = array([6, 21])
nPixCell = 35 nPixCell = 35
rcCell = ((array([y, x]) - yxBase) / nPixCell).astype(int) rcCell = ((array([y, x]) - yxBase) / nPixCell).astype(int)
print(ev) print(ev)
print(x, y, (x-21) / 35, (y-6) / 35, rcCell) print(x, y, (x-21) / 35, (y-6) / 35, rcCell)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# wid_img.register_click(evListen) # wid_img.register_click(evListen)
#wid_img.register(evListen) #wid_img.register(evListen)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
#wid_img.unregister_all() #wid_img.unregister_all()
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
ipywidgets.IntText(0) ipywidgets.IntText(0)
``` ```
%% Output %% Output
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from examples.play_model import Player from examples.play_model import Player
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
oP = Player(oEnv) oP = Player(oEnv)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
oP.step() oP.step()
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import asyncio import asyncio
def wait_for_change(widget, value): def wait_for_change(widget, value):
future = asyncio.Future() future = asyncio.Future()
def getvalue(change): def getvalue(change):
# make the new value available # make the new value available
future.set_result(change.new) future.set_result(change.new)
widget.unobserve(getvalue, value) widget.unobserve(getvalue, value)
widget.observe(getvalue, value) widget.observe(getvalue, value)
return future return future
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
slider = ipywidgets.IntSlider() slider = ipywidgets.IntSlider()
async def f(): async def f():
for i in range(10): for i in range(10):
print('did work %s'%i) print('did work %s'%i)
x = await wait_for_change(slider, 'value') x = await wait_for_change(slider, 'value')
print('async function continued with value %s'%x) print('async function continued with value %s'%x)
asyncio.ensure_future(f()) asyncio.ensure_future(f())
slider slider
``` ```
%% Output %% Output
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import threading import threading
from IPython.display import display from IPython.display import display
import time import time
progress = ipywidgets.FloatProgress(value=0.0, min=0.0, max=1.0) progress = ipywidgets.FloatProgress(value=0.0, min=0.0, max=1.0)
def work(progress): def work(progress):
total = 100 total = 100
for i in range(total): for i in range(total):
time.sleep(0.2) time.sleep(0.2)
progress.value = float(i+1)/total progress.value = float(i+1)/total
thread = threading.Thread(target=work, args=(progress,)) thread = threading.Thread(target=work, args=(progress,))
display(progress) display(progress)
thread.start() thread.start()
``` ```
%% Output %% Output
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
[2,3] == (2,3) [2,3] == (2,3)
``` ```
%% Output %% Output
False False
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment