Skip to content

Time-Series Similarity, Physics Attractors & Analog Clustering (scale_forecasting.similarity)

flowchart TD
    S1["1. Multi-Lens & Multi-Modal Embedding Extraction<br/>7 lenses: hybrid · physics_attractor · spectral_phase · elastic_dtw · minirocket · structural_signature · foundation_latent<br/>+ text_cols (TF-IDF) · attribute_cols ( Gower ) · hierarchy_cols (LCA)"] --> S2["2. Symmetric PSD Similarity & Lead-Lag Discovery<br/>compute_similarity_matrix · S_{i,i} = 1, S_{i,j} in [0, 1] · Kuramoto phase & lead-lag tau*"]
    S2 --> S3["3. Spectral Clustering & Digital-Twin Search<br/>cluster_by_similarity_df · find_similar_series_df · match_cold_start_launch_prefix_df"]
    S3 --> S4["4. Merchandising Intelligence & System-Wide Weaving<br/>recommend_substitutes_df · detect_emerging_trends_df · @similarity_global · @similarity_cold_start · similarity_hierarchy"]

similarity

Time-series similarity, dynamical-systems phase portraits, multiscale/foundation embeddings, clustering, and digital-twin analog search.

This single-capability module implements six specialized similarity lenses plus a default "hybrid" consensus positive-semidefinite (PSD) kernel:

  1. "physics_attractor" — Takens delay-coordinate state-space reconstruction, discrete kinematic phase portraits :math:(y_t, \dot{y}_t, \ddot{y}_t), Sliced Wasserstein attractor cloud distance, Largest Lyapunov divergence exponent (:math:\lambda_{\max}), Permutation Entropy (:math:H_{\text{perm}}), Sample Entropy, and Ornstein-Uhlenbeck mean-reversion damping rate (:math:\kappa_{\text{OU}}).
  2. "spectral_phase" — FFT Hilbert analytic signal :math:z_t = y_t + i\,\mathcal{H}(y_t) = A_t e^{i\theta_t}, pairwise Kuramoto phase-locking order parameter :math:R_{i,j}, Welch power spectral density Jensen-Shannon divergence, and optimal cross-correlation lead-lag shift :math:\tau_{i \to j}^*.
  3. "elastic_dtw" — Scale-normalized Sakoe-Chiba banded Dynamic Time Warping / Time-Warp Edit Distance (TWED) with physical elastic spring stiffness penalty :math:\nu > 0.
  4. "minirocket" — Deterministic pure-NumPy bank of 84 ternary dilated convolutional kernels (:math:\mathbf{w} \in \{-1, 2\}^9, :math:\sum w_k = 0) across exponential dilations with Proportion of Positive Values (PPV) pooling.
  5. "structural_signature" — 24-D standardized econometric feature vector (trend/seasonal strength, peak phase, Hurst exponent :math:H via rescaled-range :math:R/S analysis, ACF lags 1..7, PACF lags 1..3, spectral entropy, Syntetos-Boylan :math:(\log\text{ADI}, \log\text{CV}^2), skewness, kurtosis, ARCH(1) volatility clustering, level-shift ratio, zero-inflation fraction, velocity ratio, curvature ratio).
  6. "foundation_latent" — Pooled context encoder embeddings from pre-trained time-series foundation models (chronos_bolt, chronos2, timesfm_torch) with automatic deterministic fallback to L2-normalized "minirocket" + "structural_signature" embeddings when offline on pure core.
  7. "hybrid" (default) — Consensus fusion of rank-normalized RBF similarity kernels from "physics_attractor" (0.30), "spectral_phase" (0.25), "minirocket" / "elastic_dtw" shape (0.25), and "structural_signature" (0.20), projected onto the nearest symmetric PSD correlation matrix with unit diagonal (:math:S_{i,i} = 1.0, S_{i,j} \in [0, 1]).

SimilarityMatrixResult dataclass

SimilarityMatrixResult(
    matrix_df,
    pairs_df,
    embeddings_df,
    method="hybrid",
    diagnostics=dict(),
)

Result container returned by :func:compute_similarity_matrix.

Attributes:

Name Type Description
matrix_df DataFrame

Symmetric positive-semidefinite :math:(N \times N) DataFrame in :math:[0, 1] with unit diagonal (:math:S_{i,i} = 1.0), indexed and columned by ts_id.

pairs_df DataFrame

Ranked top-:math:K neighbor pairs DataFrame with per-lens similarity attributions (physics_sim, spectral_sim, shape_sim, structural_sim) and lead-lag diagnostics (optimal_lag, lag_correlation).

embeddings_df DataFrame

Per-series physical and econometric invariants plus 2D embedding coordinates.

method str

Canonical similarity method used.

diagnostics dict[str, Any]

Summary diagnostics dictionary (mean similarity, PSD minimum eigenvalue, embedding backend used, series count).

dataframe property

dataframe

Primary tabular view (pairs_df) for ergonomic DataFrame chaining.

to_dict

to_dict()

Serialize the similarity result into a JSON-compatible dictionary.

Source code in src/scale_forecasting/similarity.py
def to_dict(self) -> dict[str, Any]:
    """Serialize the similarity result into a JSON-compatible dictionary."""
    return {
        "n_series": len(self.matrix_df),
        "method": self.method,
        "matrix": self.matrix_df.to_dict(orient="index"),
        "pairs": self.pairs_df.to_dict(orient="records"),
        "embeddings": self.embeddings_df.to_dict(orient="records"),
        "diagnostics": dict(self.diagnostics),
    }

cluster_by_similarity_df

cluster_by_similarity_df(
    panel_df,
    *,
    cfg=None,
    n_clusters="auto",
    method="hybrid",
    min_cluster_size=2,
    max_clusters=8,
    text_cols=None,
    embedding_col=None,
    attribute_cols=None,
    hierarchy_cols=None,
    within_hierarchy_level=None,
    semantic_weight="auto",
    hierarchy_weight="auto",
    ts_id_col="ts_id",
    date_col="ds",
    target_col="y",
    similarity_result=None,
    **kwargs,
)

Partition a panel of time series into coherent similarity clusters via Ward linkage on the PSD similarity kernel, automatically selecting silhouette-optimal :math:K^* when n_clusters="auto" and merging clusters smaller than min_cluster_size.

Source code in src/scale_forecasting/similarity.py
def cluster_by_similarity_df(
    panel_df: pd.DataFrame,
    *,
    cfg: RunConfig | None = None,
    n_clusters: int | Literal["auto"] = "auto",
    method: str = "hybrid",
    min_cluster_size: int = 2,
    max_clusters: int = 8,
    text_cols: Sequence[str] | str | None = None,
    embedding_col: str | None = None,
    attribute_cols: Sequence[str] | None = None,
    hierarchy_cols: Sequence[str] | None = None,
    within_hierarchy_level: str | Sequence[str] | None = None,
    semantic_weight: float | Literal["auto"] = "auto",
    hierarchy_weight: float | Literal["auto"] = "auto",
    ts_id_col: str = "ts_id",
    date_col: str = "ds",
    target_col: str = "y",
    similarity_result: SimilarityMatrixResult | None = None,
    **kwargs: Any,
) -> pd.DataFrame:
    """Partition a panel of time series into coherent similarity clusters via Ward linkage on the
    PSD similarity kernel, automatically selecting silhouette-optimal :math:`K^*` when
    ``n_clusters="auto"`` and merging clusters smaller than ``min_cluster_size``."""
    out_cols = [
        "ts_id",
        "similarity_cluster_id",
        "cluster_int_id",
        "cluster_id",
        "cluster_medoid_ts_id",
        "medoid_ts_id",
        "is_medoid",
        "similarity_to_medoid",
        "cluster_silhouette",
        "silhouette_score",
        "cluster_size",
        "cluster_archetype",
        "cluster_label",
    ]
    sim_res = (
        similarity_result
        if similarity_result is not None
        else compute_similarity_matrix(
            panel_df,
            cfg=cfg,
            method=method,
            text_cols=text_cols,
            embedding_col=embedding_col,
            attribute_cols=attribute_cols,
            hierarchy_cols=hierarchy_cols,
            within_hierarchy_level=within_hierarchy_level,
            semantic_weight=semantic_weight,
            hierarchy_weight=hierarchy_weight,
            ts_id_col=ts_id_col,
            date_col=date_col,
            target_col=target_col,
            **kwargs,
        )
    )
    series_ids = list(sim_res.matrix_df.index)
    n = len(series_ids)
    if n == 0:
        return pd.DataFrame(columns=out_cols)

    is_canopy = bool(sim_res.diagnostics.get("canopy_approximation"))
    eff_min_size = 1 if is_canopy else max(1, int(min_cluster_size))
    sim_mat = sim_res.matrix_df.to_numpy(dtype=np.float64)
    dist_mat = np.sqrt(np.maximum(0.0, 1.0 - sim_mat))
    np.fill_diagonal(dist_mat, 0.0)

    max_feasible_k = min(int(max_clusters), n // eff_min_size if eff_min_size > 1 else n)
    if n <= 2 or max_feasible_k < 2 or (isinstance(n_clusters, int) and n_clusters <= 1):
        labels = np.zeros(n, dtype=np.int64)
    else:
        condensed = sp_distance.squareform(dist_mat, checks=False)
        if np.all(condensed < 1e-9):
            labels = np.zeros(n, dtype=np.int64)
        else:
            linkage = sp_cluster.hierarchy.linkage(condensed, method="ward")
            if n_clusters != "auto":
                req_k = min(int(n_clusters), max(2, max_feasible_k), n)
                raw_labels = (
                    sp_cluster.hierarchy.fcluster(linkage, t=req_k, criterion="maxclust") - 1
                )
                labels = _merge_small_clusters(raw_labels, sim_mat, eff_min_size)
            else:
                best_k = 1
                best_score = -1.0
                best_labels = np.zeros(n, dtype=np.int64)
                for cand_k in range(2, max_feasible_k + 1):
                    cand_raw = (
                        sp_cluster.hierarchy.fcluster(linkage, t=cand_k, criterion="maxclust") - 1
                    )
                    cand_merged = _merge_small_clusters(cand_raw, sim_mat, eff_min_size)
                    if np.unique(cand_merged).size < 2:
                        continue
                    sil_vals = _compute_silhouette_scores(dist_mat, cand_merged)
                    mean_sil = float(np.mean(sil_vals))
                    if mean_sil > best_score + 1e-4:
                        best_score = mean_sil
                        best_k = int(np.unique(cand_merged).size)
                        best_labels = cand_merged
                labels = best_labels if best_k >= 2 else np.zeros(n, dtype=np.int64)

    sil_scores = _compute_silhouette_scores(dist_mat, labels)
    if is_canopy:
        all_ids = sim_res.embeddings_df["ts_id"].to_numpy()
        nearest_anchor_col = np.asarray(sim_res.diagnostics["nearest_anchor_col"], dtype=np.int64)
        max_anchor_sim = np.asarray(sim_res.diagnostics["max_anchor_sim"], dtype=np.float64)
        full_labels = labels[nearest_anchor_col]
        full_sil = sil_scores[nearest_anchor_col]
        uniq_c, counts_c = np.unique(full_labels, return_counts=True)
        size_map = {int(c): int(cnt) for c, cnt in zip(uniq_c, counts_c, strict=False)}
        medoid_sid_by_c: dict[int, str] = {}
        arch_by_c: dict[int, str] = {}
        for c_val in uniq_c:
            c_int = int(c_val)
            a_mask = np.flatnonzero(labels == c_int)
            med_a_idx = int(a_mask[0]) if a_mask.size > 0 else 0
            medoid_sid_by_c[c_int] = series_ids[med_a_idx]
            sub_emb = sim_res.embeddings_df.iloc[np.flatnonzero(full_labels == c_int)[:256]]
            arch_by_c[c_int] = _describe_cluster_archetype(sub_emb)
        max_c = int(np.max(full_labels)) if full_labels.size > 0 else 0
        c_str_lut = np.array([f"cluster_{c}" for c in range(max_c + 1)], dtype=object)
        med_sid_lut = np.array(
            [medoid_sid_by_c.get(c, series_ids[0]) for c in range(max_c + 1)], dtype=object
        )
        arch_lut = np.array(
            [arch_by_c.get(c, "steady_baseline") for c in range(max_c + 1)], dtype=object
        )
        label_lut = np.array(
            [f"cluster_{c}:{arch_by_c.get(c, 'steady_baseline')}" for c in range(max_c + 1)],
            dtype=object,
        )
        size_lut = np.array([size_map.get(c, 0) for c in range(max_c + 1)], dtype=np.int64)
        c_strs = c_str_lut[full_labels]
        med_sids = med_sid_lut[full_labels]
        archs = arch_lut[full_labels]
        c_labels = label_lut[full_labels]
        c_sizes = size_lut[full_labels]
        return pd.DataFrame(
            {
                "ts_id": all_ids,
                "similarity_cluster_id": c_strs,
                "cluster_int_id": full_labels,
                "cluster_id": c_strs,
                "cluster_medoid_ts_id": med_sids,
                "medoid_ts_id": med_sids,
                "is_medoid": all_ids == med_sids,
                "similarity_to_medoid": np.round(max_anchor_sim, 6),
                "cluster_silhouette": np.round(full_sil, 6),
                "silhouette_score": np.round(full_sil, 6),
                "cluster_size": c_sizes,
                "cluster_archetype": archs,
                "cluster_label": c_labels,
            },
            columns=out_cols,
        )

    embed_df = sim_res.embeddings_df.set_index("ts_id")

    # Identify medoid and archetype per cluster
    medoid_by_cluster: dict[int, int] = {}
    archetype_by_cluster: dict[int, str] = {}
    size_by_cluster: dict[int, int] = {}
    for cid in np.unique(labels):
        c_int = int(cid)
        idx_members = np.flatnonzero(labels == c_int)
        size_by_cluster[c_int] = int(idx_members.size)
        sub_sim = sim_mat[np.ix_(idx_members, idx_members)]
        mean_sim_in_c = np.mean(sub_sim, axis=1)
        medoid_local_idx = int(np.argmax(mean_sim_in_c))
        medoid_by_cluster[c_int] = int(idx_members[medoid_local_idx])
        member_sids = [series_ids[i] for i in idx_members]
        archetype_by_cluster[c_int] = _describe_cluster_archetype(embed_df.loc[member_sids])

    rows: list[dict[str, Any]] = []
    for i, sid in enumerate(series_ids):
        c_int = int(labels[i])
        c_str = f"cluster_{c_int}"
        med_idx = medoid_by_cluster[c_int]
        med_sid = series_ids[med_idx]
        sim_to_med = float(sim_mat[i, med_idx])
        sil_val = float(sil_scores[i])
        arch = archetype_by_cluster[c_int]
        rows.append(
            {
                "ts_id": sid,
                "similarity_cluster_id": c_str,
                "cluster_int_id": c_int,
                "cluster_id": c_str,
                "cluster_medoid_ts_id": med_sid,
                "medoid_ts_id": med_sid,
                "is_medoid": bool(i == med_idx),
                "similarity_to_medoid": round(sim_to_med, 6),
                "cluster_silhouette": round(sil_val, 6),
                "silhouette_score": round(sil_val, 6),
                "cluster_size": size_by_cluster[c_int],
                "cluster_archetype": arch,
                "cluster_label": f"{c_str}:{arch}",
            }
        )
    return pd.DataFrame(rows, columns=out_cols)

compute_similarity_matrix

compute_similarity_matrix(
    panel_df,
    *,
    cfg=None,
    method="hybrid",
    top_k=10,
    max_lag=0,
    spring_stiffness=0.05,
    window_frac=0.15,
    n_components=2,
    text_cols=None,
    embedding_col=None,
    attribute_cols=None,
    hierarchy_cols=None,
    within_hierarchy_level=None,
    semantic_weight="auto",
    hierarchy_weight="auto",
    ts_id_col="ts_id",
    date_col="ds",
    target_col="y",
    allow_fallback=True,
    kernel_weights=None,
    max_exact_pairwise_series=2500,
    **kwargs,
)

Compute the symmetric PSD similarity matrix, ranked digital-twin pairs, and per-series physical/econometric embeddings across a time-series panel.

Source code in src/scale_forecasting/similarity.py
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
def compute_similarity_matrix(
    panel_df: pd.DataFrame,
    *,
    cfg: RunConfig | None = None,
    method: str = "hybrid",
    top_k: int = 10,
    max_lag: int = 0,
    spring_stiffness: float = 0.05,
    window_frac: float = 0.15,
    n_components: int = 2,
    text_cols: Sequence[str] | str | None = None,
    embedding_col: str | None = None,
    attribute_cols: Sequence[str] | None = None,
    hierarchy_cols: Sequence[str] | None = None,
    within_hierarchy_level: str | Sequence[str] | None = None,
    semantic_weight: float | Literal["auto"] = "auto",
    hierarchy_weight: float | Literal["auto"] = "auto",
    ts_id_col: str = "ts_id",
    date_col: str = "ds",
    target_col: str = "y",
    allow_fallback: bool = True,
    kernel_weights: dict[str, float] | None = None,
    max_exact_pairwise_series: int = 2500,
    **kwargs: Any,
) -> SimilarityMatrixResult:
    """Compute the symmetric PSD similarity matrix, ranked digital-twin pairs, and per-series
    physical/econometric embeddings across a time-series panel."""
    canon_method = _resolve_similarity_method(method)
    metadata_source_df = kwargs.pop("_metadata_df", None)
    meta_ts_id_col = str(kwargs.pop("_metadata_ts_id_col", ts_id_col))
    meta_target_col = str(kwargs.pop("_metadata_target_col", target_col))

    embed_cols = [
        "ts_id",
        "lyapunov_exp",
        "hurst_exp",
        "perm_entropy",
        "sample_entropy",
        "ou_damping_rate",
        "dominant_period",
        "kuramoto_sync_mean",
        "trend_strength",
        "seasonal_strength",
        "spectral_entropy",
        "adi_log",
        "cv2_log",
        "skewness",
        "kurtosis",
        "arch_volatility",
        "zero_fraction",
        "embed_x",
        "embed_y",
        "embedding_json",
        "embedding_backend_used",
    ]
    pair_cols = [
        "ts_id",
        "neighbor_ts_id",
        "ts_id_a",
        "ts_id_b",
        "rank",
        "similarity_score",
        "similarity",
        "distance",
        "physics_sim",
        "spectral_sim",
        "shape_sim",
        "structural_sim",
        "semantic_sim",
        "hierarchy_sim",
        "optimal_lag",
        "lag_correlation",
        "method",
    ]
    if isinstance(panel_df, pd.DataFrame) and not panel_df.empty and max_exact_pairwise_series > 0:
        eff_ts_col, _, _ = _resolve_cols(panel_df, cfg, ts_id_col, date_col, target_col)
        if eff_ts_col in panel_df.columns and len(panel_df) > max_exact_pairwise_series:
            ts_arr_head = panel_df[eff_ts_col].to_numpy()
            first_v = ts_arr_head[0]
            t_run = int(np.argmax(ts_arr_head[: min(len(ts_arr_head), 512)] != first_v))
            est_n = (
                len(ts_arr_head) // t_run
                if t_run > 0 and len(ts_arr_head) // t_run > max_exact_pairwise_series
                else int(panel_df[eff_ts_col].nunique())
            )
            if est_n > max_exact_pairwise_series:
                return _compute_canopy_similarity_matrix(
                    panel_df,
                    cfg=cfg,
                    canon_method=canon_method,
                    top_k=top_k,
                    n_components=n_components,
                    ts_id_col=ts_id_col,
                    date_col=date_col,
                    target_col=target_col,
                    embed_cols=embed_cols,
                    pair_cols=pair_cols,
                )

    series_ids, series_map = _extract_panel_series(
        panel_df, cfg=cfg, ts_id_col=ts_id_col, date_col=date_col, target_col=target_col
    )
    n = len(series_ids)
    if n == 0:
        return SimilarityMatrixResult(
            matrix_df=pd.DataFrame(),
            pairs_df=pd.DataFrame(columns=pair_cols),
            embeddings_df=pd.DataFrame(columns=embed_cols),
            method=canon_method,
            diagnostics={"n_series": 0, "method": canon_method},
        )

    eff_meta_panel = metadata_source_df if metadata_source_df is not None else panel_df
    meta_df = _extract_series_metadata(
        eff_meta_panel, series_ids, cfg=cfg, ts_id_col=meta_ts_id_col
    )
    valid_obs_counts = _count_valid_panel_obs(
        eff_meta_panel,
        series_ids,
        cfg=cfg,
        ts_id_col=meta_ts_id_col,
        target_col=meta_target_col,
    )

    sem_mat, has_sem = _compute_semantic_similarity_matrix(
        series_ids,
        meta_df,
        text_cols=text_cols,
        embedding_col=embedding_col,
        attribute_cols=attribute_cols,
    )
    hier_mat, has_hier = _compute_hierarchy_lca_matrix(
        series_ids,
        meta_df,
        hierarchy_cols=hierarchy_cols,
        cfg=cfg,
    )
    if not has_sem and n > 1:
        sem_mat = np.eye(n, dtype=np.float64)
    if not has_hier and n > 1:
        hier_mat = np.eye(n, dtype=np.float64)

    # Always compute the core component lenses so per-lens attributions and invariants are populated
    phys_mat, phys_inv = _compute_physics_attractor_matrix(series_ids, series_map)
    spec_mat, lag_mat, corr_mat, spec_meta = _compute_spectral_phase_matrix(
        series_ids, series_map, max_lag=max_lag
    )
    _mr_emb, mr_mat = _compute_minirocket_embeddings_and_matrix(series_ids, series_map)
    st_emb, st_mat, st_meta = _compute_structural_signature_matrix(
        series_ids, series_map, spectral_meta_map=spec_meta
    )

    dtw_mat: np.ndarray | None = None
    if canon_method in ("elastic_dtw", "hybrid") and n <= 150:
        dtw_mat = _compute_elastic_dtw_matrix(
            series_ids,
            series_map,
            spring_stiffness=spring_stiffness,
            window_frac=window_frac,
        )
    shape_mat = (
        _project_to_psd_similarity(0.60 * mr_mat + 0.40 * dtw_mat)
        if dtw_mat is not None
        else mr_mat
    )

    backend_used = "pure_numpy_scipy"
    found_emb: np.ndarray | None = None
    if canon_method == "foundation_latent":
        found_emb, _, backend_used = extract_foundation_embeddings(
            panel_df,
            cfg=cfg,
            ts_id_col=ts_id_col,
            date_col=date_col,
            target_col=target_col,
            allow_fallback=allow_fallback,
            **kwargs,
        )
        if n == 1:
            found_mat = np.ones((1, 1), dtype=np.float64)
        else:
            f_dist = sp_distance.squareform(sp_distance.pdist(found_emb, metric="cosine"))
            found_mat = _project_to_psd_similarity(1.0 - 0.5 * f_dist)
        final_mat = found_mat
    elif canon_method == "physics_attractor":
        final_mat = phys_mat
    elif canon_method == "spectral_phase":
        final_mat = spec_mat
    elif canon_method == "elastic_dtw":
        final_mat = (
            dtw_mat
            if dtw_mat is not None
            else _compute_elastic_dtw_matrix(
                series_ids,
                series_map,
                spring_stiffness=spring_stiffness,
                window_frac=window_frac,
            )
        )
        shape_mat = final_mat
    elif canon_method == "minirocket":
        final_mat = mr_mat
        shape_mat = mr_mat
    elif canon_method == "structural_signature":
        final_mat = st_mat
    else:
        # Consensus "hybrid" PSD fusion
        w_phys = 0.30
        w_spec = 0.25
        w_shape = 0.25
        w_struct = 0.20
        if kernel_weights:
            w_phys = float(
                kernel_weights.get("physics_attractor", kernel_weights.get("physics", w_phys))
            )
            w_spec = float(
                kernel_weights.get("spectral_phase", kernel_weights.get("spectral", w_spec))
            )
            w_shape = float(kernel_weights.get("shape", kernel_weights.get("minirocket", w_shape)))
            w_struct = float(
                kernel_weights.get(
                    "structural_signature", kernel_weights.get("structural", w_struct)
                )
            )
        w_sum = max(w_phys + w_spec + w_shape + w_struct, 1e-9)
        fused = (
            w_phys * phys_mat + w_spec * spec_mat + w_shape * shape_mat + w_struct * st_mat
        ) / w_sum
        final_mat = _project_to_psd_similarity(fused)

    if has_sem or has_hier:
        if not has_sem:
            w_sem = 0.0
        elif semantic_weight == "auto":
            w_sem = 0.30 if has_hier else 0.40
        else:
            w_sem = max(0.0, float(semantic_weight))

        if not has_hier:
            w_hier = 0.0
        elif hierarchy_weight == "auto":
            w_hier = 0.25 if has_sem else 0.35
        else:
            w_hier = max(0.0, float(hierarchy_weight))

        w_meta = w_sem + w_hier
        if w_meta > 0.0 and n > 1:
            if w_meta >= 0.85:
                w_behav = max(0.15, 1.0 - min(0.85, w_meta))
                scale_m = (1.0 - w_behav) / w_meta
                eff_w_sem = w_sem * scale_m
                eff_w_hier = w_hier * scale_m
            else:
                w_behav = 1.0 - w_meta
                eff_w_sem = w_sem
                eff_w_hier = w_hier

            meta_combined = (w_sem * sem_mat + w_hier * hier_mat) / max(w_meta, 1e-9)
            behav_adjusted = final_mat.copy()
            if has_sem and has_hier:
                # Damp coincidental seasonal correlation when both semantic & hierarchy are disjoint
                low_meta_gate = np.clip(meta_combined / 0.12, 0.35, 1.0)
                np.fill_diagonal(low_meta_gate, 1.0)
                behav_adjusted = behav_adjusted * low_meta_gate

            retail_fused = w_behav * behav_adjusted + eff_w_sem * sem_mat + eff_w_hier * hier_mat
            # For pre-launch / < 2 observation SKUs, drive similarity purely from metadata
            for i_idx, sid in enumerate(series_ids):
                if valid_obs_counts.get(sid, 2) < 2:
                    for j_idx in range(n):
                        if i_idx != j_idx:
                            m_val = float(meta_combined[i_idx, j_idx])
                            retail_fused[i_idx, j_idx] = m_val
                            retail_fused[j_idx, i_idx] = m_val
            final_mat = _project_to_psd_similarity(retail_fused)

    within_cols = _normalize_col_list(within_hierarchy_level, list(meta_df.columns))

    coords = _spectral_2d_coords(final_mat, n_components=max(2, n_components))

    embed_rows: list[dict[str, Any]] = []
    for idx, sid in enumerate(series_ids):
        p_info = phys_inv[sid]
        sp_info = spec_meta[sid]
        st_info = st_meta[sid]
        if found_emb is not None:
            vec_to_store = found_emb[idx, : min(16, found_emb.shape[1])]
        else:
            vec_to_store = st_emb[idx, : min(16, st_emb.shape[1])]
        embed_rows.append(
            {
                "ts_id": sid,
                "lyapunov_exp": round(float(p_info["lyapunov_exp"]), 6),
                "hurst_exp": round(float(st_info["hurst_exp"]), 6),
                "perm_entropy": round(float(p_info["perm_entropy"]), 6),
                "sample_entropy": round(float(p_info["sample_entropy"]), 6),
                "ou_damping_rate": round(float(p_info["ou_damping_rate"]), 6),
                "dominant_period": round(float(sp_info["dominant_period"]), 4),
                "kuramoto_sync_mean": round(float(sp_info["kuramoto_sync_mean"]), 6),
                "trend_strength": round(float(st_info["trend_strength"]), 6),
                "seasonal_strength": round(float(st_info["seasonal_strength"]), 6),
                "spectral_entropy": round(float(st_info["spectral_entropy"]), 6),
                "adi_log": round(float(st_info["adi_log"]), 6),
                "cv2_log": round(float(st_info["cv2_log"]), 6),
                "skewness": round(float(st_info["skewness"]), 6),
                "kurtosis": round(float(st_info["kurtosis"]), 6),
                "arch_volatility": round(float(st_info["arch_volatility"]), 6),
                "zero_fraction": round(float(st_info["zero_fraction"]), 6),
                "embed_x": round(float(coords[idx, 0]), 6),
                "embed_y": round(float(coords[idx, 1]), 6),
                "embedding_json": json.dumps([round(float(v), 5) for v in vec_to_store]),
                "embedding_backend_used": backend_used,
            }
        )
    embeddings_df = pd.DataFrame(embed_rows, columns=embed_cols)

    matrix_df = pd.DataFrame(final_mat, index=series_ids, columns=series_ids)
    matrix_df.index.name = "ts_id"

    eff_k = max(1, int(top_k))
    pair_rows: list[dict[str, Any]] = []
    for i, sid_a in enumerate(series_ids):
        candidates: list[tuple[float, int]] = []
        for j in range(n):
            if i == j:
                continue
            if within_cols:
                sid_b_cand = series_ids[j]
                same_scope = all(
                    str(meta_df.loc[sid_a, c]).strip().lower()
                    == str(meta_df.loc[sid_b_cand, c]).strip().lower()
                    for c in within_cols
                )
                if not same_scope:
                    continue
            candidates.append((float(final_mat[i, j]), j))
        candidates.sort(key=lambda item: (-item[0], series_ids[item[1]]))
        for rank_idx, (score, j) in enumerate(candidates[:eff_k], start=1):
            sid_b = series_ids[j]
            dist_val = float(math.sqrt(max(0.0, 1.0 - score)))
            pair_rows.append(
                {
                    "ts_id": sid_a,
                    "neighbor_ts_id": sid_b,
                    "ts_id_a": sid_a,
                    "ts_id_b": sid_b,
                    "rank": rank_idx,
                    "similarity_score": round(score, 6),
                    "similarity": round(score, 6),
                    "distance": round(dist_val, 6),
                    "physics_sim": round(float(phys_mat[i, j]), 6),
                    "spectral_sim": round(float(spec_mat[i, j]), 6),
                    "shape_sim": round(float(shape_mat[i, j]), 6),
                    "structural_sim": round(float(st_mat[i, j]), 6),
                    "semantic_sim": round(float(sem_mat[i, j]), 6),
                    "hierarchy_sim": round(float(hier_mat[i, j]), 6),
                    "optimal_lag": int(lag_mat[i, j]),
                    "lag_correlation": round(float(corr_mat[i, j]), 6),
                    "method": canon_method,
                }
            )
    pairs_df = pd.DataFrame(pair_rows, columns=pair_cols)

    off_diag = final_mat[np.triu_indices(n, k=1)] if n > 1 else np.array([1.0])
    min_eig = float(np.min(np.linalg.eigvalsh(final_mat))) if n >= 1 else 1.0
    diagnostics = {
        "n_series": n,
        "method": canon_method,
        "mean_pairwise_similarity": float(np.mean(off_diag)) if off_diag.size > 0 else 1.0,
        "min_eigenvalue": min_eig,
        "is_psd": bool(min_eig >= -1e-7),
        "embedding_backend_used": backend_used,
        "has_semantic_similarity": has_sem,
        "has_hierarchy_similarity": has_hier,
    }
    return SimilarityMatrixResult(
        matrix_df=matrix_df,
        pairs_df=pairs_df,
        embeddings_df=embeddings_df,
        method=canon_method,
        diagnostics=diagnostics,
    )
detect_emerging_trends_df(
    panel_df,
    *,
    window=14,
    recent_window=None,
    baseline_window=None,
    top_k_related=3,
    text_cols=None,
    embedding_col=None,
    attribute_cols=None,
    hierarchy_cols=None,
    max_lag=7,
    method="hybrid",
    cfg=None,
    ts_id_col="ts_id",
    date_col="ds",
    target_col="y",
    **kwargs,
)

Detect emerging trend breakouts, kinematic velocity/acceleration (:math:\dot{y}, \ddot{y}), directed Kuramoto/cross-correlation lead-lag bellwether leaders (:math:\tau_{i \to j}^*), and lagging co-promotion candidates.

Source code in src/scale_forecasting/similarity.py
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
def detect_emerging_trends_df(
    panel_df: pd.DataFrame,
    *,
    window: int = 14,
    recent_window: int | None = None,
    baseline_window: int | None = None,
    top_k_related: int = 3,
    text_cols: Sequence[str] | str | None = None,
    embedding_col: str | None = None,
    attribute_cols: Sequence[str] | None = None,
    hierarchy_cols: Sequence[str] | None = None,
    max_lag: int = 7,
    method: str = "hybrid",
    cfg: RunConfig | None = None,
    ts_id_col: str = "ts_id",
    date_col: str = "ds",
    target_col: str = "y",
    **kwargs: Any,
) -> pd.DataFrame:
    """Detect emerging trend breakouts, kinematic velocity/acceleration (:math:`\\dot{y},
    \\ddot{y}`), directed Kuramoto/cross-correlation lead-lag bellwether leaders
    (:math:`\\tau_{i \\to j}^*`), and lagging co-promotion candidates."""
    eff_window = int(recent_window) if recent_window is not None else int(window)
    out_cols = [
        "ts_id",
        "trend_score",
        "trend_regime",
        "recent_velocity",
        "recent_acceleration",
        "breakout_zscore",
        "hurst_exp",
        "similarity_cluster_id",
        "leading_bellwether_ts_id",
        "lag_behind_leader",
        "co_promote_candidates",
        "recommended_merchandising_action",
    ]
    series_ids, series_map = _extract_panel_series(
        panel_df, cfg=cfg, ts_id_col=ts_id_col, date_col=date_col, target_col=target_col
    )
    if not series_ids:
        return pd.DataFrame(columns=out_cols)

    meta_df = _extract_series_metadata(panel_df, series_ids, cfg=cfg, ts_id_col=ts_id_col)
    avail_cols = list(meta_df.columns)
    eff_text_cols = (
        _normalize_col_list(text_cols, avail_cols)
        if text_cols is not None
        else [c for c in _DEFAULT_TEXT_CANDIDATE_COLS if c in avail_cols]
    )
    eff_attr_cols = (
        _normalize_col_list(attribute_cols, avail_cols)
        if attribute_cols is not None
        else [c for c in _DEFAULT_ATTR_CANDIDATE_COLS if c in avail_cols]
    )
    if hierarchy_cols is not None:
        eff_hier_cols = _normalize_col_list(hierarchy_cols, avail_cols)
    elif cfg is not None and cfg.hierarchy.levels:
        eff_hier_cols = _normalize_col_list(
            [c for lvl in cfg.hierarchy.levels for c in lvl], avail_cols
        )
    else:
        eff_hier_cols = [c for c in _DEFAULT_HIER_CANDIDATE_COLS if c in avail_cols]

    eff_max_lag = max(1, int(max_lag))
    sim_res = compute_similarity_matrix(
        panel_df,
        cfg=cfg,
        method=method,
        top_k=len(series_ids),
        max_lag=eff_max_lag,
        text_cols=eff_text_cols or None,
        embedding_col=embedding_col,
        attribute_cols=eff_attr_cols or None,
        hierarchy_cols=eff_hier_cols or None,
        ts_id_col=ts_id_col,
        date_col=date_col,
        target_col=target_col,
        **kwargs,
    )
    clusters_df = cluster_by_similarity_df(
        panel_df,
        cfg=cfg,
        method=method,
        similarity_result=sim_res,
    )
    cluster_by_id = dict(
        zip(
            clusters_df["ts_id"].astype(str),
            clusters_df["similarity_cluster_id"].astype(str),
            strict=False,
        )
    )
    hurst_by_id = dict(
        zip(
            sim_res.embeddings_df["ts_id"].astype(str),
            sim_res.embeddings_df["hurst_exp"].astype(float),
            strict=False,
        )
    )

    kinematics_by_id: dict[str, dict[str, Any]] = {}
    for sid in series_ids:
        y = series_map[sid]
        t_len = int(y.size)
        w = min(max(3, eff_window), t_len)
        y_rec = y[-w:]
        y_prior = y[:-w] if t_len > w + 2 else y[: max(2, t_len // 2)]
        if baseline_window is not None and y_prior.size > max(2, int(baseline_window)):
            y_prior = y_prior[-int(baseline_window) :]

        mu_prior = float(np.mean(y_prior)) if y_prior.size > 0 else float(np.mean(y))
        sd_prior = float(np.std(y_prior)) if y_prior.size > 1 else 0.0
        scale_base = max(abs(mu_prior), float(np.mean(np.abs(y))), 1e-6)
        denom_sd = max(sd_prior, 0.05 * abs(mu_prior), 1e-6)

        y_rec_norm = y_rec / scale_base
        t_grid = np.arange(w, dtype=np.float64)
        t_centered = t_grid - float(np.mean(t_grid))
        t_ss = float(np.dot(t_centered, t_centered))
        vel = (
            float(np.dot(t_centered, y_rec_norm - np.mean(y_rec_norm)) / t_ss)
            if t_ss > 1e-12
            else 0.0
        )

        if w >= 4:
            half = w // 2
            y1 = y_rec_norm[: max(2, half)]
            y2 = y_rec_norm[half:]
            t1 = np.arange(y1.size, dtype=np.float64)
            t1 -= float(np.mean(t1))
            v1 = float(np.dot(t1, y1 - np.mean(y1)) / max(float(np.dot(t1, t1)), 1e-12))
            t2 = np.arange(y2.size, dtype=np.float64)
            t2 -= float(np.mean(t2))
            v2 = float(np.dot(t2, y2 - np.mean(y2)) / max(float(np.dot(t2, t2)), 1e-12))
            d2_mean = float(np.mean(np.diff(y_rec_norm, n=2)))
            acc = 0.60 * ((v2 - v1) / max(1.0, float(half))) + 0.40 * d2_mean
        elif w == 3:
            acc = float(y_rec_norm[2] - 2.0 * y_rec_norm[1] + y_rec_norm[0])
        else:
            acc = 0.0

        tail_len = max(3, w // 2)
        rec_level = 0.65 * float(np.mean(y_rec[-tail_len:])) + 0.35 * float(np.mean(y_rec))
        z_break = (rec_level - mu_prior) / denom_sd
        hurst_val = float(hurst_by_id.get(sid, 0.5))

        z_pos = max(0.0, z_break) / 3.0
        v_pos = max(0.0, vel * 15.0)
        a_pos = max(0.0, acc * 25.0)
        h_pos = max(0.0, hurst_val - 0.5)
        raw_strength = 0.45 * z_pos + 0.30 * v_pos + 0.15 * a_pos + 0.10 * h_pos
        if z_break < 0.0 and vel < 0.0:
            t_score = float(np.clip(0.15 * math.exp(0.5 * z_break), 0.0, 0.25))
        else:
            t_score = float(np.clip(1.0 - math.exp(-1.5 * raw_strength), 0.0, 1.0))

        if (z_break >= 1.5 and vel > 0.005 and acc >= -0.005) or (z_break >= 2.2 and vel > 0.01):
            regime = "accelerating_breakout"
        elif z_break >= 0.8 and vel > 0.002:
            regime = "steady_growth" if acc >= -0.01 else "maturing_plateau"
        elif z_break >= 1.0 and vel <= 0.002:
            regime = "maturing_plateau"
        elif vel < -0.008 and z_break < -0.8:
            regime = "declining"
        else:
            regime = "stable"

        kinematics_by_id[sid] = {
            "trend_score": t_score,
            "trend_regime": regime,
            "recent_velocity": vel,
            "recent_acceleration": acc,
            "breakout_zscore": z_break,
            "hurst_exp": hurst_val,
        }

    # Build pair lookup and evaluate directed lead-lag (including prior-window lag when a leader
    # has just surged in the recent window ahead of its follower).
    pairs_by_src: dict[str, list[dict[str, Any]]] = {sid: [] for sid in series_ids}
    pair_map: dict[tuple[str, str], dict[str, Any]] = {}
    for row in sim_res.pairs_df.to_dict(orient="records"):
        sa = str(row["ts_id"])
        sb = str(row["neighbor_ts_id"])
        r_copy = {str(k): v for k, v in row.items()}
        pairs_by_src.setdefault(sa, []).append(r_copy)
        pair_map[(sa, sb)] = r_copy

    leader_for_id: dict[str, tuple[str, int]] = {}
    followers_by_leader: dict[str, list[str]] = {sid: [] for sid in series_ids}

    for sid_i in series_ids:
        yi = series_map[sid_i]
        best_leader = ""
        best_lag = 0
        best_leader_score = -1.0
        for sid_j in series_ids:
            if sid_j == sid_i:
                continue
            kj = kinematics_by_id[sid_j]
            if kj["trend_regime"] not in ("accelerating_breakout", "steady_growth"):
                continue
            p_ji = pair_map.get((sid_j, sid_i))
            sim_ji = float(p_ji["similarity_score"]) if p_ji is not None else 0.0
            opt_lag = int(p_ji["optimal_lag"]) if p_ji is not None else 0
            lag_corr = float(p_ji["lag_correlation"]) if p_ji is not None else 0.0

            # Also check pre-breakout / detrended lag if leader surged ahead of follower at the tail
            if opt_lag <= 0 or lag_corr < 0.45:
                yj = series_map[sid_j]
                zj, _, _, fj = _zscore(yj)
                zi, _, _, fi = _zscore(yi)
                alt_lag, alt_corr = _compute_optimal_lead_lag(zj, zi, fj, fi, max_lag=eff_max_lag)
                if alt_lag > 0 and alt_corr > lag_corr:
                    opt_lag, lag_corr = alt_lag, alt_corr
                if (opt_lag <= 0 or lag_corr < 0.45) and min(yj.size, yi.size) > eff_window + 6:
                    cut = max(6, int(eff_window) // 2)
                    zj_p, _, _, fjp = _zscore(yj[:-cut])
                    zi_p, _, _, fip = _zscore(yi[:-cut])
                    p_lag, p_corr = _compute_optimal_lead_lag(
                        zj_p, zi_p, fjp, fip, max_lag=eff_max_lag
                    )
                    if p_lag > 0 and p_corr >= 0.50:
                        opt_lag, lag_corr = p_lag, p_corr

            if (
                opt_lag > 0
                and lag_corr >= 0.45
                and sim_ji >= 0.25
                and (
                    kj["trend_score"] > kinematics_by_id[sid_i]["trend_score"] - 0.05
                    or kj["breakout_zscore"] >= kinematics_by_id[sid_i]["breakout_zscore"]
                )
            ):
                cand_rank_score = float(kj["trend_score"]) * 0.6 + lag_corr * 0.4
                if cand_rank_score > best_leader_score:
                    best_leader_score = cand_rank_score
                    best_leader = sid_j
                    best_lag = int(opt_lag)

        if best_leader and best_lag > 0:
            leader_for_id[sid_i] = (best_leader, best_lag)
            followers_by_leader.setdefault(best_leader, []).append(sid_i)

    eff_k_rel = max(1, int(top_k_related))
    rows_out: list[dict[str, Any]] = []
    for sid in series_ids:
        k_info = kinematics_by_id[sid]
        regime = str(k_info["trend_regime"])
        leader_id, lag_steps = leader_for_id.get(sid, ("", 0))
        own_followers = followers_by_leader.get(sid, [])

        if not leader_id and regime in ("accelerating_breakout", "steady_growth"):
            leader_id = sid
            lag_steps = 0

        # Build co_promote_candidates prioritizing lagging followers and top similarity twins
        rel_ids: list[str] = []
        for f_sid in own_followers:
            if f_sid != sid and f_sid not in rel_ids:
                rel_ids.append(f_sid)
        for p_row in pairs_by_src.get(sid, []):
            nbr = str(p_row["neighbor_ts_id"])
            if nbr != sid and nbr not in rel_ids:
                rel_ids.append(nbr)
            if len(rel_ids) >= eff_k_rel:
                break
        co_promote_str = ",".join(rel_ids[:eff_k_rel])

        if lag_steps > 0 and leader_id and leader_id != sid:
            action = "co_promote_lagging_twin"
        elif regime == "accelerating_breakout":
            if own_followers or float(k_info["breakout_zscore"]) < 6.0:
                action = "promote_trend_leader"
            else:
                action = "replenish_breakout_risk"
        elif regime == "steady_growth":
            action = "promote_trend_leader"
        elif regime == "declining":
            action = "clearance_candidate"
        else:
            action = "hold_baseline"

        rows_out.append(
            {
                "ts_id": sid,
                "trend_score": round(float(k_info["trend_score"]), 6),
                "trend_regime": regime,
                "recent_velocity": round(float(k_info["recent_velocity"]), 6),
                "recent_acceleration": round(float(k_info["recent_acceleration"]), 6),
                "breakout_zscore": round(float(k_info["breakout_zscore"]), 6),
                "hurst_exp": round(float(k_info["hurst_exp"]), 6),
                "similarity_cluster_id": cluster_by_id.get(sid, "cluster_0"),
                "leading_bellwether_ts_id": leader_id,
                "lag_behind_leader": int(lag_steps),
                "co_promote_candidates": co_promote_str,
                "recommended_merchandising_action": action,
            }
        )

    out_df = pd.DataFrame(rows_out, columns=out_cols)
    return out_df.sort_values(
        ["trend_score", "breakout_zscore", "ts_id"],
        ascending=[False, False, True],
        kind="mergesort",
    ).reset_index(drop=True)

embed_series_df

embed_series_df(
    panel_df,
    *,
    cfg=None,
    method="hybrid",
    n_components=2,
    text_cols=None,
    embedding_col=None,
    attribute_cols=None,
    hierarchy_cols=None,
    within_hierarchy_level=None,
    semantic_weight="auto",
    hierarchy_weight="auto",
    ts_id_col="ts_id",
    date_col="ds",
    target_col="y",
    allow_fallback=True,
    **kwargs,
)

Compute per-series physical & econometric invariants and low-dimensional embedding coordinates.

Returns a DataFrame with one row per ts_id containing dynamical invariants (lyapunov_exp, hurst_exp, perm_entropy, sample_entropy, ou_damping_rate, dominant_period, kuramoto_sync_mean), structural statistics (trend_strength, seasonal_strength, spectral_entropy, adi_log, cv2_log, skewness, kurtosis, arch_volatility, zero_fraction), 2D coordinates (embed_x, embed_y), embedding_json, and embedding_backend_used.

Source code in src/scale_forecasting/similarity.py
def embed_series_df(
    panel_df: pd.DataFrame,
    *,
    cfg: RunConfig | None = None,
    method: str = "hybrid",
    n_components: int = 2,
    text_cols: Sequence[str] | str | None = None,
    embedding_col: str | None = None,
    attribute_cols: Sequence[str] | None = None,
    hierarchy_cols: Sequence[str] | None = None,
    within_hierarchy_level: str | Sequence[str] | None = None,
    semantic_weight: float | Literal["auto"] = "auto",
    hierarchy_weight: float | Literal["auto"] = "auto",
    ts_id_col: str = "ts_id",
    date_col: str = "ds",
    target_col: str = "y",
    allow_fallback: bool = True,
    **kwargs: Any,
) -> pd.DataFrame:
    """Compute per-series physical & econometric invariants and low-dimensional embedding
    coordinates.

    Returns a DataFrame with one row per ``ts_id`` containing dynamical invariants
    (``lyapunov_exp``, ``hurst_exp``, ``perm_entropy``, ``sample_entropy``, ``ou_damping_rate``,
    ``dominant_period``, ``kuramoto_sync_mean``), structural statistics (``trend_strength``,
    ``seasonal_strength``, ``spectral_entropy``, ``adi_log``, ``cv2_log``, ``skewness``,
    ``kurtosis``, ``arch_volatility``, ``zero_fraction``), 2D coordinates (``embed_x``,
    ``embed_y``), ``embedding_json``, and ``embedding_backend_used``.
    """
    canon_method = _resolve_similarity_method(method)
    res = compute_similarity_matrix(
        panel_df,
        cfg=cfg,
        method=canon_method,
        n_components=n_components,
        text_cols=text_cols,
        embedding_col=embedding_col,
        attribute_cols=attribute_cols,
        hierarchy_cols=hierarchy_cols,
        within_hierarchy_level=within_hierarchy_level,
        semantic_weight=semantic_weight,
        hierarchy_weight=hierarchy_weight,
        ts_id_col=ts_id_col,
        date_col=date_col,
        target_col=target_col,
        allow_fallback=allow_fallback,
        **kwargs,
    )
    return res.embeddings_df.copy()

extract_foundation_embeddings

extract_foundation_embeddings(
    panel_df,
    *,
    model_name="chronos_bolt",
    cfg=None,
    ts_id_col="ts_id",
    date_col="ds",
    target_col="y",
    allow_fallback=True,
    encoder_fn=None,
    **kwargs,
)

Extract pooled encoder embeddings for each series in panel_df.

When encoder_fn is provided or a foundation model pipeline (chronos_bolt, chronos2, timesfm_torch) is explicitly loaded/configured, extracts latent encoder states. When running offline on pure core (default allow_fallback=True), deterministically falls back to the L2-normalized concatenation of "minirocket" and "structural_signature" embeddings and records embedding_backend_used = "minirocket_structural_fallback".

Source code in src/scale_forecasting/similarity.py
def extract_foundation_embeddings(
    panel_df: pd.DataFrame,
    *,
    model_name: str = "chronos_bolt",
    cfg: RunConfig | None = None,
    ts_id_col: str = "ts_id",
    date_col: str = "ds",
    target_col: str = "y",
    allow_fallback: bool = True,
    encoder_fn: Callable[[list[np.ndarray]], np.ndarray] | None = None,
    **kwargs: Any,
) -> tuple[np.ndarray, list[str], str]:
    """Extract pooled encoder embeddings for each series in ``panel_df``.

    When ``encoder_fn`` is provided or a foundation model pipeline (``chronos_bolt``,
    ``chronos2``, ``timesfm_torch``) is explicitly loaded/configured, extracts latent encoder
    states. When running offline on pure core (default ``allow_fallback=True``), deterministically
    falls back to the L2-normalized concatenation of ``"minirocket"`` and
    ``"structural_signature"`` embeddings and records
    ``embedding_backend_used = "minirocket_structural_fallback"``.
    """
    series_ids, series_map = _extract_panel_series(
        panel_df, cfg=cfg, ts_id_col=ts_id_col, date_col=date_col, target_col=target_col
    )
    n = len(series_ids)
    if n == 0:
        return np.zeros((0, 16), dtype=np.float64), [], "minirocket_structural_fallback"

    if encoder_fn is not None:
        raw_list = [series_map[sid] for sid in series_ids]
        emb = np.asarray(encoder_fn(raw_list), dtype=np.float64)
        if emb.ndim == 1:
            emb = emb.reshape(n, -1)
        norms = np.linalg.norm(emb, axis=1, keepdims=True)
        norms[norms < 1e-12] = 1.0
        return emb / norms, series_ids, str(model_name)

    if kwargs.get("use_pretrained_pipeline", False):
        try:
            import torch
            from chronos import ChronosBoltPipeline

            repo_id = str(kwargs.get("repo_id", "amazon/chronos-bolt-small"))
            pipeline = ChronosBoltPipeline.from_pretrained(repo_id, device_map="cpu")
            if hasattr(pipeline, "embed"):
                tensors = [torch.tensor(series_map[sid], dtype=torch.float32) for sid in series_ids]
                embeds, _ = pipeline.embed(tensors)
                pooled = embeds.mean(dim=1).detach().cpu().numpy().astype(np.float64)
                norms = np.linalg.norm(pooled, axis=1, keepdims=True)
                norms[norms < 1e-12] = 1.0
                return pooled / norms, series_ids, model_name
        except Exception as exc:
            if not allow_fallback:
                raise RuntimeError(
                    f"Foundation embedding extraction failed for {model_name!r} and "
                    "allow_fallback=False."
                ) from exc

    if not allow_fallback:
        raise RuntimeError(
            f"Foundation model encoder {model_name!r} is not loaded and allow_fallback=False."
        )

    mr_emb, _ = _compute_minirocket_embeddings_and_matrix(series_ids, series_map)
    st_emb, _, _ = _compute_structural_signature_matrix(series_ids, series_map)
    st_std = np.std(st_emb, axis=0)
    st_std[st_std < 1e-9] = 1.0
    st_norm = (st_emb - np.mean(st_emb, axis=0)) / st_std
    concat = np.hstack([mr_emb, st_norm])
    norms = np.linalg.norm(concat, axis=1, keepdims=True)
    norms[norms < 1e-12] = 1.0
    return concat / norms, series_ids, "minirocket_structural_fallback"

find_similar_series_df

find_similar_series_df(
    panel_df,
    *,
    query_ts_id=None,
    top_k=5,
    mode="full_history",
    method="hybrid",
    prefix_len=None,
    window=None,
    max_lag=0,
    text_cols=None,
    embedding_col=None,
    attribute_cols=None,
    hierarchy_cols=None,
    within_hierarchy_level=None,
    semantic_weight="auto",
    hierarchy_weight="auto",
    cfg=None,
    ts_id_col="ts_id",
    date_col="ds",
    target_col="y",
    candidate_ts_ids=None,
    **kwargs,
)

Find top-:math:K digital-twin series across full history, relative-age launch prefixes (mode="launch_prefix"), or recent rolling windows (mode="recent_window").

Source code in src/scale_forecasting/similarity.py
def find_similar_series_df(
    panel_df: pd.DataFrame,
    *,
    query_ts_id: str | None = None,
    top_k: int = 5,
    mode: str = "full_history",
    method: str = "hybrid",
    prefix_len: int | None = None,
    window: int | None = None,
    max_lag: int = 0,
    text_cols: Sequence[str] | str | None = None,
    embedding_col: str | None = None,
    attribute_cols: Sequence[str] | None = None,
    hierarchy_cols: Sequence[str] | None = None,
    within_hierarchy_level: str | Sequence[str] | None = None,
    semantic_weight: float | Literal["auto"] = "auto",
    hierarchy_weight: float | Literal["auto"] = "auto",
    cfg: RunConfig | None = None,
    ts_id_col: str = "ts_id",
    date_col: str = "ds",
    target_col: str = "y",
    candidate_ts_ids: Sequence[str] | None = None,
    **kwargs: Any,
) -> pd.DataFrame:
    """Find top-:math:`K` digital-twin series across full history, relative-age launch prefixes
    (``mode="launch_prefix"``), or recent rolling windows (``mode="recent_window"``)."""
    canon_mode = _resolve_matching_mode(mode)
    canon_method = _resolve_similarity_method(method)
    out_cols = [
        "query_ts_id",
        "ts_id",
        "neighbor_ts_id",
        "match_ts_id",
        "rank",
        "similarity_score",
        "similarity",
        "distance",
        "physics_sim",
        "spectral_sim",
        "shape_sim",
        "structural_sim",
        "semantic_sim",
        "hierarchy_sim",
        "optimal_lag",
        "lag_correlation",
        "scale_ratio",
        "level_offset",
        "velocity_sim",
        "acceleration_sim",
        "matching_mode",
        "method",
    ]
    series_ids, series_map = _extract_panel_series(
        panel_df, cfg=cfg, ts_id_col=ts_id_col, date_col=date_col, target_col=target_col
    )
    if len(series_ids) <= 1:
        return pd.DataFrame(columns=out_cols)

    if query_ts_id is not None and str(query_ts_id) not in series_map:
        raise ValueError(
            f"query_ts_id {query_ts_id!r} not found in panel series {series_ids[:10]}."
        )

    meta_df = _extract_series_metadata(panel_df, series_ids, cfg=cfg, ts_id_col=ts_id_col)
    valid_obs_counts = _count_valid_panel_obs(
        panel_df, series_ids, cfg=cfg, ts_id_col=ts_id_col, target_col=target_col
    )
    within_cols = _normalize_col_list(within_hierarchy_level, list(meta_df.columns))

    # Slice series according to matching mode before computing similarity
    sliced_rows: list[dict[str, Any]] = []
    sliced_map: dict[str, np.ndarray] = {}
    if canon_mode == "launch_prefix":
        if prefix_len is not None and int(prefix_len) >= 1:
            eff_len = int(prefix_len)
        elif query_ts_id is not None:
            eff_len = max(1, int(series_map[str(query_ts_id)].size))
        else:
            eff_len = max(3, int(min(arr.size for arr in series_map.values())))
        for sid in series_ids:
            arr = series_map[sid][:eff_len]
            sliced_map[sid] = arr
            for t_idx, val in enumerate(arr):
                sliced_rows.append({"ts_id": sid, "ds": t_idx, "y": float(val)})
    elif canon_mode == "recent_window":
        eff_win = (
            max(2, int(window))
            if window is not None
            else (
                max(2, int(prefix_len))
                if prefix_len is not None
                else max(3, min(28, min(arr.size for arr in series_map.values())))
            )
        )
        for sid in series_ids:
            arr = series_map[sid][-eff_win:]
            sliced_map[sid] = arr
            for t_idx, val in enumerate(arr):
                sliced_rows.append({"ts_id": sid, "ds": t_idx, "y": float(val)})
    else:
        for sid in series_ids:
            arr = series_map[sid]
            sliced_map[sid] = arr
            for t_idx, val in enumerate(arr):
                sliced_rows.append({"ts_id": sid, "ds": t_idx, "y": float(val)})

    sliced_df = pd.DataFrame(sliced_rows)
    sim_res = compute_similarity_matrix(
        sliced_df,
        cfg=cfg,
        method=canon_method,
        top_k=len(series_ids),
        max_lag=max_lag,
        text_cols=text_cols,
        embedding_col=embedding_col,
        attribute_cols=attribute_cols,
        hierarchy_cols=hierarchy_cols,
        within_hierarchy_level=within_hierarchy_level,
        semantic_weight=semantic_weight,
        hierarchy_weight=hierarchy_weight,
        ts_id_col="ts_id",
        date_col="ds",
        target_col="y",
        _metadata_df=panel_df,
        _metadata_ts_id_col=ts_id_col,
        _metadata_target_col=target_col,
        **kwargs,
    )

    cand_set = {str(c) for c in candidate_ts_ids} if candidate_ts_ids is not None else None
    queries = [str(query_ts_id)] if query_ts_id is not None else series_ids
    eff_k = max(1, int(top_k))

    pairs_lookup: dict[tuple[str, str], dict[str, Any]] = {}
    for row in sim_res.pairs_df.to_dict(orient="records"):
        pairs_lookup[(str(row["ts_id"]), str(row["neighbor_ts_id"]))] = {
            str(k): v for k, v in row.items()
        }

    result_rows: list[dict[str, Any]] = []
    for q_id in queries:
        ya = sliced_map[q_id]
        q_obs = valid_obs_counts.get(q_id, int(ya.size))
        scored_neighbors: list[tuple[float, str, dict[str, Any]]] = []
        for n_id in series_ids:
            if n_id == q_id:
                continue
            if cand_set is not None and n_id not in cand_set:
                continue
            if within_cols:
                same_scope = all(
                    str(meta_df.loc[q_id, c]).strip().lower()
                    == str(meta_df.loc[n_id, c]).strip().lower()
                    for c in within_cols
                )
                if not same_scope:
                    continue
            p_info = pairs_lookup.get((q_id, n_id))
            if p_info is None:
                continue
            yb = sliced_map[n_id]
            scale_r, lvl_off, vel_sim, acc_sim = _kinematic_velocity_acceleration_sim(ya, yb)
            base_sim = float(p_info["similarity_score"])
            if canon_mode == "launch_prefix" and min(ya.size, yb.size) >= 2 and q_obs >= 2:
                # Blend prefix shape similarity with initial kinematic velocity & acceleration
                z_a, _, _, flat_a = _zscore(ya)
                z_b, _, _, flat_b = _zscore(yb[: ya.size])
                if flat_a and flat_b:
                    corr_p = 1.0
                elif flat_a or flat_b or z_a.size != z_b.size:
                    corr_p = base_sim
                else:
                    c_raw = float(np.dot(z_a, z_b) / max(float(z_a.size), 1.0))
                    corr_p = 0.5 * (float(np.clip(c_raw, -1.0, 1.0)) + 1.0)
                combined_sim = float(
                    np.clip(
                        0.45 * base_sim + 0.25 * corr_p + 0.20 * vel_sim + 0.10 * acc_sim,
                        0.0,
                        1.0,
                    )
                )
            else:
                combined_sim = base_sim

            enriched = dict(p_info)
            enriched["similarity_score"] = round(combined_sim, 6)
            enriched["similarity"] = round(combined_sim, 6)
            enriched["distance"] = round(float(math.sqrt(max(0.0, 1.0 - combined_sim))), 6)
            enriched["scale_ratio"] = round(scale_r, 6)
            enriched["level_offset"] = round(lvl_off, 6)
            enriched["velocity_sim"] = round(vel_sim, 6)
            enriched["acceleration_sim"] = round(acc_sim, 6)
            scored_neighbors.append((combined_sim, n_id, enriched))

        scored_neighbors.sort(key=lambda item: (-item[0], item[1]))
        for rank_idx, (_, n_id, info) in enumerate(scored_neighbors[:eff_k], start=1):
            result_rows.append(
                {
                    "query_ts_id": q_id,
                    "ts_id": q_id,
                    "neighbor_ts_id": n_id,
                    "match_ts_id": n_id,
                    "rank": rank_idx,
                    "similarity_score": info["similarity_score"],
                    "similarity": info["similarity"],
                    "distance": info["distance"],
                    "physics_sim": info["physics_sim"],
                    "spectral_sim": info["spectral_sim"],
                    "shape_sim": info["shape_sim"],
                    "structural_sim": info["structural_sim"],
                    "semantic_sim": info["semantic_sim"],
                    "hierarchy_sim": info["hierarchy_sim"],
                    "optimal_lag": info["optimal_lag"],
                    "lag_correlation": info["lag_correlation"],
                    "scale_ratio": info["scale_ratio"],
                    "level_offset": info["level_offset"],
                    "velocity_sim": info["velocity_sim"],
                    "acceleration_sim": info["acceleration_sim"],
                    "matching_mode": canon_mode,
                    "method": canon_method,
                }
            )
    return pd.DataFrame(result_rows, columns=out_cols)

plot_similarity_map

plot_similarity_map(
    panel_or_result,
    *,
    method="hybrid",
    n_clusters="auto",
    ax=None,
    title=None,
    **kwargs,
)

Plot a 2D similarity embedding & cluster map (or 2-panel map + sorted similarity heatmap when ax=None), returning the matplotlib Axes.

Source code in src/scale_forecasting/similarity.py
def plot_similarity_map(
    panel_or_result: pd.DataFrame | SimilarityMatrixResult,
    *,
    method: str = "hybrid",
    n_clusters: int | Literal["auto"] = "auto",
    ax: Any | None = None,
    title: str | None = None,
    **kwargs: Any,
) -> Any:
    """Plot a 2D similarity embedding & cluster map (or 2-panel map + sorted similarity heatmap
    when ``ax=None``), returning the matplotlib ``Axes``."""
    import matplotlib.pyplot as plt

    if isinstance(panel_or_result, SimilarityMatrixResult):
        sim_res = panel_or_result
        clusters_df = cluster_by_similarity_df(
            pd.DataFrame(),
            n_clusters=n_clusters,
            method=sim_res.method,
            similarity_result=sim_res,
        )
    else:
        sim_res = compute_similarity_matrix(panel_or_result, method=method, **kwargs)
        clusters_df = cluster_by_similarity_df(
            panel_or_result,
            n_clusters=n_clusters,
            method=method,
            similarity_result=sim_res,
        )

    embed_df = sim_res.embeddings_df
    if ax is None:
        _, axes = plt.subplots(1, 2, figsize=(12, 5))
        ax_scatter, ax_heat = axes[0], axes[1]
    else:
        ax_scatter = ax
        ax_heat = None

    if not embed_df.empty and not clusters_df.empty:
        merged = embed_df.merge(
            clusters_df[
                [
                    "ts_id",
                    "similarity_cluster_id",
                    "cluster_int_id",
                    "is_medoid",
                    "cluster_archetype",
                ]
            ],
            on="ts_id",
            how="left",
        )
        for cid, grp in merged.groupby("similarity_cluster_id", sort=True):
            arch = str(grp["cluster_archetype"].iloc[0])
            ax_scatter.scatter(
                grp["embed_x"],
                grp["embed_y"],
                label=f"{cid} ({arch})",
                s=60,
                alpha=0.85,
            )
            meds = grp[grp["is_medoid"]]
            if not meds.empty:
                ax_scatter.scatter(
                    meds["embed_x"],
                    meds["embed_y"],
                    marker="*",
                    s=180,
                    edgecolors="black",
                    linewidths=1.0,
                )
        for row in merged.to_dict(orient="records"):
            ax_scatter.annotate(
                str(row["ts_id"]),
                (float(row["embed_x"]), float(row["embed_y"])),
                fontsize=8,
                alpha=0.8,
            )
        ax_scatter.legend(loc="best", fontsize=8)

    ax_scatter.set_xlabel("Similarity Embedding Axis 1 (embed_x)")
    ax_scatter.set_ylabel("Similarity Embedding Axis 2 (embed_y)")
    ax_scatter.set_title(title or f"Time-Series Similarity Map ({sim_res.method})")
    ax_scatter.grid(True, alpha=0.25)

    if ax_heat is not None and not sim_res.matrix_df.empty:
        order_ids = (
            clusters_df.sort_values(["cluster_int_id", "ts_id"])["ts_id"].tolist()
            if not clusters_df.empty
            else list(sim_res.matrix_df.index)
        )
        sorted_mat = sim_res.matrix_df.loc[order_ids, order_ids].to_numpy(dtype=np.float64)
        im = ax_heat.imshow(sorted_mat, vmin=0.0, vmax=1.0, cmap="viridis", aspect="auto")
        ax_heat.set_xticks(range(len(order_ids)))
        ax_heat.set_yticks(range(len(order_ids)))
        ax_heat.set_xticklabels(order_ids, rotation=45, ha="right", fontsize=7)
        ax_heat.set_yticklabels(order_ids, fontsize=7)
        ax_heat.set_title("Block-Diagonal Similarity Matrix")
        plt.colorbar(im, ax=ax_heat, fraction=0.046, pad=0.04)

    return ax_scatter

recommend_substitutes_df

recommend_substitutes_df(
    panel_df,
    inventory_df=None,
    *,
    query_ts_id=None,
    top_k=5,
    text_cols=None,
    embedding_col=None,
    attribute_cols=None,
    hierarchy_cols=None,
    within_hierarchy_level=None,
    require_in_stock=True,
    exclude_out_of_stock=None,
    on_hand_col="on_hand",
    inventory_col=None,
    safety_stock_col="safety_stock",
    method="hybrid",
    semantic_weight="auto",
    hierarchy_weight="auto",
    cfg=None,
    ts_id_col="ts_id",
    date_col="ds",
    target_col="y",
    **kwargs,
)

Recommend top-:math:K in-stock retail assortment substitutes combining semantic/attribute similarity, Wu-Palmer hierarchy LCA proximity, behavioral trajectory similarity, and inventory availability surplus.

Source code in src/scale_forecasting/similarity.py
def recommend_substitutes_df(
    panel_df: pd.DataFrame,
    inventory_df: pd.DataFrame | None = None,
    *,
    query_ts_id: str | Sequence[str] | None = None,
    top_k: int = 5,
    text_cols: Sequence[str] | str | None = None,
    embedding_col: str | None = None,
    attribute_cols: Sequence[str] | None = None,
    hierarchy_cols: Sequence[str] | None = None,
    within_hierarchy_level: str | Sequence[str] | None = None,
    require_in_stock: bool = True,
    exclude_out_of_stock: bool | None = None,
    on_hand_col: str = "on_hand",
    inventory_col: str | None = None,
    safety_stock_col: str = "safety_stock",
    method: str = "hybrid",
    semantic_weight: float | Literal["auto"] = "auto",
    hierarchy_weight: float | Literal["auto"] = "auto",
    cfg: RunConfig | None = None,
    ts_id_col: str = "ts_id",
    date_col: str = "ds",
    target_col: str = "y",
    **kwargs: Any,
) -> pd.DataFrame:
    """Recommend top-:math:`K` in-stock retail assortment substitutes combining semantic/attribute
    similarity, Wu-Palmer hierarchy LCA proximity, behavioral trajectory similarity, and inventory
    availability surplus."""
    eff_require_in_stock = (
        bool(exclude_out_of_stock) if exclude_out_of_stock is not None else bool(require_in_stock)
    )
    eff_on_hand_col = str(inventory_col) if inventory_col is not None else on_hand_col
    out_cols = [
        "query_ts_id",
        "substitute_ts_id",
        "rank",
        "substitution_score",
        "similarity_score",
        "semantic_sim",
        "hierarchy_sim",
        "available_units",
        "stock_status",
        "substitution_rationale",
    ]
    series_ids, series_map = _extract_panel_series(
        panel_df, cfg=cfg, ts_id_col=ts_id_col, date_col=date_col, target_col=target_col
    )
    if len(series_ids) <= 1:
        return pd.DataFrame(columns=out_cols)

    meta_df = _extract_series_metadata(panel_df, series_ids, cfg=cfg, ts_id_col=ts_id_col)
    avail_cols = list(meta_df.columns)

    eff_text_cols = (
        _normalize_col_list(text_cols, avail_cols)
        if text_cols is not None
        else [c for c in _DEFAULT_TEXT_CANDIDATE_COLS if c in avail_cols]
    )
    eff_attr_cols = (
        _normalize_col_list(attribute_cols, avail_cols)
        if attribute_cols is not None
        else [c for c in _DEFAULT_ATTR_CANDIDATE_COLS if c in avail_cols]
    )
    if hierarchy_cols is not None:
        eff_hier_cols = _normalize_col_list(hierarchy_cols, avail_cols)
    elif cfg is not None and cfg.hierarchy.levels:
        eff_hier_cols = _normalize_col_list(
            [c for lvl in cfg.hierarchy.levels for c in lvl], avail_cols
        )
    else:
        eff_hier_cols = [c for c in _DEFAULT_HIER_CANDIDATE_COLS if c in avail_cols]

    within_cols = _normalize_col_list(within_hierarchy_level, avail_cols)

    sim_res = compute_similarity_matrix(
        panel_df,
        cfg=cfg,
        method=method,
        top_k=len(series_ids),
        text_cols=eff_text_cols or None,
        embedding_col=embedding_col,
        attribute_cols=eff_attr_cols or None,
        hierarchy_cols=eff_hier_cols or None,
        within_hierarchy_level=within_hierarchy_level,
        semantic_weight=semantic_weight,
        hierarchy_weight=hierarchy_weight,
        ts_id_col=ts_id_col,
        date_col=date_col,
        target_col=target_col,
        **kwargs,
    )
    has_sem = bool(sim_res.diagnostics.get("has_semantic_similarity", False))
    has_hier = bool(sim_res.diagnostics.get("has_hierarchy_similarity", False))

    avail_map, status_map, has_inv = _extract_inventory_snapshot(
        panel_df,
        inventory_df,
        series_ids,
        series_map,
        ts_id_col=ts_id_col,
        date_col=date_col,
        on_hand_col=eff_on_hand_col,
        safety_stock_col=safety_stock_col,
    )

    if query_ts_id is None:
        queries = list(series_ids)
    elif isinstance(query_ts_id, str):
        if str(query_ts_id) not in series_map:
            raise ValueError(
                f"query_ts_id {query_ts_id!r} not found in panel series {series_ids[:10]}."
            )
        queries = [str(query_ts_id)]
    else:
        queries = [str(q) for q in query_ts_id if str(q) in series_map]

    pairs_lookup: dict[tuple[str, str], dict[str, Any]] = {}
    for row in sim_res.pairs_df.to_dict(orient="records"):
        pairs_lookup[(str(row["ts_id"]), str(row["neighbor_ts_id"]))] = {
            str(k): v for k, v in row.items()
        }

    pos_avails = [max(0.0, v) for v in avail_map.values() if v > 0.0]
    max_pos_avail = max(pos_avails) if pos_avails else 1.0
    eff_k = max(1, int(top_k))

    rows: list[dict[str, Any]] = []
    for q_id in queries:
        candidates: list[tuple[float, str, dict[str, Any]]] = []
        for cand_id in series_ids:
            if cand_id == q_id:
                continue
            if within_cols:
                same_scope = all(
                    str(meta_df.loc[q_id, c]).strip().lower()
                    == str(meta_df.loc[cand_id, c]).strip().lower()
                    for c in within_cols
                )
                if not same_scope:
                    continue

            c_status = status_map.get(cand_id, "adequate_stock")
            c_avail = float(avail_map.get(cand_id, 0.0))
            if has_inv and eff_require_in_stock and (c_status == "out_of_stock" or c_avail <= 0.0):
                continue

            p_info = pairs_lookup.get((q_id, cand_id))
            if p_info is None:
                continue

            sim_score = float(p_info["similarity_score"])
            sem_sim = float(p_info["semantic_sim"])
            hier_sim = float(p_info["hierarchy_sim"])
            behav_sim = (
                0.30 * float(p_info["physics_sim"])
                + 0.25 * float(p_info["spectral_sim"])
                + 0.25 * float(p_info["shape_sim"])
                + 0.20 * float(p_info["structural_sim"])
            )

            if has_inv:
                if c_avail <= 0.0 or c_status == "out_of_stock":
                    inv_bonus = 0.0
                else:
                    norm_av = float(np.clip(c_avail / max(max_pos_avail, 1.0), 0.0, 1.0))
                    inv_bonus = (
                        0.50 + 0.50 * norm_av
                        if c_status == "in_stock_surplus"
                        else 0.35 + 0.45 * norm_av
                    )
            else:
                inv_bonus = sim_score

            if has_inv and (c_avail <= 0.0 or c_status == "out_of_stock"):
                sub_score = 0.0
            elif has_sem and has_hier:
                sub_score = 0.40 * sem_sim + 0.25 * hier_sim + 0.20 * behav_sim + 0.15 * inv_bonus
                if sem_sim < 0.12 and hier_sim < 0.15:
                    sub_score *= 0.35
            elif has_sem:
                sub_score = 0.55 * sem_sim + 0.30 * behav_sim + 0.15 * inv_bonus
                if sem_sim < 0.10:
                    sub_score *= 0.50
            elif has_hier:
                sub_score = 0.45 * hier_sim + 0.40 * behav_sim + 0.15 * inv_bonus
                if hier_sim < 0.10:
                    sub_score *= 0.50
            else:
                sub_score = 0.85 * sim_score + 0.15 * inv_bonus

            sub_score = float(np.clip(sub_score, 0.0, 1.0))
            rationale_parts: list[str] = []
            if has_sem:
                rationale_parts.append(f"semantic_sim={sem_sim:.2f}")
            if has_hier:
                rationale_parts.append(f"hierarchy_sim={hier_sim:.2f}")
            rationale_parts.append(f"trajectory_sim={behav_sim:.2f}")
            rationale_parts.append(f"stock={c_status} (available_units={c_avail:.1f})")
            rationale = f"Substitute {cand_id} for {q_id}: " + ", ".join(rationale_parts)

            candidates.append(
                (
                    sub_score,
                    cand_id,
                    {
                        "query_ts_id": q_id,
                        "substitute_ts_id": cand_id,
                        "substitution_score": round(sub_score, 6),
                        "similarity_score": round(sim_score, 6),
                        "semantic_sim": round(sem_sim, 6),
                        "hierarchy_sim": round(hier_sim, 6),
                        "available_units": round(c_avail, 4),
                        "stock_status": c_status,
                        "substitution_rationale": rationale,
                    },
                )
            )

        candidates.sort(key=lambda item: (-item[0], item[1]))
        for rank_idx, (_, _, info) in enumerate(candidates[:eff_k], start=1):
            row_out = dict(info)
            row_out["rank"] = rank_idx
            rows.append(row_out)

    return pd.DataFrame(rows, columns=out_cols)