Skip to content

Commit

Permalink
format code
Browse files Browse the repository at this point in the history
  • Loading branch information
wangxiaomeng030 committed Nov 4, 2024
1 parent 3ce8205 commit 4b1fc50
Show file tree
Hide file tree
Showing 46 changed files with 237 additions and 65 deletions.
22 changes: 14 additions & 8 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,23 @@ exclude: '^slam/model_components/slam_helpers_splatam\.py$|^scripts/download_dat

repos:
- repo: https://github.com/pycqa/flake8.git
rev: 3.8.3
rev: 7.1.1
hooks:
- id: flake8

- repo: https://github.com/LOTEAT/isort
rev: 5.10.1
hooks:
- id: isort

- repo: https://github.com/pre-commit/mirrors-yapf
rev: v0.30.0
rev: v0.32.0
hooks:
- id: yapf
additional_dependencies: [toml]

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.1.0
rev: v5.0.0
hooks:
- id: trailing-whitespace
- id: check-yaml
Expand All @@ -27,13 +30,16 @@ repos:
args: ["--remove"]
- id: mixed-line-ending
args: ["--fix=lf"]
- repo: https://github.com/myint/docformatter
rev: v1.3.1

- repo: https://github.com/PyCQA/docformatter.git
rev: v1.7.5
hooks:
- id: docformatter
args: ["--in-place", "--wrap-descriptions", "79"]
additional_dependencies: [tomli]
args: ["--in-place", "--config", "./pyproject.toml"]

- repo: https://github.com/codespell-project/codespell
rev: v2.1.0
rev: v2.3.0
hooks:
- id: codespell
args: ["--skip", "*.ipynb,tools/data/hvu/label_map.json", "-L", "te,nd,thre,Gool,gool"]
args: ["--skip", "*.ipynb,tools/data/hvu/label_map.json", "-L", "te,nd,thre,Gool,gool,CoFusion,cofusion"]
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,10 @@ Note: The default configuration in the algorithm is suitable for Replica. If you
The license for our codebase is under the [Apache-2.0](LICENSE).
Please note that this license only applies to the code in our library, the dependencies of which are separate and individually licensed. In the source code files, we have made specific licensing declarations for the third-party code being used. We would like to pay tribute to open-source implementations to which we rely on. Please be aware that utilizing both external dependencies and the fundamental code from their original sources might impact our codebase's licensing.

## Contributing

We appreciate all contributions to improve XRDSLAM. Please refer to [contributing.md](docs/contributing.md) for the contributing guideline.

## Acknowledgement

In addition to the implemented algorithm ([NICE-SLAM](https://github.com/cvg/nice-slam),[Co-SLAM](https://github.com/HengyiWang/Co-SLAM),[Vox-Fusion](https://github.com/zju3dv/Vox-Fusion),[Point-SLAM](https://github.com/eriksandstroem/Point-SLAM),[SplaTAM](https://github.com/spla-tam/SplaTAM), [DPVO](https://github.com/princeton-vl/DPVO), [NeuralRecon](https://github.com/zju3dv/NeuralRecon)), our code also adapt some codes from [Nerfstudio](https://github.com/nerfstudio-project/nerfstudio/), [Sdfstudio](https://autonomousvision.github.io/sdfstudio/). Thanks for making the code available.
Expand Down
69 changes: 69 additions & 0 deletions docs/contributing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Contributing to XRDSLAM

All kinds of contributions are welcome, including but not limited to the following.

- Fixes (typo, bugs)
- New features and components

## Workflow

1. Fork and pull the latest xrdslam
1. Checkout a new branch with a meaningful name (do not use master branch for PRs)
1. Commit your changes
1. Create a PR

```{note}
- If you plan to add some new features that involve large changes, it is encouraged to open an issue for discussion first.
- If you are the author of some papers and would like to include your method to xrnerf, please contact us. We will much appreciate your contribution.
```

## Code style

### Python

We adopt [PEP8](https://www.python.org/dev/peps/pep-0008/) as the preferred code style.

We use the following tools for linting and formatting:

- [flake8](http://flake8.pycqa.org/en/latest/): linter
- [yapf](https://github.com/google/yapf): formatter
- [isort](https://github.com/timothycrosley/isort): sort imports

Style configurations of yapf and isort can be found in [setup.cfg](../setup.cfg).

We use [pre-commit hook](https://pre-commit.com/) that checks and formats for `flake8`, `yapf`, `isort`, `trailing whitespaces`,
fixes `end-of-files`, sorts `requirements.txt` automatically on every commit.
The config for a pre-commit hook is stored in [.pre-commit-config](../.pre-commit-config.yaml).

After you clone the repository, you will need to install initialize pre-commit hook.

```
pip install pre-commit==3.8.0
```

From the repository folder

```
pre-commit install
```

If you are facing an issue when installing markdown lint, you may install ruby for markdown lint by
referring to [this repo](https://github.com/innerlee/setup) by following the usage and taking [`zzruby.sh`](https://github.com/innerlee/setup/blob/master/zzruby.sh)

or by the following steps

```shell
# install rvm
curl -L https://get.rvm.io | bash -s -- --autolibs=read-fail
rvm autolibs disable
# install ruby
rvm install 2.7.1
```

After this on every commit check code linters and formatter will be enforced.

> Before you create a PR, make sure that your code lints and is formatted by yapf.
### C++ and CUDA

We follow the [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html).
2 changes: 1 addition & 1 deletion scripts/utils/eval_ate.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
def get_tensor_from_camera(RT, Tquad=False):
"""Convert transformation matrix to quaternion and translation."""
gpu_id = -1
if type(RT) == torch.Tensor:
if isinstance(RT, torch.Tensor):
if RT.get_device() != -1:
RT = RT.detach().cpu()
gpu_id = RT.get_device()
Expand Down
1 change: 1 addition & 0 deletions scripts/utils/viz_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ def animation_callback(vis):


class SLAMFrontend:

def __init__(self,
output,
init_pose,
Expand Down
1 change: 1 addition & 0 deletions slam/algorithms/base_algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ class AlgorithmConfig(InstantiateConfig):


class Algorithm():

def __init__(self, config: AlgorithmConfig, camera: Camera,
device: str) -> None:
self.config = config
Expand Down
1 change: 1 addition & 0 deletions slam/algorithms/coslam.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ class CoSLAMConfig(AlgorithmConfig):


class CoSLAM(Algorithm):

def __init__(self, config: CoSLAMConfig, camera: Camera,
device: str) -> None:
super().__init__(config, camera, device)
Expand Down
8 changes: 4 additions & 4 deletions slam/algorithms/dpvo.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ def gmap(self):

def corr(self, coords, indices=None):
"""This function is from DPVO, licensed under the MIT License."""
"""local correlation volume."""
"""Local correlation volume."""
ii, jj = indices if indices is not None else (self.kk, self.jj)
ii1 = ii % (self.M * self.mem)
jj1 = jj % (self.mem)
Expand All @@ -224,7 +224,7 @@ def corr(self, coords, indices=None):

def reproject(self, indices=None):
"""This function is from DPVO, licensed under the MIT License."""
"""reproject patch k from i -> j."""
"""Reproject patch k from i -> j."""
(ii, jj, kk) = indices if indices is not None else (self.ii, self.jj,
self.kk)
coords = pops.transform(SE3(self.poses), self.patches, self.intrinsics,
Expand All @@ -249,7 +249,7 @@ def remove_factors(self, m):

def motion_probe(self):
"""This function is from DPVO, licensed under the MIT License."""
"""kinda hacky way to ensure enough motion for initialization."""
"""Kinda hacky way to ensure enough motion for initialization."""
kk = torch.arange(self.m - self.M, self.m, device='cuda')
jj = self.n * torch.ones_like(kk)
ii = self.ix[kk]
Expand Down Expand Up @@ -383,7 +383,7 @@ def get_pose(self, t):

def get_all_poses(self):
"""This function is from DPVO, licensed under the MIT License."""
"""interpolate missing poses."""
"""Interpolate missing poses."""
self.traj = {}
for i in range(self.n):
self.traj[self.tstamps_[i].item()] = self.poses_[i]
Expand Down
1 change: 1 addition & 0 deletions slam/algorithms/neural_recon.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ class NeuralReconConfig(AlgorithmConfig):


class NeuralRecon(Algorithm):

def __init__(self, config: NeuralReconConfig, camera: Camera,
device: str) -> None:
super().__init__(config, camera, device)
Expand Down
5 changes: 2 additions & 3 deletions slam/algorithms/voxfusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class VoxFusionConfig(AlgorithmConfig):


class VoxFusion(Algorithm):

def __init__(self, config: VoxFusionConfig, camera: Camera,
device: str) -> None:
super().__init__(config, camera, device)
Expand Down Expand Up @@ -202,9 +203,7 @@ def extract_mesh(self, res=8, clean_mesh=False, require_color=False):
verts, faces = self.marching_cubes(
voxel_centres,
sdf_grid) # [N_verts, 3], [N_face, 3 (3 ids of verts)]
'''
# TODO: clean mesh need depth and pose, use key frame info
'''
"""# TODO: clean mesh need depth and pose, use key frame info"""
colors = None
if require_color:
verts_torch = torch.from_numpy(verts).float().cuda()
Expand Down
16 changes: 12 additions & 4 deletions slam/common/datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ def get_dataset(data_path, data_type, device='cuda:0'):

# RGBD dataset
class BaseDataset(Dataset):

def __init__(self, data_path, device='cuda:0'):
super(BaseDataset, self).__init__()
self.data_format = 'RGBD'
Expand Down Expand Up @@ -138,6 +139,7 @@ def get_camera(self):


class Replica(BaseDataset):

def __init__(self, data_path, device='cuda:0'):
super(Replica, self).__init__(data_path, device)
self.color_paths = sorted(
Expand Down Expand Up @@ -168,6 +170,7 @@ def load_poses(self, path):

# mono_imu dataset
class Euroc(Dataset):

def __init__(self, data_path, device='cuda:0'):

self.data_format = 'MonoImu'
Expand Down Expand Up @@ -334,6 +337,7 @@ def load_poses(self, path):


class Azure(BaseDataset):

def __init__(self, data_path, device='cuda:0'):
super(Azure, self).__init__(data_path, device)
self.color_paths = sorted(
Expand Down Expand Up @@ -371,6 +375,7 @@ def load_poses(self, path):


class ScanNet(BaseDataset):

def __init__(self, data_path, device='cuda:0'):
super(ScanNet, self).__init__(data_path, device)
self.input_folder = os.path.join(self.input_folder, 'frames')
Expand Down Expand Up @@ -402,6 +407,7 @@ def load_poses(self, path):


class Scenes7(BaseDataset):

def __init__(self, data_path, device='cuda:0'):
super(Scenes7, self).__init__(data_path, device)
self.color_paths = sorted(
Expand Down Expand Up @@ -436,6 +442,7 @@ def load_poses(self, path):


class CoFusion(BaseDataset):

def __init__(self, data_path, device='cuda:0'):
super(CoFusion, self).__init__(data_path, device)
self.input_folder = os.path.join(data_path)
Expand All @@ -459,14 +466,15 @@ def load_poses(self, path):


class TUM_RGBD(BaseDataset):

def __init__(self, data_path, device='cuda:0'):
super(TUM_RGBD, self).__init__(data_path, device)
self.color_paths, self.depth_paths, self.poses = self.loadtum(
self.input_folder, frame_rate=32)
self.n_img = len(self.color_paths)

def parse_list(self, filepath, skiprows=0):
"""read list data."""
"""Read list data."""
data = np.loadtxt(filepath,
delimiter=' ',
dtype=np.unicode_,
Expand All @@ -478,7 +486,7 @@ def associate_frames(self,
tstamp_depth,
tstamp_pose,
max_dt=0.08):
"""pair images, depths, and poses."""
"""Pair images, depths, and poses."""
associations = []
for i, t in enumerate(tstamp_image):
if tstamp_pose is None:
Expand All @@ -497,7 +505,7 @@ def associate_frames(self,
return associations

def loadtum(self, datapath, frame_rate=-1):
"""read video data in tum-rgbd format."""
"""Read video data in tum-rgbd format."""
if os.path.isfile(os.path.join(datapath, 'groundtruth.txt')):
pose_list = os.path.join(datapath, 'groundtruth.txt')
elif os.path.isfile(os.path.join(datapath, 'pose.txt')):
Expand Down Expand Up @@ -544,7 +552,7 @@ def loadtum(self, datapath, frame_rate=-1):
return images, depths, poses

def pose_matrix_from_quaternion(self, pvec):
"""convert 4x4 pose matrix to (t, q)"""
"""Convert 4x4 pose matrix to (t, q)"""
from scipy.spatial.transform import Rotation

pose = np.eye(4)
Expand Down
1 change: 1 addition & 0 deletions slam/common/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@


class Frame(nn.Module):

def __init__(self,
fid,
rgb,
Expand Down
1 change: 1 addition & 0 deletions slam/common/mesher.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ class MesherConfig(InstantiateConfig):


class Mesher():

def __init__(self, config: MesherConfig, camera: Camera, bounding_box,
marching_cubes_bound) -> None:
self.config = config
Expand Down
1 change: 1 addition & 0 deletions slam/configs/base_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
# Pretty printing class
class PrintableConfig: # pylint: disable=too-few-public-methods
"""Printable Config defining str function."""

def __str__(self):
lines = [self.__class__.__name__ + ':']
for key, val in vars(self).items():
Expand Down
7 changes: 5 additions & 2 deletions slam/configs/input_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -497,5 +497,8 @@
tyro.conf.FlagConversionOff[tyro.extras.subcommand_type_from_defaults(
defaults=algorithm_configs, descriptions=descriptions)]]
"""Union[] type over config types, annotated with default instances for use
with tyro.cli(). Allows the user to pick between one of several base
configurations, and then override values in it."""
with tyro.cli().
Allows the user to pick between one of several base configurations, and
then override values in it.
"""
1 change: 1 addition & 0 deletions slam/engine/optimizers.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ class Optimizers:
config: The optimizer configuration object.
param_groups: A dictionary of parameter groups to optimize.
"""

def __init__(self,
config: Dict[str, Any] = None,
param_groups: Dict[str, List[Parameter]] = None,
Expand Down
4 changes: 3 additions & 1 deletion slam/engine/schedulers.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class SchedulerConfig(InstantiateConfig):
"""Basic scheduler config."""

_target: Type = field(default_factory=lambda: Scheduler)
"""target class to instantiate"""
"""Target class to instantiate."""


class Scheduler:
Expand Down Expand Up @@ -70,6 +70,7 @@ class NiceSLAMScheduler(Scheduler):

def get_scheduler(self, optimizer: Optimizer,
lr_init: float) -> LRScheduler:

def func(step):
if self.config.coarse:
learning_factor = self.config.stage_lr.coarse
Expand Down Expand Up @@ -101,6 +102,7 @@ class PointSLAMScheduler(Scheduler):

def get_scheduler(self, optimizer: Optimizer,
lr_init: float) -> LRScheduler:

def func(step):
if step <= self.config.max_steps * self.config.geo_iter_ratio:
learning_factor = self.config.start_lr
Expand Down
Loading

0 comments on commit 4b1fc50

Please sign in to comment.