Skip to content

Commit

Permalink
Fixing CI
Browse files Browse the repository at this point in the history
  • Loading branch information
chraibi committed Mar 13, 2024
1 parent ca10ac5 commit 5c90f2d
Show file tree
Hide file tree
Showing 11 changed files with 108 additions and 112 deletions.
11 changes: 5 additions & 6 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,16 @@
Date: August 11, 2023
"""

import glob
import json
from pathlib import Path
from src import motivation_model as mm
import jupedsim as jps

import numpy as np
import pandas as pd
import pedpy
import streamlit as st
from jupedsim.internal.notebook_utils import animate, read_sqlite_file

from simulation import main
from src import motivation_model as mm
from src.analysis import run
from src.inifile_parser import (
parse_fps,
Expand Down Expand Up @@ -159,7 +157,7 @@ def read_data(output_file: str) -> pd.DataFrame:
data,
Path(OUTPUT_FILE),
)
msg.code(f"Finished simulation. Evac time {evac_time} s")
msg.code(f"Finished simulation. Evac time {evac_time:.2f} s")
st.empty()
output_path = Path(OUTPUT_FILE)
if Path("values.txt").exists():
Expand All @@ -179,7 +177,8 @@ def read_data(output_file: str) -> pd.DataFrame:
max_value = float(data["motivation_parameters"]["max_value"])
min_value = float(data["motivation_parameters"]["min_value"])
seed = data["motivation_parameters"]["seed"]
number_agents = float(parse_number_agents(data))
number_agents = int(parse_number_agents(data))
motivation_strategy: mm.MotivationStrategy
if strategy == "default":
motivation_strategy = mm.DefaultMotivationStrategy(
width=width, height=height
Expand Down
2 changes: 1 addition & 1 deletion files/bottleneck.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"a_ped": 1.0,
"d_ped": 0.2,
"a_wall": 1.0,
"d_wall": 0.2,
"d_wall": 0.19,
"radius": 0.10
},
"simulation_parameters": {
Expand Down
47 changes: 20 additions & 27 deletions simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,33 @@

# Copyright © 2012-2022 Forschungszentrum Jülich GmbH
# SPDX-License-Identifier: LGPL-3.0-or-later
import logging
import contextlib
import json
import logging
import pathlib
import random
import sys
import time
from typing import Any, Dict, Iterator, List, Tuple, TypeAlias
from typing import Any, Dict, Iterator, Tuple, TypeAlias

import _io
import jupedsim as jps
from jupedsim.distributions import distribute_by_number

from src import motivation_model as mm
from src.inifile_parser import (
parse_accessible_areas,
parse_destinations,
parse_distribution_polygons,
parse_fps,
parse_radius,
parse_motivation_doors,
parse_motivation_parameter,
parse_motivation_strategy,
parse_normal_time_gap,
parse_normal_v_0,
parse_number_agents,
parse_simulation_time,
parse_time_step,
parse_velocity_init_parameters,
parse_way_points,
)
from src.logger_config import init_logger, log_debug, log_error, log_info
from src.utilities import (
build_geometry,
distribute_and_add_agents,
init_journey,
)
from src.inifile_parser import (parse_accessible_areas, parse_destinations,
parse_distribution_polygons, parse_fps,
parse_motivation_doors,
parse_motivation_parameter,
parse_motivation_strategy,
parse_normal_time_gap, parse_normal_v_0,
parse_number_agents, parse_radius,
parse_simulation_time, parse_time_step,
parse_velocity_init_parameters,
parse_way_points)
from src.logger_config import init_logger, log_debug, log_error
from src.utilities import (build_geometry, distribute_and_add_agents,
init_journey)

# import cProfile
# import pstats
Expand Down Expand Up @@ -109,6 +101,7 @@ def init_simulation(
choose_motivation_strategy = parse_motivation_strategy(_data)
number_agents = parse_number_agents(_data)
# =================
motivation_strategy: mm.MotivationStrategy
if choose_motivation_strategy == "default":
motivation_strategy = mm.DefaultMotivationStrategy(width=width, height=height)
if choose_motivation_strategy == "EVC":
Expand Down Expand Up @@ -198,7 +191,7 @@ def main(
_simulation_time: float,
_data: Dict[str, Any],
_trajectory_path: pathlib.Path,
) -> None:
) -> float:
"""Main simulation loop.
:param fps:
Expand Down Expand Up @@ -250,7 +243,7 @@ def main(
)
logging.info(f"simulation time: {simulation.iteration_count()*_time_step} [s]")
# logging.info(f"Trajectory: {_trajectory_path}")
return simulation.iteration_count() * _time_step
return float(simulation.iteration_count() * _time_step)


if __name__ == "__main__":
Expand Down
49 changes: 18 additions & 31 deletions src/analysis.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,26 @@
import glob
import numpy as np
import numpy.typing as npt
from typing import Any
import pedpy

import streamlit as st
from .utilities import (
create_empty_figure,
update_figure_layout,
calculate_heatmap_values,
add_heatmap_trace,
add_polygon_traces,
customize_fig_layout,
)
import json
from pathlib import Path
from .inifile_parser import parse_fps, parse_accessible_areas, parse_geometry
from shapely import Polygon
from shapely.ops import unary_union
from typing import Any

import matplotlib.pyplot as plt
from pedpy.column_identifier import (
CUMULATED_COL,
DENSITY_COL,
FRAME_COL,
ID_COL,
)
import numpy as np
import numpy.typing as npt
import pedpy
from .plotting import (
plot_density_time_series,
plotly_nt_series,
plot_flow_time_series,
plot_speed_time_series,
)
from .ui import ui_measurement_parameters
import streamlit as st
from jupedsim.internal.notebook_utils import read_sqlite_file
from pedpy.column_identifier import FRAME_COL, ID_COL

from .inifile_parser import parse_fps
from .plotting import (plot_density_time_series, plot_flow_time_series,
plot_speed_time_series, plotly_nt_series)
from .ui import ui_measurement_parameters
from .utilities import (add_heatmap_trace, add_polygon_traces,
calculate_heatmap_values, create_empty_figure,
customize_fig_layout, update_figure_layout)

# from shapely import Polygon
# from shapely.ops import unary_union


def generate_heatmap(
Expand Down Expand Up @@ -67,7 +54,7 @@ def generate_heatmap(
st.plotly_chart(fig)


def run():
def run() -> None:
selected = st.sidebar.radio(
"Choose option",
[
Expand Down
14 changes: 7 additions & 7 deletions src/inifile_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@

import json
import sys
from typing import Dict, List, Optional, Tuple, TypeAlias, Any
from typing import Any, Dict, List, Optional, Tuple, TypeAlias

import jsonschema
import shapely
from shapely import GeometryCollection, Polygon
from shapely.ops import unary_union
from shapely import Polygon, GeometryCollection

Point: TypeAlias = Tuple[float, float]

Expand Down Expand Up @@ -124,7 +124,7 @@ def parse_distribution_polygons(
return _distribution_polygons


def parse_measurement_line(json_data: Dict[str, Any]) -> Dict[int, List[List[float]]]:
def parse_measurement_line(json_data: Dict[str, Any]) -> List[Point]:
"""Measurement line has two points."""

_points: List[Point] = []
Expand Down Expand Up @@ -291,21 +291,21 @@ def parse_motivation_strategy(json_data: Dict[str, Any]) -> str:
"motivation_parameters" in json_data
and "motivation_strategy" in json_data["motivation_parameters"]
):
return json_data["motivation_parameters"]["motivation_strategy"]
return str(json_data["motivation_parameters"]["motivation_strategy"])

return "default"


def parse_motivation_parameter(json_data: Dict[str, Any], parameter: str) -> str:
def parse_motivation_parameter(json_data: Dict[str, Any], parameter: str) -> int:
"""Get motivation parameter."""

if (
"motivation_parameters" in json_data
and parameter in json_data["motivation_parameters"]
):
return float(json_data["motivation_parameters"][parameter])
return int(json_data["motivation_parameters"][parameter])

return 1.0
return 1


def is_motivation_active(json_data: Dict[str, Any]) -> int:
Expand Down
5 changes: 3 additions & 2 deletions src/json2xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
- jpsvis_doors
- accessible_areas: Make a union on all walls to get a nice polygon
"""
"""

import json
import sys
import xml.etree.ElementTree as ET
Expand All @@ -26,7 +27,7 @@ def add_transitions(_root: ET.Element, _data: Dict[str, Any]) -> None:
:returns:
"""
if not "jpsvis_doors" in _data:
if "jpsvis_doors" not in _data:
return

destinations = _data["jpsvis_doors"]
Expand Down
1 change: 1 addition & 0 deletions src/logger_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""

import logging

import jupedsim as jps

# # Create a handler that writes INFO and DEBUG messages to stdout
Expand Down
35 changes: 24 additions & 11 deletions src/motivation_model.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
"""Module for motivational model."""

import random
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, Optional, Tuple, TypeAlias
from typing import Any, List, Optional, Tuple, TypeAlias

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.figure import Figure

from .logger_config import log_debug

Point: TypeAlias = Tuple[float, float]


class MotivationStrategy(ABC):
@abstractmethod
def motivation(self, params: dict[str, Any]) -> float:
pass

# abstractmethod
def plot(self) -> List[Figure]:
pass


@dataclass
class DefaultMotivationStrategy:
class DefaultMotivationStrategy(MotivationStrategy):
"""Default strategy for motivation calculation based on distance."""

width: float = 1.0
Expand All @@ -35,7 +48,7 @@ def motivation(self, params: dict[str, Any]) -> float:

return float(np.exp(expr) * np.e * self.height)

def plot(self):
def plot(self) -> List[Figure]:
fig = plt.figure()
distances = np.linspace(0, 10, 100)
m = []
Expand All @@ -53,15 +66,15 @@ def plot(self):


@dataclass
class EVCStrategy:
class EVCStrategy(MotivationStrategy):
"""Motivation theory based on E.V.C (model4)."""

width: float = 1.0
height: float = 1.0
max_reward: int = 0
seed: int = 0
min_value: int = 0
max_value: int = 1
min_value: float = 0
max_value: float = 1

@staticmethod
def name() -> str:
Expand All @@ -87,14 +100,14 @@ def competition(got_reward: int, max_reward: int) -> float:
got_reward: How many got reward
max_reward: hom many max can get reward
"""
comp = 0
comp = 0.0
if got_reward <= max_reward:
comp = 1 - got_reward / max_reward

return comp

@staticmethod
def value(min_v: float, max_v: float, seed: Optional[float] = None):
def value(min_v: float, max_v: float, seed: Optional[float] = None) -> float:
"""Random value in interval. seed is optional."""
if seed is not None:
random.seed(seed)
Expand All @@ -108,7 +121,7 @@ def motivation(self, params: dict[str, Any]) -> float:
got_reward = self.max_reward - number_agents_in_simulation
if "seed" not in params:
params["seed"] = None
return (
return float(
EVCStrategy.value(self.min_value, self.max_value, params["seed"])
* EVCStrategy.competition(got_reward, self.max_reward)
* EVCStrategy.expectancy(
Expand All @@ -118,7 +131,7 @@ def motivation(self, params: dict[str, Any]) -> float:
)
)

def plot(self):
def plot(self) -> List[Figure]:
"""Plot functions for inspection."""
fig0, ax0 = plt.subplots(ncols=1, nrows=1)
fig1, ax1 = plt.subplots(ncols=1, nrows=1)
Expand Down Expand Up @@ -183,7 +196,7 @@ def plot(self):
ax3.set_xlabel("Distance / m")
ax3.set_ylabel("Motivation")

return fig0, fig1, fig2, fig3
return [fig0, fig1, fig2, fig3]


@dataclass
Expand Down
Loading

0 comments on commit 5c90f2d

Please sign in to comment.