Skip to content

Commit fcb8e46

Browse files
committed
logging and plot improbements
1 parent 09b6856 commit fcb8e46

File tree

11 files changed

+70
-33
lines changed

11 files changed

+70
-33
lines changed

.vscode/settings.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
{
2-
"python.pythonPath": "C:\\Users\\Federico\\.conda\\envs\\dev\\python.exe",
2+
"python.pythonPath": "/Users/federicoclaudi/miniconda3/envs/dev/bin/python",
33
"cSpell.enabled": true
44
}

proj/animation/animate.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,15 @@
44
save_videocap_to_video,
55
)
66
import click
7+
import logging
78

89

910
def animate_from_images(folder, savepath, fps):
1011
cap = get_cap_from_images_folder(folder, img_format="%2d.png")
1112
save_videocap_to_video(cap, savepath, ".mp4", fps=fps)
1213

1314
gifpath = savepath.replace(".mp4", ".gif")
14-
print(
15+
logging.info(
1516
"To save the video as GIF, use: \n"
1617
+ f'ffmpeg -i "{savepath}" -f gif "{gifpath}"'
1718
)

proj/environment/environment.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import numpy as np
2+
import logging
3+
24
from fcutils.maths.geometry import calc_distance_between_points_2d
35

46
from proj.environment.trajectories import (
@@ -90,6 +92,7 @@ def plan(self, curr_x, g_traj, itern):
9092
self.moved_to_next.append(self.itern)
9193

9294
self.curr_traj_waypoint_idx = min_idx + n_ahead
95+
self.model.curr_traj_waypoint_idx = self.curr_traj_waypoint_idx
9396
self.current_traj_waypoint = g_traj[min_idx, :]
9497

9598
start = min_idx + n_ahead
@@ -120,6 +123,9 @@ def isdone(self, curr_x, trajectory):
120123
dist = curr_x.r
121124

122125
if dist <= self.model.trajectory["min_dist"]:
126+
logging.info(
127+
f"Reached the end of the threshold as we're within {self.model.trajectory['min_dist']} from the end"
128+
)
123129
return True
124130
else:
125131
return False

proj/environment/manager.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import pandas as pd
44
from fancylog import fancylog
55
import logging
6+
67
from rich.logging import RichHandler
78

89
from fcutils.file_io.io import save_yaml
@@ -56,6 +57,9 @@ def __init__(self, model, winstor=False):
5657
for fld in folders:
5758
fld.mkdir(exist_ok=True)
5859

60+
self._start_logging()
61+
62+
def _start_logging(self):
5963
# Start logging
6064
fancylog.start_logging(
6165
output_dir=str(self.datafolder),
@@ -67,16 +71,24 @@ def __init__(self, model, winstor=False):
6771
file_log_level="INFO",
6872
)
6973

70-
print(f"Saving data at: {self.datafolder}")
71-
logging.info("\n\n\n\n")
72-
logging.info(f"Saving data at: {self.datafolder}")
73-
74+
# log main folder
7475
log = logging.getLogger("rich")
76+
log.setLevel(logging.INFO)
77+
7578
log.info(
7679
f"[bold green] Saving data at: {self.datafolder}",
7780
extra={"markup": True},
7881
)
7982

83+
# log config.py
84+
logging.info("=" * 20)
85+
logging.info("=" * 20)
86+
with open("proj/model/config.py") as f:
87+
conf = f.read()
88+
logging.info(conf)
89+
logging.info("=" * 20)
90+
logging.info("=" * 20)
91+
8092
def _save_results(self):
8193
# save config
8294
save_yaml(

proj/environment/plotter.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import matplotlib.pyplot as plt
2+
import numpy as np
3+
import logging
4+
25
from fcutils.plotting.utils import clean_axes
36
from fcutils.plotting.colors import desaturate_color
47
from fcutils.plotting.plot_elements import plot_line_outlined
5-
import numpy as np
68

79
from proj.utils import salmon
810
from proj.animation import variables_colors as colors
@@ -13,7 +15,9 @@ def press(event, self):
1315
Deals with key press during interactive visualizatoin
1416
"""
1517
if event.key == "c":
16-
print("stopping")
18+
logging.info(
19+
"Stopping because user manually terminated simulation (presed C)"
20+
)
1721
self.stop = True
1822

1923

proj/environment/trajectories.py

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ def compute_trajectory_stats(trajectory, duration, planning_params):
7878

7979
# log stuff
8080
log = logging.getLogger("rich")
81+
log.setLevel(logging.INFO)
82+
8183
log.info(
8284
f"""
8385
n_points = {n_points}
@@ -201,19 +203,24 @@ def from_tracking(n_steps, params, planning_params, cache_fld, *args):
201203
speed = line_smoother(trial.body_speed) * trial.fps
202204
ang_speed = np.ones_like(speed) # it will be ignored
203205

206+
# get start frame
207+
from_start = calc_distance_from_point(np.array([x, y]), [x[0], y[0]])
208+
start = np.where(from_start > params["dist_th"])[0][0]
209+
210+
if start >= len(x):
211+
logging.error("Bad trajectory")
212+
raise ValueError("Bad trajectory")
213+
204214
# resample variables so that samples are uniformly distributed
205215
vars = dict(x=x, y=y, angle=angle, speed=speed, ang_speed=ang_speed)
206216
if params["resample"]:
207217
for k, v in vars.items():
208-
vars[k] = _interpol(v, params["max_deg_interpol"], n_steps)
209-
210-
# get start frame
211-
from_start = calc_distance_from_point(np.array([x, y]), [x[0], y[0]])
212-
start = np.where(from_start > params["dist_th"])[0][0]
218+
vars[k] = _interpol(
219+
v[start:-1], params["max_deg_interpol"], n_steps
220+
)
213221

214-
# stack and cut
222+
# stack
215223
trajectory = np.vstack(vars.values()).T
216-
trajectory = trajectory[start:-1, :]
217224

218225
return compute_trajectory_stats(
219226
trajectory, len(x) / trial.fps, planning_params

proj/model/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ class Config:
4343
max_speed=100,
4444
min_speed=80,
4545
min_dist=100, # if agent is within this distance from trajectory end the goal is considered achieved
46-
dist_th=100, # keep frames only after moved away from start location
46+
dist_th=300, # keep frames only after moved away from start location
4747
resample=True, # if True when using tracking trajectory resamples it
4848
max_deg_interpol=8, # if using track fit a N degree polynomial to daa to smoothen
4949
randomize=True, # if true when using tracking it pulls a random trial

proj/model/model.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,13 +84,18 @@ def reset(self):
8484
tau_l=[],
8585
r=[],
8686
gamma=[],
87+
trajectory_idx=[],
8788
)
8889

8990
def _append_history(self):
9091
for ntuple in [self.curr_x, self.curr_control]:
9192
for k, v in ntuple._asdict().items():
9293
self.history[k].append(v)
9394

95+
self.history["trajectory_idx"].append(
96+
self.curr_traj_waypoint_idx
97+
) # this is updated by env.plan
98+
9499
def _make_simbols(self):
95100
# state variables
96101
x, y, theta, thetadot = symbols("x, y, theta, thetadot", real=True)

proj/plotting/results.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import matplotlib.pyplot as plt
22
import numpy as np
3+
import logging
34

45
from fcutils.plotting.utils import clean_axes, save_figure
56
from fcutils.plotting.colors import desaturate_color
@@ -102,9 +103,8 @@ def _plot_v(history, trajectory, plot_every, ax=None):
102103
)
103104

104105
# plot history speed
105-
x = np.linspace(0, len(trajectory), len(v))
106106
ax.plot(
107-
x, v, color=colors["v"], lw=2, zorder=100,
107+
history["trajectory_idx"], v, color=colors["v"], lw=2, zorder=100,
108108
)
109109

110110

@@ -113,9 +113,9 @@ def _plot_accel(history, ax=None):
113113
vdot = derivative(v)
114114
omegadot = derivative(omega)
115115

116-
plot_line_outlined(ax, vdot, lw=2, color=colors["v"], label="$v$")
116+
plot_line_outlined(ax, vdot, lw=2, color=colors["v"], label="$\dot{v}$")
117117
plot_line_outlined(
118-
ax, omegadot, lw=2, color=colors["omega"], label="$\omega$"
118+
ax, omegadot, lw=2, color=colors["omega"], label="$\dot{\omega}$"
119119
)
120120
ax.legend()
121121

@@ -150,3 +150,4 @@ def plot_results(results_folder, plot_every=20, save_path=None):
150150

151151
if save_path is not None:
152152
save_figure(f, str(save_path))
153+
logging.info(f"Saved summary figure at: {save_path}")

proj/run/runner.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -86,11 +86,11 @@ def run_experiment(
8686
)
8787

8888
# Check if we're done
89-
if (
90-
environment.isdone(model.curr_x, trajectory)
91-
or environment.stop
92-
):
93-
print(f"Reached end of trajectory after {itern} steps")
89+
if environment.isdone(model.curr_x, trajectory):
90+
log.info("environment says we're DONE")
91+
break
92+
if environment.stop:
93+
log.info("environment says STOP")
9494
break
9595

9696
log.info(f"Terminated after {itern} iterations.")

0 commit comments

Comments
 (0)