Skip to content

Commit

Permalink
changed tests, search changes with !ATTN
Browse files Browse the repository at this point in the history
  • Loading branch information
Alina Voilova committed Sep 16, 2024
1 parent 9564f54 commit fb4397e
Show file tree
Hide file tree
Showing 11 changed files with 296 additions and 199 deletions.
12 changes: 10 additions & 2 deletions portfolyo/core/pfline/interop.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,16 +224,24 @@ def _check_unit(
if isinstance(v, float | int):
if dim is not tools.unit.NAMES_AND_DIMENSIONS["nodim"]:
raise DimensionalityError(
"Float or int only allowed for dimensionless value. To specify a physical quantity, add a unit."
dim,
tools.unit.NAMES_AND_DIMENSIONS["nodim"],
extra_msg="Float or int only allowed for dimensionless value. To specify a physical quantity, add a unit.",
)
else:
return float(v)

elif isinstance(v, tools.unit.Q_):
if not v.dimensionality == dim:
raise DimensionalityError(
f"Incorrect dimension for this attribute; expected {dim}, got {v.dimensionality}"
dim,
v.pint.dimensionality,
extra_msg=f"Incorrect dimension for this attribute; expected {dim}, got {v.pint.dimensionality}",
)
# if the dim is nodim, we retun float
elif v.dimensionality == tools.unit.NAMES_AND_DIMENSIONS["nodim"]:
return float(v)
# else
else:
return v

Expand Down
11 changes: 10 additions & 1 deletion portfolyo/core/pfstate/pfstate_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from ... import tools
from ..pfline import Kind, PfLine, create
from portfolyo.tools.unit import Q_


def make_pflines(
Expand Down Expand Up @@ -67,7 +68,15 @@ def prepare_unsourcedprice(unsourcedprice: Any, ref_idx: pd.DatetimeIndex) -> Pf

def prepare_sourced(sourced: Any, ref_idx: pd.DatetimeIndex) -> PfLine:
if sourced is None:
return create.flatpfline(pd.DataFrame({"q": 0, "r": 0}, ref_idx))
return create.flatpfline(
pd.DataFrame(
{
"q": [Q_(0, "MWh") for _ in range(len(ref_idx))],
"r": [Q_(0, "Eur") for _ in range(len(ref_idx))],
},
ref_idx,
)
)

sourced = create.pfline(sourced)
if sourced.kind is not Kind.COMPLETE:
Expand Down
3 changes: 2 additions & 1 deletion portfolyo/tools/unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,8 @@ def avoid_frame_of_objects(fr: Series_or_DataFrame) -> Series_or_DataFrame:
return fr
if hasattr(fr, "pint"):
if isinstance(fr.dtype, pint_pandas.PintType):
return fr
# Ensure the magnitudes are floats too.
return fr.pint.magnitude.astype(float).astype(f"pint[{fr.pint.units}]")
# We may have a series of pint quantities. Convert to pint-series, if possible.
try:
return fr.astype(f"pint[{fr.iloc[0].units}]")
Expand Down
20 changes: 16 additions & 4 deletions tests/core/pfline/test_flat.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,13 +87,25 @@ def test_flatpfline_access(columns: str, available: str, constructor: type):
series[freq] = {"i": idx, "w": w, "q": q, "p": p, "r": q * p}


@pytest.mark.parametrize(
"columns, dtype",
[("w", "pint[MW]"), ("q", "pint[MWh]"), ("p", "pint[Eur/MWh]"), ("r", "pint[Eur]")],
)
@pytest.mark.parametrize("freq_in", ["MS", "D", "15min"])
@pytest.mark.parametrize("freq_out", ["MS", "D", "15min"])
@pytest.mark.parametrize("columns", ["w", "q", "p", "pw", "wr"])
def test_flatpfline_asfreqcorrect1(freq_in: str, freq_out: str, columns: str):
def test_flatpfline_asfreqcorrect1(
freq_in: str, freq_out: str, columns: str, dtype: str
):
"""Test if changing frequency is done correctly (when it's possible), for uniform pflines."""
pfl_in = create.flatpfline({col: series[freq_in][col] for col in columns})
expected_out = create.flatpfline({col: series[freq_out][col] for col in columns})
# pfl_in = create.flatpfline({col: series[freq_in][col] for col in columns})
# !ATTN: before there were double columns such as pw or wr
pfl_in = create.flatpfline(
{col: series[freq_in][col].astype(dtype) for col in columns}
)

expected_out = create.flatpfline(
{col: series[freq_out][col].astype(dtype) for col in columns}
)
pfl_out = pfl_in.asfreq(freq_out)
assert pfl_out == expected_out

Expand Down
13 changes: 9 additions & 4 deletions tests/core/pfline/test_flat_helper.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from typing import Any

import pandas as pd
from pint import DimensionalityError
import pytest

from portfolyo import dev, testing
Expand Down Expand Up @@ -51,25 +52,29 @@ def test_makedataframe_freqtz(freq, tz):
(DF[["w", "q"]], DF[["w", "q"]]),
({"w": DF["w"]}, DF[["w", "q"]]),
({"w": DF["w"], "q": DF["q"]}, DF[["w", "q"]]),
({"w": DF["w"].pint.m}, DF[["w", "q"]]),
({"w": DF["w"].pint.m}, DimensionalityError),
(DF["w"], DF[["w", "q"]]),
([DF["w"], DF["q"]], DF[["w", "q"]]),
(DF[["p"]], DF[["p"]]),
({"p": DF["p"].pint.m}, DF[["p"]]),
({"p": DF["p"].pint.m}, DimensionalityError),
(DF[["r"]], DF[["r"]]),
({"r": DF["r"].pint.m}, DF[["r"]]),
({"r": DF["r"].pint.m}, DimensionalityError),
(DF, DF),
(DF[["w", "p"]], DF),
(DF[["w", "p", "q"]], DF),
(DF[["r", "w"]], DF),
({"r": DF["r"].pint.m, "w": DF["w"]}, DF),
({"r": DF["r"].pint.m, "w": DF["w"]}, DimensionalityError),
([DF["r"], DF["w"]], DF),
]


@pytest.mark.parametrize("data,expected", TESTCASES_INPUTTYPES)
def test_makedataframe_inputtypes(data: Any, expected: pd.DataFrame):
"""Test if dataframe can be created from various input types."""
if type(expected) is type and issubclass(expected, Exception):
with pytest.raises(expected):
_ = flat_helper._dataframe(data)
return
result = flat_helper._dataframe(data)
testing.assert_frame_equal(result, expected)

Expand Down
Loading

0 comments on commit fb4397e

Please sign in to comment.