Skip to content

Commit

Permalink
brought in changes from downstream project repo
Browse files Browse the repository at this point in the history
  • Loading branch information
calbaker committed Feb 7, 2025
1 parent bd88093 commit 5a89ea8
Show file tree
Hide file tree
Showing 12 changed files with 65 additions and 28 deletions.
3 changes: 2 additions & 1 deletion python/altrios/altrios_pyo3.pyi
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import altrios.altrios_pyo3 as altpy
from typing import Any, Dict, List, Optional
from typing import Any, Dict, List, Optional, Path
import polars as pl
from typing_extensions import Self
from typing import Union, Tuple
Expand Down Expand Up @@ -1027,6 +1027,7 @@ def run_dispatch(
def make_est_times(
speed_limit_train_sim: SpeedLimitTrainSim,
network: List[Link],
path_for_failed_sim: Optional[Path]=None
) -> Tuple[EstTimeNet, Consist]:
...

Expand Down
2 changes: 1 addition & 1 deletion python/altrios/demos/demo_variable_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@
# print results as dataframe
print("Results as dataframe:\n", train_sim.to_dataframe(), sep="")
if ENABLE_REF_OVERRIDE:
df:pl.DataFrame = train_sim.to_dataframe().lazy().collect()
df:pl.DataFrame = train_sim.to_dataframe()
df.write_csv(ref_dir / "to_dataframe_expected.csv")
if ENABLE_ASSERTS:
print("Checking output of `to_dataframe`")
Expand Down
3 changes: 2 additions & 1 deletion python/altrios/demos/rollout_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
#targets = [0,0.05,0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.45,0.5,0.55,0.6,0.65,0.7,0.75, 0.8]
train_planner_config = planner_config.TrainPlannerConfig(
cars_per_locomotive={"Default": 50},
target_cars_per_train={"Default": 90})
target_cars_per_train={"Default": 90},
require_diesel=True)
targets = [0.5]
for target in targets:
scenario_infos, metrics = rollout.simulate_prescribed_rollout(
Expand Down
6 changes: 4 additions & 2 deletions python/altrios/demos/sim_manager_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@

train_planner_config = planner_config.TrainPlannerConfig(
cars_per_locomotive={"Default": 50},
target_cars_per_train={"Default": 90})
target_cars_per_train={"Default": 90},
require_diesel=True)

t0_main = time.perf_counter()

Expand All @@ -50,7 +51,8 @@
grid_emissions_factors,
nodal_energy_prices,
speed_limit_train_sims,
timed_paths
timed_paths,
train_consist_plan_untrimmed
) = sim_manager.main(
network=network,
rail_vehicles=rail_vehicles,
Expand Down
15 changes: 11 additions & 4 deletions python/altrios/metric_calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -1126,11 +1126,18 @@ def calculate_meet_pass_events(
slts_results = []
i = 0
for slts in info.sims.tolist():
df = (slts.to_dataframe()
if len(info.sims.tolist()[0].history.i) == 0:
print("No SpeedLimitTrainSim history was saved, so meet pass events cannot be counted.")
return metric("Meet_Pass_Events", units, None)

df = slts.to_dataframe()
if ("history.time" not in df.collect_schema()) or ("history.speed" not in df.collect_schema()):
print("SpeedLimitTrainSim history doesn't include time and/or speed, so meet pass events cannot be counted.")
return metric("Meet_Pass_Events", units, None)

df = (df
.select("history.time", "history.speed")
.with_columns(
pl.lit(i).alias("train_idx")
)
.with_columns(pl.lit(i).alias("train_idx"))
)
if df.height > 0:
slts_results.append(df)
Expand Down
14 changes: 7 additions & 7 deletions python/altrios/resources/Default Demand.csv
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Origin,Destination,Train_Type,Number_of_Cars,Number_of_Containers
Hibbing,Allouez,Unit,798,0
Hibbing,Allouez,Manifest,863,0
Hibbing,Allouez,Intermodal,740,740
Allouez,Hibbing,Unit,777,0
Allouez,Hibbing,Manifest,1076,0
Allouez,Hibbing,Intermodal,707,707
Origin,Destination,Train_Type,Number_of_Days,Number_of_Cars,Number_of_Containers
Hibbing,Allouez,Unit,21,798,0
Hibbing,Allouez,Manifest,21,863,0
Hibbing,Allouez,Intermodal,21,740,1480
Allouez,Hibbing,Unit,21,777,0
Allouez,Hibbing,Manifest,21,1076,0
Allouez,Hibbing,Intermodal,21,707,1414
Original file line number Diff line number Diff line change
Expand Up @@ -1100,8 +1100,8 @@
['loco_con']['history']['energy_res']
['loco_con']['history']['energy_fuel']
['loco_con']['save_interval']
['n_cars_by_type']['Manifest_Loaded']
['n_cars_by_type']['Manifest_Empty']
['n_cars_by_type']['Manifest_Loaded']
['state']['time']
['state']['i']
['state']['offset']
Expand Down
2 changes: 1 addition & 1 deletion python/altrios/rollout.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def simulate_prescribed_rollout(
for idx, scenario_year in enumerate(years):
t0 = time.perf_counter()
(
train_consist_plan, loco_pool, refuel_facilities, grid_emissions_factors, nodal_energy_prices, speed_limit_train_sims, timed_paths
train_consist_plan, loco_pool, refuel_facilities, grid_emissions_factors, nodal_energy_prices, speed_limit_train_sims, timed_paths, train_consist_plan_untrimmed
) = sim_manager.main(
network=network,
rail_vehicles=rail_vehicles,
Expand Down
10 changes: 9 additions & 1 deletion python/altrios/train_planner/data_prep.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,15 @@ def build_locopool(
# Compute the 24-hour window with the most total locomotives needed
# (assuming each loco is only dispatched once in a given day)
loco_mass = config.loco_info['Loco_Mass_Tons'].mean()
hp_per_ton = config.hp_required_per_ton['Default'][dispatch_schedule.select(pl.col("Train_Type").mode()).item()]
# Average hp_per_ton, weighted by total number of cars.
# Max hp_per_ton across trains would be more conservative if runs are failing.
hp_per_ton = (dispatch_schedule
.select(
(pl.col("HP_Required").truediv("Tons_Per_Train"))
.mul(pl.col("Number_of_Cars")).sum()
.truediv(pl.col("Number_of_Cars").sum())
).item()
)
hp_per_loco = config.loco_info['HP'].mean() - loco_mass * hp_per_ton
initial_size_hp = (dispatch_schedule
.with_columns((pl.col("Hour") // 24).cast(pl.Int32).alias("Day"),
Expand Down
4 changes: 2 additions & 2 deletions python/altrios/train_planner/planner.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@ def run_train_planner(
dispatch_order = (dispatched.select(
pl.col('Locomotive_ID')
.rank().alias('rank').cast(pl.UInt32)
).with_row_count().sort('row_nr'))
).with_row_index().sort('index'))
dispatched = dispatched.sort('Locomotive_ID')
loco_start_soc_pct = dispatched.select(pl.col('SOC_J') / pl.col('Capacity_J')).to_series()
locos = [
Expand Down Expand Up @@ -473,7 +473,7 @@ def run_train_planner(
scenario_year=scenario_year
)

(est_time_net, loco_con_out) = alt.make_est_times(slts, network)
(est_time_net, loco_con_out) = alt.make_est_times(slts, network, config.failed_sim_logging_path)
travel_time = (
est_time_net.get_running_time_hours()
* config.dispatch_scaling_dict["time_mult_factor"]
Expand Down
10 changes: 6 additions & 4 deletions python/altrios/train_planner/planner_config.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from __future__ import annotations
import os
import polars as pl
import pandas as pd
from typing import Dict, Callable, Optional
from typing import Dict, Callable, Optional, Union
from dataclasses import dataclass, field
import altrios as alt
from altrios import defaults
Expand Down Expand Up @@ -49,6 +50,7 @@ class TrainPlannerConfig:
require_diesel: bool = False
manifest_empty_return_ratio: float = 0.6
loco_pool_safety_factor: float = 1.1
failed_sim_logging_path: Union[str, os.PathLike] = None
hp_required_per_ton: Dict = field(default_factory = lambda: {
"Default": {
"Unit": 2.0,
Expand All @@ -57,9 +59,9 @@ class TrainPlannerConfig:
}
})
dispatch_scaling_dict: Dict = field(default_factory = lambda: {
"time_mult_factor": 2.0,
"hours_add": 3,
"energy_mult_factor": 1.8
"time_mult_factor": 1.4,
"hours_add": 2,
"energy_mult_factor": 1.25
})
loco_info: pd.DataFrame = field(default_factory = lambda: pd.DataFrame({
"Diesel_Large": {
Expand Down
22 changes: 19 additions & 3 deletions rust/altrios-core/src/train/speed_limit_train_sim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,7 @@ impl SpeedLimitTrainSim {
// Verify that train has sufficient power to move
if self.state.speed < uc::MPH * 0.1 && f_pos_max <= res_net {
bail!(
"{}\nTrain does not have sufficient power to move!\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}", // ,\nlink={:?}
"{}\nTrain does not have sufficient power to move!\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}", // ,\nlink={:?}
format_dbg!(),
// force_max
format!(
Expand All @@ -518,7 +518,8 @@ impl SpeedLimitTrainSim {
// force based on speed target
format!("pwr_pos_max / speed_target.min(v_max): {} N", (pwr_pos_max / speed_target.min(v_max)).get::<si::newton>().format_eng(Some(5))),
// pwr_pos_max
format!("pwr_pos_max: {} W", pwr_pos_max.get::<si::watt>().format_eng(Some(5))
format!("pwr_pos_max: {} W", pwr_pos_max.get::<si::watt>().format_eng(Some(5)),

),
// SOC across all RES-equipped locomotives
format!(
Expand Down Expand Up @@ -552,7 +553,22 @@ impl SpeedLimitTrainSim {
// grade at rear of train
format!("grade_back: {}", self.state.grade_back.get::<si::ratio>().format_eng(Some(5))),
format!("f_pos_max: {} N", f_pos_max.get::<si::newton>().format_eng(Some(5))),
format!("res_net: {} N", res_net.get::<si::newton>().format_eng(Some(5)))
format!("res_net: {} N", res_net.get::<si::newton>().format_eng(Some(5))),
format_dbg!(self.fric_brake.force_max),
format_dbg!(self.state.res_grade),
format_dbg!(self.state.elev_front),
format_dbg!(self.state.elev_back),
format_dbg!(self.state.offset),
format_dbg!(self.state.offset_back),
format_dbg!(self.state.speed),
format_dbg!(self.state.speed_limit),
format_dbg!(self.state.speed_target),
format_dbg!(self.state.time),
format_dbg!(self.state.dt),
format_dbg!(self.state.i),
format_dbg!(self.state.total_dist),
format_dbg!(self.state.link_idx_front),
format_dbg!(self.state.offset_in_link)
)
}

Expand Down

0 comments on commit 5a89ea8

Please sign in to comment.