File size: 8,510 Bytes
0dd91bb ec8df18 0dd91bb ec8df18 0dd91bb ec8df18 0dd91bb ec8df18 0dd91bb ec8df18 0dd91bb ec8df18 0dd91bb ec8df18 0dd91bb ec8df18 0dd91bb e3bd00e 0dd91bb ec8df18 0dd91bb ec8df18 0dd91bb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 | """Excel correlation file parsing and auto-detection."""
import pandas as pd
# Fallback if detection fails (covers DE 6-territory and EN 10-territory models)
_DEFAULT_REWARDS = [
'Abenteuer', 'Autonomie', 'Disziplin', 'Sicherheit', 'Genuss', 'Erregung',
'Adventure', 'Autonomy', 'Discipline', 'Security', 'Enjoyment', 'Excitement',
'GreaterGood', 'Caring', 'Acceptance', 'Control', 'SelfPromotion', 'Achievement', 'Freedom',
]
def detect_reward_territories(df):
"""Detect reward territory names from the Excel file.
Row 4 (0-indexed row 3) contains section headers. The one with
'per reward field' marks the reward territory columns. Row 5 (0-indexed
row 4) underneath lists the individual territory names.
Returns:
list of territory name strings, or _DEFAULT_REWARDS if detection fails.
"""
# Find the 'per reward field' header in row 4 (0-indexed row 3)
reward_col_start = None
for col_idx in range(df.shape[1]):
val = df.iloc[3, col_idx]
if pd.notna(val) and isinstance(val, str) and 'per reward field' in val.lower():
reward_col_start = col_idx
break
if reward_col_start is None:
return list(_DEFAULT_REWARDS)
# Read territory names from row 5 (0-indexed row 4) under that header
territories = []
for col_idx in range(reward_col_start, df.shape[1]):
val = df.iloc[4, col_idx]
if pd.notna(val) and isinstance(val, str) and val.strip():
territories.append(val.strip())
else:
break
return territories if territories else list(_DEFAULT_REWARDS)
def detect_data_start_row(df):
"""Find DATA_START_ROW by detecting the 2nd text block in column B.
The Excel files have two data blocks: means (block 1) and deviations (block 2).
We want block 2 (deviations) since those show what's distinctive.
Returns:
(row_number, blocks) where row_number is 1-based and blocks is a list
of (start, end) tuples for each text block found.
"""
in_block = False
block_start = None
blocks = []
for row_idx in range(df.shape[0]):
val = df.iloc[row_idx, 1]
has_text = pd.notna(val) and isinstance(val, str) and len(str(val).strip()) > 0
if has_text and not in_block:
in_block = True
block_start = row_idx + 1
elif not has_text and in_block:
in_block = False
blocks.append((block_start, row_idx))
block_start = None
if in_block:
blocks.append((block_start, df.shape[0]))
if len(blocks) >= 2:
return blocks[1][0], blocks
elif blocks:
return blocks[0][0], blocks
return None, []
def detect_cutoff_value(df):
"""Find CORR_THRESHOLD by searching for 'Cut-off used in columns' in column B.
Note: This detection fails on all known real files — they don't contain this text.
Falls back to the default (6.0) in the UI.
"""
for row_idx in range(df.shape[0]):
val = df.iloc[row_idx, 1]
if pd.notna(val) and isinstance(val, str) and 'cut-off used in columns' in val.lower():
for col_idx in range(df.shape[1]):
cell_val = df.iloc[row_idx, col_idx]
if pd.notna(cell_val) and isinstance(cell_val, (int, float)):
return round(float(cell_val), 2)
return None
def detect_correlation_column_start(df):
"""Find CORR_COL_START by detecting first large column block (>50 cols) in row 5.
Row 5 (0-indexed row 4) contains the column headers for the correlation matrix.
The first block of >50 consecutive non-empty cells is the "mean across all brands"
correlation matrix.
"""
in_block = False
block_start = None
col_blocks = []
for col_idx in range(df.shape[1]):
val = df.iloc[4, col_idx]
has_data = pd.notna(val) and str(val).strip()
if has_data and not in_block:
in_block = True
block_start = col_idx
elif not has_data and in_block:
in_block = False
col_blocks.append((block_start, col_idx - 1))
block_start = None
if in_block:
col_blocks.append((block_start, df.shape[1] - 1))
for start, end in col_blocks:
if end - start + 1 > 50:
return start
return None
def detect_nonrewards_patterns(df, data_start_idx, rewards_factors):
"""Count Rewards vs Nonrewards attributes starting from data_start_idx.
Classification is based on whether the territory part of the variable code
(3rd segment of PREFIX_PA_Territory_Attribute) appears in rewards_factors.
"""
rewards_count = 0
nonrewards_count = 0
rewards_set = set(rewards_factors)
for row_idx in range(data_start_idx, min(data_start_idx + 200, df.shape[0])):
code = df.iloc[row_idx, 1]
if pd.notna(code) and isinstance(code, str):
if '_PA_' in code:
parts = code.split('_')
if len(parts) >= 3:
factor = parts[2]
if factor in rewards_set:
rewards_count += 1
else:
nonrewards_count += 1
return {'Rewards': rewards_count, 'Nonrewards': nonrewards_count}
def extract_network_data(df, data_start_row, corr_col_start, rewards_factors):
"""Extract attributes, codes, category indices, and correlation matrix from the Excel data.
Args:
df: Raw DataFrame (no header, 0-indexed)
data_start_row: 1-based row number where deviation data starts
corr_col_start: 0-based column index where correlation matrix starts
rewards_factors: list of territory names classified as Rewards
Returns:
dict with keys: attribute_names, attribute_codes, category_indices,
nonrewards_attrs, driver_names, corr_df
"""
data_start_idx = data_start_row - 1
rewards_set = set(rewards_factors)
# Get driver codes from row 5 (0-indexed row 4)
driver_codes = []
for col_idx in range(corr_col_start, df.shape[1]):
driver_code = df.iloc[4, col_idx]
if pd.notna(driver_code) and isinstance(driver_code, str) and driver_code.strip():
driver_codes.append(str(driver_code))
else:
break
# Get attributes from rows
attribute_names = []
attribute_codes = []
category_indices = []
nonrewards_attrs = set()
for row_idx in range(data_start_idx, df.shape[0]):
attr_code = df.iloc[row_idx, 1]
attr_name = df.iloc[row_idx, 2]
cat_idx = df.iloc[row_idx, 3]
if pd.notna(attr_name) and attr_name != '':
code_str = str(attr_code) if pd.notna(attr_code) else ''
attribute_codes.append(code_str)
attribute_names.append(str(attr_name))
try:
cat_val = float(cat_idx) if pd.notna(cat_idx) else 0
except (ValueError, TypeError):
cat_val = 0
category_indices.append(cat_val)
# Classify: if territory NOT in rewards → Nonreward
if '_PA_' in code_str:
parts = code_str.split('_')
if len(parts) >= 3:
factor = parts[2]
if factor not in rewards_set:
nonrewards_attrs.add(str(attr_name))
else:
break
# Map codes to display names
code_to_name = dict(zip(attribute_codes, attribute_names))
driver_names = [code_to_name.get(code, code) for code in driver_codes]
# Build correlation matrix
corr_data = []
for row_idx in range(data_start_idx, data_start_idx + len(attribute_names)):
row_data = []
for col_idx in range(corr_col_start, corr_col_start + len(driver_codes)):
val = df.iloc[row_idx, col_idx]
try:
row_data.append(float(val) if pd.notna(val) else 0)
except (ValueError, TypeError):
row_data.append(0)
corr_data.append(row_data)
corr_df = pd.DataFrame(corr_data, index=attribute_names, columns=driver_names)
return {
'attribute_names': attribute_names,
'attribute_codes': attribute_codes,
'category_indices': category_indices,
'nonrewards_attrs': nonrewards_attrs,
'driver_names': driver_names,
'corr_df': corr_df,
'attr_to_cat_idx': dict(zip(attribute_names, category_indices)),
}
|