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=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_NAMES = dict([(camera_model.model_name, 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 = {camera_model.model_name: camera_model for camera_model in CAMERA_MODELS}
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)
"""
cameras = {}
with open(path, "r") as fid:
with open(path) as fid:
while True:
line = fid.readline()
if not line:
@@ -160,7 +160,7 @@ def write_cameras_text(cameras, path):
HEADER = (
"# Camera list with one line of data per camera:\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:
fid.write(HEADER)
@@ -194,7 +194,7 @@ def read_images_text(path):
void Reconstruction::WriteImagesText(const std::string& path)
"""
images = {}
with open(path, "r") as fid:
with open(path) as fid:
while True:
line = fid.readline()
if not line:
@@ -272,7 +272,7 @@ def write_images_text(images, path):
"# Image list with two lines of data per image:\n"
+ "# IMAGE_ID, QW, QX, QY, QZ, TX, TY, TZ, CAMERA_ID, NAME\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:
@@ -316,7 +316,7 @@ def read_pointsTD_text(path):
void Reconstruction::WritePoints3DText(const std::string& path)
"""
points3D = {}
with open(path, "r") as fid:
with open(path) as fid:
while True:
line = fid.readline()
if not line:
@@ -374,7 +374,7 @@ def write_pointsTD_text(points3D, path):
HEADER = (
"# 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"
+ "# 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:
+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)
).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]
mask, semantics = None, None
if "mask" in batch:
+3 -3
View File
@@ -37,9 +37,9 @@ class Field(nn.Module):
frustums=Frustums(
origins=positions,
directions=torch.ones_like(positions),
starts=torch.zeros_like((positions[..., :1])),
ends=torch.zeros_like((positions[..., :1])),
pixel_area=torch.ones_like((positions[..., :1])),
starts=torch.zeros_like(positions[..., :1]),
ends=torch.zeros_like(positions[..., :1]),
pixel_area=torch.ones_like(positions[..., :1]),
)
)
density, _ = self.get_density(ray_samples)
+1 -1
View File
@@ -192,7 +192,7 @@ class RFFEncoding(Encoding):
if covs is None:
encoded_inputs = torch.sin(torch.cat([scaled_inputs, scaled_inputs + torch.pi / 2.0], dim=-1))
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(
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]
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]
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.
"""
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)
@@ -102,10 +102,8 @@ def get_project_root(path: str) -> str:
project_root = os.getenv("PROJECT_ROOT")
if project_root is None:
logging.info(
(
"Please set PROJECT_ROOT to the root directory of this repo. "
"Going to try calling get_git_root(path) instead."
)
"Please set PROJECT_ROOT to the root directory of this repo. "
"Going to try calling get_git_root(path) instead."
)
project_root = get_git_root(path)
return project_root
+21 -36
View File
@@ -15,7 +15,6 @@
"""Geometry to render meshes, textures, etc.
"""
from __future__ import absolute_import, division, print_function
import base64
import sys
@@ -25,13 +24,8 @@ from typing import Any, BinaryIO, Dict, Iterable, List, Optional, Tuple
import numpy as np
import umsgpack
if sys.version_info >= (3, 0):
UNICODE = str
from io import BytesIO, StringIO
else:
from StringIO import StringIO
BytesIO = StringIO
UNICODE = str
from io import BytesIO, StringIO
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):
super(OrthographicCamera, self).__init__()
super().__init__()
self.left = left
self.right = right
self.top = top
@@ -492,7 +486,7 @@ class PerspectiveCamera(SceneElement):
film_offset: float = 0,
focus: float = 10,
):
super(PerspectiveCamera, self).__init__()
super().__init__()
self.fov = fov
self.aspect = aspect
self.far = far
@@ -583,15 +577,12 @@ def data_from_stream(stream: BinaryIO) -> str:
Raises:
ValueError: invalid stream type
"""
if sys.version_info >= (3, 0):
if isinstance(stream, BytesIO):
data = stream.read().decode(encoding="utf-8")
elif isinstance(stream, StringIO):
data = stream.read()
else:
raise ValueError(f"Stream must be instance of StringIO or BytesIO, not {type(stream)}")
else:
if isinstance(stream, BytesIO):
data = stream.read().decode(encoding="utf-8")
elif isinstance(stream, StringIO):
data = stream.read()
else:
raise ValueError(f"Stream must be instance of StringIO or BytesIO, not {type(stream)}")
return data
@@ -629,7 +620,7 @@ class ObjMeshGeometry(MeshGeometry):
Args:
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")
@staticmethod
@@ -659,7 +650,7 @@ class DaeMeshGeometry(MeshGeometry):
Args:
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")
@staticmethod
@@ -702,15 +693,12 @@ class StlMeshGeometry(MeshGeometry):
Args:
f: binary io stream to read from
"""
if sys.version_info >= (3, 0):
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:
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)}")
_, extcode = threejs_type(np.uint8)
encoded = umsgpack.Ext(extcode, arr.tobytes())
return MeshGeometry(encoded, "stl")
@@ -746,15 +734,12 @@ class PlyMeshGeometry(MeshGeometry):
Args:
f: binary io stream to read from
"""
if sys.version_info >= (3, 0):
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:
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)}")
_, extcode = threejs_type(np.uint8)
encoded = umsgpack.Ext(extcode, arr.tobytes())
return MeshGeometry(encoded, "stl")
+1 -3
View File
@@ -15,13 +15,11 @@
"""Path class
"""
from __future__ import absolute_import, division, print_function
import sys
from typing import Tuple
if sys.version_info >= (3, 0):
UNICODE = str
UNICODE = str
class Path:
-1
View File
@@ -14,7 +14,6 @@
"""Server bridge to faciliate interactions between python backend and javascript front end"""
from __future__ import absolute_import, division, print_function
import sys
from typing import Callable, List, Optional
+2 -4
View File
@@ -16,7 +16,6 @@
Functions for traversing server bridge tree nodes (storage)
"""
from __future__ import absolute_import, division, print_function
from collections import defaultdict
from typing import List
@@ -28,7 +27,7 @@ class TreeNode(defaultdict):
__slots__ = ["object", "transform", "properties", "animation"]
def __init__(self, *args, **kwargs):
super(TreeNode, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.object = None
self.properties = []
self.transform = None
@@ -46,8 +45,7 @@ def walk(tree: TreeNode) -> None:
"""
yield tree
for v in tree.values():
for t in walk(v): # could use `yield from` if we didn't need python2
yield t
yield from walk(v)
def find_node(tree: TreeNode, path: List[str]) -> TreeNode: