|
| 1 | +from pathlib import Path |
| 2 | +from typing import Dict, List, Union, TYPE_CHECKING |
| 3 | +import pandas as pd |
| 4 | +import numpy as np |
| 5 | + |
| 6 | +from events.model_system_event_listener import ModelSystemEventListener |
| 7 | + |
| 8 | +if TYPE_CHECKING: |
| 9 | + from modelsystem import ModelSystem |
| 10 | + from datatypes.demand import Demand |
| 11 | + from datatypes.purpose import TourPurpose |
| 12 | + |
| 13 | + |
| 14 | +class DemandAnalysis(ModelSystemEventListener): |
| 15 | + """ |
| 16 | + A class to analyze demand in a model system by listening to specific events. |
| 17 | + """ |
| 18 | + |
| 19 | + mode_demands: List[Dict[str, int]] |
| 20 | + """ A list of dictionaries to store mode demands for each iteration. """ |
| 21 | + result_path: Path |
| 22 | + """ The path to the result file. """ |
| 23 | + |
| 24 | + def __init__(self): |
| 25 | + super().__init__() |
| 26 | + self.mode_demands = [] |
| 27 | + |
| 28 | + def on_model_system_initialized(self, model_system: 'ModelSystem'): |
| 29 | + # Get result path when model system is initialized |
| 30 | + self.result_path = Path(model_system.resultdata.path) / 'mode_analysis_results.csv' |
| 31 | + |
| 32 | + def on_iteration_started(self, iteration: Union[int, str], previous_impedance: Dict[str, Dict[str, np.ndarray]]): |
| 33 | + # Add new row for each iteration |
| 34 | + self.mode_demands.append({'iteration': iteration}) |
| 35 | + |
| 36 | + def on_purpose_demand_calculated(self, purpose: 'TourPurpose', demand: 'Demand'): |
| 37 | + # Sum mode demand for each purpose after it has been calculated |
| 38 | + current_results = self.mode_demands[-1] |
| 39 | + for m, d in demand.items(): |
| 40 | + current_results[m] = d.matrix.sum() + current_results.get(m, 0) |
| 41 | + |
| 42 | + def on_iteration_complete(self, iteration: Union[str, int], impedance: Dict[str, Dict[str, np.ndarray]], gap: Dict[str, float]): |
| 43 | + # Print resuts after last iteration |
| 44 | + if iteration == 'last' or iteration is None: |
| 45 | + pd.DataFrame(self.mode_demands)\ |
| 46 | + .to_csv(self.result_path, index=False) |
0 commit comments