Skip to content

Commit

Permalink
refactor: fix more typing
Browse files Browse the repository at this point in the history
  • Loading branch information
jorgenengelsen committed May 23, 2023
1 parent b78b035 commit 08394a3
Show file tree
Hide file tree
Showing 16 changed files with 60 additions and 41 deletions.
7 changes: 7 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,13 @@ warn_return_any = false
warn_unused_configs = true
warn_redundant_casts = true
warn_unused_ignores = true
strict_equality = true
strict_concatenate = true
check_untyped_defs = true

no_implicit_reexport = true


warn_no_return = false
disable_error_code = ["call-overload", "union-attr", "valid-type", "return-value", "attr-defined", "assignment"]
namespace_packages = true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"""


def transpose(a: List[List[Union[str, int, float]]]):
def transpose(a: List[List[Union[str, int, float]]]) -> List[List[Union[str, int, float]]]:
"""Easily transpose from row based to column based data, and other
way around, in order to use the format that best fits a certain
purpose to work with such a list/dataframe.
Expand Down Expand Up @@ -104,7 +104,7 @@ def elementwise_multiplication(
return result


def array_to_list(result_array: Union[np.ndarray, List[np.ndarray], None]):
def array_to_list(result_array: Union[np.ndarray, List[np.ndarray], None]) -> Optional[List]:
"""Method to convert numpy arrays and list of numpy arrays into lists (or list of lists). Method is used recurrsivly on lists so needs to handle None aswell.
Args:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class Period:
start: datetime = datetime.min
end: datetime = datetime.max

def __str__(self):
def __str__(self) -> str:
return f"{self.start}:{self.end}"

def __contains__(self, time: datetime) -> bool:
Expand Down Expand Up @@ -116,7 +116,7 @@ class Frequency(str, enum.Enum):
MONTH = "MS"
DAY = "D"

def formatstring(self):
def formatstring(self) -> str:
"""The format to write a string describing a certain period of time."""
if self.value == "YS":
return "%Y"
Expand Down
4 changes: 2 additions & 2 deletions src/ecalc/libraries/libecalc/common/libecalc/common/units.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,11 @@ class Unit(str, Enum):
NORWEGIAN_KRONER_PER_DAY = "NOK/d"
NORWEGIAN_KRONER = "NOK"

def __str__(self):
def __str__(self) -> str:
return self.value

@classmethod
def validator(cls, unit: str):
def validator(cls, unit: Union[str, Unit]) -> Unit:
if isinstance(unit, str):
return Unit(unit)
return unit
Expand Down
22 changes: 13 additions & 9 deletions src/ecalc/libraries/libecalc/common/libecalc/common/utils/rates.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def to_stream_day(calendar_day_rates: np.ndarray, regularity: List[float]) -> np
The corresponding stream day rates
"""
regularity = np.asarray(regularity, dtype=np.float64) # type: ignore[assignment]
return np.divide(calendar_day_rates, regularity, out=np.zeros_like(calendar_day_rates), where=regularity != 0.0)
return np.divide(calendar_day_rates, regularity, out=np.zeros_like(calendar_day_rates), where=regularity != 0.0) # type: ignore[comparison-overlap]

@staticmethod
def to_calendar_day(stream_day_rates: np.ndarray, regularity: List[float]) -> np.ndarray:
Expand Down Expand Up @@ -130,12 +130,12 @@ class Config:
use_enum_values = True

@validator("values", each_item=True, pre=True)
def convert_none_to_nan(cls, v, field: ModelField):
def convert_none_to_nan(cls, v: float, field: ModelField) -> TimeSeriesValue:
if field.outer_type_ is float and v is None:
return math.nan
return v

def __len__(self):
def __len__(self) -> int:
return len(self.values)

@abstractmethod
Expand Down Expand Up @@ -214,7 +214,9 @@ def __setitem__(self, indices: Union[slice, int, List[int]], values: Union[TimeS
f"Could not update timeseries, Combination of indices of type '{type(indices)}' and values of type '{type(values)}' is not supported"
)

def __eq__(self, other) -> bool:
def __eq__(self, other: object) -> bool:
if not isinstance(other, TimeSeries):
return NotImplemented
return bool(
# Check that all values are either both NaN or equal
all([np.isnan(other) and np.isnan(this) or other == this for this, other in zip(self.values, other.values)])
Expand Down Expand Up @@ -281,7 +283,7 @@ def resample(self, freq: Frequency) -> Self:
unit=self.unit,
)

def __mul__(self, other) -> Self:
def __mul__(self, other: object) -> Self:
if not isinstance(other, TimeSeriesBoolean):
raise TypeError(
f"TimeSeriesBoolean can only be multiplied by another TimeSeriesBoolean. Received type '{str(other.__class__)}'."
Expand Down Expand Up @@ -365,7 +367,7 @@ def resample(self, freq: Frequency) -> Self:
unit=self.unit,
)

def __truediv__(self, other) -> TimeSeriesRate:
def __truediv__(self, other: object) -> TimeSeriesRate:
if not isinstance(other, TimeSeriesVolumesCumulative):
raise TypeError(f"Dividing TimeSeriesVolumesCumulative by '{str(other.__class__)}' is not supported.")

Expand Down Expand Up @@ -494,7 +496,7 @@ def to_rate(self, regularity: List[float] = None) -> TimeSeriesRate:


class TimeSeriesIntensity(TimeSeries[float]):
def resample(self, freq: Frequency):
def resample(self, freq: Frequency) -> TimeSeriesIntensity:
"""
Resample emission intensity according to given frequency.
Slinear is used in order to only interpolate, not extrapolate.
Expand Down Expand Up @@ -539,7 +541,7 @@ class TimeSeriesRate(TimeSeries[float]):
regularity: Optional[List[float]]

@validator("regularity", pre=True, always=True)
def set_regularity(cls, regularity, values):
def set_regularity(cls, regularity: List[float], values: List[float]) -> List[float]:
return regularity or [1] * len(values.get("values"))

def __add__(self, other: TimeSeriesRate) -> Self:
Expand Down Expand Up @@ -754,7 +756,9 @@ def __getitem__(self, indices: Union[slice, int, List[int], np.ndarray]) -> Time
f"Unsupported indexing operation. Got '{type(indices)}', expected indices as a slice, single index or a list of indices"
)

def __eq__(self, other) -> bool:
def __eq__(self, other: object) -> bool:
if not isinstance(other, TimeSeriesRate):
raise NotImplementedError
return bool(
# Check that all values are either both NaN or equal
all([np.isnan(other) and np.isnan(this) or other == this for this, other in zip(self.values, other.values)])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class Config:
arbitrary_types_allowed = True

@abstractmethod
def extend(self, other) -> ConsumerFunctionResultBase:
def extend(self, other: object) -> ConsumerFunctionResultBase:
...


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def __init__(
raise IncompatibleDataError(message=message)

@property
def number_of_consumers(self):
def number_of_consumers(self) -> int:
return len(self.consumers)

@abstractmethod
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ class Config:

@root_validator
def check_list_length(cls, values):
def _log_error(field: str, field_values: List[np.ndarray], n_rates) -> None:
def _log_error(field: str, field_values: List[np.ndarray], n_rates: int) -> None:
error_message = (
f"All attributes in a consumer system operational setting must have the same number of elements"
f"(corresponding to the number of consumers). The number of elements in {field} "
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class ConsumerSystemComponentResult(BaseModel):
consumer_model_result: Union[PumpModelResult, CompressorTrainResult]

@property
def energy_usage(self):
def energy_usage(self) -> List[Optional[float]]:
return self.consumer_model_result.energy_usage

@property
Expand All @@ -35,7 +35,7 @@ def power(self) -> np.ndarray:
return np.zeros_like(self.consumer_model_result.energy_usage)

@property
def rate(self):
def rate(self) -> List[Optional[float]]:
return self.consumer_model_result.rate


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ def evaluate_turbine_based_on_compressor_model_result(

def _calculate_remaining_capacity_in_train_given_standard_rate(
self, standard_rate: float, suction_pressure: float, discharge_pressure: float, max_power: float
):
) -> float:
"""Expression used in optimization to find the rate that utilizes the compressor trains capacity."""
return self.compressor_model.evaluate_rate_ps_pd(
rate=np.asarray([standard_rate]),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Union
from typing import List, Tuple, Union

import numpy as np
import pandas as pd
Expand Down Expand Up @@ -453,9 +453,9 @@ def _get_minimum_rates(
lower_rate_qh_lower_pd_function: interp1d,
lower_rate_qh_upper_ps_function: interp1d,
minimum_rate_function: LinearInterpolatorSimplicesDefined,
suction_pressure,
discharge_pressure,
):
suction_pressure: Union[np.ndarray, List[float]],
discharge_pressure: Union[np.ndarray, List[float]],
) -> Tuple[np.ndarray, np.ndarray, LinearInterpolatorSimplicesDefined]:
pd_projected = np.fmax(discharge_pressure, lower_rate_qh_lower_pd_function(suction_pressure))
ps_projected = np.fmin(suction_pressure, lower_rate_qh_upper_ps_function(pd_projected))
minimum_rates = minimum_rate_function(ps_projected, pd_projected)
Expand Down Expand Up @@ -632,7 +632,7 @@ def _setup_minimum_pd_projection_functions(
rate_axis: int = 0,
ps_axis: int = 1,
pd_axis: int = 2,
):
) -> Tuple[interp1d, interp1d, LinearInterpolatorSimplicesDefined]:
"""Function wich returns functions to be used for computations of the minimum
discharge pressure for a given (rate, suction pressure) point.
These are to be used to set the actual discharge pressure to minimum discharge
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ def evaluate(
outlet_stream,
) = calculate_outlet_pressure_and_stream(
polytropic_efficiency=polytropic_efficiency,
polytropic_head_J_per_kg=polytropic_head_J_per_kg,
polytropic_head_joule_per_kg=polytropic_head_J_per_kg,
inlet_stream=inlet_stream_compressor,
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,24 @@ def calculate_power_in_megawatt(

def calculate_outlet_pressure_and_stream(
polytropic_efficiency: float,
polytropic_head_J_per_kg: float, # noqa
polytropic_head_joule_per_kg: float,
inlet_stream: FluidStream,
) -> Tuple[float, FluidStream]:
""":param polytropic_efficiency: (0, 1]
:param polytropic_head_J_per_kg:
:param inlet_stream:
:return:
"""
Args:
polytropic_efficiency: Allowed values (0, 1]
polytropic_head_joule_per_kg:
inlet_stream:
Returns:
"""

outlet_pressure_this_stage_bara_based_on_inlet_z_and_kappa = calculate_outlet_pressure_campbell(
kappa=inlet_stream.kappa,
polytropic_efficiency=polytropic_efficiency,
polytropic_head_fluid_Joule_per_kg=polytropic_head_J_per_kg,
polytropic_head_fluid_Joule_per_kg=polytropic_head_joule_per_kg,
molar_mass=inlet_stream.molar_mass_kg_per_mol,
z_inlet=inlet_stream.z,
inlet_temperature_K=inlet_stream.temperature_kelvin,
Expand All @@ -59,7 +65,7 @@ def calculate_outlet_pressure_and_stream(

outlet_stream_compressor_current_iteration = inlet_stream.set_new_pressure_and_enthalpy_change(
new_pressure=outlet_pressure_this_stage_bara_based_on_inlet_z_and_kappa,
enthalpy_change_joule_per_kg=polytropic_head_J_per_kg / polytropic_efficiency,
enthalpy_change_joule_per_kg=polytropic_head_joule_per_kg / polytropic_efficiency,
)

outlet_pressure_this_stage_bara = outlet_pressure_this_stage_bara_based_on_inlet_z_and_kappa * 0.95
Expand All @@ -73,7 +79,7 @@ def calculate_outlet_pressure_and_stream(
outlet_pressure_this_stage_bara = calculate_outlet_pressure_campbell(
kappa=kappa_average,
polytropic_efficiency=polytropic_efficiency,
polytropic_head_fluid_Joule_per_kg=polytropic_head_J_per_kg,
polytropic_head_fluid_Joule_per_kg=polytropic_head_joule_per_kg,
molar_mass=inlet_stream.molar_mass_kg_per_mol,
z_inlet=z_average,
inlet_temperature_K=inlet_stream.temperature_kelvin,
Expand All @@ -82,7 +88,7 @@ def calculate_outlet_pressure_and_stream(

outlet_stream_compressor_current_iteration = inlet_stream.set_new_pressure_and_enthalpy_change(
new_pressure=outlet_pressure_this_stage_bara,
enthalpy_change_joule_per_kg=polytropic_head_J_per_kg / polytropic_efficiency,
enthalpy_change_joule_per_kg=polytropic_head_joule_per_kg / polytropic_efficiency,
)

diff = abs(outlet_pressure_previous - outlet_pressure_this_stage_bara) / outlet_pressure_this_stage_bara
Expand All @@ -98,7 +104,7 @@ def calculate_outlet_pressure_and_stream(
f" inlet_z: {inlet_stream.z}."
f" inlet_kappa: {inlet_stream.kappa}."
f" polytropic_efficiency: {polytropic_efficiency}."
f" polytropic_head_J_per_kg: {polytropic_head_J_per_kg}."
f" polytropic_head_joule_per_kg: {polytropic_head_joule_per_kg}."
f" molar_mass_kg_per_mol: {inlet_stream.molar_mass_kg_per_mol}."
f" inlet_temperature_kelvin: {inlet_stream.temperature_kelvin}."
f" inlet_pressure_bara: {inlet_stream.pressure_bara}."
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Callable
from typing import Callable, Union

import numpy as np
from libecalc.common.logger import logger
Expand Down Expand Up @@ -91,7 +91,7 @@ def secant_method(
minimum_x_value = min(x0, x1)
maximum_x_value = max(x0, x1)

def limit_to_bounds(x, x_min, x_max):
def limit_to_bounds(x: Union[int, float], x_min: Union[int, float], x_max: Union[int, float]) -> Union[int, float]:
return max(min(x, x_max), x_min) if bounded_to_input_x_interval else x

x2 = np.nan # Dummy value before iteration
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

from typing import Optional

import numpy as np
from libecalc import dto
from libecalc.common.units import Unit
Expand Down Expand Up @@ -28,7 +30,7 @@ def __init__(
)

@property
def max_power(self):
def max_power(self) -> Optional[float]:
return (
self._maximum_load * self.data_transfer_object.energy_usage_adjustment_factor
- self.data_transfer_object.energy_usage_adjustment_constant
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
IGNORED_ZIP_CONTENTS_KEYWORDS = [".DS_Store", "__MACOSX"]


def is_main_yaml_file(file: IO):
def is_main_yaml_file(file: IO) -> bool:
"""Deprecated. To be removed when zip is verified.
:param file:
:return:
Expand Down

0 comments on commit 08394a3

Please sign in to comment.