Code cleanup (#234)

This commit is contained in:
Matthew Tancik authored and GitHub committed 2022-07-31 18:22:57 -07:00
1 parent 8b414bafab
commit e35781fe85
14 files changed
+46 -68

No files matched your search

+8 -8
View File
@@ -66,8 +66,8 @@ CAMERA_MODELS = {
CameraModel(model_id=9, model_name="RADIAL_FISHEYE", num_params=5), CameraModel(model_id=9, model_name="RADIAL_FISHEYE", num_params=5),
CameraModel(model_id=10, model_name="THIN_PRISM_FISHEYE", num_params=12), CameraModel(model_id=10, model_name="THIN_PRISM_FISHEYE", num_params=12),
} }
CAMERA_MODEL_IDS = dict([(camera_model.model_id, camera_model) for camera_model in CAMERA_MODELS]) CAMERA_MODEL_IDS = {camera_model.model_id: camera_model for camera_model in CAMERA_MODELS}
CAMERA_MODEL_NAMES = dict([(camera_model.model_name, camera_model) for camera_model in CAMERA_MODELS]) CAMERA_MODEL_NAMES = {camera_model.model_name: camera_model for camera_model in CAMERA_MODELS}
def read_next_bytes(fid, num_bytes, format_char_sequence, endian_character="<"): def read_next_bytes(fid, num_bytes, format_char_sequence, endian_character="<"):
@@ -109,7 +109,7 @@ def read_cameras_text(path):
void Reconstruction::ReadCamerasText(const std::string& path) void Reconstruction::ReadCamerasText(const std::string& path)
""" """
cameras = {} cameras = {}
with open(path, "r") as fid: with open(path) as fid:
while True: while True:
line = fid.readline() line = fid.readline()
if not line: if not line:
@@ -160,7 +160,7 @@ def write_cameras_text(cameras, path):
HEADER = ( HEADER = (
"# Camera list with one line of data per camera:\n" "# Camera list with one line of data per camera:\n"
+ "# CAMERA_ID, MODEL, WIDTH, HEIGHT, PARAMS[]\n" + "# CAMERA_ID, MODEL, WIDTH, HEIGHT, PARAMS[]\n"
+ "# Number of cameras: {}\n".format(len(cameras)) + f"# Number of cameras: {len(cameras)}\n"
) )
with open(path, "w") as fid: with open(path, "w") as fid:
fid.write(HEADER) fid.write(HEADER)
@@ -194,7 +194,7 @@ def read_images_text(path):
void Reconstruction::WriteImagesText(const std::string& path) void Reconstruction::WriteImagesText(const std::string& path)
""" """
images = {} images = {}
with open(path, "r") as fid: with open(path) as fid:
while True: while True:
line = fid.readline() line = fid.readline()
if not line: if not line:
@@ -272,7 +272,7 @@ def write_images_text(images, path):
"# Image list with two lines of data per image:\n" "# Image list with two lines of data per image:\n"
+ "# IMAGE_ID, QW, QX, QY, QZ, TX, TY, TZ, CAMERA_ID, NAME\n" + "# IMAGE_ID, QW, QX, QY, QZ, TX, TY, TZ, CAMERA_ID, NAME\n"
+ "# POINTS2D[] as (X, Y, POINT3D_ID)\n" + "# POINTS2D[] as (X, Y, POINT3D_ID)\n"
+ "# Number of images: {}, mean observations per image: {}\n".format(len(images), mean_observations) + f"# Number of images: {len(images)}, mean observations per image: {mean_observations}\n"
) )
with open(path, "w") as fid: with open(path, "w") as fid:
@@ -316,7 +316,7 @@ def read_pointsTD_text(path):
void Reconstruction::WritePoints3DText(const std::string& path) void Reconstruction::WritePoints3DText(const std::string& path)
""" """
points3D = {} points3D = {}
with open(path, "r") as fid: with open(path) as fid:
while True: while True:
line = fid.readline() line = fid.readline()
if not line: if not line:
@@ -374,7 +374,7 @@ def write_pointsTD_text(points3D, path):
HEADER = ( HEADER = (
"# 3D point list with one line of data per point:\n" "# 3D point list with one line of data per point:\n"
+ "# POINT3D_ID, X, Y, Z, R, G, B, ERROR, TRACK[] as (IMAGE_ID, POINT2D_IDX)\n" + "# POINT3D_ID, X, Y, Z, R, G, B, ERROR, TRACK[] as (IMAGE_ID, POINT2D_IDX)\n"
+ "# Number of points: {}, mean track length: {}\n".format(len(points3D), mean_track_length) + f"# Number of points: {len(points3D)}, mean track length: {mean_track_length}\n"
) )
with open(path, "w") as fid: with open(path, "w") as fid:
+1 -1
View File
@@ -41,7 +41,7 @@ def collate_image_dataset_batch(batch, num_rays_per_batch, keep_full_image: bool
* torch.tensor([num_images, image_height, image_width], device=device) * torch.tensor([num_images, image_height, image_width], device=device)
).long() ).long()
c, y, x = [i.flatten() for i in torch.split(indices, 1, dim=-1)] c, y, x = (i.flatten() for i in torch.split(indices, 1, dim=-1))
image = batch["image"][c, y, x] image = batch["image"][c, y, x]
mask, semantics = None, None mask, semantics = None, None
if "mask" in batch: if "mask" in batch:
+3 -3
View File
@@ -37,9 +37,9 @@ class Field(nn.Module):
frustums=Frustums( frustums=Frustums(
origins=positions, origins=positions,
directions=torch.ones_like(positions), directions=torch.ones_like(positions),
starts=torch.zeros_like((positions[..., :1])), starts=torch.zeros_like(positions[..., :1]),
ends=torch.zeros_like((positions[..., :1])), ends=torch.zeros_like(positions[..., :1]),
pixel_area=torch.ones_like((positions[..., :1])), pixel_area=torch.ones_like(positions[..., :1]),
) )
) )
density, _ = self.get_density(ray_samples) density, _ = self.get_density(ray_samples)
+1 -1
View File
@@ -192,7 +192,7 @@ class RFFEncoding(Encoding):
if covs is None: if covs is None:
encoded_inputs = torch.sin(torch.cat([scaled_inputs, scaled_inputs + torch.pi / 2.0], dim=-1)) encoded_inputs = torch.sin(torch.cat([scaled_inputs, scaled_inputs + torch.pi / 2.0], dim=-1))
else: else:
input_var = torch.sum(((covs @ self.b_matrix)) * self.b_matrix, -2) input_var = torch.sum((covs @ self.b_matrix) * self.b_matrix, -2)
encoded_inputs = expected_sin( encoded_inputs = expected_sin(
torch.cat([scaled_inputs, scaled_inputs + torch.pi / 2.0], dim=-1), torch.cat(2 * [input_var], dim=-1) torch.cat([scaled_inputs, scaled_inputs + torch.pi / 2.0], dim=-1), torch.cat(2 * [input_var], dim=-1)
) )
+1 -1
View File
@@ -105,7 +105,7 @@ class SpacedSampler(Sampler):
bins = torch.linspace(0.0, 1.0, num_samples + 1).to(ray_bundle.origins.device)[None, ...] # [1, num_samples+1] bins = torch.linspace(0.0, 1.0, num_samples + 1).to(ray_bundle.origins.device)[None, ...] # [1, num_samples+1]
s_near, s_far = [self.spacing_fn(x) for x in (ray_bundle.nears, ray_bundle.fars)] s_near, s_far = (self.spacing_fn(x) for x in (ray_bundle.nears, ray_bundle.fars))
bins = self.spacing_fn_inv(bins * s_far + (1 - bins) * s_near) # [num_rays, num_samples+1] bins = self.spacing_fn_inv(bins * s_far + (1 - bins) * s_near) # [num_rays, num_samples+1]
if self.train_stratified and self.training: if self.train_stratified and self.training:
+3 -5
View File
@@ -29,7 +29,7 @@ def load_from_json(filename: str):
filename: The filename to load from. filename: The filename to load from.
""" """
assert filename.endswith(".json") assert filename.endswith(".json")
with open(filename, "r", encoding="UTF-8") as file: with open(filename, encoding="UTF-8") as file:
return json.load(file) return json.load(file)
@@ -102,10 +102,8 @@ def get_project_root(path: str) -> str:
project_root = os.getenv("PROJECT_ROOT") project_root = os.getenv("PROJECT_ROOT")
if project_root is None: if project_root is None:
logging.info( logging.info(
( "Please set PROJECT_ROOT to the root directory of this repo. "
"Please set PROJECT_ROOT to the root directory of this repo. " "Going to try calling get_git_root(path) instead."
"Going to try calling get_git_root(path) instead."
)
) )
project_root = get_git_root(path) project_root = get_git_root(path)
return project_root return project_root
+21 -36
View File
@@ -15,7 +15,6 @@
"""Geometry to render meshes, textures, etc. """Geometry to render meshes, textures, etc.
""" """
from __future__ import absolute_import, division, print_function
import base64 import base64
import sys import sys
@@ -25,13 +24,8 @@ from typing import Any, BinaryIO, Dict, Iterable, List, Optional, Tuple
import numpy as np import numpy as np
import umsgpack import umsgpack
if sys.version_info >= (3, 0): UNICODE = str
UNICODE = str from io import BytesIO, StringIO
from io import BytesIO, StringIO
else:
from StringIO import StringIO
BytesIO = StringIO
class SceneElement: class SceneElement:
@@ -434,7 +428,7 @@ class OrthographicCamera(SceneElement):
""" """
def __init__(self, left: float, right: float, top: float, bottom: float, near: float, far: float, zoom: int = 1): def __init__(self, left: float, right: float, top: float, bottom: float, near: float, far: float, zoom: int = 1):
super(OrthographicCamera, self).__init__() super().__init__()
self.left = left self.left = left
self.right = right self.right = right
self.top = top self.top = top
@@ -492,7 +486,7 @@ class PerspectiveCamera(SceneElement):
film_offset: float = 0, film_offset: float = 0,
focus: float = 10, focus: float = 10,
): ):
super(PerspectiveCamera, self).__init__() super().__init__()
self.fov = fov self.fov = fov
self.aspect = aspect self.aspect = aspect
self.far = far self.far = far
@@ -583,15 +577,12 @@ def data_from_stream(stream: BinaryIO) -> str:
Raises: Raises:
ValueError: invalid stream type ValueError: invalid stream type
""" """
if sys.version_info >= (3, 0): if isinstance(stream, BytesIO):
if isinstance(stream, BytesIO): data = stream.read().decode(encoding="utf-8")
data = stream.read().decode(encoding="utf-8") elif isinstance(stream, StringIO):
elif isinstance(stream, StringIO):
data = stream.read()
else:
raise ValueError(f"Stream must be instance of StringIO or BytesIO, not {type(stream)}")
else:
data = stream.read() data = stream.read()
else:
raise ValueError(f"Stream must be instance of StringIO or BytesIO, not {type(stream)}")
return data return data
@@ -629,7 +620,7 @@ class ObjMeshGeometry(MeshGeometry):
Args: Args:
fname: file name to read from fname: file name to read from
""" """
with open(fname, "r", encoding="utf8") as f: with open(fname, encoding="utf8") as f:
return MeshGeometry(f.read(), "obj") return MeshGeometry(f.read(), "obj")
@staticmethod @staticmethod
@@ -659,7 +650,7 @@ class DaeMeshGeometry(MeshGeometry):
Args: Args:
fname: file name to read from fname: file name to read from
""" """
with open(fname, "r", encoding="utf8") as f: with open(fname, encoding="utf8") as f:
return MeshGeometry(f.read(), "dae") return MeshGeometry(f.read(), "dae")
@staticmethod @staticmethod
@@ -702,15 +693,12 @@ class StlMeshGeometry(MeshGeometry):
Args: Args:
f: binary io stream to read from f: binary io stream to read from
""" """
if sys.version_info >= (3, 0): if isinstance(f, BytesIO):
if isinstance(f, BytesIO):
arr = np.frombuffer(f.read(), dtype=np.uint8)
elif isinstance(f, StringIO):
arr = np.frombuffer(bytes(f.read(), "utf-8"), dtype=np.uint8)
else:
raise ValueError(f"Stream must be instance of StringIO or BytesIO, not {type(f)}")
else:
arr = np.frombuffer(f.read(), dtype=np.uint8) arr = np.frombuffer(f.read(), dtype=np.uint8)
elif isinstance(f, StringIO):
arr = np.frombuffer(bytes(f.read(), "utf-8"), dtype=np.uint8)
else:
raise ValueError(f"Stream must be instance of StringIO or BytesIO, not {type(f)}")
_, extcode = threejs_type(np.uint8) _, extcode = threejs_type(np.uint8)
encoded = umsgpack.Ext(extcode, arr.tobytes()) encoded = umsgpack.Ext(extcode, arr.tobytes())
return MeshGeometry(encoded, "stl") return MeshGeometry(encoded, "stl")
@@ -746,15 +734,12 @@ class PlyMeshGeometry(MeshGeometry):
Args: Args:
f: binary io stream to read from f: binary io stream to read from
""" """
if sys.version_info >= (3, 0): if isinstance(f, BytesIO):
if isinstance(f, BytesIO):
arr = np.frombuffer(f.read(), dtype=np.uint8)
elif isinstance(f, StringIO):
arr = np.frombuffer(bytes(f.read(), "utf-8"), dtype=np.uint8)
else:
raise ValueError(f"Stream must be instance of StringIO or BytesIO, not {type(f)}")
else:
arr = np.frombuffer(f.read(), dtype=np.uint8) arr = np.frombuffer(f.read(), dtype=np.uint8)
elif isinstance(f, StringIO):
arr = np.frombuffer(bytes(f.read(), "utf-8"), dtype=np.uint8)
else:
raise ValueError(f"Stream must be instance of StringIO or BytesIO, not {type(f)}")
_, extcode = threejs_type(np.uint8) _, extcode = threejs_type(np.uint8)
encoded = umsgpack.Ext(extcode, arr.tobytes()) encoded = umsgpack.Ext(extcode, arr.tobytes())
return MeshGeometry(encoded, "stl") return MeshGeometry(encoded, "stl")
+1 -3
View File
@@ -15,13 +15,11 @@
"""Path class """Path class
""" """
from __future__ import absolute_import, division, print_function
import sys import sys
from typing import Tuple from typing import Tuple
if sys.version_info >= (3, 0): UNICODE = str
UNICODE = str
class Path: class Path:
-1
View File
@@ -14,7 +14,6 @@
"""Server bridge to faciliate interactions between python backend and javascript front end""" """Server bridge to faciliate interactions between python backend and javascript front end"""
from __future__ import absolute_import, division, print_function
import sys import sys
from typing import Callable, List, Optional from typing import Callable, List, Optional
+2 -4
View File
@@ -16,7 +16,6 @@
Functions for traversing server bridge tree nodes (storage) Functions for traversing server bridge tree nodes (storage)
""" """
from __future__ import absolute_import, division, print_function
from collections import defaultdict from collections import defaultdict
from typing import List from typing import List
@@ -28,7 +27,7 @@ class TreeNode(defaultdict):
__slots__ = ["object", "transform", "properties", "animation"] __slots__ = ["object", "transform", "properties", "animation"]
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(TreeNode, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.object = None self.object = None
self.properties = [] self.properties = []
self.transform = None self.transform = None
@@ -46,8 +45,7 @@ def walk(tree: TreeNode) -> None:
""" """
yield tree yield tree
for v in tree.values(): for v in tree.values():
for t in walk(v): # could use `yield from` if we didn't need python2 yield from walk(v)
yield t
def find_node(tree: TreeNode, path: List[str]) -> TreeNode: def find_node(tree: TreeNode, path: List[str]) -> TreeNode:
+1 -1
View File
@@ -52,7 +52,7 @@ def _load_checkpoint(config: DictConfig, graph: Graph) -> None:
if config.load_step is None: if config.load_step is None:
print("Loading latest checkpoint from load_dir") print("Loading latest checkpoint from load_dir")
# NOTE: this is specific to the checkpoint name format # NOTE: this is specific to the checkpoint name format
load_step = sorted([int(x[x.find("-") + 1 : x.find(".")]) for x in os.listdir(config.load_dir)])[-1] load_step = sorted(int(x[x.find("-") + 1 : x.find(".")]) for x in os.listdir(config.load_dir))[-1]
else: else:
load_step = config.load_step load_step = config.load_step
load_path = os.path.join(config.load_dir, f"step-{load_step:09d}.ckpt") load_path = os.path.join(config.load_dir, f"step-{load_step:09d}.ckpt")
+1 -1
View File
@@ -212,7 +212,7 @@ def main(config: DictConfig):
unrolled_path = os.path.join(os.getcwd(), ".hydra/config.yaml") unrolled_path = os.path.join(os.getcwd(), ".hydra/config.yaml")
if os.path.exists(unrolled_path): if os.path.exists(unrolled_path):
with open(unrolled_path, "r", encoding="utf8") as f: with open(unrolled_path, encoding="utf8") as f:
unrolled_config = yaml.safe_load(f) unrolled_config = yaml.safe_load(f)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
logger.info("Printing current config setup") logger.info("Printing current config setup")
+1 -1
View File
@@ -48,7 +48,7 @@ def test_broadcasting():
assert tensor_dataclass.b.shape == (4, 6, 2) assert tensor_dataclass.b.shape == (4, 6, 2)
a = torch.ones((4, 6, 3)) a = torch.ones((4, 6, 3))
b = torch.ones((2)) b = torch.ones(2)
tensor_dataclass = TestTensorDataclass(a=a, b=b) tensor_dataclass = TestTensorDataclass(a=a, b=b)
assert tensor_dataclass.b.shape == (4, 6, 2) assert tensor_dataclass.b.shape == (4, 6, 2)
+2 -2
View File
@@ -71,7 +71,7 @@ def test_drawing():
v["random"].set_transform(get_translation_matrix([-0.5, -0.5, 0])) v["random"].set_transform(get_translation_matrix([-0.5, -0.5, 0]))
v = vis["lines"] v = vis["lines"]
v.set_transform(get_translation_matrix(([-2, -3, 0]))) v.set_transform(get_translation_matrix([-2, -3, 0]))
vertices = np.random.random((3, 10)).astype(np.float32) vertices = np.random.random((3, 10)).astype(np.float32)
v["line_segments"].set_object(g.LineSegments(g.PointsGeometry(vertices))) v["line_segments"].set_object(g.LineSegments(g.PointsGeometry(vertices)))
@@ -104,7 +104,7 @@ def test_drawing():
g.LineBasicMaterial(vertexColors=True), g.LineBasicMaterial(vertexColors=True),
) )
) )
v["triad"].set_transform(get_translation_matrix(([0, 5, 0]))) v["triad"].set_transform(get_translation_matrix([0, 5, 0]))
v["triad_function"].set_object(g.triad(0.5)) v["triad_function"].set_object(g.triad(0.5))
v["triad_function"].set_transform(get_translation_matrix([0, 6, 0])) v["triad_function"].set_transform(get_translation_matrix([0, 6, 0]))