Skip to content
Snippets Groups Projects
Commit 10a084d7 authored by Erik Nygren's avatar Erik Nygren
Browse files

added __init__.py in examples to get editor working

parent 4e9a18df
No related branches found
No related tags found
No related merge requests found
......@@ -33,6 +33,7 @@ class View(object):
class JupEditor(object):
def __init__(self, env, wid_img):
print("Correct editor")
self.env = env
self.wid_img = wid_img
......
%% Cell type:markdown id: tags:
# Jupyter Canvas Widget - Rail Editor
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.
%% Cell type:markdown id: tags:
## You need to run all cells before trying to edit the rails!
%% Cell type:code id: tags:
``` python
%load_ext autoreload
%autoreload 2
```
%% Cell type:code id: tags:
``` python
import image_attendant as imat
import ipywidgets
import IPython
import jpy_canvas
import numpy as np
from numpy import array
import time
from collections import deque
from matplotlib import pyplot as plt
import io
from PIL import Image
```
%% Cell type:code id: tags:
``` python
from ipywidgets import IntSlider, link, VBox, RadioButtons, HBox, interact
```
%% Cell type:code id: tags:
``` python
import sys
print(sys.path)
```
%% Output
['', 'C:\\Users\\u224870\\Innovation\\progressive_growing_of_gans', 'c:\\users\\u224870\\appdata\\local\\programs\\python\\python36\\python36.zip', 'c:\\users\\u224870\\appdata\\local\\programs\\python\\python36\\DLLs', 'c:\\users\\u224870\\appdata\\local\\programs\\python\\python36\\lib', 'c:\\users\\u224870\\appdata\\local\\programs\\python\\python36', 'c:\\users\\u224870\\appdata\\local\\programs\\python\\python36\\lib\\site-packages', 'c:\\users\\u224870\\appdata\\local\\programs\\python\\python36\\lib\\site-packages\\flatland_rl-0.1.1-py3.6.egg', 'c:\\users\\u224870\\projekte_git\\jupyter_canvas_widget', 'c:\\users\\u224870\\appdata\\local\\programs\\python\\python36\\lib\\site-packages\\IPython\\extensions', 'C:\\Users\\u224870\\.ipython']
%% Cell type:code id: tags:
``` python
import flatland.core.env
from flatland.envs.rail_env import RailEnv, random_rail_generator
from flatland.core.transitions import RailEnvTransitions
from flatland.core.env_observation_builder import TreeObsForRailEnv
import flatland.utils.rendertools as rt
from flatland.utils.editor import JupEditor
```
%% Output
cpu
%% Cell type:code id: tags:
``` python
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:90% !important; }</style>"))
```
%% Output
%% Cell type:code id: tags:
``` python
oEnv = RailEnv(width=20,
height=20,
rail_generator=random_rail_generator(cell_type_relative_proportion=[1,1] + [0.5] * 6),
number_of_agents=0,
obs_builder_object=TreeObsForRailEnv(max_depth=2))
obs = oEnv.reset()
```
%% Cell type:code id: tags:
``` python
sfEnv = "../flatland/env-data/tests/test1.npy"
sfEnv = "C:/Users/u224870/Projekte_Git/flatland/env-data/tests/test1.npy"
if True:
oEnv.rail.load_transition_map(sfEnv)
oEnv.width = oEnv.rail.width
oEnv.height = oEnv.rail.height
```
%% Cell type:code id: tags:
``` python
oRT = rt.RenderTool(oEnv)
```
%% Cell type:code id: tags:
``` python
oEnv.width
```
%% Output
10
%% Cell type:markdown id: tags:
### Clear the rails
%% Cell type:code id: tags:
``` python
oEnv.rail.grid[:,:] = 0
```
%% Cell type:markdown id: tags:
### 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.
%% Cell type:code id: tags:
``` python
oFig = plt.figure(figsize=(10,10))
oRT.renderEnv(spacing=False, arrows=False, sRailColor="gray", show=False)
img = oRT.getImage()
print(type(img))
plt.clf() # if you don't want the image to appear here
pass
wid_img = jpy_canvas.Canvas(img)
```
%% Output
<class 'numpy.ndarray'>
%% Cell type:markdown id: tags:
### Update the function - in case external code updated
%% Cell type:code id: tags:
``` python
wid_img.unregister_all()
oEditor = JupEditor(oEnv, wid_img)
oEditor = JupEditor(oEnv,wid_img)
wid_img.register_move(oEditor.event_handler)
wid_img.register_click(oEditor.on_click)
```
%% Output
Correct editor
%% Cell type:markdown id: tags:
### Some more widgets
%% Cell type:code id: tags:
``` python
wid_drawMode = ipywidgets.RadioButtons(options=["Draw", "Erase", "Origin", "Destination"])
wid_drawMode.observe(oEditor.setDrawMode, names="value")
wid_debug = ipywidgets.Checkbox(description = "Debug")
wid_debug.observe(oEditor.setDebug, names="value")
wid_output = ipywidgets.Output()
oEditor.setOutput(wid_output)
wid_filename = ipywidgets.Text(description = "Filename")
wid_filename.value = sfEnv
oEditor.setFilename(sfEnv)
wid_filename.observe(oEditor.setFilename_event, names="value")
wid_size = ipywidgets.IntSlider(min=5, max=30, step=5, description="Regen Size")
wid_size.observe(oEditor.setRegenSize_event, names="value")
prog_steps = ipywidgets.IntProgress(value=0, min=0, max=20, step=1, description="Step")
#prog_steps.observe(oEditor.)
ldButtons = [
dict(name = "Refresh", method = oEditor.redraw_event),
dict(name = "Clear", method = oEditor.clear),
dict(name = "Regenerate", method = oEditor.regenerate_event),
dict(name = "Load", method = oEditor.load),
dict(name = "Save", method = oEditor.save),
dict(name = "Step", method = oEditor.step_event),
dict(name = "Run Steps", method = oEditor.start_run_event),
]
lwid_buttons = []
for dButton in ldButtons:
wid_button = ipywidgets.Button(description = dButton["name"])
wid_button.on_click(dButton["method"])
lwid_buttons.append(wid_button)
#wid_debug = interact(oEditor.setDebug, debug=False)
vbox_controls = VBox([wid_filename, wid_drawMode, *lwid_buttons, wid_size, wid_debug])
```
%% Cell type:markdown id: tags:
### 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
%% Cell type:code id: tags:
``` python
# wid_box
wid_main = HBox([wid_img, vbox_controls])
wid_output.clear_output()
wid_main
```
%% 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:
``` python
oEditor.env.number_of_agents
```
%% Output
0
%% Cell type:code id: tags:
``` python
wid_output
```
%% Output
%% Cell type:code id: tags:
``` python
import threading
def bgUpdate(editor):
for i in range(100):
editor.step_event()
time.sleep(0.2)
```
%% Cell type:code id: tags:
``` python
thread = threading.Thread(target=bgUpdate, args = (oEditor,))
```
%% Cell type:code id: tags:
``` python
#thread.start()
```
%% Cell type:markdown id: tags:
### Save the image (change the filename...)
%% Cell type:code id: tags:
``` python
oEnv.rail.save_transition_map("../flatland/env-data/tests/test-editor.npy")
```
%% Output
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-21-a40691809d2c> in <module>()
----> 1 oEnv.rail.save_transition_map("../flatland/env-data/tests/test-editor.npy")
c:\users\u224870\appdata\local\programs\python\python36\lib\site-packages\flatland_rl-0.1.1-py3.6.egg\flatland\core\transition_map.py in save_transition_map(self, filename)
259
260 """
--> 261 np.save(filename, self.grid)
262
263 def load_transition_map(self, filename, override_gridsize=True):
c:\users\u224870\appdata\local\programs\python\python36\lib\site-packages\numpy\lib\npyio.py in save(file, arr, allow_pickle, fix_imports)
490 if not file.endswith('.npy'):
491 file = file + '.npy'
--> 492 fid = open(file, "wb")
493 own_fid = True
494 elif is_pathlib_path(file):
FileNotFoundError: [Errno 2] No such file or directory: '../flatland/env-data/tests/test-editor.npy'
%% Cell type:markdown id: tags:
## Junk below here
%% Cell type:code id: tags:
``` python
def evListen(wid, ev):
x = ev["canvasX"]
y=ev["canvasY"]
yxBase = array([6, 21])
nPixCell = 35
rcCell = ((array([y, x]) - yxBase) / nPixCell).astype(int)
print(ev)
print(x, y, (x-21) / 35, (y-6) / 35, rcCell)
```
%% Cell type:code id: tags:
``` python
# wid_img.register_click(evListen)
#wid_img.register(evListen)
```
%% Cell type:code id: tags:
``` python
#wid_img.unregister_all()
```
%% Cell type:code id: tags:
``` python
ipywidgets.IntText(0)
```
%% Output
%% Cell type:code id: tags:
``` python
from examples.play_model import Player
```
%% Cell type:code id: tags:
``` python
oP = Player(oEnv)
```
%% Cell type:code id: tags:
``` python
oP.step()
```
%% Cell type:code id: tags:
``` python
import asyncio
def wait_for_change(widget, value):
future = asyncio.Future()
def getvalue(change):
# make the new value available
future.set_result(change.new)
widget.unobserve(getvalue, value)
widget.observe(getvalue, value)
return future
```
%% Cell type:code id: tags:
``` python
slider = ipywidgets.IntSlider()
async def f():
for i in range(10):
print('did work %s'%i)
x = await wait_for_change(slider, 'value')
print('async function continued with value %s'%x)
asyncio.ensure_future(f())
slider
```
%% Output
%% Cell type:code id: tags:
``` python
import threading
from IPython.display import display
import time
progress = ipywidgets.FloatProgress(value=0.0, min=0.0, max=1.0)
def work(progress):
total = 100
for i in range(total):
time.sleep(0.2)
progress.value = float(i+1)/total
thread = threading.Thread(target=work, args=(progress,))
display(progress)
thread.start()
```
%% Output
%% Cell type:code id: tags:
``` python
[2,3] == (2,3)
```
%% Output
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