Skip to content

Instantly share code, notes, and snippets.

View cmower's full-sized avatar

Chris Mower cmower

View GitHub Profile
@cmower
cmower / import_from_file.py
Created July 13, 2024 14:52
Given a function name (string), and a path to a Python script (string), import the function from the script.
import os
import sys
import importlib.util
from typing import Callable
def import_from_file(script_path: str, function_name: str) -> Callable:
"""
Imports a function from a Python script file given the file path and the function name.
Args:
@cmower
cmower / rate.py
Last active June 11, 2024 06:18
Convenience class for sleeping in a loop at a specified rate (based on rospy.Rate)
from time import time_ns, sleep
class Rate(object):
"""
Convenience class for sleeping in a loop at a specified rate
"""
def __init__(self, hz, reset=True):
"""
@cmower
cmower / draw_frame_pybullet.py
Created June 14, 2023 18:04
Draw a frame in PyBullet.
import pybullet as p
import numpy as np
def draw_frame(T: np.ndarray) -> None:
""" Draw a frame represented by the 4-by-4 homogenous transformation matrix T."""
for i in range(3):
color = [0, 0, 0]
color[i] = 1
p.addUserDebugLine(
lineFromXYZ=T[:3, 3],
@cmower
cmower / get_robot_description.py
Last active April 27, 2023 14:52
How to get robot description (i.e. string containing URDF) from the robot state publisher node in ROS 2 Python.
from rclpy.node import Node
from rcl_interfaces.srv import GetParameters
class MyNode(Node):
def get_robot_description(self) -> str:
client = self.create_client(
GetParameters, "robot_state_publisher/get_parameters"
)
while not client.wait_for_service(timeout_sec=1.0):
@cmower
cmower / average_quaternion.py
Created April 3, 2023 17:06
Averaging Quaternions
import numpy as np
def quaternion_average(*quaternions):
"""Compute the average quaternion."""
# Markley, F. Landis, Yang Cheng, John Lucas Crassidis, and Yaakov Oshman.
# "Averaging quaternions." Journal of Guidance, Control, and Dynamics, 2007.
# https://ntrs.nasa.gov/citations/20070017872
Q = np.concatenate([q.flatten().reshape(-1, 1) for q in quaternions], axis=1)
evals, evecs = np.linalg.eig(Q @ Q.T)
return evecs[:, evals.argmax()]
@cmower
cmower / debug.py
Last active May 20, 2022 07:34
Python debugging
class Debugger:
"""Simple class for debugging"""
def __init__(self):
self.it = 0
def __call__(self, msg=''):
print('-'*40, f'DEBUG {self.it} {msg}', end=(' ' if msg else '') +'-'*40)
self.it += 1
@cmower
cmower / How-To-Install-SDL-On-Ubuntu.md
Last active April 13, 2023 15:10 — forked from aaangeletakis/How-To-Install-SDL-On-Ubuntu.md
How do I install SDL on ubuntu?

What you need to do to install SDL is:

#install sdl2
sudo apt install libsdl2-dev libsdl2-2.0-0 -y;

#install sdl image  - if you want to display images
sudo apt install libjpeg-dev libwebp-dev libtiff5-dev libsdl2-image-dev libsdl2-image-2.0-0 -y;

#install sdl mixer - if you want sound
@cmower
cmower / print_type_layout.py
Last active October 12, 2023 07:13
Print layout of a python dict/list, i.e. only keys/indexes and the types of the values.
def print_type_layout(x, indent=0, incr=2):
if isinstance(x, dict):
print(" " * indent, "{")
for k, v in x.items():
print(" " * indent, f"'{k}':", end="")
if isinstance(v, (dict, list)):
print("")
print_type_layout(v, indent=indent + incr)
else:
print(f" {type(v)}")
@cmower
cmower / ros_node_base_class.py
Last active April 5, 2021 12:04
ROS node base class.
"""Base class for ROS nodes, a ROS package using this will always require geometry_msgs and tf2_ros as deps."""
import tf2_ros
from geometry_msg.msg import TransformStamped
class RosNode:
def __init__(self, rospy):
"""Child-classes need to make a call to super().__init__(rospy)"""
self.__rp = rospy
self.__tf_broadcaster = tf2_ros.TransformBroadcaster()
@cmower
cmower / video_split.py
Created February 8, 2021 21:47
Split each frame of a video into individual images.
import cv2
"""Assumes video is called myvideo.MOV in the current directory and there
exists a directory called images/ in the same directory."""
filename = 'myvideo.MOV'
cap = cv2.VideoCapture(filename)
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fc = 0