harbor run -t openthoughts/tasktrove-exp-flat25-pseudocode-v2-5k-pseudocode-4354harbor download openthoughts/tasktrove-exp-flat25-pseudocode-v2-5k-pseudocode-4354PSEUDOCODE SPECIFICATION
Module: zoo/chronos/data/tsdataset.py
Class TSDataset
Attributes
Class methods
from_pandas(df, dt_col, target_col, extra_feature_col=None, id_col=None, with_split=False, val_ratio=0.1, test_ratio=0.1, largest_look_back=None, largest_horizon=None)
// Input validation
ensure dt_col is string
if target_col is string: target_cols <- [target_col]
else: target_cols <- list(target_col)
if extra_feature_col is None: extra_cols <- []
else if string: extra_cols <- [extra_feature_col]
else: extra_cols <- list(extra_feature_col)
if id_col is None:
id_list <- ['0'] // single-id scenario
_id_col <- None
else:
id_list <- unique values of df[id_col] cast to string
_id_col <- id_col
// Datetime interpretation
try_parse_result <- attempt to convert df[dt_col] to datetime
_is_pd_datetime <- parsed_success
// Initialize base instance data
instance <- new TSDataset
instance._raw_df <- df.copy()
instance._dt_col <- dt_col
instance._id_list <- id_list
instance._feature_col <- extra_cols
instance._target_col <- target_cols
instance._extra_feature_col <- extra_cols
instance._id_col <- _id_col
instance._is_pd_datetime <- _is_pd_datetime
instance._rolled <- False
instance._scaler <- None
instance._split_kind <- 'single' if not with_split else 'split'
if with_split is True:
N <- df.shape[0]
val_num <- floor(N * val_ratio)
test_num <- floor(N * test_ratio)
train_df <- df.iloc[0 : N - val_num - test_num]
valid_df <- df.iloc[N - val_num - test_num : N - test_num]
test_df <- df.iloc[N - test_num : N]
// Recursively create split datasets without further splitting
ts_train <- from_pandas(train_df, dt_col, target_col, extra_feature_col, id_col=None,
with_split=False, largest_look_back=largest_look_back,
largest_horizon=largest_horizon)
ts_valid <- from_pandas(valid_df, dt_col, target_col, extra_feature_col, id_col=None,
with_split=False, largest_look_back=largest_look_back,
largest_horizon=largest_horizon)
ts_test <- from_pandas(test_df, dt_col, target_col, extra_feature_col, id_col=None,
with_split=False, largest_look_back=largest_look_back,
largest_horizon=largest_horizon)
// Ensure independent copies
instance._split_by_train <- ts_train
instance._split_by_valid <- ts_valid
instance._split_by_test <- ts_test
// Return three TSDataset objects
return (ts_train, ts_valid, ts_test)
else:
// Non-split mode: return single configured instance
return instance
Instance methods
roll(lookback, horizon, feature_col=None, target_col=None, id_sensitive=False)
// Determine feature/target sets for this roll
feats <- feature_col if provided else self._feature_col
targets <- target_col if provided else self._target_col
ids <- self._id_list
X_list <- empty list
Y_list <- empty list
for each id in ids:
df_id <- self.to_pandas()[ self.to_pandas()['id'] == id ]
sort df_id by self._dt_col ascending
for t from lookback to len(df_id) - horizon:
window <- df_id.iloc[(t - lookback) : t]
// Collect exogenous features at each time in window
X_window_feats <- window[feats] (as matrix with shape (lookback, len(feats)))
// Collect targets at each time in window
Y_window_targets <- window[targets] (shape (lookback, len(targets)))
// Build per-step feature vectors
if id_sensitive:
id_index <- index of id in ids
id_onehot <- one_hot_vector(length = len(ids), position = id_index)
// Repeat id_onehot for each time step in window
id_seq <- tile(id_onehot, (lookback, 1))
// Concatenate per time step:
// features at each t: [X_at_t, Y_at_t, id_onehot]
// For window, we flatten across time to shape (lookback, len(feats) + len(targets) + len(ids))
window_feat <- concatenate along last axis: [X_window_feats, Y_window_targets, id_seq]
else:
window_feat <- concatenate along last axis: [X_window_feats, Y_window_targets]
// Append to arrays
X_list.append(window_feat) // shape (lookback, feature_dim_with_or_without_id)
if horizon > 0:
// Y follows horizon steps ahead of window end
Y_slice <- df_id.iloc[t : t + horizon][targets]
Y_list.append(Y_slice.values) // shape (horizon, len(targets))
// Stack results
self._X <- stack(X_list) // shape (num_windows_total, lookback, feature_dim)
if horizon > 0:
self._Y <- stack(Y_list) // shape (num_windows_total, horizon, len(targets))
else:
self._Y <- None
self._rolled <- True
// No explicit return
to_numpy()
if not self._rolled:
raise RuntimeError("roll() must be called before to_numpy()")
return (self._X, self._Y)
to_pandas()
// Return a copy of the underlying raw data subset for this dataset
if self._split_kind == 'split':
// If per-split storage exists, return a copy of the relevant split subset
if self._raw_df_by_split contains 'train' and 'valid' and 'test':
return copy(self._raw_df_by_split[current_context_split])
else:
return copy(self._raw_df) // fallback
else:
return copy(self._raw_df)
impute(mode="last")
if mode != "last": error
df <- self.to_pandas()
// Forward-fill within each id group if id exists
if self._id_col is not None:
df <- df.groupby(self._id_col).ffill()
else:
df <- df.ffill()
self._raw_df <- df.copy()
deduplicate()
df <- self.to_pandas()
df <- df.drop_duplicates()
self._raw_df <- df.copy()
gen_dt_feature()
df <- self.to_pandas()
// Ensure dt_col exists and is datetime
dt <- df[self._dt_col]
dt <- as_datetime(dt) // best-effort; set _is_pd_datetime accordingly
df[self._dt_col] <- dt
// Compute features
df['IS_AWAKE'] <- (dt.time >= 06:00) AND (dt.time <= 22:00) // example semantics
df['IS_BUSY_HOURS'] <- (dt.hour >= 9 AND dt.hour <= 17)
df['HOUR'] <- dt.hour
df['DAY'] <- dt.day
df['IS_WEEKEND'] <- dt.weekday() in {5, 6}
df['WEEKDAY'] <- dt.weekday()
df['MONTH'] <- dt.month
df['DAYOFYEAR'] <- dt.dayofyear
df['WEEKOFYEAR'] <- dt.isocalendar().week (or equivalent)
df['MINUTE'] <- dt.minute
// Update internal structures
new_features <- list of newly created feature column names
for f in new_features:
if f not in self._feature_col:
append f to self._feature_col
self._raw_df <- df.copy()
gen_rolling_feature(settings="minimal", window_size=None)
df <- self.to_pandas()
// Choose window_size (default if None)
ws <- window_size if window_size is not None else 3
// Determine a base numeric column to compute rolling statistics
candidate_cols <- self._feature_col + self._target_col
numeric_cols <- [c for c in candidate_cols if c in df.columns and is_numeric(df[c])]
if numeric_cols is empty:
return // nothing to roll
// Example: compute rolling mean for each numeric column by id
ids <- self._id_list
for col in numeric_cols:
new_col <- "rolling_mean_{}_{}".format(ws, col)
df[new_col] <- NaN
for each id in ids:
segment <- df[df['id'] == id].sort_values(self._dt_col)
rolled <- segment[col].rolling(window=ws, min_periods=1).mean()
df.loc[segment.index, new_col] <- rolled
if new_col(s) were added:
append their names to self._feature_col
self._raw_df <- df.copy()
gen_global_feature()
df <- self.to_pandas()
// Compute a simple global feature(s) across all data
global_mean <- mean of all numeric columns in df (excluding dt and id, as appropriate)
df['GLOBAL_MEAN'] <- global_mean
// If multiple global features desired, compute and append similarly
self._raw_df <- df.copy()
update self._feature_col to include 'GLOBAL_MEAN' and any others
resample(rule, start=None, end=None)
df <- self.to_pandas().copy()
if start is not None or end is not None:
df <- df[(df[self._dt_col] >= start) AND (df[self._dt_col] <= end)]
// Resample per-id
ids <- unique values of df['id'] if 'id' exists else ['0']
res_list <- []
for id_val in ids:
df_id <- df[df['id'] == id_val].sort_values(self._dt_col)
df_id <- df_id.set_index(self._dt_col)
df_res <- df_id.resample(rule).mean().reset_index()
df_res['id'] <- id_val
res_list.append(df_res)
df_res_all <- concatenate(res_list).sort_values([self._dt_col, 'id']).reset_index(drop=True)
self._raw_df <- df_res_all.copy()
// Update internal structures if needed
self._split_kind remains as is
scale(scaler, fit=True)
df <- self.to_pandas()
numeric_cols <- [c for c in df.columns if is_numeric(df[c])]
// Exclude non-scalable columns such as dt_col and id_col
numeric_cols <- numeric_cols excluding self._dt_col and (self._id_col if not None)
data <- df[numeric_cols].values
if fit is True:
self._scaler <- clone(scaler)
scaled <- self._scaler.fit_transform(data)
else:
scaled <- self._scaler.transform(data)
df[numeric_cols] <- scaled
self._raw_df <- df.copy()
unscale()
if self._scaler is None: return
df <- self.to_pandas()
numeric_cols <- [c for c in df.columns if is_numeric(df[c])]
numeric_cols <- numeric_cols excluding self._dt_col and (self._id_col if not None)
data <- df[numeric_cols].values
original <- self._scaler.inverse_transform(data)
df[numeric_cols] <- original
self._raw_df <- df.copy()
unscale_numpy(pred)
if self._scaler is None: raise error
return self._scaler.inverse_transform(pred)
_check_basic_invariants()
df <- self.to_pandas()
assert df is DataFrame
if self._rolled is True:
assert shapes of self._X and self._Y consistent with last roll
assert self._feature_col is not None
assert self._target_col is not None
assert self._dt_col in df.columns
if self._id_col is not None:
assert 'id' column exists (or per-id handling)
Auxiliary accessors and behaviors
to_pandas() returns Pandas DataFrame representing the current raw data subset to_numpy() returns the most recent X, Y produced by the last roll() _check_basic_invariants() is used by tests to validate internal consistency; should raise no exceptions if all good
Notes (design decisions and expectations)
Deliverable