Skip to content

Commit

Permalink
Merge branch 'v1.0.0' into dev-frenet-utils
Browse files Browse the repository at this point in the history
  • Loading branch information
AhmadAmine998 committed Apr 15, 2024
2 parents 1cba4a3 + 5dbba85 commit 35eea7e
Show file tree
Hide file tree
Showing 50 changed files with 3,189 additions and 2,677 deletions.
32 changes: 0 additions & 32 deletions Pipfile

This file was deleted.

1,380 changes: 0 additions & 1,380 deletions Pipfile.lock

This file was deleted.

22 changes: 12 additions & 10 deletions examples/random_trackgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,17 @@ def main(args):
outdir.mkdir(parents=True, exist_ok=True)

for i in range(n_maps):
try:
print(f"[info] creating track {i}")
track, track_int, track_ext = create_track()
convert_track(track, track_int, track_ext, i, outdir)
print(f"[info] saved track {i} in {outdir}/")
except Exception as _: # noqa: F841
print("[error] failed to create track. Retrying...")
continue
print()
while True:
try:
print(f"[info] creating track {i}")
track, track_int, track_ext = create_track()
convert_track(track, track_int, track_ext, i, outdir)
print(f"[info] saved track {i} in {outdir}/")
break
except Exception as _: # noqa: F841
print("[error] failed to create track. Retrying...")
continue
print()


def create_track():
Expand Down Expand Up @@ -250,7 +252,7 @@ def convert_track(track, track_int, track_ext, track_id, outdir):
"--seed", type=int, default=123, help="The seed for the numpy rng"
)
parser.add_argument(
"--n_maps", type=int, default=3, help="Number of maps to create"
"--n-maps", type=int, default=3, help="Number of maps to create"
)
parser.add_argument(
"--outdir", type=pathlib.Path, default="./maps", help="Out directory"
Expand Down
59 changes: 59 additions & 0 deletions examples/run_in_empty_track.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import numpy as np

from waypoint_follow import PurePursuitPlanner
from f1tenth_gym.envs.track import Track
import gymnasium as gym


def main():
"""
Demonstrate the creation of an empty map with a custom reference line.
This is useful for testing and debugging control algorithms on standard maneuvers.
"""
# create sinusoidal reference line with custom velocity profile
xs = np.linspace(0, 100, 200)
ys = np.sin(xs / 2.0) * 5.0
velxs = 4.0 * (1 + (np.abs(np.cos(xs / 2.0))))

# create track from custom reference line
track = Track.from_refline(x=xs, y=ys, velx=velxs)

# env and planner
env = gym.make(
"f1tenth_gym:f1tenth-v0",
config={
"map": track,
"num_agents": 1,
"observation_config": {"type": "kinematic_state"},
},
render_mode="human",
)
planner = PurePursuitPlanner(track=track, wb=0.17145 + 0.15875)

# rendering callbacks
env.add_render_callback(track.raceline.render_waypoints)
env.add_render_callback(planner.render_lookahead_point)

# simulation
obs, info = env.reset()
done = False
env.render()

while not done:
speed, steer = planner.plan(
obs["agent_0"]["pose_x"],
obs["agent_0"]["pose_y"],
obs["agent_0"]["pose_theta"],
lookahead_distance=0.8,
vgain=1.0,
)
action = np.array([[steer, speed]])
obs, timestep, terminated, truncated, infos = env.step(action)
done = terminated or truncated
env.render()

env.close()


if __name__ == "__main__":
main()
2 changes: 1 addition & 1 deletion examples/video_recording.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def main():
}

env = gym.make(
"f110_gym:f110-v0",
"f1tenth_gym:f1tenth-v0,
config={
"map": "Spielberg",
"num_agents": 1,
Expand Down
24 changes: 4 additions & 20 deletions examples/waypoint_follow.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,13 +196,6 @@ def load_waypoints(self, conf):
conf.wpt_path, delimiter=conf.wpt_delim, skiprows=conf.wpt_rowskip
).astype(np.float32)

def render_waypoints(self, e):
"""
Callback to render waypoints.
"""
points = self.waypoints[:, :2]
e.render_closed_lines(points, color=(128, 0, 0), size=1)

def render_lookahead_point(self, e):
"""
Callback to render the lookahead point.
Expand Down Expand Up @@ -300,7 +293,7 @@ def main():

num_agents = 3
env = gym.make(
"f110_gym:f110-v0",
"f1tenth_gym:f1tenth-v0",
config={
"map": "Spielberg",
"num_agents": num_agents,
Expand All @@ -310,28 +303,19 @@ def main():
"model": "st",
"observation_config": {"type": "kinematic_state"},
"params": {"mu": 1.0},
"reset_config": {"type": "random_static"},
"reset_config": {"type": "rl_random_static"},
},
render_mode="human",
)
track = env.unwrapped.track

planner = PurePursuitPlanner(track=track, wb=0.17145 + 0.15875)

poses = np.array(
[
[
track.raceline.xs[0],
track.raceline.ys[0],
track.raceline.yaws[0],
]
]
)
env.unwrapped.add_render_callback(planner.render_waypoints)
env.unwrapped.add_render_callback(track.raceline.render_waypoints)
env.unwrapped.add_render_callback(planner.render_local_plan)
env.unwrapped.add_render_callback(planner.render_lookahead_point)

obs, info = env.reset(options={"poses": poses})
obs, info = env.reset()
done = False
env.render()

Expand Down
6 changes: 6 additions & 0 deletions f1tenth_gym/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import gymnasium as gym

gym.register(
id="f1tenth-v0",
entry_point="f1tenth_gym.envs:F110Env",
)
File renamed without changes.
2 changes: 1 addition & 1 deletion gym/f110_gym/envs/action.py → f1tenth_gym/envs/action.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import warnings
import gymnasium as gym
import numpy as np
from f110_gym.envs.dynamic_models import pid_steer, pid_accl
from .dynamic_models import pid_steer, pid_accl


class LongitudinalActionEnum(Enum):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,12 @@
"""
from __future__ import annotations
import numpy as np
from f110_gym.envs.dynamic_models import DynamicModel
from f110_gym.envs.action import CarAction
from f110_gym.envs.collision_models import collision_multiple, get_vertices
from f110_gym.envs.integrator import EulerIntegrator, IntegratorType
from f110_gym.envs.laser_models import ScanSimulator2D, check_ttc_jit, ray_cast
from .dynamic_models import DynamicModel
from .action import CarAction
from .collision_models import collision_multiple, get_vertices
from .integrator import EulerIntegrator, IntegratorType
from .laser_models import ScanSimulator2D, check_ttc_jit, ray_cast
from .track import Track


class RaceCar(object):
Expand Down Expand Up @@ -177,14 +178,14 @@ def update_params(self, params):
"""
self.params = params

def set_map(self, map_name: str):
def set_map(self, map: str | Track):
"""
Sets the map for scan simulator
Args:
map_name (str): name of the map
map (str | Track): name of the map, or Track object
"""
RaceCar.scan_simulator.set_map(map_name)
RaceCar.scan_simulator.set_map(map)

def reset(self, pose):
"""
Expand Down Expand Up @@ -430,18 +431,18 @@ def __init__(
num_beams = self.agents[0].scan_simulator.num_beams
self.agent_scans = np.empty((self.num_agents, num_beams))

def set_map(self, map_name):
def set_map(self, map: str | Track):
"""
Sets the map of the environment and sets the map for scan simulator of each agent
Args:
map_name (str): name of the map
map (str | Track): name of the map, or Track object
Returns:
None
"""
for agent in self.agents:
agent.set_map(map_name)
agent.set_map(map)

def update_params(self, params, agent_idx=-1):
"""
Expand Down
File renamed without changes.
File renamed without changes.
36 changes: 20 additions & 16 deletions gym/f110_gym/envs/f110_env.py → f1tenth_gym/envs/f110_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,19 @@
# gym imports
import gymnasium as gym

from f110_gym.envs.action import (CarAction,
from .action import (CarAction,
from_single_to_multi_action_space)
from f110_gym.envs.integrator import IntegratorType
from f110_gym.envs.rendering import make_renderer
from .integrator import IntegratorType
from .rendering import make_renderer

from f110_gym.envs.track import Track
from .track import Track

# base classes
from f110_gym.envs.base_classes import Simulator, DynamicModel
from f110_gym.envs.observation import observation_factory
from f110_gym.envs.reset import make_reset_fn
from f110_gym.envs.track import Track
from f110_gym.envs.utils import deep_update
from .base_classes import Simulator, DynamicModel
from .observation import observation_factory
from .reset import make_reset_fn
from .track import Track
from .utils import deep_update


# others
Expand Down Expand Up @@ -95,7 +95,7 @@ def __init__(self, config: dict = None, render_mode=None, **kwargs):
self.configure(config)

self.seed = self.config["seed"]
self.map_name = self.config["map"]
self.map = self.config["map"]
self.params = self.config["params"]
self.num_agents = self.config["num_agents"]
self.timestep = self.config["timestep"]
Expand Down Expand Up @@ -143,10 +143,14 @@ def __init__(self, config: dict = None, render_mode=None, **kwargs):
model=self.model,
action_type=self.action_type,
)
self.sim.set_map(self.map_name)
self.track = Track.from_track_name(
self.map_name
) # load track in gym env for convenience
self.sim.set_map(self.map)

if isinstance(self.map, Track):
self.track = self.map
else:
self.track = Track.from_track_name(
self.map
) # load track in gym env for convenience

# observations
self.agent_ids = [f"agent_{i}" for i in range(self.num_agents)]
Expand Down Expand Up @@ -226,8 +230,8 @@ def default_config(cls) -> dict:
"integrator": "rk4",
"model": "st",
"control_input": ["speed", "steering_angle"],
"observation_config": {"type": "original"},
"reset_config": {"type": "grid_static"},
"observation_config": {"type": None},
"reset_config": {"type": None},
}

def configure(self, config: dict) -> None:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import warnings
from abc import abstractmethod
from enum import Enum

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@
Prototype of Utility functions and classes for simulating 2D LIDAR scans
Author: Hongrui Zheng
"""

from __future__ import annotations
import unittest

import numpy as np
from f110_gym.envs.track import Track
from .track import Track
from numba import njit
from scipy.ndimage import distance_transform_edt as edt

Expand Down Expand Up @@ -448,24 +448,30 @@ def __init__(self, num_beams, fov, eps=0.0001, theta_dis=2000, max_range=30.0):
self.map_height = None
self.map_width = None
self.map_resolution = None
self.track = None
self.map_img = None
self.origin = None
self.dt = None

# precomputing corresponding cosines and sines of the angle array
theta_arr = np.linspace(0.0, 2 * np.pi, num=theta_dis)
self.sines = np.sin(theta_arr)
self.cosines = np.cos(theta_arr)

def set_map(self, map_name: str):
def set_map(self, map: str | Track):
"""
Set the bitmap of the scan simulator by path
Args:
map_name (str): name of the racetrack in the map dir, e.g. "Levine"
map (str | Track): path to the map file, or Track object
Returns:
flag (bool): if image reading and loading is successful
"""
self.track = Track.from_track_name(map_name)
if isinstance(map, str):
self.track = Track.from_track_name(map)
elif isinstance(map, Track):
self.track = map

# load map image
self.map_img = self.track.occupancy_map
Expand Down
Loading

0 comments on commit 35eea7e

Please sign in to comment.