Skip to content

Commit e7faa02

Browse files
committed
better logging
1 parent 5e3fd41 commit e7faa02

File tree

7 files changed

+55
-123
lines changed

7 files changed

+55
-123
lines changed

proj/__init__.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
# Set up logging
2-
import logging
3-
4-
for module in ["matplotlib", "pandas", "numpy"]:
5-
requests_logger = logging.getLogger("matplotlib")
6-
requests_logger.setLevel(logging.ERROR)
2+
from proj.utils.logging import log
73

84
# import stuff
95
from proj.model.config import Config

proj/environment/manager.py

Lines changed: 15 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,21 @@
11
import shutil
22
import numpy as np
33
import pandas as pd
4-
from fancylog import fancylog
54
import logging
5+
import json
66

77
from rich.logging import RichHandler
88

99
from fcutils.file_io.io import save_yaml
1010

1111

1212
from proj.utils.misc import timestamp
13-
from proj import paths
13+
from proj import paths, log
1414
from proj.animation.animate import animate_from_images
1515
from proj.plotting.results import plot_results
1616
from proj.utils.dropbox import DropBoxUtils, upload_folder
1717
from proj.utils.slack import send_slack_message
1818

19-
FORMAT = "%(message)s"
20-
logging.basicConfig(
21-
level="NOTSET", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()]
22-
)
23-
2419

2520
class Manager:
2621
def __init__(self, model, winstor=False):
@@ -62,20 +57,10 @@ def __init__(self, model, winstor=False):
6257
self._start_logging()
6358

6459
def _start_logging(self):
65-
# Start logging
66-
fancylog.start_logging(
67-
output_dir=str(self.datafolder),
68-
filename=self.exp_name + ".log",
69-
multiprocessing_aware=False,
70-
write_git=False,
71-
verbose=False,
72-
write_cli_args=False,
73-
file_log_level="INFO",
74-
)
75-
76-
# log main folder
77-
log = logging.getLogger("rich")
78-
log.setLevel(logging.INFO)
60+
filename = str(self.datafolder / f"{self.exp_name}.log")
61+
fh = logging.FileHandler(filename)
62+
fh.setFormatter(RichHandler())
63+
log.addHandler(fh)
7964

8065
log.info(
8166
f"[bold green] Saving data at: {self.datafolder}",
@@ -84,12 +69,8 @@ def _start_logging(self):
8469

8570
def _log_conf(self):
8671
# log config.py
87-
try:
88-
with open("proj/model/config.py") as f:
89-
conf = "\n" + f.read()
90-
except FileNotFoundError:
91-
conf = self.model.config_dict()
92-
logging.info(conf)
72+
conf = json.dumps(self.model.config_dict(), sort_keys=True, indent=4)
73+
log.info("Config parameters:\n" + conf, extra={"markup": True})
9374

9475
def _save_results(self):
9576
# save config
@@ -145,7 +126,9 @@ def _save_video(self):
145126
def _upload_to_dropbox(self):
146127
dbx = DropBoxUtils()
147128
dpx_path = self.datafolder.name
148-
logging.info(f"Uploading data to dropbox at: {dpx_path}")
129+
log.info(
130+
f"Uploading data to dropbox at: {dpx_path}", extra={"markup": True}
131+
)
149132

150133
upload_folder(dbx, self.datafolder, dpx_path)
151134

@@ -170,13 +153,13 @@ def conclude(self):
170153

171154
# Upload results to dropbox
172155
if self.winstor:
173-
logging.info("Uploading to dropbox")
156+
log.info("Uploading to dropbox", extra={"markup": True})
174157
try:
175158
self._upload_to_dropbox()
176159
except Exception as e:
177160
logging.error(f"Failed to upload to dropbox: {e}")
178161

179-
logging.info("Sending slack message")
162+
log.info("Sending slack message", extra={"markup": True})
180163
send_slack_message(
181164
f"""
182165
\n
@@ -187,10 +170,10 @@ def conclude(self):
187170
"""
188171
)
189172
else:
190-
logging.info("Did not upload to dropbox")
173+
log.info("Did not upload to dropbox", extra={"markup": True})
191174

192175
def failed(self):
193-
logging.info("Sending slack FAILED message")
176+
log.info("Sending slack FAILED message", extra={"markup": True})
194177
if self.winstor:
195178
send_slack_message(
196179
f"""

proj/model/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ class Config:
6868
distance=150,
6969
max_speed=100,
7070
min_speed=80,
71-
min_dist=5, # if agent is within this distance from trajectory end the goal is considered achieved
71+
min_dist=0, # if agent is within this distance from trajectory end the goal is considered achieved
7272
# ? for trajectories from data
7373
px_to_cm=1 / 30.8, # convert px values to cm
7474
# dist_th=60, # keep frames only after moved away from start location

proj/run/runner.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from rich import print
99
from rich.text import Text
1010
import logging
11+
import traceback
1112

1213

1314
class SpeedColumn(TextColumn):
@@ -112,11 +113,14 @@ def run_experiment(
112113
if environment.stop:
113114
log.info("environment says STOP")
114115
break
116+
115117
except Exception as e:
116118
logging.error(
117-
f"Failed to take next step in simulation.\n error {e}"
119+
f"Failed to take next step in simulation.\nError: {e}\n\n"
118120
)
119-
break
121+
logging.error(traceback.print_exc())
122+
environment.failed()
123+
return
120124

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

proj/utils/logging.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import logging
2+
from rich.logging import RichHandler
3+
4+
# supress warnings
5+
import pandas as pd
6+
import warnings
7+
8+
warnings.simplefilter(action="ignore", category=pd.errors.PerformanceWarning)
9+
10+
# Set up RICH logger
11+
logging.basicConfig(
12+
level=logging.INFO,
13+
format="%(message)s",
14+
datefmt="[%X]",
15+
handlers=[RichHandler(rich_tracebacks=True)],
16+
)
17+
18+
log = logging.getLogger("rich")
19+
20+
21+
# Disable logging some packages
22+
for module in [
23+
"matplotlib",
24+
"pandas",
25+
"numpy",
26+
"tensorflow",
27+
"pandas",
28+
"tables",
29+
]:
30+
logger = logging.getLogger(module)
31+
logger.setLevel(logging.ERROR)

setup.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
"fancylog",
1919
"slackclient",
2020
"dropbox",
21+
"json",
2122
]
2223

2324
setup(

workspace.py

Lines changed: 0 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -1,83 +0,0 @@
1-
# %%
2-
3-
4-
from behaviour.tracking.tracking import prepare_tracking_data
5-
from fcutils.maths.geometry import (
6-
calc_angle_between_vectors_of_points_2d as get_bone_angle,
7-
)
8-
import numpy as np
9-
import pandas as pd
10-
11-
# %%
12-
path = "/Users/federicoclaudi/Dropbox (UCL - SWC)/Rotation_vte/Locomotion/control/behav_data/Zane/ZM_200913_ZM006_videoDeepCut_resnet50_DLCSep6shuffle1_200000.h5"
13-
14-
15-
tracking = prepare_tracking_data(
16-
path, smooth_dir_mvmt=False, likelihood_th=0.8, interpolate_nans=True
17-
)
18-
19-
20-
body_orientation = get_bone_angle(
21-
tracking["body"].x.values,
22-
tracking["body"].y.values,
23-
tracking["tail_base"].x.values,
24-
tracking["tail_base"].y.values,
25-
)
26-
27-
28-
# %%
29-
escapes_file = "/Users/federicoclaudi/Dropbox (UCL - SWC)/Rotation_vte/Locomotion/control/behav_data/Zane/escapes.txt"
30-
with open(escapes_file, "r") as f:
31-
escapes = [int(e) for e in f.readlines()]
32-
33-
# %%
34-
trials = {}
35-
for bp in tracking.keys():
36-
trials[bp + "_xy"] = []
37-
trials[bp + "_speed"] = []
38-
39-
if bp == "body":
40-
trials[bp + "_orientation"] = []
41-
42-
43-
for escape in escapes:
44-
for bp in tracking.keys():
45-
start = escape
46-
end = start + 1000
47-
x = tracking[bp].x[start:end]
48-
y = tracking[bp].y[start:end]
49-
s = tracking[bp].speed[start:end]
50-
51-
trials[bp + "_xy"].append(np.vstack([x, y]).T)
52-
trials[bp + "_speed"].append(s)
53-
54-
if bp == "body":
55-
trials["body_orientation"].append(body_orientation[start:end])
56-
57-
58-
trials = pd.DataFrame(trials)
59-
60-
# %%
61-
import matplotlib.pyplot as plt
62-
63-
f, ax = plt.subplots()
64-
65-
for i, trial in trials.iterrows():
66-
angle = np.unwrap(np.radians(90 - trial.body_orientation))
67-
ax.scatter(trial.body_xy[:, 0], trial.body_xy[:, 1], c=angle)
68-
69-
ax.axis("equal")
70-
71-
# %%
72-
f, ax = plt.subplots()
73-
for bp in tracking.keys():
74-
ax.plot(tracking[bp].x[5000:5500], tracking[bp].y[5000:5500])
75-
76-
# %%
77-
trials.to_hdf(
78-
"/Users/federicoclaudi/Dropbox (UCL - SWC)/Rotation_vte/Locomotion/control/behav_data/zanes.h5",
79-
key="hdf",
80-
)
81-
82-
83-
# %%

0 commit comments

Comments
 (0)