Skip to content

Commit

Permalink
formating
Browse files Browse the repository at this point in the history
  • Loading branch information
chraibi committed Mar 1, 2024
1 parent 83b7749 commit 2425ed3
Show file tree
Hide file tree
Showing 9 changed files with 109 additions and 54 deletions.
54 changes: 29 additions & 25 deletions analysis_tab.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Analysis data, speed, density, flow, etc."""

import logging
import glob
import logging
import os
import pickle
import time
Expand Down Expand Up @@ -577,7 +577,7 @@ def calculate_speed_profile(
plots.download_file(figname)


def ui_tab3_analysis() -> Tuple[Optional[str], Optional[int], st_column]:
def ui_tab3_analysis() -> Tuple[str, Optional[int], st_column]:
"""Prepare ui elements."""
c0, c1, c2 = st.columns((1, 1, 1))
if st.sidebar.button(
Expand All @@ -595,31 +595,35 @@ def ui_tab3_analysis() -> Tuple[Optional[str], Optional[int], st_column]:

st.sidebar.divider()
if utilities.is_running_locally():
calculations = st.radio(
"**Choose calculation**",
[
"N-T",
"Time series",
"FD_classical",
"FD_voronoi (load)",
"FD_voronoi (calculate)",
"Density profile",
"Speed profile",
],
horizontal=True,
calculations = str(
st.radio(
"**Choose calculation**",
[
"N-T",
"Time series",
"FD_classical",
"FD_voronoi (load)",
"FD_voronoi (calculate)",
"Density profile",
"Speed profile",
],
horizontal=True,
)
)
else:
calculations = st.radio(
"**Choose calculation**",
[
"N-T",
"Time series",
"FD_classical",
"FD_voronoi (load)",
"Density profile",
"Speed profile",
],
horizontal=True,
calculations = str(
st.radio(
"**Choose calculation**",
[
"N-T",
"Time series",
"FD_classical",
"FD_voronoi (load)",
"Density profile",
"Speed profile",
],
horizontal=True,
)
)
exclude = ["N-T", "Density profile", "Speed profile", "FD_voronoi (load)"]
if calculations in exclude:
Expand Down
28 changes: 21 additions & 7 deletions anim.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ def _get_line_color(disk_color: str) -> str:
return "black" if brightness > 127 else "white"


def _create_orientation_line(row: pd.DataFrame, line_length: float = 0.2, color: str = "black") -> Shape:
def _create_orientation_line(
row: pd.DataFrame, line_length: float = 0.2, color: str = "black"
) -> Shape:
"""Create orientation Shape object."""
end_x = row["x"] + line_length * 0
end_y = row["y"] + line_length * 0
Expand Down Expand Up @@ -111,7 +113,9 @@ def _get_colormap(frame_data: pd.DataFrame, max_speed: float) -> List[Scatter]:
return [scatter_trace]


def _get_shapes_for_frame(frame_data: pd.DataFrame, min_speed: float, max_speed: float) -> Tuple[Shape, Scatter, Shape]:
def _get_shapes_for_frame(
frame_data: pd.DataFrame, min_speed: float, max_speed: float
) -> Tuple[Shape, Scatter, Shape]:
"""Construct circles as Shapes for agents, Hover and Directions."""

def create_shape(row: pd.DataFrame) -> Shape:
Expand Down Expand Up @@ -206,7 +210,9 @@ def _create_fig(
fig = go.Figure(
data=geometry_traces + initial_scatter_trace + initial_hover_trace,
frames=frames,
layout=go.Layout(shapes=initial_shapes + initial_arrows, title=title, title_x=0.5),
layout=go.Layout(
shapes=initial_shapes + initial_arrows, title=title, title_x=0.5
),
)
fig.update_layout(
updatemenus=[_get_animation_controls()],
Expand Down Expand Up @@ -269,7 +275,9 @@ def _get_slider_controls(steps: List[Dict[str, Any]]) -> Dict[str, Any]:
}


def _get_processed_frame_data(data_df: pd.DataFrame, frame_num: int, max_agents: int) -> Tuple[pd.DataFrame, int]:
def _get_processed_frame_data(
data_df: pd.DataFrame, frame_num: int, max_agents: int
) -> Tuple[pd.DataFrame, int]:
"""Process frame data and ensure it matches the maximum agent count."""
frame_data = data_df[data_df["frame"] == frame_num]
agent_count = len(frame_data)
Expand Down Expand Up @@ -342,7 +350,9 @@ def animate(
# Calculate page_end
frame_end = st.session_state.start_frame + page_size
frame_start = st.session_state.start_frame
data_df = data_df0[(data_df0["frame"] >= frame_start) & (data_df0["frame"] <= frame_end)]
data_df = data_df0[
(data_df0["frame"] >= frame_start) & (data_df0["frame"] <= frame_end)
]

min_speed = data_df["speed"].min()
max_speed = data_df["speed"].max()
Expand All @@ -361,8 +371,12 @@ def animate(
) = _get_shapes_for_frame(initial_frame_data, min_speed, max_speed)
color_map_trace = _get_colormap(initial_frame_data, max_speed)
for frame_num in selected_frames:
frame_data, agent_count = _get_processed_frame_data(data_df, frame_num, max_agents)
shapes, hover_traces, arrows = _get_shapes_for_frame(frame_data, min_speed, max_speed)
frame_data, agent_count = _get_processed_frame_data(
data_df, frame_num, max_agents
)
shapes, hover_traces, arrows = _get_shapes_for_frame(
frame_data, min_speed, max_speed
)
# title = f"<b>{title_note + ' | ' if title_note else ''}N: {agent_count}</b>"
title = f"<b>{title_note + ' | ' if title_note else ''}Number of Agents: {initial_agent_count}. Frame: {frame_num}</b>"
frame_name = str(int(frame_num))
Expand Down
4 changes: 2 additions & 2 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Main entry point to the data visualisator for MADRAS project."""

import logging

import streamlit as st

import analysis_tab
Expand All @@ -8,8 +10,6 @@
import map_tab
import traj_tab
import ui
from utilities import is_running_locally
import logging

# Basic configuration for logging
logging.basicConfig(
Expand Down
12 changes: 9 additions & 3 deletions datafactory.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,15 +132,21 @@ def unzip_files(zip_path: Union[str, Path], destination: Union[str, Path]) -> No
# Extract only if file (ignores directories)
if not member.is_dir():
# Build target filename path
target_path = os.path.join(destination, os.path.basename(member.filename))
target_path = os.path.join(
destination, os.path.basename(member.filename)
)
# Ensure target directory exists (e.g., if not extracting directories)
os.makedirs(os.path.dirname(target_path), exist_ok=True)
# Extract file
with zip_ref.open(member, "r") as source, open(target_path, "wb") as target:
with zip_ref.open(member, "r") as source, open(
target_path, "wb"
) as target:
shutil.copyfileobj(source, target)


def download_and_unzip_files(url: str, destination: Union[str, Path], unzip_destination: Union[str, Path]) -> None:
def download_and_unzip_files(
url: str, destination: Union[str, Path], unzip_destination: Union[str, Path]
) -> None:
"""
Download a ZIP file from a specified URL.
Expand Down
18 changes: 13 additions & 5 deletions drawing.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
import utilities


def drawing_canvas(trajectory_data: pedpy.TrajectoryData, walkable_area: pedpy.WalkableArea) -> Tuple[Any, float, float, float]:
def drawing_canvas(
trajectory_data: pedpy.TrajectoryData, walkable_area: pedpy.WalkableArea
) -> Tuple[Any, float, float, float]:
"""Draw trajectories as img and prepare canvas."""
drawing_mode = st.sidebar.radio(
"**Measurement:**",
Expand All @@ -27,14 +29,16 @@ def drawing_canvas(trajectory_data: pedpy.TrajectoryData, walkable_area: pedpy.W

stroke_width = st.sidebar.slider("**Stroke width:**", 1, 25, 3)
if st.session_state.bg_img is None:
logging("START new canvas")
logging.info("START new canvas")
data = trajectory_data.data
min_x = trajectory_data.data["x"].min()
max_x = trajectory_data.data["x"].max()
min_y = trajectory_data.data["y"].min()
max_y = trajectory_data.data["y"].max()

bg_img, img_width, img_height, dpi, scale = plots.bg_img(data, min_x, max_x, min_y, max_y)
bg_img, img_width, img_height, dpi, scale = plots.bg_img(
data, min_x, max_x, min_y, max_y
)
st.session_state.scale = scale
st.session_state.dpi = dpi
st.session_state.img_width = img_width
Expand Down Expand Up @@ -84,14 +88,18 @@ def get_measurement_area(
boundaries,
)
if not rects:
measurement_areas.append(utilities.setup_measurement_area(min_x, max_x, min_y, max_y))
measurement_areas.append(
utilities.setup_measurement_area(min_x, max_x, min_y, max_y)
)
return measurement_areas

for ir, _ in enumerate(rects):
from_x = rects[ir]["x"][0]
to_x = rects[ir]["x"][1]
from_y = rects[ir]["y"][3]
to_y = rects[ir]["y"][0]
measurement_areas.append(utilities.setup_measurement_area(from_x, to_x, from_y, to_y))
measurement_areas.append(
utilities.setup_measurement_area(from_x, to_x, from_y, to_y)
)

return measurement_areas
8 changes: 6 additions & 2 deletions map_tab.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,12 @@ def load_cameras_from_json(file_path: str) -> Dict[str, Camera]:
try:
# Ensure the data structure is as expected
location = tuple(info["location"])
assert isinstance(location, tuple) and len(location) == 2, "Location must be a tuple of two floats."
assert all(isinstance(x, float) for x in location), "Location elements must be floats."
assert (
isinstance(location, tuple) and len(location) == 2
), "Location must be a tuple of two floats."
assert all(
isinstance(x, float) for x in location
), "Location elements must be floats."
location = cast(Tuple[float, float], location)
url = info["url"]
name = info["name"]
Expand Down
19 changes: 14 additions & 5 deletions traj_tab.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""Show general results, including ploting, animation, ..."""

import time
import logging
import time

import pedpy
import streamlit as st
from shapely import Polygon
Expand Down Expand Up @@ -41,7 +42,9 @@ def run_tab2(selected_file: str, msg: DeltaGenerator) -> None:
frame_step=5,
speed_calculation=pedpy.SpeedCalculation.BORDER_SINGLE_SIDED,
)
data_with_speed = data_with_speed.merge(trajectory_data.data, on=["id", "frame"], how="left")
data_with_speed = data_with_speed.merge(
trajectory_data.data, on=["id", "frame"], how="left"
)

ids = trajectory_data.data["id"].unique()
start_time = time.time()
Expand Down Expand Up @@ -111,11 +114,17 @@ def run_tab2(selected_file: str, msg: DeltaGenerator) -> None:
max_value=5.0,
)

fig2 = plots.plot_trajectories_figure_mpl(trajectory_data, walkable_area, with_colors=True, alpha=alpha, lw=lw)
fig2 = plots.plot_trajectories_figure_mpl(
trajectory_data, walkable_area, with_colors=True, alpha=alpha, lw=lw
)
# pfig, ax = plt.subplots()
# pedpy.plot_trajectories(traj=trajectory_data, walkable_area=walkable_area, axes=ax)
c1.pyplot(fig2)
figname = "trajectories_" + selected_file.split("/")[-1].split(".txt")[0] + "_colors.pdf"
figname = (
"trajectories_"
+ selected_file.split("/")[-1].split(".txt")[0]
+ "_colors.pdf"
)
fig2.savefig(figname, bbox_inches="tight", pad_inches=0.1)
plots.download_file(figname, c1, label="color")
# fig3z = plots.plot_trajectories_figure_mpl(trajectory_data, walkable_area, with_colors=False)
Expand All @@ -126,7 +135,7 @@ def run_tab2(selected_file: str, msg: DeltaGenerator) -> None:

end_time = time.time()
elapsed_time = end_time - start_time
logging(f"Time taken to plot trajectories: {elapsed_time:.2f} seconds")
logging.info(f"Time taken to plot trajectories: {elapsed_time:.2f} seconds")

if do_animate:
# pr = cProfile.Profile()
Expand Down
4 changes: 3 additions & 1 deletion ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ def init_app_looks() -> None:
repo_name = f"[![Repo]({gh})]({repo})"
c1, c2 = st.sidebar.columns((1.2, 0.5))
c2.markdown(repo_name, unsafe_allow_html=True)
c1.write("[![DOI](https://zenodo.org/badge/760394097.svg)](https://zenodo.org/doi/10.5281/zenodo.10694866)")
c1.write(
"[![DOI](https://zenodo.org/badge/760394097.svg)](https://zenodo.org/doi/10.5281/zenodo.10694866)"
)
st.sidebar.image(f"{ROOT_DIR}/logo.png", use_column_width=True)


Expand Down
16 changes: 12 additions & 4 deletions utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ def get_id_by_name(direction_name: str) -> int:
return -1


def get_measurement_lines(trajectory_data: pd.DataFrame, distance_to_bounding: float) -> List[Direction]:
def get_measurement_lines(
trajectory_data: pd.DataFrame, distance_to_bounding: float
) -> List[Direction]:
"""Create 4 measurement lines inside the walkable_area."""
min_x = trajectory_data.data["x"].min() + distance_to_bounding
max_x = trajectory_data.data["x"].max() - distance_to_bounding
Expand All @@ -70,11 +72,15 @@ def get_measurement_lines(trajectory_data: pd.DataFrame, distance_to_bounding: f

return [
Direction(
info=DirectionInfo(id=get_id_by_name("East"), name="East", color=get_color_by_name("East")),
info=DirectionInfo(
id=get_id_by_name("East"), name="East", color=get_color_by_name("East")
),
line=pedpy.MeasurementLine([[min_x, min_y], [min_x, max_y]]),
),
Direction(
info=DirectionInfo(id=get_id_by_name("West"), name="West", color=get_color_by_name("West")),
info=DirectionInfo(
id=get_id_by_name("West"), name="West", color=get_color_by_name("West")
),
line=pedpy.MeasurementLine([[max_x, min_y], [max_x, max_y]]),
),
Direction(
Expand Down Expand Up @@ -112,7 +118,9 @@ def setup_walkable_area(trajectory_data: pd.DataFrame) -> pedpy.WalkableArea:
return pedpy.WalkableArea(rectangle_polygon)


def setup_measurement_area(min_x: float, max_x: float, min_y: float, max_y: float) -> pedpy.MeasurementArea:
def setup_measurement_area(
min_x: float, max_x: float, min_y: float, max_y: float
) -> pedpy.MeasurementArea:
"""Create measurement_area from trajectories."""
rectangle_coords = [
[min_x, min_y],
Expand Down

0 comments on commit 2425ed3

Please sign in to comment.