Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: improve readability #419

Merged
merged 3 commits into from
Mar 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 107 additions & 51 deletions src/phoenix/metrics/timeseries.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from datetime import datetime, timedelta
from functools import partial
from itertools import accumulate, chain, repeat, takewhile
from typing import Any, Callable, Iterable, Iterator, List, Tuple, cast
from itertools import accumulate, repeat
from typing import Any, Callable, Iterable, Iterator, Tuple, cast

import pandas as pd
from typing_extensions import TypeAlias
Expand Down Expand Up @@ -33,7 +33,10 @@ def timeseries(
)


def _calculate(df: pd.DataFrame, calcs: Iterable[Metric]) -> "pd.Series[Any]":
def _calculate(
df: pd.DataFrame,
calcs: Iterable[Metric],
) -> "pd.Series[Any]":
"""
Calculates each metric on the dataframe.
"""
Expand All @@ -45,12 +48,17 @@ def _calculate(df: pd.DataFrame, calcs: Iterable[Metric]) -> "pd.Series[Any]":


def row_interval_from_sorted_time_index(
idx: pd.Index, start: datetime, end: datetime
time_index: pd.Index,
time_start: datetime,
time_stop: datetime,
) -> Tuple[StartIndex, StopIndex]:
"""
Returns end exclusive time slice from sorted index.
"""
return cast(Tuple[StartIndex, StopIndex], idx.searchsorted((start, end)))
return cast(
Tuple[StartIndex, StopIndex],
time_index.searchsorted((time_start, time_stop)),
)


def _aggregator(
Expand All @@ -65,66 +73,59 @@ def _aggregator(
"""
Calls groupby on the dataframe and apply metric calculations on each group.
"""
calcs: Tuple[Metric, ...] = tuple(metrics)
input_column_indices: List[int] = sorted(
{
dataframe.columns.get_loc(column_name)
for calc in calcs
for column_name in calc.input_column_names()
}
)
calcs = tuple(metrics)
unique_input_column_indices = set()
for calc in calcs:
for column_name in calc.input_column_names():
column_index = dataframe.columns.get_loc(column_name)
unique_input_column_indices.add(column_index)
input_column_indices = sorted(unique_input_column_indices)
# need at least one column in the dataframe, so take the first one
# if input_column_indices is empty
if len(input_column_indices) == 0:
input_column_indices = [0]
dataframe = dataframe.iloc[:, input_column_indices]
return pd.concat(
chain(
(pd.DataFrame(),),
(
dataframe.iloc[
slice(*row_interval_from_sorted_time_index(dataframe.index, start, end)),
input_column_indices or [0], # need at least one, so take the first one
]
.groupby(group, group_keys=True)
.apply(partial(_calculate, calcs=calcs))
.loc[start_time:end_time, :] # type: ignore # slice has no overload for datetime
for start, end, group in _groupers(
start_time=start_time,
end_time=end_time,
evaluation_window=evaluation_window,
sampling_interval=sampling_interval,
)
),
_results(
calcs=calcs,
dataframe=dataframe,
start_time=start_time,
end_time=end_time,
evaluation_window=evaluation_window,
sampling_interval=sampling_interval,
),
verify_integrity=True,
)


StartTime: TypeAlias = datetime
EndTime: TypeAlias = datetime
Comment on lines +101 to +102
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the benefit of this? Honest question. The way I see it: It forces me to have more information and reference this type, vs knowing in code that the type is datetime

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably tenuous but mostly intended to give names to the return signature (like how you can name return variables in go)

Iterator[Tuple[StartTime, EndTime, pd.Grouper]]

vs

Iterator[Tuple[datetime, datetime, pd.Grouper]]



def _groupers(
start_time: datetime,
end_time: datetime,
evaluation_window: timedelta,
sampling_interval: timedelta,
) -> Iterator[Tuple[datetime, datetime, pd.Grouper]]:
) -> Iterator[Tuple[StartTime, EndTime, pd.Grouper]]:
"""
Yields pandas.Groupers from time series parameters.
"""
if not sampling_interval:
return
total_time_span = end_time - start_time
divisible = evaluation_window % sampling_interval == timedelta()
max_offset = end_time - start_time
if divisible and evaluation_window < max_offset:
if divisible and evaluation_window < total_time_span:
max_offset = evaluation_window
yield from (
(
(start_time if divisible else end_time - offset) - evaluation_window,
end_time - offset,
pd.Grouper( # type: ignore # mypy finds the wrong Grouper
freq=evaluation_window,
origin=end_time,
offset=-offset,
# Each point in timeseries will be labeled by the end instant of
# its evaluation window.
label="right",
sort=False,
),
)
else:
max_offset = total_time_span
offsets = accumulate(
repeat(sampling_interval),
initial=timedelta(),
)
for offset in offsets:
if offset >= max_offset:
return
# Each Grouper is like a row in a brick wall, where each brick is an
# evaluation window. By shifting each row of bricks by the sampling
# interval, we can get all the brick's right edges to line up with the
Expand All @@ -140,8 +141,63 @@ def _groupers(
# ┌─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐ combine into
# └─┴─┴─┴─┴─┴─┴─┴─┴─┴2┴1┘0 final time series
#
for offset in takewhile(
lambda offset: offset < max_offset,
accumulate(repeat(sampling_interval), initial=timedelta()),
grouper = pd.Grouper( # type: ignore # mypy finds the wrong Grouper
freq=evaluation_window,
origin=end_time,
offset=-offset,
# Each point in timeseries will be labeled by the end instant of
# its evaluation window.
label="right",
sort=False,
)
)
time_stop = end_time - offset
if divisible:
time_start = start_time - evaluation_window
else:
time_start = time_stop - evaluation_window
yield (
time_start,
time_stop,
grouper,
)


def _results(
calcs: Iterable[Metric],
dataframe: pd.DataFrame,
start_time: datetime,
end_time: datetime,
evaluation_window: timedelta,
sampling_interval: timedelta,
) -> Iterator[pd.DataFrame]:
"""
Yields metric results for each data point in time series.
"""
yield pd.DataFrame()
calculate_metrics = partial(_calculate, calcs=calcs)
# pandas time indexing is end-inclusive
result_slice = slice(start_time, end_time)
for (
time_start, # inclusive
time_stop, # exclusive
group,
) in _groupers(
start_time=start_time,
end_time=end_time,
evaluation_window=evaluation_window,
sampling_interval=sampling_interval,
):
row_start, row_stop = row_interval_from_sorted_time_index(
time_index=dataframe.index,
time_start=time_start, # inclusive
time_stop=time_stop, # exclusive
)
# pandas row indexing is stop-exclusive
row_slice = slice(row_start, row_stop)
filtered = dataframe.iloc[row_slice, :]
yield filtered.groupby(
group,
group_keys=True,
).apply(
calculate_metrics,
).loc[result_slice, :]
6 changes: 3 additions & 3 deletions src/phoenix/server/api/types/EmbeddingDimension.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,9 +191,9 @@ def UMAPPoints(
row_id_start, row_id_stop = 0, len(dataframe)
if dataset_id == DatasetType.PRIMARY:
row_id_start, row_id_stop = row_interval_from_sorted_time_index(
dataframe.index,
start=time_range.start,
end=time_range.end,
time_index=dataframe.index,
time_start=time_range.start,
time_stop=time_range.end,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
time_stop=time_range.end,
time_end=time_range.end,

Copy link
Contributor Author

@RogerHYang RogerHYang Mar 24, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

stop was intended to emphasize its end exclusive-ness, matching the terminology in the range built-in

class range(start, stop, step=1)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My 2 cents: I think end is more clear even with the note about exclusivity

Copy link
Contributor Author

@RogerHYang RogerHYang Mar 24, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will stay with stop, given the ambiguity with end. see JavaScript below.

const result = endOfHour(new Date(2014, 8, 2, 11, 55))
//=> Tue Sep 02 2014 11:59:59.999

Comment on lines +195 to +196
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
time_start=time_range.start,
time_stop=time_range.end,
start_time=time_range.start,
end_time=time_range.end,

to match _results in timeseries?

)
vector_column = dataset.get_embedding_vector_column(self.name)
for row_id in range(row_id_start, row_id_stop)[:n_samples]:
Expand Down