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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FactoryNet Loader - Easy access to hackathon datasets.
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
from factorynet_loader import load_factorynet
|
| 6 |
+
|
| 7 |
+
# Load AURSAD data
|
| 8 |
+
df, metadata = load_factorynet("aursad")
|
| 9 |
+
|
| 10 |
+
# Get specific columns
|
| 11 |
+
setpoints = df[[c for c in df.columns if c.startswith("setpoint_")]]
|
| 12 |
+
efforts = df[[c for c in df.columns if c.startswith("effort_")]]
|
| 13 |
+
feedback = df[[c for c in df.columns if c.startswith("feedback_")]]
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import pandas as pd
|
| 17 |
+
import json
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Tuple, List, Optional, Dict
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
from datasets import load_dataset
|
| 24 |
+
HF_AVAILABLE = True
|
| 25 |
+
except ImportError:
|
| 26 |
+
HF_AVAILABLE = False
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# HuggingFace repo
|
| 30 |
+
HF_REPO = "forgis/factorynet-hackathon"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def load_factorynet(
|
| 34 |
+
dataset: str = "aursad",
|
| 35 |
+
split: str = "train",
|
| 36 |
+
from_hf: bool = True,
|
| 37 |
+
local_path: Optional[Path] = None,
|
| 38 |
+
) -> Tuple[pd.DataFrame, List[Dict]]:
|
| 39 |
+
"""
|
| 40 |
+
Load FactoryNet dataset.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
dataset: "aursad" or "voraus"
|
| 44 |
+
split: "train" (full data) or future splits
|
| 45 |
+
from_hf: If True, load from HuggingFace Hub
|
| 46 |
+
local_path: Local path override
|
| 47 |
+
|
| 48 |
+
Returns:
|
| 49 |
+
df: DataFrame with time series
|
| 50 |
+
metadata: List of episode metadata dicts
|
| 51 |
+
"""
|
| 52 |
+
if from_hf and HF_AVAILABLE:
|
| 53 |
+
return _load_from_hf(dataset, split)
|
| 54 |
+
elif local_path:
|
| 55 |
+
return _load_from_local(local_path, dataset)
|
| 56 |
+
else:
|
| 57 |
+
raise ValueError("Either set from_hf=True or provide local_path")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _load_from_hf(dataset: str, split: str) -> Tuple[pd.DataFrame, List[Dict]]:
|
| 61 |
+
"""Load from HuggingFace Hub."""
|
| 62 |
+
ds = load_dataset(HF_REPO, data_dir=dataset, split=split)
|
| 63 |
+
df = ds.to_pandas()
|
| 64 |
+
|
| 65 |
+
# Try to load metadata
|
| 66 |
+
try:
|
| 67 |
+
from huggingface_hub import hf_hub_download
|
| 68 |
+
meta_file = hf_hub_download(
|
| 69 |
+
repo_id=HF_REPO,
|
| 70 |
+
filename=f"{dataset}/{dataset}_metadata.json",
|
| 71 |
+
repo_type="dataset"
|
| 72 |
+
)
|
| 73 |
+
with open(meta_file) as f:
|
| 74 |
+
metadata = json.load(f)
|
| 75 |
+
except:
|
| 76 |
+
metadata = []
|
| 77 |
+
|
| 78 |
+
return df, metadata
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _load_from_local(local_path: Path, dataset: str) -> Tuple[pd.DataFrame, List[Dict]]:
|
| 82 |
+
"""Load from local files."""
|
| 83 |
+
local_path = Path(local_path)
|
| 84 |
+
|
| 85 |
+
# Find parquet file
|
| 86 |
+
parquet_files = list(local_path.glob(f"**/*{dataset}*factorynet*.parquet"))
|
| 87 |
+
if not parquet_files:
|
| 88 |
+
parquet_files = list(local_path.glob("**/*.parquet"))
|
| 89 |
+
|
| 90 |
+
if not parquet_files:
|
| 91 |
+
raise FileNotFoundError(f"No parquet files found in {local_path}")
|
| 92 |
+
|
| 93 |
+
df = pd.read_parquet(parquet_files[0])
|
| 94 |
+
|
| 95 |
+
# Load metadata
|
| 96 |
+
meta_files = list(local_path.glob(f"**/*{dataset}*metadata*.json"))
|
| 97 |
+
if meta_files:
|
| 98 |
+
with open(meta_files[0]) as f:
|
| 99 |
+
metadata = json.load(f)
|
| 100 |
+
else:
|
| 101 |
+
metadata = []
|
| 102 |
+
|
| 103 |
+
return df, metadata
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def get_episode(df: pd.DataFrame, episode_id: str) -> pd.DataFrame:
|
| 107 |
+
"""Extract a single episode from the dataset."""
|
| 108 |
+
return df[df["episode_id"] == episode_id].copy()
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def get_episodes_by_fault(df: pd.DataFrame, metadata: List[Dict], fault_type: str) -> pd.DataFrame:
|
| 112 |
+
"""Get all episodes of a specific fault type."""
|
| 113 |
+
fault_episodes = [m["episode_id"] for m in metadata if m.get("fault_type") == fault_type]
|
| 114 |
+
return df[df["episode_id"].isin(fault_episodes)].copy()
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def extract_features(df: pd.DataFrame, window_size: int = 100) -> np.ndarray:
|
| 118 |
+
"""
|
| 119 |
+
Extract basic features for anomaly detection.
|
| 120 |
+
|
| 121 |
+
Returns array of shape (n_windows, n_features).
|
| 122 |
+
"""
|
| 123 |
+
# Get signal columns
|
| 124 |
+
signal_cols = [c for c in df.columns if any(
|
| 125 |
+
c.startswith(p) for p in ["setpoint_", "effort_", "feedback_"]
|
| 126 |
+
)]
|
| 127 |
+
|
| 128 |
+
data = df[signal_cols].values
|
| 129 |
+
|
| 130 |
+
# Sliding window features
|
| 131 |
+
n_windows = len(data) // window_size
|
| 132 |
+
features = []
|
| 133 |
+
|
| 134 |
+
for i in range(n_windows):
|
| 135 |
+
window = data[i * window_size : (i + 1) * window_size]
|
| 136 |
+
# Basic stats per column
|
| 137 |
+
feat = np.concatenate([
|
| 138 |
+
window.mean(axis=0), # Mean
|
| 139 |
+
window.std(axis=0), # Std
|
| 140 |
+
window.max(axis=0), # Max
|
| 141 |
+
window.min(axis=0), # Min
|
| 142 |
+
np.abs(np.diff(window, axis=0)).mean(axis=0), # Mean absolute diff
|
| 143 |
+
])
|
| 144 |
+
features.append(feat)
|
| 145 |
+
|
| 146 |
+
return np.array(features)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def compute_causal_residual(df: pd.DataFrame, axis: int = 0) -> pd.Series:
|
| 150 |
+
"""
|
| 151 |
+
Compute causal residual: effort that can't be explained by setpoint.
|
| 152 |
+
|
| 153 |
+
High residual = anomaly (effort without command, or command without effort).
|
| 154 |
+
"""
|
| 155 |
+
setpoint = df[f"setpoint_pos_{axis}"]
|
| 156 |
+
effort = df[f"effort_torque_{axis}"] if f"effort_torque_{axis}" in df.columns else df[f"effort_current_{axis}"]
|
| 157 |
+
|
| 158 |
+
# Simple approach: effort should correlate with setpoint change
|
| 159 |
+
setpoint_diff = setpoint.diff().abs()
|
| 160 |
+
effort_normalized = (effort - effort.mean()) / effort.std()
|
| 161 |
+
|
| 162 |
+
# Residual: effort that doesn't match setpoint activity
|
| 163 |
+
residual = effort_normalized - setpoint_diff / (setpoint_diff.max() + 1e-6)
|
| 164 |
+
|
| 165 |
+
return residual
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
# Quick test
|
| 169 |
+
if __name__ == "__main__":
|
| 170 |
+
print("Testing FactoryNet loader...")
|
| 171 |
+
|
| 172 |
+
# Try local load
|
| 173 |
+
try:
|
| 174 |
+
df, meta = load_factorynet("aursad", from_hf=False,
|
| 175 |
+
local_path=Path(__file__).parent.parent / "output" / "aursad_real")
|
| 176 |
+
print(f"Loaded {len(df)} rows, {len(df.columns)} columns")
|
| 177 |
+
print(f"Metadata for {len(meta)} episodes")
|
| 178 |
+
print(f"Columns: {df.columns.tolist()[:10]}...")
|
| 179 |
+
|
| 180 |
+
# Test feature extraction
|
| 181 |
+
features = extract_features(df)
|
| 182 |
+
print(f"Extracted features: {features.shape}")
|
| 183 |
+
|
| 184 |
+
except Exception as e:
|
| 185 |
+
print(f"Local load failed: {e}")
|
| 186 |
+
print("Try: pip install datasets && load with from_hf=True")
|