class Upsample(base.Op):
id = "upsample"
title = _("Upsample")
description = _(
"One row per time interval (finer than the data): new rows are filled forward, "
"backward, from the nearest row, interpolated or left missing."
)
category = categories.TIMESERIES
icon = "mdi.chart-timeline-variant-shimmer"
class Params(base.Params):
time_column: str = _time_field()
rule: str = Field("1s", title=N_("Interval"), min_length=1, description=FREQ_DESCRIPTION)
method: Literal["asfreq", "ffill", "bfill", "nearest", "interpolate"] = Field(
"ffill", title=N_("Fill new rows")
)
@classmethod
def apply(cls, params: Params, *inputs: Frame) -> Frame:
frame = inputs[0]
_check_column(frame, params.time_column)
resampler = frame.set_index(params.time_column).resample(params.rule)
return getattr(resampler, params.method)().reset_index()
@classmethod
def to_code(cls, params: Params, inputs: Sequence[str], output: str) -> str:
var = inputs[0]
column, rule = base.literal(params.time_column), base.literal(params.rule)
return (
f"{output} = {var}.set_index({column}).resample({rule}).{params.method}().reset_index()"
)
@classmethod
def from_code(cls, stmt: ast.stmt, bound: Mapping[str, Any]) -> base.Match | None:
assign = base.assignment(stmt)
if assign is None:
return None
chain = series.unchain(assign[1])
if chain is None:
return None
root, links = chain
if not (
isinstance(root, ast.Name)
and root.id in bound
and len(links) == 4 # noqa: PLR2004
and [link.name for link in (links[0], links[1], links[3])]
== ["set_index", "resample", "reset_index"]
and all(link.kind == "call" and len(link.args) <= 1 for link in links)
and links[0].args
and links[1].args
):
return None
try:
column = base.literal_value(links[0].args[0])
rule = base.literal_value(links[1].args[0])
params = cls.Params(time_column=column, rule=rule, method=links[2].name) # ty: ignore[invalid-argument-type]
except ValueError:
return None
return series.confirm(cls, params, [root.id], assign[0], stmt)