Skip to content
Snippets Groups Projects
Commit 01fb10f8 authored by hagrid67's avatar hagrid67
Browse files

mostly just adding trailing junk

parent c2b8a390
No related branches found
No related tags found
No related merge requests found
%% 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 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 = "C:/Users/u224870/Projekte_Git/flatland/env-data/tests/test1.npy"
sfEnv = "../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:code id: tags:
``` python
import sys
sys.path
```
%% Output
['/home/jeremy/projects/heating',
'/home/jeremy/projects/aicrowd/rl-trains/MAgent/python',
'/home/jeremy/ve367/lib/python36.zip',
'/home/jeremy/ve367/lib/python3.6',
'/home/jeremy/ve367/lib/python3.6/lib-dynload',
'/usr/lib/python3.6',
'',
'/home/jeremy/ve367/lib/python3.6/site-packages',
'/home/jeremy/projects/aicrowd/rl-trains/torch-rl/torch_rl',
'/home/jeremy/projects/aicrowd/rl-trains/gym-minigrid',
'/home/jeremy/projects/aicrowd/rl-trains/flatland',
'/home/jeremy/projects/aicrowd/rl-trains/Jupyter_Canvas_Widget',
'/home/jeremy/ve367/lib/python3.6/site-packages/IPython/extensions',
'/home/jeremy/.ipython']
%% 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_debug_move = ipywidgets.Checkbox(description = "Debug mouse move")
wid_debug_move.observe(oEditor.setDebugMove, 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, wid_debug_move])
```
%% 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
%% Cell type:code id: tags:
``` python
wid_output.clear_output()
wid_output
```
%% Output
%% Cell type:markdown id: tags:
### Experimental
enable the thread.start below to try background stepping of the agents. It tends to make a mess.
%% 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
if False:
thread.start()
```
%% Cell type:markdown id: tags:
### Save the image (change the filename...)
%% Cell type:code id: tags:
``` python
if False:
oEnv.rail.save_transition_map("../flatland/env-data/tests/test-editor.npy")
```
%% Output
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-20-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
binTrans = format(32800, "#016b")
[binTrans[i+2:i+6] for i in range(0, len(binTrans)-2, 4)]
```
%% Output
['1000', '0000', '0010', '0000']
%% Cell type:code id: tags:
``` python
oEnv.rail
```
%% Output
<flatland.core.transition_map.GridTransitionMap at 0x7fc6dd6c9e48>
%% Cell type:code id: tags:
``` python
binDeadend = 0b0010000110000100
format(~binDeadend & 0xffff, "#018b")
```
%% Output
'0b1101111001111011'
%% Cell type:code id: tags:
``` python
oEnv.rail.cell_neighbours_valid((2,5))
```
%% Output
True
%% Cell type:code id: tags:
``` python
oEnv.rail.grid[2,6] & binDeadend
```
%% Output
0
%% Cell type:code id: tags:
``` python
oTrans = oEnv.rail.grid[2,5]
oTrans
oEnv.rail.transitions.repr(oTrans, 1)
```
%% Output
''
%% Cell type:code id: tags:
``` python
oEnv.rail.transitions.is_valid(oTrans)
```
%% Output
True
%% Cell type:code id: tags:
``` python
oEnv.rail.transitions.gDir2dRC
```
%% Output
array([[-1, 0],
[ 0, 1],
[ 1, 0],
[ 0, -1]])
%% Cell type:code id: tags:
``` python
binTrans = oEnv.rail.get_transitions((2,2))
sBinTrans = format(binTrans, "#018b")[2:]
print(sBinTrans)
lsBinTrans = [ sBinTrans[i:i+4] for i in range(0,16, 4)]
print(lsBinTrans)
```
%% Output
0000000000000000
['0000', '0000', '0000', '0000']
%% Cell type:code id: tags:
``` python
lnBinTrans = array([ binTrans >> 8, binTrans & 0xff ], dtype=np.uint8)
g2binTrans = np.unpackbits(lnBinTrans).reshape(4,4)
g2binTrans
```
%% Output
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=uint8)
%% Cell type:code id: tags:
``` python
gDirIn = g2binTrans.any(axis=1)
gDirOut = g2binTrans.any(axis=0)
print(gDirIn)
print(gDirOut)
```
%% Output
[False False False False]
[False False False False]
%% Cell type:code id: tags:
``` python
giDirOut = np.argwhere(gDirOut)[:,0]
giDirOut
```
%% Output
array([], dtype=int64)
%% Cell type:code id: tags:
``` python
any((0,0,0))
```
%% Output
False
%% Cell type:code id: tags:
``` python
oEnv.rail.transitions.gDir2dRC
```
%% Output
array([[-1, 0],
[ 0, 1],
[ 1, 0],
[ 0, -1]])
%% Cell type:code id: tags:
``` python
oEnv.rail.transitions.gDir2dRC[giDirOut,:]
```
%% Output
array([], shape=(0, 2), dtype=int64)
%% Cell type:code id: tags:
``` python
t4TransOut = oEnv.rail.get_transitions((2,2,3))
print (t4TransOut)
for iDir in np.argwhere(t4TransOut)[:,0]:
print(iDir, oEnv.rail.transitions.gDir2dRC[iDir])
```
%% Output
(0, 0, 0, 0)
%% Cell type:code id: tags:
``` python
lsRepr = []
sDirs = "NESW"
lsDirs = list(sDirs)
cell_transition = oTrans
sbinTrans = format(cell_transition, "#018b")[2:]
print(sbinTrans)
for iDirIn in range(0,4):
sDirTrans = sbinTrans[iDirIn*4:iDirIn*4+4]
if sDirTrans=="0000":
continue
sDirsOut = [
lsDirs[iDirOut]
for iDirOut in range(0,4)
if sDirTrans[iDirOut]=="1"
]
lsRepr.append(lsDirs[iDirIn] + ":" + "".join(sDirsOut))
", ".join(lsRepr)
```
%% Output
0000000000000000
''
%% Cell type:code id: tags:
``` python
s="1010"
ints = int(s,2)
gs = array(ints, dtype=np.uint8)
print(gs, np.unpackbits(gs)[4:8])
```
%% Output
10 [1 0 1 0]
%% Cell type:code id: tags:
``` python
oEnv.rail.transitions.repr(1025)
```
%% Output
'N:0000 E:0100 S:0000 W:0001'
......
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