@@ -28,6 +28,50 @@ def __init__(self) -> None:
2828 self ._battery_buckets : dict [frozenset [int ], SortedSet [Proposal ]] = {}
2929 self ._target_power : dict [frozenset [int ], Power ] = {}
3030
31+ def _calc_target_power (
32+ self ,
33+ proposals : SortedSet [Proposal ],
34+ system_bounds : PowerMetrics ,
35+ ) -> Power :
36+ """Calculate the target power for the given batteries.
37+
38+ Args:
39+ proposals: The proposals for the given batteries.
40+ system_bounds: The system bounds for the batteries in the proposal.
41+
42+ Returns:
43+ The new target power for the batteries.
44+ """
45+ lower_bound = (
46+ system_bounds .inclusion_bounds .lower
47+ if system_bounds .inclusion_bounds
48+ # if a target power exists from a previous proposal, and the system bounds
49+ # have become unavailable, force the target power to be zero, by narrowing
50+ # the bounds to zero.
51+ else Power .zero ()
52+ )
53+ upper_bound = (
54+ system_bounds .inclusion_bounds .upper
55+ if system_bounds .inclusion_bounds
56+ else Power .zero ()
57+ )
58+
59+ target_power = Power .zero ()
60+ for next_proposal in reversed (proposals ):
61+ if upper_bound < lower_bound :
62+ break
63+ if next_proposal .preferred_power > upper_bound :
64+ target_power = upper_bound
65+ elif next_proposal .preferred_power < lower_bound :
66+ target_power = lower_bound
67+ else :
68+ target_power = next_proposal .preferred_power
69+ if next_proposal .bounds :
70+ lower_bound = max (lower_bound , next_proposal .bounds [0 ])
71+ upper_bound = min (upper_bound , next_proposal .bounds [1 ])
72+
73+ return target_power
74+
3175 @override
3276 def get_target_power (
3377 self ,
@@ -83,33 +127,7 @@ def get_target_power(
83127 if proposals is None :
84128 return None
85129
86- lower_bound = (
87- system_bounds .inclusion_bounds .lower
88- if system_bounds .inclusion_bounds
89- # if a target power exists from a previous proposal, and the system bounds
90- # have become unavailable, force the target power to be zero, by narrowing
91- # the bounds to zero.
92- else Power .zero ()
93- )
94- upper_bound = (
95- system_bounds .inclusion_bounds .upper
96- if system_bounds .inclusion_bounds
97- else Power .zero ()
98- )
99-
100- target_power = Power .zero ()
101- for next_proposal in reversed (proposals ):
102- if upper_bound < lower_bound :
103- break
104- if next_proposal .preferred_power > upper_bound :
105- target_power = upper_bound
106- elif next_proposal .preferred_power < lower_bound :
107- target_power = lower_bound
108- else :
109- target_power = next_proposal .preferred_power
110- if next_proposal .bounds :
111- lower_bound = max (lower_bound , next_proposal .bounds [0 ])
112- upper_bound = min (upper_bound , next_proposal .bounds [1 ])
130+ target_power = self ._calc_target_power (proposals , system_bounds )
113131
114132 if (
115133 battery_ids not in self ._target_power
0 commit comments