Skip to content

Commit

Permalink
manual ruff fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
nim65s committed Oct 17, 2023
1 parent ccebb32 commit 8ddfae8
Show file tree
Hide file tree
Showing 60 changed files with 428 additions and 261 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,12 @@
)
from happypose.pose_estimators.megapose.evaluation.runner_utils import format_results
from happypose.pose_estimators.megapose.inference.icp_refiner import ICPRefiner
from happypose.toolbox.datasets.datasets_cfg import make_object_dataset

# Pose estimator
# from happypose.pose_estimators.megapose.inference.teaserpp_refiner import TeaserppRefiner
from happypose.pose_estimators.megapose.inference.teaserpp_refiner import (
TeaserppRefiner,
)
from happypose.toolbox.datasets.datasets_cfg import make_object_dataset
from happypose.toolbox.lib3d.rigid_mesh_database import MeshDataBase
from happypose.toolbox.renderer.panda3d_batch_renderer import Panda3dBatchRenderer
from happypose.toolbox.utils.distributed import get_rank, get_tmp_dir
Expand Down Expand Up @@ -86,7 +88,9 @@ def load_pose_models(coarse_run_id, refiner_run_id, n_workers):
# object_ds = BOPObjectDataset(BOP_DS_DIR / 'tless/models_cad')
# object_ds = make_object_dataset(cfg.object_ds_name)
# mesh_db = MeshDataBase.from_object_ds(object_ds)
# renderer = BulletBatchRenderer(object_set=cfg.urdf_ds_name, n_workers=n_workers, gpu_renderer=gpu_renderer)
# renderer = BulletBatchRenderer(
# object_set=cfg.urdf_ds_name, n_workers=n_workers, gpu_renderer=gpu_renderer
# )
#

object_dataset = make_object_dataset("ycbv")
Expand Down Expand Up @@ -210,9 +214,14 @@ def run_eval(
# See https://stackoverflow.com/a/53287330
assert cfg.coarse_run_id is not None
assert cfg.refiner_run_id is not None
# TODO (emaitre): This fuction seems to take the wrong parameters. Trying to fix this
# TODO (emaitre): This fuction seems to take the wrong parameters. Trying to fix
# this.
"""
coarse_model, refiner_model, mesh_db = happypose.toolbox.inference.utils.load_pose_models(
(
coarse_model,
refiner_model,
mesh_db,
) = happypose.toolbox.inference.utils.load_pose_models(
coarse_run_id=cfg.coarse_run_id,
refiner_run_id=cfg.refiner_run_id,
n_workers=cfg.n_rendering_workers,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,8 @@ def get_preds():
n_dets = len(this_batch_detections)

logger.debug(
f"Full predictions: {n_dets} detections + pose estimation in {duration:.3f} s",
f"Full predictions: {n_dets} detections + pose estimation "
f"in {duration:.3f} s",
)
logger.debug(f"{'-'*80}")
return this_batch_detections, all_preds, duration
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,8 @@ def run_inference_pipeline(
Returns: A dict with keys
- 'final': final preds
- 'refiner/final': preds at final refiner iteration (before depth refinement)
- 'refiner/final': preds at final refiner iteration (before depth
refinement)
- 'depth_refinement': preds after depth refinement.
Expand Down Expand Up @@ -130,14 +131,16 @@ def run_inference_pipeline(
# - 'refiner/iteration=5`
# - `depth_refiner`
# Note: Since we support multi-hypotheses we need to potentially
# go back and extract out the 'refiner/iteration=1`, `refiner/iteration=5` things for the ones that were actually the highest scoring at the end.
# go back and extract out the 'refiner/iteration=1`, `refiner/iteration=5`
# things for the ones that were actually the highest scoring at the end.

all_preds = {}
data_TCO_refiner = extra_data["refiner"]["preds"]

k_0 = f"refiner/iteration={self.inference_cfg.n_refiner_iterations}"
all_preds = {
"final": preds,
f"refiner/iteration={self.inference_cfg.n_refiner_iterations}": data_TCO_refiner,
k_0: data_TCO_refiner,
"refiner/final": data_TCO_refiner,
"coarse": extra_data["coarse"]["preds"],
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
import pandas as pd
import torch

import happypose.pose_estimators.cosypose.cosypose.utils.tensor_collection as tc

# MegaPose
import happypose.toolbox.utils.tensor_collection as tc
from happypose.toolbox.inference.detector import DetectorModule
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,12 @@ def icp_refinement(

# import trimesh
# print(points_src.shape, points_tgt.shape)
# trimesh.Trimesh(vertices=points_src[:, :3], normals=points_src[:, 3:]).export(DEBUG_DATA_DIR / 'src.ply')
# trimesh.Trimesh(vertices=points_tgt[:, :3], normals=points_tgt[:, 3:]).export(DEBUG_DATA_DIR / 'tgt.ply')
# trimesh.Trimesh(vertices=points_src[:, :3], normals=points_src[:, 3:]).export(
# DEBUG_DATA_DIR / "src.ply"
# )
# trimesh.Trimesh(vertices=points_tgt[:, :3], normals=points_tgt[:, 3:]).export(
# DEBUG_DATA_DIR / "tgt.ply"
# )
# raise ValueError

tolerence = 0.05
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,8 @@ def batched_model_predictions(self, model, images, K, obj_data, n_iterations=1):
preds[f"iteration={n}"].append(batch_preds)

logger.debug(
f"Pose prediction on {len(obj_data)} detections (n_iterations={n_iterations}): {timer.stop()}",
f"Pose prediction on {len(obj_data)} detections "
f"(n_iterations={n_iterations}): {timer.stop()}",
)
preds = dict(preds)
for k, v in preds.items():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ def batched_model_predictions(self, model, images, K, obj_data, n_iterations=1):
preds[f"iteration={n}"].append(batch_preds)

logger.debug(
f"Pose prediction on {len(obj_data)} detections (n_iterations={n_iterations}): {timer.stop()}",
f"Pose prediction on {len(obj_data)} detections "
f"(n_iterations={n_iterations}): {timer.stop()}",
)
preds = dict(preds)
for k, v in preds.items():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class MeshDataBase:
def __init__(self, obj_list):
self.infos = {obj["label"]: obj for obj in obj_list}
self.meshes = {
l: trimesh.load(obj["mesh_path"]) for l, obj in self.infos.items()
m: trimesh.load(obj["mesh_path"]) for m, obj in self.infos.items()
}

@staticmethod
Expand Down Expand Up @@ -92,9 +92,9 @@ def n_sym_mapping(self):
return {label: obj["n_sym"] for label, obj in self.infos.items()}

def select(self, labels):
ids = [self.label_to_id[l] for l in labels]
ids = [self.label_to_id[label] for label in labels]
return Meshes(
infos=[self.infos[l] for l in labels],
infos=[self.infos[label] for label in labels],
labels=self.labels[ids],
points=self.points[ids],
symmetries=self.symmetries[ids],
Expand Down
17 changes: 13 additions & 4 deletions happypose/pose_estimators/cosypose/cosypose/models/efficientnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,12 +144,16 @@ def forward(self, inputs, drop_connect_rate=None):
return x

def set_swish(self, memory_efficient=True):
"""Sets swish function as memory efficient (for training) or standard (for export)."""
"""
Sets swish function as memory efficient (for training) or standard (for export).
"""
self._swish = MemoryEfficientSwish() if memory_efficient else Swish()


class EfficientNet(nn.Module):
"""An EfficientNet model. Most easily loaded with the .from_name or .from_pretrained methods.
"""
An EfficientNet model. Most easily loaded with the .from_name or .from_pretrained
methods.
Args:
----
Expand Down Expand Up @@ -238,7 +242,9 @@ def __init__(self, blocks_args=None, global_params=None, in_channels=3):
self._swish = MemoryEfficientSwish()

def set_swish(self, memory_efficient=True):
"""Sets swish function as memory efficient (for training) or standard (for export)."""
"""
Sets swish function as memory efficient (for training) or standard (for export).
"""
self._swish = MemoryEfficientSwish() if memory_efficient else Swish()
for block in self._blocks:
block.set_swish(memory_efficient)
Expand All @@ -261,7 +267,10 @@ def extract_features(self, inputs):
return x

def forward(self, inputs):
"""Calls extract_features to extract features, applies final linear layer, and returns logits."""
"""
Calls extract_features to extract features, applies final linear layer, and
returns logits.
"""
inputs.size(0)
# Convolution layers
x = self.extract_features(inputs)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Copied from https://github.com/lukemelas/EfficientNet-PyTorch
This file contains helper functions for building the model and for loading model parameters.
These helper functions are built to mirror those in the official TensorFlow implementation.
This file contains helper functions for building the model and for loading model
parameters.
These helper functions are built to mirror those in the official TensorFlow
implementation.
"""

import collections
Expand Down Expand Up @@ -120,7 +122,8 @@ def drop_connect(inputs, p, training):


def get_same_padding_conv2d(image_size=None):
"""Chooses static padding if you have specified an image size, and dynamic padding otherwise.
"""Chooses static padding if you have specified an image size, and dynamic padding
otherwise.
Static padding is necessary for ONNX exporting of models.
"""
if image_size is None:
Expand Down Expand Up @@ -193,7 +196,9 @@ def __init__(

# Calculate padding based on image size and save it
assert image_size is not None
ih, iw = image_size if type(image_size) == list else [image_size, image_size]
ih, iw = (
image_size if isinstance(image_size, list) else [image_size, image_size]
)
kh, kw = self.weight.size()[-2:]
sh, sw = self.stride
oh, ow = math.ceil(ih / sh), math.ceil(iw / sw)
Expand Down Expand Up @@ -252,7 +257,9 @@ def efficientnet_params(model_name):


class BlockDecoder:
"""Block Decoder for readability, straight from the official TensorFlow repository."""
"""
Block Decoder for readability, straight from the official TensorFlow repository.
"""

@staticmethod
def _decode_block_string(block_string):
Expand Down Expand Up @@ -377,7 +384,8 @@ def get_model_params(model_name, override_params):
else:
raise NotImplementedError("model name is not pre-defined: %s" % model_name)
if override_params:
# ValueError will be raised here if override_params has fields not included in global_params.
# ValueError will be raised here if override_params has fields not included in
# global_params.
global_params = global_params._replace(**override_params)
return blocks_args, global_params

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ def conv3x3(in_planes, out_planes, stride=1):

class BasicBlockV2(nn.Module):
r"""BasicBlock V2 from
`"Identity Mappings in Deep Residual Networks"<https://arxiv.org/abs/1603.05027>`_ paper.
`"Identity Mappings in Deep Residual Networks"
<https://arxiv.org/abs/1603.05027>`_ paper.
This is used for ResNet V2 for 18, 34 layers.
Args:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,8 @@ def align_TCO_cand(self, TWO_9d, TCW_9d):
def forward_jacobian(self, TWO_9d, TCW_9d, residuals_threshold):
_, TCO_cand_aligned = self.align_TCO_cand(TWO_9d, TCW_9d)

# NOTE: This could be *much* faster by computing gradients manually, reducing number of operations.
# NOTE: This could be *much* faster by computing gradients manually, reducing
# number of operations.
cand_ids, view_ids, obj_ids, point_ids, xy_ids = (
self.residuals_ids[k]
for k in ("cand_id", "view_id", "obj_id", "point_id", "xy_id")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@

orig_names = (ds_dir / "ycbv_friendly_names.txt").read_text()
orig_names = {
str(int(l.split(" ")[0])): l.split(" ")[1] for l in orig_names.split("\n")[:-1]
str(int(line.split(" ")[0])): line.split(" ")[1]
for line in orig_names.split("\n")[:-1]
}

infos = json.loads((models_dir / "models_info.json").read_text())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@
make_object_dataset,
make_scene_dataset,
)
from happypose.pose_estimators.cosypose.cosypose.datasets.wrappers.multiview_wrapper import (
from happypose.pose_estimators.cosypose.cosypose.datasets.wrappers.multiview_wrapper import ( # noqa: E501
MultiViewWrapper,
)
from happypose.pose_estimators.cosypose.cosypose.evaluation.pred_runner.bop_predictions import (
from happypose.pose_estimators.cosypose.cosypose.evaluation.pred_runner.bop_predictions import ( # noqa: E501
BopPredictionRunner,
)
from happypose.pose_estimators.cosypose.cosypose.evaluation.runner_utils import (
Expand All @@ -46,7 +46,7 @@
from happypose.pose_estimators.cosypose.cosypose.lib3d.rigid_mesh_database import (
MeshDataBase,
)
from happypose.pose_estimators.cosypose.cosypose.rendering.bullet_batch_renderer import (
from happypose.pose_estimators.cosypose.cosypose.rendering.bullet_batch_renderer import ( # noqa: E501
BulletBatchRenderer,
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from happypose.pose_estimators.cosypose.cosypose.datasets.datasets_cfg import (
make_scene_dataset,
)
from happypose.pose_estimators.cosypose.cosypose.datasets.wrappers.multiview_wrapper import (
from happypose.pose_estimators.cosypose.cosypose.datasets.wrappers.multiview_wrapper import ( # noqa: E501
MultiViewWrapper,
)

Expand Down
Loading

0 comments on commit 8ddfae8

Please sign in to comment.