update docstrings and random cleanups (#387)

* fixing docstrings and small nits; up to fileds

* finished adding and fixing docstrings
This commit is contained in:
evonneng authored and GitHub committed 2022-09-10 23:09:44 -07:00
1 parent bd5967461d
commit d50c71ac43
52 files changed
+846 -646

No files matched your search

+1 -2
View File
@@ -30,8 +30,7 @@ def get_interpolated_camera_path(cameras: Cameras, steps: int) -> Cameras:
"""Generate a camera path between two cameras.
Args:
camera_a: The first camera.
camera_b: The second camera.
cameras: Cameras object containing intrinsics of all cameras.
steps: The number of steps to interpolate between the two cameras.
Returns:
+7 -5
View File
@@ -57,6 +57,8 @@ class Cameras:
fy: Focal length y.
cx: Principal point x.
cy: Principal point y.
width: Image width.
height: Image height.
distortion_params: OpenCV 6 radial distortion coefficients.
camera_type: Type of camera model.
"""
@@ -114,10 +116,10 @@ class Cameras:
def to(self, device: Union[torch.device, str]) -> "Cameras":
"""
Args:
Device to move the camera to.
device: Device to move the camera onto
Returns:
Cameras: Cameras on the specified device.
Cameras on the specified device.
"""
distortion_params = self.distortion_params.to(device) if self.distortion_params is not None else None
return Cameras(
@@ -135,10 +137,10 @@ class Cameras:
def get_image_coords(self, pixel_offset: float = 0.5) -> TensorType["height", "width", 2]:
"""
Args:
pixel_offset (float): Offset for each pixel. Defaults to center of pixel (0.5)
pixel_offset: Offset for each pixel. Defaults to center of pixel (0.5)
Returns:
TensorType["image_height", "image_width", 2]: Grid of image coordinates.
Grid of image coordinates.
"""
image_height = self.image_height
image_width = self.image_width
@@ -251,7 +253,7 @@ class Cameras:
"""Convert a camera to a json dictionary.
Args:
camera_idx (int): Index of the camera to convert.
camera_idx: Index of the camera to convert.
image: An image in range [0, 1] that is encoded to a base64 string. Defaults to None.
max_size: Max size to resize the image to. Defaults to None.
+44 -52
View File
@@ -28,35 +28,32 @@ from nerfactory.utils.tensor_dataclass import TensorDataclass
@dataclass
class Frustums(TensorDataclass):
"""Describes region of space as a frustum.
Attributes:
origins: xyz coordinate for ray origin.
directions: Direction of ray.
starts: Where the frustum starts along a ray.
ends: Where the frustum ends along a ray.
pixel_area: Projected area of pixel a distance 1 away from origin.
"""
"""Describes region of space as a frustum."""
origins: TensorType["bs":..., 3]
"""xyz coordinate for ray origin."""
directions: TensorType["bs":..., 3]
"""Direction of ray."""
starts: TensorType["bs":..., 1]
"""Where the frustum starts along a ray."""
ends: TensorType["bs":..., 1]
"""Where the frustum ends along a ray."""
pixel_area: TensorType["bs":..., 1]
"""Projected area of pixel a distance 1 away from origin."""
def get_positions(self) -> TensorType[..., 3]:
"""Calulates "center" position of frustum. Not weighted by mass.
Returns:
TensorType[..., 3]: xyz positions.
xyz positions.
"""
return self.origins + self.directions * (self.starts + self.ends) / 2
def get_gaussian_blob(self) -> Gaussians:
"""Calculates of guassian approximation of conical frustum.
"""Calculates guassian approximation of conical frustum.
Resturns:
Gaussians: Conical frustums approximated by gaussian distribution.
Conical frustums approximated by gaussian distribution.
"""
# Cone radius is set such that the square pixel_area matches the cone area.
cone_radius = torch.sqrt(self.pixel_area) / 1.7724538509055159 # r = sqrt(pixel_area / pi)
@@ -73,7 +70,7 @@ class Frustums(TensorDataclass):
"""Helper function to generate a placeholder frustum.
Returns:
Frustums: A size 1 frustum with meaningless values.
A size 1 frustum with meaningless values.
"""
return Frustums(
origins=torch.ones((1, 3)).to(device),
@@ -86,30 +83,27 @@ class Frustums(TensorDataclass):
@dataclass
class RaySamples(TensorDataclass):
"""Samples along a ray
Args:
frustums: Frustums along ray.
camera_indices: Camera index.
valid_mask: Rays that are valid.
deltas: "width" of each sample.
ts: sample-camera distance of each sample.
"""
"""Samples along a ray"""
frustums: Frustums
"""Frustums along ray."""
camera_indices: Optional[TensorType["bs":..., 1]] = None
"""Camera index."""
valid_mask: Optional[TensorType["bs":..., 1]] = None
"""Rays that are valid."""
deltas: Optional[TensorType["bs":..., 1]] = None
""""width" of each sample."""
metadata: Optional[Dict[str, TensorType["bs":..., "latent_dims"]]] = None
"""addtional information relevant to generating ray samples"""
def get_weights(self, densities: TensorType[..., "num_samples", 1]) -> TensorType[..., "num_samples", 1]:
"""Return weights based on predicted densities
Args:
densities (TensorType[..., "num_samples", 1]): Predicted densities for samples along ray
densities: Predicted densities for samples along ray
Returns:
TensorType[..., "num_samples", 1]: Weights for each sample
Weights for each sample
"""
delta_density = self.deltas * densities
@@ -134,14 +128,18 @@ class RaySamples(TensorDataclass):
return weights
def set_valid_mask(self, valid_mask: TensorType[..., "num_samples"]) -> None:
"""Sets valid mask"""
"""Sets valid mask
Args:
valid_mask: the mask to use
"""
self.valid_mask = valid_mask
def apply_masks(self) -> "RaySamples":
"""Use valid_mask to mask samples.
Returns:
RaySamples: New set of masked samples.
New set of masked samples.
"""
if self.valid_mask is not None:
return self[self.valid_mask[..., 0]]
@@ -150,36 +148,33 @@ class RaySamples(TensorDataclass):
@dataclass
class RayBundle(TensorDataclass):
"""A bundle of ray parameters.
Args:
origins: Ray origins (XYZ)
directions: Unit ray direction vector
pixel_area: Projected area of pixel a distance 1 away from origin
camera_indices: Camera indices
nears: Distance along ray to start sampling
fars: Rays Distance along ray to stop sampling
valid_mask: Rays that are valid
num_rays_per_chunk: Number of rays per chunk
metadata: Additional metadata or data needed for interpolation, will mimic shape of rays
"""
"""A bundle of ray parameters."""
# TODO(ethan): make sure the sizes with ... are correct
origins: TensorType[..., 3]
"""Ray origins (XYZ)"""
directions: TensorType[..., 3]
"""Unit ray direction vector"""
pixel_area: TensorType[..., 1]
"""Projected area of pixel a distance 1 away from origin"""
camera_indices: Optional[TensorType[..., 1]] = None
"""Camera indices"""
nears: Optional[TensorType[..., 1]] = None
"""Distance along ray to start sampling"""
fars: Optional[TensorType[..., 1]] = None
"""Rays Distance along ray to stop sampling"""
valid_mask: Optional[TensorType[..., 1, bool]] = None
"""Rays that are valid"""
num_rays_per_chunk: int = 128
"""Number of rays per chunk"""
metadata: Optional[Dict[str, TensorType["num_rays", "latent_dims"]]] = None
"""Additional metadata or data needed for interpolation, will mimic shape of rays"""
def set_camera_indices(self, camera_index: int) -> None:
"""Sets all of the the camera indices to a specific camera index.
Args:
camera_index (int): Camera index.
camera_index: Camera index.
"""
self.camera_indices = torch.ones_like(self.origins[..., 0:1]).long() * camera_index
@@ -191,10 +186,10 @@ class RayBundle(TensorDataclass):
"""Returns a RayBundle as a subset of rays.
Args:
num_rays (int): Number of rays in output RayBundle
num_rays: Number of rays in output RayBundle
Returns:
RayBundle: RayBundle with subset of rays.
RayBundle with subset of rays.
"""
assert num_rays <= len(self)
indices = random.sample(range(len(self)), k=num_rays)
@@ -204,11 +199,11 @@ class RayBundle(TensorDataclass):
"""Flattens RayBundle and extracts chunk given start and end indicies.
Args:
start_idx (int): Start index of RayBundle chunk.
end_idx (int): End index of RayBundle chunk.
start_idx: Start index of RayBundle chunk.
end_idx: End index of RayBundle chunk.
Returns:
RayBundle: Flattened RayBundle with end_idx-start_idx rays.
Flattened RayBundle with end_idx-start_idx rays.
"""
return self.flatten()[start_idx:end_idx]
@@ -216,17 +211,14 @@ class RayBundle(TensorDataclass):
def get_ray_samples(
self, bin_starts: TensorType["bs":..., "num_samples", 1], bin_ends: TensorType["bs":..., "num_samples", 1]
) -> RaySamples:
"""Produces samples for each ray by projection points along the ray direction.
Currently samples uniformly.
"""Produces samples for each ray by projection points along the ray direction. Currently samples uniformly.
Args:
bin_starts (TensorType[..., "num_samples", 1]): Distance from origin to start of bin.
bin_ends (TensorType[..., "num_samples", 1]): Distance from origin to end of bin.
bin_starts: Distance from origin to start of bin.
bin_ends: Distance from origin to end of bin.
Returns:
RaySamples: Samples projected along ray.
Samples projected along ray.
"""
device = self.origins.device
+46 -106
View File
@@ -18,7 +18,7 @@ Camera transformation helper code.
"""
import math
from typing import Literal, Tuple
from typing import List, Literal, Optional, Tuple
import numpy as np
import torch
@@ -27,80 +27,31 @@ from torchtyping import TensorType
_EPS = np.finfo(float).eps * 4.0
def unit_vector(data, axis=None, out=None):
def unit_vector(data, axis: Optional[int] = None) -> np.ndarray:
"""Return ndarray normalized by length, i.e. Euclidean norm, along axis.
>>> v0 = np.random.random(3)
>>> v1 = unit_vector(v0)
>>> np.allclose(v1, v0 / np.linalg.norm(v0))
True
>>> v0 = np.random.rand(5, 4, 3)
>>> v1 = unit_vector(v0, axis=-1)
>>> v2 = v0 / np.expand_dims(np.sqrt(np.sum(v0*v0, axis=2)), 2)
>>> np.allclose(v1, v2)
True
>>> v1 = unit_vector(v0, axis=1)
>>> v2 = v0 / np.expand_dims(np.sqrt(np.sum(v0*v0, axis=1)), 1)
>>> np.allclose(v1, v2)
True
>>> v1 = np.empty((5, 4, 3))
>>> unit_vector(v0, axis=1, out=v1)
>>> np.allclose(v1, v2)
True
>>> list(unit_vector([]))
[]
>>> list(unit_vector([1]))
[1.0]
Args:
axis: the axis along which to normalize into unit vector
out: where to write out the data to. If None, returns a new np ndarray
"""
if out is None:
data = np.array(data, dtype=np.float64, copy=True)
if data.ndim == 1:
data /= math.sqrt(np.dot(data, data))
return data
else:
if out is not data:
out[:] = np.array(data, copy=False)
data = out
data = np.array(data, dtype=np.float64, copy=True)
if data.ndim == 1:
data /= math.sqrt(np.dot(data, data))
return data
length = np.atleast_1d(np.sum(data * data, axis))
np.sqrt(length, length)
if axis is not None:
length = np.expand_dims(length, axis)
data /= length
if out is None:
return data
return data
def quaternion_from_matrix(matrix, isprecise=False):
def quaternion_from_matrix(matrix, isprecise: bool = False) -> np.ndarray:
"""Return quaternion from rotation matrix.
If isprecise is True, the input matrix is assumed to be a precise rotation
matrix and a faster algorithm is used.
>>> q = quaternion_from_matrix(np.identity(4), True)
>>> np.allclose(q, [1, 0, 0, 0])
True
>>> q = quaternion_from_matrix(np.diag([1, -1, -1, 1]))
>>> np.allclose(q, [0, 1, 0, 0]) or np.allclose(q, [0, -1, 0, 0])
True
>>> R = rotation_matrix(0.123, (1, 2, 3))
>>> q = quaternion_from_matrix(R, True)
>>> np.allclose(q, [0.9981095, 0.0164262, 0.0328524, 0.0492786])
True
>>> R = [[-0.545, 0.797, 0.260, 0], [0.733, 0.603, -0.313, 0],
... [-0.407, 0.021, -0.913, 0], [0, 0, 0, 1]]
>>> q = quaternion_from_matrix(R)
>>> np.allclose(q, [0.19069, 0.43736, 0.87485, -0.083611])
True
>>> R = [[0.395, 0.362, 0.843, 0], [-0.626, 0.796, -0.056, 0],
... [-0.677, -0.498, 0.529, 0], [0, 0, 0, 1]]
>>> q = quaternion_from_matrix(R)
>>> np.allclose(q, [0.82336615, -0.13610694, 0.46344705, -0.29792603])
True
>>> R = random_rotation_matrix()
>>> q = quaternion_from_matrix(R)
>>> is_same_transform(R, quaternion_matrix(q))
True
>>> R = euler_matrix(0.0, 0.0, np.pi/2.0)
>>> np.allclose(quaternion_from_matrix(R, isprecise=False),
... quaternion_from_matrix(R, isprecise=True))
True
Args:
matrix: rotation matrix to obtain quaternion
isprecise: if True, input matrix is assumed to be precise rotation matrix and a faster algorithm is used.
"""
M = np.array(matrix, dtype=np.float64, copy=False)[:4, :4]
if isprecise:
@@ -151,21 +102,14 @@ def quaternion_from_matrix(matrix, isprecise=False):
return q
def quaternion_slerp(quat0, quat1, fraction, spin=0, shortestpath=True):
def quaternion_slerp(quat0, quat1, fraction: float, spin: int = 0, shortestpath: bool = True) -> np.ndarray:
"""Return spherical linear interpolation between two quaternions.
>>> q0 = random_quaternion()
>>> q1 = random_quaternion()
>>> q = quaternion_slerp(q0, q1, 0)
>>> np.allclose(q, q0)
True
>>> q = quaternion_slerp(q0, q1, 1, 1)
>>> np.allclose(q, q1)
True
>>> q = quaternion_slerp(q0, q1, 0.5)
>>> angle = math.acos(np.dot(q0, q))
>>> (np.allclose(2, math.acos(np.dot(q0, q1)) / angle) or
np.allclose(2, math.acos(-np.dot(q0, q1)) / angle))
True
Args:
quat0: first quaternion
quat1: second quaternion
fraction: how much to interpolate between quat0 vs quat1 (if 0, closer to quat0; if 1, closer to quat1)
spin: how much of an additional spin to place on the interpolation
shortestpath: whether to return the short or long path to rotation
"""
q0 = unit_vector(quat0[:4])
q1 = unit_vector(quat1[:4])
@@ -192,17 +136,11 @@ def quaternion_slerp(quat0, quat1, fraction, spin=0, shortestpath=True):
return q0
def quaternion_matrix(quaternion):
def quaternion_matrix(quaternion) -> np.ndarray:
"""Return homogeneous rotation matrix from quaternion.
>>> M = quaternion_matrix([0.99810947, 0.06146124, 0, 0])
>>> np.allclose(M, rotation_matrix(0.123, [1, 0, 0]))
True
>>> M = quaternion_matrix([1, 0, 0, 0])
>>> np.allclose(M, np.identity(4))
True
>>> M = quaternion_matrix([0, 1, 0, 0])
>>> np.allclose(M, np.diag([1, -1, -1, 1]))
True
Args:
quaternion: value to convert to matrix
"""
q = np.array(quaternion, dtype=np.float64, copy=True)
n = np.dot(q, q)
@@ -220,13 +158,12 @@ def quaternion_matrix(quaternion):
)
def get_interpolated_poses(poseA, poseB, steps=10):
def get_interpolated_poses(poseA, poseB, steps: int = 10) -> List[float]:
"""Return interpolation of poses with specified number of steps.
Args:
poseA
poseB
Return:
list of poses
poseA: first pose
poseB: second pose
steps: number of steps the interpolated pose path should contain
"""
quatA = quaternion_from_matrix(poseA[:3, :3])
@@ -245,11 +182,14 @@ def get_interpolated_poses(poseA, poseB, steps=10):
return posesAB
def get_interpolated_K(KA, KB, steps=10):
def get_interpolated_K(KA, KB, steps: int = 10) -> TensorType[3, 4]:
"""
Interpolate between two camera poses.
Returns interpolated path between two camera poses with specified number of steps.
Args:
Returns:
KA: camera matrix 1
KB: camera matrix 2
steps: number of steps the interpolated pose path should contain
"""
Ks = []
ts = np.linspace(0, 1, steps)
@@ -288,7 +228,7 @@ def get_interpolated_poses_many(
def get_swirl_poses(pose):
"""
Returns a swirl around the camera poses.
# TODO(ethan): add parameters and make this work
# TODO(ethan): add parameters and make this work + add docstrings + return type
"""
N_frames = 30 * 4
dx = np.linspace(0, 0.03, N_frames)
@@ -302,12 +242,12 @@ def get_swirl_poses(pose):
return poses
def normalize(x):
def normalize(x) -> TensorType[...]:
"""Returns a normalized vector."""
return x / torch.linalg.norm(x)
def viewmatrix(lookat, up, pos):
def viewmatrix(lookat, up, pos) -> TensorType[...]:
"""Returns a camera transformation matrix.
Args:
@@ -316,7 +256,7 @@ def viewmatrix(lookat, up, pos):
pos: The position of the camera.
Returns:
torch.Tensor: A camera transformation matrix.
A camera transformation matrix.
"""
vec2 = normalize(lookat)
vec1_avg = normalize(up)
@@ -333,7 +273,7 @@ def get_distortion_params(
k4: float = 0.0,
p1: float = 0.0,
p2: float = 0.0,
):
) -> TensorType[...]:
"""Returns a distortion parameters matrix.
Args:
@@ -349,8 +289,6 @@ def get_distortion_params(
return torch.Tensor([k1, k2, k3, k4, p1, p2])
# Addapted from MultiNeRF
# https://github.com/google-research/multinerf/blob/b02228160d3179300c7d499dca28cb9ca3677f32/internal/camera_utils.py#L477-L509
def radial_and_tangential_undistort(
coords: TensorType["num_coords":..., 2],
distortion_params: TensorType["num_coords":..., 6],
@@ -358,6 +296,8 @@ def radial_and_tangential_undistort(
max_iterations=10,
) -> TensorType["num_coords":..., 2]:
"""Computes undistorted coords given opencv distortion parameters.
Addapted from MultiNeRF
https://github.com/google-research/multinerf/blob/b02228160d3179300c7d499dca28cb9ca3677f32/internal/camera_utils.py#L477-L509
Args:
coords: The distorted coordinates.
@@ -389,8 +329,6 @@ def radial_and_tangential_undistort(
return torch.stack([x, y], dim=-1)
# Adapted from MultiNeRF:
# https://github.com/google-research/multinerf/blob/b02228160d3179300c7d499dca28cb9ca3677f32/internal/camera_utils.py#L427-L474
def _compute_residual_and_jacobian(
x: TensorType["num_coords":...],
y: TensorType["num_coords":...],
@@ -406,6 +344,8 @@ def _compute_residual_and_jacobian(
TensorType["num_coords":...],
]:
"""Auxiliary function of radial_and_tangential_undistort() that computes residuals and jacobians.
Adapted from MultiNeRF:
https://github.com/google-research/multinerf/blob/b02228160d3179300c7d499dca28cb9ca3677f32/internal/camera_utils.py#L427-L474
Args:
x: The updated x coordinates.