added start/stop button (#173)

* added start/stop button

* added declorator; fixed camera interrupt race condition

* add docs + typechecking
This commit is contained in:
evonneng authored and GitHub committed 2022-07-19 16:33:01 -07:00
1 parent 05b92e228b
commit 12c7d41241
7 files changed
+164 -57

No files matched your search

+12
View File
@@ -45,6 +45,18 @@ def check_profiler_enabled(func: Callable) -> Callable:
return wrapper
def check_visualizer_enabled(func: Callable) -> Callable:
"""Decorator: check if visualizer is enabled"""
def wrapper(self, *args, **kwargs):
ret = None
if self.vis:
ret = func(self, *args, **kwargs)
return ret
return wrapper
def check_main_thread(func: Callable) -> Callable:
"""Decorator: check if you are on main thread"""
+2 -2
View File
@@ -27,12 +27,12 @@ from typing import Dict
import imageio
import numpy as np
import torch
import wandb
from omegaconf import ListConfig
from torch.utils.tensorboard import SummaryWriter
from torchtyping import TensorType
from pyrad.utils.config import LoggingConfig
import wandb
from pyrad.utils.config import LoggingConfig
from pyrad.utils.decorators import check_main_thread, decorate_all
to8b = lambda x: (255 * torch.clamp(x, min=0, max=1)).to(torch.uint8)
+24
View File
@@ -98,6 +98,20 @@ export class Viewer extends Component {
}
}
send_training_state_over_websocket(value) {
if (this.state.websocket.readyState === WebSocket.OPEN) {
let cmd = "set_training_state";
let path = "Training State";
let data = {
type: cmd,
path: path,
training_state: value,
};
let message = msgpack.encode(data);
this.state.websocket.send(message);
}
}
send_output_type_over_websocket(value) {
/* update the output option in the python server
if the user changes selection */
@@ -166,13 +180,23 @@ export class Viewer extends Component {
let output_options_control = new (function () {
this.output_options = "default";
})();
let params = {
switch: false
};
// add controls
this.state.gui
.add(output_options_control, "output_options", object)
.name("Output Options")
.listen()
.onChange((value) => {
this.send_output_type_over_websocket(value);
});
this.state.gui.add(params, "switch")
.name("Pause Training?")
.listen()
.onChange((value)=>{
this.send_training_state_over_websocket(value);
});
}
this.created_controls = true;
}
+77 -29
View File
@@ -13,6 +13,10 @@
# limitations under the License.
from dataclasses import dataclass
from typing import Any, Dict, List
import numpy as np
from pyrad.viewer.server.geometry import (
Mesh,
MeshPhongMaterial,
@@ -25,13 +29,24 @@ from pyrad.viewer.server.geometry import (
from pyrad.viewer.server.path import Path
class SetObject:
class SetObject: # pylint: disable=too-few-public-methods
"""Set object command class: Instantiates and sets the object according to object type
Args:
geometry_or_object (_type_): object to be set
material (_type_, optional): material to be set. Defaults to None.
path (str): path of object in tree. Defaults to None.
Raises:
ValueError: error if material is not set for object
"""
__slots__ = ["object", "path"]
def __init__(self, geometry_or_object, material=None, path=None):
if isinstance(geometry_or_object, Object):
if material is not None:
raise (ValueError("Please supply either an Object OR a Geometry and a Material"))
raise ValueError("Please supply either an Object OR a Geometry and a Material")
self.object = geometry_or_object
elif isinstance(geometry_or_object, (OrthographicCamera, PerspectiveCamera)):
self.object = geometry_or_object
@@ -47,70 +62,103 @@ class SetObject:
else:
self.path = Path()
def lower(self):
def lower(self) -> Dict[str, Any]:
"""creates properly formatted json
Returns:
Dict[str, Any]: json in proper format
"""
return {"type": "set_object", "object": self.object.lower(), "path": self.path.lower()}
@dataclass
class GetObject:
"""Get object command class
Args:
path (str): path of object in tree. Defaults to None.
"""
__slots__ = ["path"]
def __init__(self, path):
self.path = path
path: str
def lower(self):
def lower(self) -> Dict[str, Any]:
"""creates properly formatted json with object
Returns:
Dict[str, Any]: json in proper format
"""
return {"type": "get_object", "path": self.path.lower()}
@dataclass
class SetTransform:
"""Set transform command class"""
__slots__ = ["matrix", "path"]
def __init__(self, matrix, path):
self.matrix = matrix
self.path = path
matrix: np.ndarray
path: str
def lower(self):
"""creates properly formatted json with transform matrix
Returns:
Dict[str, Any]: json in proper format
"""
return {"type": "set_transform", "path": self.path.lower(), "matrix": list(self.matrix.T.flatten())}
@dataclass
class SetOutputOptions:
"""Set output options command class"""
__slots__ = ["output_options", "path"]
def __init__(self, output_options, path):
self.output_options = output_options
self.path = path
output_options: List[str]
path: str
def lower(self):
"""creates properly formatted json with list of possible output options
Returns:
Dict[str, Any]: json in proper format
"""
return {"type": "set_output_options", "path": self.path.lower(), "output_options": list(self.output_options)}
class SetOutputType:
__slots__ = ["output_type", "path"]
def __init__(self, output_type, path):
self.output_type = output_type
self.path = path
def lower(self):
return {"type": "set_output_options", "path": self.path.lower(), "output_options": list(self.output_type)}
@dataclass
class Delete:
"""Delete current state command class"""
__slots__ = ["path"]
def __init__(self, path):
self.path = path
path: str
def lower(self):
"""creates properly formatted json updating tree
Returns:
Dict[str, Any]: json in proper format
"""
return {"type": "delete", "path": self.path.lower()}
@dataclass
class SetProperty:
"""Set property command class"""
__slots__ = ["path", "key", "value"]
def __init__(self, key, value, path):
self.key = key
self.value = value
self.path = path
key: str
value: list
path: str
def lower(self):
"""creates properly formatted json setting property
Returns:
Dict[str, Any]: json in proper format
"""
return {"type": "set_property", "path": self.path.lower(), "property": self.key.lower(), "value": self.value}
+5
View File
@@ -42,6 +42,7 @@ WEBSOCKET_COMMANDS = [
"set_object",
"set_output_options",
"set_output_type",
"set_training_state",
"get_object",
"set_property",
"delete",
@@ -107,6 +108,8 @@ class WebSocketHandler(tornado.websocket.WebSocketHandler):
find_node(self.bridge.tree, path).object = data
elif type_ == "set_output_type":
find_node(self.bridge.tree, path).object = data
elif type_ == "set_training_state":
find_node(self.bridge.tree, path).object = data
elif type_ == "offer":
offer = RTCSessionDescription(m["data"]["sdp"], m["data"]["type"])
@@ -193,6 +196,8 @@ class ZMQWebSocketBridge(object):
find_node(self.tree, path).object = data
elif cmd == "set_output_type":
find_node(self.tree, path).object = data
elif cmd == "set_training_state":
find_node(self.tree, path).object = data
elif cmd == "get_object":
data = find_node(self.tree, path).object
if isinstance(data, type(None)):
+21 -5
View File
@@ -25,6 +25,7 @@ from typing import List
import numpy as np
import torch
from pyrad.utils.decorators import check_visualizer_enabled, decorate_all
import pyrad.viewer.server.cameras as c
import pyrad.viewer.server.geometry as g
@@ -107,6 +108,7 @@ class CheckThread(threading.Thread):
camera_object["matrix"], self.state.prev_camera_matrix
):
self.state.check_interrupt_vis = True
self.state.prev_camera_matrix = camera_object["matrix"]
# check output type
data = self.state.vis["/Output Type"].get_object()
@@ -119,6 +121,7 @@ class CheckThread(threading.Thread):
time.sleep(0.001)
@decorate_all([check_visualizer_enabled])
class VisualizerState:
"""Class to hold state for visualizer variables"""
@@ -144,13 +147,26 @@ class VisualizerState:
def init_scene(self, image_dataset: ImageDataset, dataset_inputs: DatasetInputs) -> None:
"""initializes the scene with the datasets"""
if self.vis:
self._draw_scene_in_viewer(image_dataset, dataset_inputs)
self._draw_scene_in_viewer(image_dataset, dataset_inputs)
def update_scene(self, step: int, graph: Graph) -> None:
"""updates the scene based on the graph weights"""
if self._is_render_step(step):
self._render_image_in_viewer(graph)
data = self.vis["/Training State"].get_object()
if data is None or not data["training_state"]:
# in training mode, render every few steps
if self._is_render_step(step):
self._render_image_in_viewer(graph)
else:
# in pause training mode, enter render loop with set graph
local_step = step
run_loop = data["training_state"]
while run_loop:
if self._is_render_step(local_step):
self._render_image_in_viewer(graph)
data = self.vis["/Training State"].get_object()
run_loop = data["training_state"]
local_step += 1
def check_interrupt(self, frame, event, arg):
"""raises interrupt when flag has been set and not already on lowest resolution"""
@@ -162,7 +178,7 @@ class VisualizerState:
def _is_render_step(self, step: int, default_steps: int = 5) -> bool:
"""dynamically calculate when to render grapic based on resolution of image"""
if self.vis and step != 0:
if step != 0:
if self.res_upscale_factor == 1:
return True
steps_per_render_image = min(default_steps * self.res_upscale_factor, 100)
+23 -21
View File
@@ -27,14 +27,13 @@ from pyrad.viewer.server.commands import (
GetObject,
SetObject,
SetOutputOptions,
SetOutputType,
SetProperty,
SetTransform,
)
from pyrad.viewer.server.path import Path
class ViewerWindow(object):
class ViewerWindow:
context = zmq.Context()
def __init__(self, zmq_url):
@@ -82,7 +81,7 @@ class ViewerWindow(object):
signal.alarm(timeout_in_sec)
try:
logging.info("Sending ping to the viewer Bridge Server...")
response = self.send_ping()
_ = self.send_ping()
logging.info("Successfully connected.")
signal.alarm(0) # cancel the alarm
except Exception as e:
@@ -90,17 +89,16 @@ class ViewerWindow(object):
sys.exit()
class Viewer(object):
"""Visualizer class for connecting to the bridge server."""
class Viewer:
"""Visualizer class for connecting to the bridge server.
Args:
zmq_url (str, optional): _description_. Defaults to None.
window (ViewerWindow, optional): _description_. Defaults to None.
timeout (str, optional): _description_. Defaults to None.
"""
def __init__(self, zmq_url: str = None, window: ViewerWindow = None):
"""_summary_
Args:
zmq_url (str, optional): _description_. Defaults to None.
window (ViewerWindow, optional): _description_. Defaults to None.
timeout (str, optional): _description_. Defaults to None.
"""
if zmq_url is None and window is None:
raise ValueError("Must specify either zmq_url or window.")
if window is None:
@@ -120,6 +118,14 @@ class Viewer(object):
return Viewer.view_into(self.window, self.path.append(path))
def set_object(self, geometry, material=None):
"""Set the object at the current path
Args:
geometry (_type_): _description_
material (_type_, optional): _description_. Defaults to None.
Returns:
_type_: _description_
"""
return self.window.send(SetObject(geometry, material, self.path))
def get_object(self):
@@ -146,25 +152,21 @@ class Viewer(object):
return self.window.client.recv()
def set_transform(self, matrix=np.eye(4)):
"""Set the transform"""
assert matrix.shape == (4, 4)
return self.window.send(SetTransform(matrix, self.path))
def set_property(self, key, value):
"""Set the property"""
return self.window.send(SetProperty(key, value, self.path))
def set_output_options(self, options):
"""Set the output options"""
return self.window.send(SetOutputOptions(options, self.path))
def set_output_type(self, type):
data = self.window.send(SetOutputType(type, self.path))
data = umsgpack.unpackb(data)
if isinstance(data, str) and data.find("error") == 0:
# some error meaning that the object does not exist
return None
return data
def delete(self):
"""Delete the contents of the window"""
return self.window.send(Delete(self.path))
def __repr__(self):
return "<Viewer using: {window} at path: {path}>".format(window=self.window, path=self.path)
return f"<Viewer using: {self.window} at path: {self.path}>"