fix: unify mypy environments for local checks and CI (#1291)

The isolated pre-commit mypy hook previously omitted runtime type information that
make mypy used, hiding errors involving dependencies such as Pydantic and Pendulum.
Makefile, pre-commit and CI now run the same full-project typing policy in the
development environment defined by uv.lock.

- Use uv run --locked --exact --extra dev and the same mypy arguments for Makefile
  and the local hook. Check all of src and tests, including on configuration-only
  changes.
- Pin Python 3.13 for local development and the pre-commit CI job, and install the
  locked pre-commit version in CI.
- Disable incremental analysis because existing Pendulum cache state changes mypy 2.3.1
  diagnostics. Document the policy, the performance tradeoff and the existing typing debt.
- Add a regression test that exercises Makefile, the hook and the CI command in a
  temporary project, accepting valid dependency types and detecting deliberate
  Pydantic/Pendulum assignment errors.

Resolve the newly detected mypy diagnostics.

- Enable the numpydantic and Pydantic mypy plugins, retaining strict Pydantic
  constructor typing with init_typed = true. Validate raw/coercible payloads through model_validate.
- Propagate concrete record, provider and time-window types through generic collections,
  factories and lookup methods. Preserve runtime field inspection and generated time-window
  documentation.
- Align Pendulum annotations with actual factory/arithmetic results while retaining Pydantic
  validation adapters at runtime. Correct optional values, array boundaries, REST handlers
  and plotting interfaces.
- Add pinned scipy-stubs and types-psutil, update uv.lock, and supply the plugins' dependencies.
- Add runtime regression coverage for validated path defaults, normalized time-series metadata,
  generic field inspection, invalid timestamps and unsupported provider imports.

Runtime and compatibility details:

- Validate path defaults as Path objects while retaining raw string defaults needed by
  migration serialization with exclude_defaults.
- Normalize feed-in tariff lists and default charge rates to NumPy arrays; reject missing
  timestamps/uninitialized values explicitly. Importing into a provider without import support
  returns HTTP 400.
- Public JSON schemas and OpenAPI structure match main (excluding the generated version).

Signed-off-by: dr-dimitry

Signed-off-by: dr-dimitry
Signed-off-by: Bobby Noelte <b0661n0e17e@gmail.com>
Co-authored-by: dr-dimitri <87113560+dr-dimitri@users.noreply.github.com>
Co-authored-by: Normann <github@koldrack.com>
This commit is contained in:
Bobby Noelte
2026-09-10 23:20:35 +02:00
committed by GitHub
co-authored by dr-dimitri Normann
parent 5b584cbb57
commit 1abdd345c4
114 changed files with 2217 additions and 1322 deletions
@@ -125,7 +125,7 @@ class GeneticSimulation(PydanticBaseModel):
self.pv_prediction_wh = np.array(parameters.pv_forecast_wh, float)
self.elect_price_hourly = np.array(parameters.electricity_price_per_wh, float)
self.elect_revenue_per_hour_arr = (
parameters.feed_in_tariff_per_wh
np.asarray(parameters.feed_in_tariff_per_wh, dtype=float)
if isinstance(parameters.feed_in_tariff_per_wh, list)
else np.full(len(self.load_energy_array), parameters.feed_in_tariff_per_wh, float)
)
@@ -1205,21 +1205,21 @@ class GeneticOptimization(OptimizationBase):
)
# Simulation may have changed something, use simulation values
ac_charge_hours = self.simulation.ac_charge_hours
if ac_charge_hours is None:
ac_charge_hours = []
else:
ac_charge_hours = ac_charge_hours.tolist()
dc_charge_hours = self.simulation.dc_charge_hours
if dc_charge_hours is None:
dc_charge_hours = []
else:
dc_charge_hours = dc_charge_hours.tolist()
discharge = self.simulation.bat_discharge_hours
if discharge is None:
discharge = []
else:
discharge = discharge.tolist()
ac_charge_hours = (
self.simulation.ac_charge_hours.tolist()
if self.simulation.ac_charge_hours is not None
else []
)
dc_charge_hours = (
self.simulation.dc_charge_hours.tolist()
if self.simulation.dc_charge_hours is not None
else []
)
discharge = (
self.simulation.bat_discharge_hours.tolist()
if self.simulation.bat_discharge_hours is not None
else []
)
return GeneticSolution(
**{
@@ -62,10 +62,10 @@ class GeneticCommonSettings(SettingsBaseModel):
# --- Penalties (existing) -------------------------------------------------
penalties: dict[str, Union[float, int, str]] = Field(
default_factory=lambda: {
"ev_soc_miss": 10,
"ac_charge_break_even": 1.0,
},
default_factory=lambda: dict[str, float | int | str](
ev_soc_miss=10,
ac_charge_break_even=1.0,
),
json_schema_extra={
"description": "Penalty parameters used in fitness evaluation.",
"examples": [{"ev_soc_miss": 10}],
@@ -141,7 +141,11 @@ class GeneticVisualizationReport(ConfigMixin):
marker = markers[idx] if markers and idx < len(markers) else "o" # Marker style
line_style = line_styles[idx] if line_styles and idx < len(line_styles) else "-"
plt.plot(
timestamps, y_data, label=label, marker=marker, linestyle=line_style
mdates.date2num(timestamps),
np.asarray(y_data, dtype=float),
label=label,
marker=marker,
linestyle=line_style,
) # Plot line
# Format the time axis
@@ -178,8 +182,15 @@ class GeneticVisualizationReport(ConfigMixin):
# Add vertical line for the current date if within the axis range
current_time = pendulum.now(self.config.general.timezone)
if timestamps[0].subtract(hours=2) <= current_time <= timestamps[-1]:
plt.axvline(current_time, color="r", linestyle="--", label="Now")
plt.text(current_time, plt.ylim()[1], "Now", color="r", ha="center", va="bottom")
plt.axvline(mdates.date2num(current_time), color="r", linestyle="--", label="Now")
plt.text(
mdates.date2num(current_time),
plt.ylim()[1],
"Now",
color="r",
ha="center",
va="bottom",
)
# Add a second x-axis on top
ax1 = plt.gca()
@@ -191,7 +202,9 @@ class GeneticVisualizationReport(ConfigMixin):
# ax2.set_xticks(timestamps[::48]) # Set ticks every 12 hours
# ax2.set_xticklabels([f"{int(h)}" for h in hours_since_start[::48]])
# ax2.set_xticks(timestamps[:: len(timestamps) // 24]) # Select 10 evenly spaced ticks
ax2.set_xticks(timestamps[:: len(timestamps) // 12]) # Select 10 evenly spaced ticks
ax2.set_xticks(
mdates.date2num(timestamps[:: len(timestamps) // 12])
) # Select 10 evenly spaced ticks
# ax2.set_xticklabels([f"{int(h)}" for h in hours_since_start[:: len(timestamps) // 24]])
ax2.set_xticklabels([f"{int(h)}" for h in hours_since_start[:: len(timestamps) // 12]])
if x2label:
@@ -251,7 +264,13 @@ class GeneticVisualizationReport(ConfigMixin):
line_style = (
line_styles[idx] if line_styles and idx < len(line_styles) else "-"
) # Line style
plt.plot(x, y_data, label=label, marker=marker, linestyle=line_style) # Plot line
plt.plot(
x,
np.asarray(y_data, dtype=float),
label=label,
marker=marker,
linestyle=line_style,
) # Plot line
plt.title(title) # Set title
plt.xlabel(xlabel) # Set x-axis label
@@ -16,6 +16,7 @@ from akkudoktoreos.devices.genetic0.genetic0homeappliance import Genetic0HomeApp
from akkudoktoreos.devices.genetic0.genetic0inverter import Genetic0Inverter
from akkudoktoreos.optimization.genetic0.genetic0params import (
Genetic0EnergyManagementParameters,
Genetic0OptimizationParameters,
)
from akkudoktoreos.optimization.genetic0.genetic0solution import (
Genetic0SimulationResult,
@@ -128,7 +129,7 @@ class Genetic0Simulation(PydanticBaseModel):
self.pv_prediction_wh = np.array(parameters.pv_forecast_wh, float)
self.elect_price_hourly = np.array(parameters.electricity_price_per_wh, float)
self.elect_revenue_per_hour_arr = (
parameters.feed_in_tariff_per_wh
np.asarray(parameters.feed_in_tariff_per_wh, dtype=float)
if isinstance(parameters.feed_in_tariff_per_wh, list)
else np.full(len(self.load_energy_array), parameters.feed_in_tariff_per_wh, float)
)
@@ -741,7 +742,7 @@ class Genetic0Optimization(OptimizationBase):
def evaluate(
self,
individual: list[int],
parameters: Genetic0EnergyManagementParameters,
parameters: Genetic0OptimizationParameters,
start_hour: int,
worst_case: bool,
) -> tuple[float]:
@@ -1056,7 +1057,7 @@ class Genetic0Optimization(OptimizationBase):
def optimize_ems(
self,
parameters: Genetic0EnergyManagementParameters,
parameters: Genetic0OptimizationParameters,
start_hour: Optional[int] = None,
worst_case: bool = False,
ngen: Optional[int] = None,
@@ -1208,21 +1209,21 @@ class Genetic0Optimization(OptimizationBase):
)
# Simulation may have changed something, use simulation values
ac_charge_hours = self.simulation.ac_charge_hours
if ac_charge_hours is None:
ac_charge_hours = []
else:
ac_charge_hours = ac_charge_hours.tolist()
dc_charge_hours = self.simulation.dc_charge_hours
if dc_charge_hours is None:
dc_charge_hours = []
else:
dc_charge_hours = dc_charge_hours.tolist()
discharge = self.simulation.bat_discharge_hours
if discharge is None:
discharge = []
else:
discharge = discharge.tolist()
ac_charge_hours = (
self.simulation.ac_charge_hours.tolist()
if self.simulation.ac_charge_hours is not None
else []
)
dc_charge_hours = (
self.simulation.dc_charge_hours.tolist()
if self.simulation.dc_charge_hours is not None
else []
)
discharge = (
self.simulation.bat_discharge_hours.tolist()
if self.simulation.bat_discharge_hours is not None
else []
)
return Genetic0Solution(
**{
@@ -52,10 +52,10 @@ class Genetic0CommonSettings(SettingsBaseModel):
# --- Penalties (existing) -------------------------------------------------
penalties: dict[str, Union[float, int, str]] = Field(
default_factory=lambda: {
"ev_soc_miss": 10,
"ac_charge_break_even": 1.0,
},
default_factory=lambda: dict[str, float | int | str](
ev_soc_miss=10,
ac_charge_break_even=1.0,
),
json_schema_extra={
"description": "Penalty parameters used in fitness evaluation.",
"examples": [{"ev_soc_miss": 10}],
@@ -141,7 +141,11 @@ class Genetic0VisualizationReport(ConfigMixin):
marker = markers[idx] if markers and idx < len(markers) else "o" # Marker style
line_style = line_styles[idx] if line_styles and idx < len(line_styles) else "-"
plt.plot(
timestamps, y_data, label=label, marker=marker, linestyle=line_style
mdates.date2num(timestamps),
np.asarray(y_data, dtype=float),
label=label,
marker=marker,
linestyle=line_style,
) # Plot line
# Format the time axis
@@ -178,8 +182,15 @@ class Genetic0VisualizationReport(ConfigMixin):
# Add vertical line for the current date if within the axis range
current_time = pendulum.now(self.config.general.timezone)
if timestamps[0].subtract(hours=2) <= current_time <= timestamps[-1]:
plt.axvline(current_time, color="r", linestyle="--", label="Now")
plt.text(current_time, plt.ylim()[1], "Now", color="r", ha="center", va="bottom")
plt.axvline(mdates.date2num(current_time), color="r", linestyle="--", label="Now")
plt.text(
mdates.date2num(current_time),
plt.ylim()[1],
"Now",
color="r",
ha="center",
va="bottom",
)
# Add a second x-axis on top
ax1 = plt.gca()
@@ -191,7 +202,9 @@ class Genetic0VisualizationReport(ConfigMixin):
# ax2.set_xticks(timestamps[::48]) # Set ticks every 12 hours
# ax2.set_xticklabels([f"{int(h)}" for h in hours_since_start[::48]])
# ax2.set_xticks(timestamps[:: len(timestamps) // 24]) # Select 10 evenly spaced ticks
ax2.set_xticks(timestamps[:: len(timestamps) // 12]) # Select 10 evenly spaced ticks
ax2.set_xticks(
mdates.date2num(timestamps[:: len(timestamps) // 12])
) # Select 10 evenly spaced ticks
# ax2.set_xticklabels([f"{int(h)}" for h in hours_since_start[:: len(timestamps) // 24]])
ax2.set_xticklabels([f"{int(h)}" for h in hours_since_start[:: len(timestamps) // 12]])
if x2label:
@@ -251,7 +264,13 @@ class Genetic0VisualizationReport(ConfigMixin):
line_style = (
line_styles[idx] if line_styles and idx < len(line_styles) else "-"
) # Line style
plt.plot(x, y_data, label=label, marker=marker, linestyle=line_style) # Plot line
plt.plot(
x,
np.asarray(y_data, dtype=float),
label=label,
marker=marker,
linestyle=line_style,
) # Plot line
plt.title(title) # Set title
plt.xlabel(xlabel) # Set x-axis label